cc-safety-net 2.6.17 → 2.6.18

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.
@@ -1,2 +1,2 @@
1
- import{X,x,at,l}from"./index-cxqk4wed.js";import{K,Pe,ge,_e}from"./index-7w6trghf.js";import{resolve as f}from"node:path";var nt=new Map([["bash","posix"],["pwsh","powershell"]]),g={agent:"deepseek-harness",debugLabel:"deepseek-harness tool guard",extract:(e,i,r)=>w(e,i,r),getSessionId:(e)=>e?.agent?.session.header.id,allow:void 0,block:(e)=>X(e),includeEvidenceOnError:(e)=>e.route.kind==="command"};function bt(e){let i=k();e.tools.guard((r)=>i(r,process.cwd()))}function k(e={}){return _e(g,e)}function w(e,i,r){if(!e||typeof e!=="object")return Pe(null);let d=e,u=d.agent?.session.header.cwd??i,o=at([u],r),n=d.name;if(typeof n!=="string"||n.trim()==="")return K(o??null);if(!o)return ge({directory:"session",problem:"unusable",cwd:u},{toolName:n});let t=d.arguments,c=nt.get(n);if(!c)return l(n,t,{kind:x(n)},{configCwd:o,executionCwd:o},null);if(!t||typeof t!=="object"||Array.isArray(t))return K(o,{toolName:n});let p=t,a=p.command;if(typeof a!=="string"||a.trim()==="")return K(o,{toolName:n});let s=p.workdir;if(s!==void 0&&(typeof s!=="string"||s.trim()===""))return K(o,{command:a,toolName:n});let m=s===void 0?o:at([f(o,s)],r);if(!m)return ge({directory:"requested",problem:"unusable",cwd:s},{command:a,toolName:n});return l(n,t,{kind:"command",shell:c},{configCwd:o,executionCwd:m},a)}
1
+ import{X,x,at,l}from"./index-1p1q38x4.js";import{K,Pe,ge,_e}from"./index-tz7650sh.js";import{resolve as f}from"node:path";var nt=new Map([["bash","posix"],["pwsh","powershell"]]),g={agent:"deepseek-harness",debugLabel:"deepseek-harness tool guard",extract:(e,i,r)=>w(e,i,r),getSessionId:(e)=>e?.agent?.session.header.id,allow:void 0,block:(e)=>X(e),includeEvidenceOnError:(e)=>e.route.kind==="command"};function bt(e){let i=k();e.tools.guard((r)=>i(r,process.cwd()))}function k(e={}){return _e(g,e)}function w(e,i,r){if(!e||typeof e!=="object")return Pe(null);let d=e,u=d.agent?.session.header.cwd??i,o=at([u],r),n=d.name;if(typeof n!=="string"||n.trim()==="")return K(o??null);if(!o)return ge({directory:"session",problem:"unusable",cwd:u},{toolName:n});let t=d.arguments,c=nt.get(n);if(!c)return l(n,t,{kind:x(n)},{configCwd:o,executionCwd:o},null);if(!t||typeof t!=="object"||Array.isArray(t))return K(o,{toolName:n});let p=t,a=p.command;if(typeof a!=="string"||a.trim()==="")return K(o,{toolName:n});let s=p.workdir;if(s!==void 0&&(typeof s!=="string"||s.trim()===""))return K(o,{command:a,toolName:n});let m=s===void 0?o:at([f(o,s)],r);if(!m)return ge({directory:"requested",problem:"unusable",cwd:s},{command:a,toolName:n});return l(n,t,{kind:"command",shell:c},{configCwd:o,executionCwd:m},a)}
2
2
  export{nt,bt};
@@ -1,2 +1,2 @@
1
- import{X,x,Ct,l}from"./index-cxqk4wed.js";import{K,Pe,ge,_e}from"./index-7w6trghf.js";var tt=new Map([["bash","posix"],["powershell","powershell"]]),u={agent:"pi",debugLabel:"pi tool_call",extract:(o,n,i)=>C(o,n,i),getSessionId:(o,n)=>n.sessionManager.getSessionId(),allow:void 0,block:(o)=>p(o),includeEvidenceOnError:(o)=>o.route.kind==="command"};function vt(o){o.on("tool_call",s)}var s=m();function m(o={}){return _e(u,o)}function C(o,n,i){if(!o||typeof o!=="object")return;let e=o;if(e.type!==void 0&&e.type!=="tool_call")return;if(typeof e.toolName!=="string"||e.toolName.trim()==="")return d(n);if(typeof n.cwd!=="string"||n.cwd.trim()==="")return Pe(null,{toolName:e.toolName});let t=Ct(".",[n.cwd],i);if(!t)return ge({directory:"session",problem:"unusable",cwd:n.cwd},{toolName:e.toolName});let r=tt.get(e.toolName);if(!e.input||typeof e.input!=="object")return r?d(n,e.toolName):void 0;if(!r)return l(e.toolName,e.input,{kind:x(e.toolName)},{configCwd:t,executionCwd:t},null);let a=e.input.command;if(typeof a!=="string"||a.trim()==="")return d(n,e.toolName);return l(e.toolName,e.input,{kind:"command",shell:r},{configCwd:t,executionCwd:t},a)}function d(o,n){return K(typeof o.cwd==="string"&&o.cwd.trim()?o.cwd:null,{toolName:n})}function p(o){return{block:!0,reason:X(o)}}
1
+ import{X,x,Ct,l}from"./index-1p1q38x4.js";import{K,Pe,ge,_e}from"./index-tz7650sh.js";var tt=new Map([["bash","posix"],["powershell","powershell"]]),u={agent:"pi",debugLabel:"pi tool_call",extract:(o,n,i)=>C(o,n,i),getSessionId:(o,n)=>n.sessionManager.getSessionId(),allow:void 0,block:(o)=>p(o),includeEvidenceOnError:(o)=>o.route.kind==="command"};function vt(o){o.on("tool_call",s)}var s=m();function m(o={}){return _e(u,o)}function C(o,n,i){if(!o||typeof o!=="object")return;let e=o;if(e.type!==void 0&&e.type!=="tool_call")return;if(typeof e.toolName!=="string"||e.toolName.trim()==="")return d(n);if(typeof n.cwd!=="string"||n.cwd.trim()==="")return Pe(null,{toolName:e.toolName});let t=Ct(".",[n.cwd],i);if(!t)return ge({directory:"session",problem:"unusable",cwd:n.cwd},{toolName:e.toolName});let r=tt.get(e.toolName);if(!e.input||typeof e.input!=="object")return r?d(n,e.toolName):void 0;if(!r)return l(e.toolName,e.input,{kind:x(e.toolName)},{configCwd:t,executionCwd:t},null);let a=e.input.command;if(typeof a!=="string"||a.trim()==="")return d(n,e.toolName);return l(e.toolName,e.input,{kind:"command",shell:r},{configCwd:t,executionCwd:t},a)}function d(o,n){return K(typeof o.cwd==="string"&&o.cwd.trim()?o.cwd:null,{toolName:n})}function p(o){return{block:!0,reason:X(o)}}
2
2
  export{tt,vt};
@@ -1,4 +1,4 @@
1
- import{a,s,Y,m,je,u,Ve,b,F,f,j}from"./index-cxqk4wed.js";import{appendFileSync as re,mkdirSync as oe}from"node:fs";import{isAbsolute as ie,join as S}from"node:path";import{lstatSync as D,readdirSync as V,readFileSync as B,rmdirSync as K,statSync as C,unlinkSync as X,utimesSync as z,writeFileSync as Z}from"node:fs";import{join as g}from"node:path";function se(t,e={}){return Ve(u(t,e),t.home).policy.audit.retention_days}var A=86400000,Q=".last-prune",W=/^\d{4}-\d{2}$/,q=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,L=(t)=>Math.floor(t/A);function J(t,e,r=()=>new Date){try{let n=r().getTime();if(!C(e,{throwIfNoEntry:!1})?.isDirectory())return;let o=g(e,Q),c=C(o,{throwIfNoEntry:!1})?.mtimeMs;if(c!==void 0&&L(c)===L(n))return;let i=n-se(t)*A,d=new Date(n).toISOString().slice(0,7);for(let l of v(e)){if(l.isDirectory()){ee(g(e,l.name),i,d);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))te(g(e,l.name),i)}Z(o,"",{mode:384}),z(o,n/1000,n/1000)}catch{}}function ee(t,e,r){for(let n of v(t)){if(!n.isDirectory()||!W.test(n.name))continue;let o=g(t,n.name);for(let c of v(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`)+A;if(!Number.isFinite(d)||d>=e)continue;G(g(o,c.name))}if(n.name!==r)O(o)}O(t)}function te(t,e){try{let r=D(t);if(r.mtimeMs>=e)return;let n=B(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(D(t).mtimeMs!==r.mtimeMs)return;G(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 v(t){try{return V(t,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function G(t){try{X(t)}catch{}}function O(t){try{K(t)}catch{}}var ae="2.6.17",ce=1e4,de=2000,ue=256,le=32768;function me(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 fe(t){return(t??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function I(t,e,r,n,o,c,i={}){let d=me(e);if(!d)return;let l=U(t);if(!l)return;try{let y=(i.now??(()=>new Date))().toISOString(),_=p(Y(r),i.failureStage?Number.POSITIVE_INFINITY:ce),N=p(Y(n),de),h=i.toolName?p(Y(i.toolName),ue):void 0,E=c===null?void 0:p(Y(c),le),w=S(l,fe(E?.value??null),y.slice(0,7));oe(w,{recursive:!0,mode:448});let R=S(w,`${y.slice(0,10)}-${d}.jsonl`),P={ts:y,id:(i.createId??je)(),v:ae,sessionId:d,decision:i.decision??"deny",agent:i.agent,shape:i.shape,level:i.level,configFallback:i.configFallback,toolName:h?.value,command:_.value,segment:N.value,..._.truncated||N.truncated||h?.truncated||E?.truncated?{truncated:!0}:{},reason:o,ruleId:i.ruleId,intent:i.intent,failureStage:i.failureStage,errorCode:i.errorCode,cwd:E?.value??null};re(R,`${JSON.stringify(P)}
1
+ import{a,s,Y,m,je,u,Ve,b,F,f,j}from"./index-1p1q38x4.js";import{appendFileSync as re,mkdirSync as oe}from"node:fs";import{isAbsolute as ie,join as S}from"node:path";import{lstatSync as D,readdirSync as V,readFileSync as B,rmdirSync as K,statSync as C,unlinkSync as X,utimesSync as z,writeFileSync as Z}from"node:fs";import{join as g}from"node:path";function se(t,e={}){return Ve(u(t,e),t.home).policy.audit.retention_days}var A=86400000,Q=".last-prune",W=/^\d{4}-\d{2}$/,q=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,L=(t)=>Math.floor(t/A);function J(t,e,r=()=>new Date){try{let n=r().getTime();if(!C(e,{throwIfNoEntry:!1})?.isDirectory())return;let o=g(e,Q),c=C(o,{throwIfNoEntry:!1})?.mtimeMs;if(c!==void 0&&L(c)===L(n))return;let i=n-se(t)*A,d=new Date(n).toISOString().slice(0,7);for(let l of v(e)){if(l.isDirectory()){ee(g(e,l.name),i,d);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))te(g(e,l.name),i)}Z(o,"",{mode:384}),z(o,n/1000,n/1000)}catch{}}function ee(t,e,r){for(let n of v(t)){if(!n.isDirectory()||!W.test(n.name))continue;let o=g(t,n.name);for(let c of v(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`)+A;if(!Number.isFinite(d)||d>=e)continue;G(g(o,c.name))}if(n.name!==r)O(o)}O(t)}function te(t,e){try{let r=D(t);if(r.mtimeMs>=e)return;let n=B(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(D(t).mtimeMs!==r.mtimeMs)return;G(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 v(t){try{return V(t,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function G(t){try{X(t)}catch{}}function O(t){try{K(t)}catch{}}var ae="2.6.18",ce=1e4,de=2000,ue=256,le=32768;function me(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 fe(t){return(t??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function I(t,e,r,n,o,c,i={}){let d=me(e);if(!d)return;let l=U(t);if(!l)return;try{let y=(i.now??(()=>new Date))().toISOString(),_=p(Y(r),i.failureStage?Number.POSITIVE_INFINITY:ce),N=p(Y(n),de),h=i.toolName?p(Y(i.toolName),ue):void 0,E=c===null?void 0:p(Y(c),le),w=S(l,fe(E?.value??null),y.slice(0,7));oe(w,{recursive:!0,mode:448});let R=S(w,`${y.slice(0,10)}-${d}.jsonl`),P={ts:y,id:(i.createId??je)(),v:ae,sessionId:d,decision:i.decision??"deny",agent:i.agent,shape:i.shape,level:i.level,configFallback:i.configFallback,toolName:h?.value,command:_.value,segment:N.value,..._.truncated||N.truncated||h?.truncated||E?.truncated?{truncated:!0}:{},reason:o,ruleId:i.ruleId,intent:i.intent,failureStage:i.failureStage,errorCode:i.errorCode,cwd:E?.value??null};re(R,`${JSON.stringify(P)}
3
3
  `,{encoding:"utf-8",mode:384}),J(t,l,i.now)}catch{}}function p(t,e){return{value:t.slice(0,e),truncated:t.length>e}}function rt(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 U(t){let e=rt(t);return e?S(e,".cc-safety-net","logs"):null}function k(t,e,r,n=!0,o){if(e.decision.kind==="allow"){if(!r||t.route.kind!=="command")return;let d=T(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?T(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 T(t){return"command"in t?t.command??"":""}function x(t,e,r,n){if(!e)return;let o;try{o=r()}catch{return}if(typeof o!=="string"||!o.trim())return;I(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 Ae(t,e,r,n){let o;try{o=r()}catch{return}if(typeof o!=="string"||!o.trim())return;I(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 H(t,e,r){try{let n=j(e,{environment:t,...r.guard});return M(t,e,n,r),n}catch(n){if(!(n instanceof f))throw n;throw M(t,e,n.evaluation,r,!(n.cause instanceof m),{stage:n.stage,errorCode:ge(n.cause)}),n}}function M(t,e,r,n,o=!0,c){x(t,k(r.promotedInvocation??e,r,n.guard?.auditAllowed??!1,o,c),n.audit.getSessionId,{agent:n.audit.agent,shape:n.audit.shape})}function ge(t){if(t instanceof s)return a[t.kind].errorCode;if(t instanceof m)return"tool-input-limit";if(t instanceof b)return"structural-shell-syntax-limit";if(t instanceof F)return"unparseable-command";return"unexpected-error"}
4
4
  export{se,J,rt,U,Ae,H};
@@ -1,2 +1,2 @@
1
- import{Ie,Z,G,P,St,c,n,Oe,S,f}from"./index-cxqk4wed.js";import{Ae,H}from"./index-823nnrjs.js";function K(o,t={}){return{malformed:!0,denial:G(t),cwd:o}}function Pe(o,t={}){return{malformed:!0,denial:Z(t),cwd:o}}function ge(o,t){return{malformed:!0,denial:P(o,t),cwd:o.cwd}}function _e(o,t={}){return(e,i)=>{try{return p(e,i,o,t)}catch(a){return console.error("CC Safety Net error:",a),o.block(Z())}}}function p(o,t,e,i){let a=c();if(e.cancelled?.(t))return e.block(Z());let l=e.extract(o,t,a.paths);if(!l)return e.allow;let d=()=>e.getSessionId(o,t);if("malformed"in l)return Ae(a,l.denial,d,{agent:e.agent,toolName:l.denial.toolName,cwd:l.cwd}),e.block(l.denial);let u=(r,s)=>{let m=Ie(r,{includeEvidence:s});return m?e.block(m):e.allow};try{let r=H(a,l,{guard:{auditAllowed:Oe(a.env),policyOptions:i.policyOptions,dependencies:i.guardDependencies},audit:{agent:e.agent,getSessionId:d}});return u(r,!0)}catch(r){if(!(r instanceof f))throw r;if(S(n.debug,a.env))console.error(`CC Safety Net debug: ${e.debugLabel} analysis failed: ${St(r.cause)}`);return u(r.evaluation,e.includeEvidenceOnError(l))}}
1
+ import{Ie,Z,G,P,St,c,n,Oe,S,f}from"./index-1p1q38x4.js";import{Ae,H}from"./index-8m4sxbp8.js";function K(o,t={}){return{malformed:!0,denial:G(t),cwd:o}}function Pe(o,t={}){return{malformed:!0,denial:Z(t),cwd:o}}function ge(o,t){return{malformed:!0,denial:P(o,t),cwd:o.cwd}}function _e(o,t={}){return(e,i)=>{try{return p(e,i,o,t)}catch(a){return console.error("CC Safety Net error:",a),o.block(Z())}}}function p(o,t,e,i){let a=c();if(e.cancelled?.(t))return e.block(Z());let l=e.extract(o,t,a.paths);if(!l)return e.allow;let d=()=>e.getSessionId(o,t);if("malformed"in l)return Ae(a,l.denial,d,{agent:e.agent,toolName:l.denial.toolName,cwd:l.cwd}),e.block(l.denial);let u=(r,s)=>{let m=Ie(r,{includeEvidence:s});return m?e.block(m):e.allow};try{let r=H(a,l,{guard:{auditAllowed:Oe(a.env),policyOptions:i.policyOptions,dependencies:i.guardDependencies},audit:{agent:e.agent,getSessionId:d}});return u(r,!0)}catch(r){if(!(r instanceof f))throw r;if(S(n.debug,a.env))console.error(`CC Safety Net debug: ${e.debugLabel} analysis failed: ${St(r.cause)}`);return u(r.evaluation,e.includeEvidenceOnError(l))}}
2
2
  export{K,Pe,ge,_e};
package/dist/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a,s,$e,ot,T,xt,it,c,n,st,_,S,he,wt,m,De,x,ct,l,o,w,i,ce,r,h,ve,B,Et,kt,p,be,xe,Rt,L,Q,le,C,Tt,A,y,ue,W,u,O,ee,lt,ut,M,E,D,Se,we,Ue,de,d,e,He,Ne,Ge,Ce,dt,pt,pe,Le,fe,Be,te,z,We,Ee,V,ft,q,ne,re,me,mt,gt,k,I,ze,ht,qe,R,Ke,Me,Je,v,t,oe,ke,b,F,g,N,Pt,Ye,Ze,f,j}from"./chunks/index-cxqk4wed.js";import{tt}from"./chunks/index-qr496znd.js";import{Xe,Te}from"./chunks/index-x65f5t9p.js";import{nt}from"./chunks/index-p0tjjrnj.js";import"./chunks/index-7w6trghf.js";import{se,J,rt,U,H}from"./chunks/index-823nnrjs.js";var Cf=["-h","--help"];function fn(P,G){let K=Object.entries(P.booleans??{}),Y=Object.entries(P.values??{}),Z=Object.entries(P.lists??{}),X=Object.fromEntries(K.map(([_e])=>[_e,!1])),ie={},ae=Object.fromEntries(Z.map(([_e])=>[_e,[]])),ge=[],ye=[],Pe=!1,Re=-1;for(let[_e,Ae]of G.entries()){if(_e<=Re)continue;if(Ae==="--"){ge.push(...G.slice(_e+1));break}if(Cf.includes(Ae)){Pe=!0;continue}let Ie=K.find(([,Ve])=>Ve.includes(Ae));if(Ie){X[Ie[0]]=!0;continue}let je=Y.find(([,Ve])=>Ve.includes(Ae));if(je){let Ve=G[_e+1];if(Ve===void 0||Ve.startsWith("-")){ye.push(`${Ae} requires a value`);continue}ie[je[0]]=Ve,Re=_e+1;continue}let Oe=Z.find(([,Ve])=>Ve.includes(Ae));if(Oe){let Ve=G.slice(_e+1),nn=Ve.findIndex((an)=>an.startsWith("-")),rn=Ve.slice(0,nn===-1?Ve.length:nn);if(rn.length===0){ye.push(`${Ae} requires at least one value`);continue}ae[Oe[0]]=[...ae[Oe[0]]??[],...rn],Re=_e+rn.length;continue}if(Ae.startsWith("-")){ye.push(`Unknown option for ${P.label}: ${Ae}`);continue}if(P.positionals==="tail"){ge.push(...G.slice(_e));break}ge.push(Ae)}if(P.positionals!=="list"&&P.positionals!=="tail")ye.push(...ge.map((_e)=>`Unexpected argument for ${P.label}: ${_e}`));return{flags:X,values:ie,lists:ae,positionals:ge,help:Pe,errors:ye}}function $n(P){for(let G of P)console.error(G);return P.length>0}import{readdirSync as Af,statSync as Xs,unlinkSync as _f}from"node:fs";import{basename as Qs,dirname as If,isAbsolute as Of,join as $f,relative as Df,resolve as Nf,sep as Lf}from"node:path";var Ws=(P)=>{let G=Date.now()-new Date(P).getTime();if(!Number.isFinite(G))return"";let K=Math.floor(G/60000),Y=Math.floor(K/60),Z=Math.floor(Y/24);if(Z>0)return`${Z}d ago`;if(Y>0)return`${Y}h ago`;if(K>0)return`${K}m ago`;return"just now"},Go=(P)=>{let G=(P??"").trim().split(/\s+/).filter((Z)=>Z&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(Z)),K=G[0]?.split("/").pop();if(!K)return null;let Y=G[1];return Y&&/^[a-z][a-z0-9-]*$/.test(Y)?`${K} ${Y}`:K};function Ys(P){let G=(Z)=>`${Z.sessionId}
1
+ import{a,s,$e,ot,T,xt,it,c,n,st,_,S,he,wt,m,De,x,ct,l,o,w,i,ce,r,h,ve,B,Et,kt,p,be,xe,Rt,L,Q,le,C,Tt,A,y,ue,W,u,O,ee,lt,ut,M,E,D,Se,we,Ue,de,d,e,He,Ne,Ge,Ce,dt,pt,pe,Le,fe,Be,te,z,We,Ee,V,ft,q,ne,re,me,mt,gt,k,I,ze,ht,qe,R,Ke,Me,Je,v,t,oe,ke,b,F,g,N,Pt,Ye,Ze,f,j}from"./chunks/index-1p1q38x4.js";import{tt}from"./chunks/index-8c31a7e4.js";import{Xe,Te}from"./chunks/index-03hfs9tb.js";import{nt}from"./chunks/index-7nndhfn3.js";import"./chunks/index-tz7650sh.js";import{se,J,rt,U,H}from"./chunks/index-8m4sxbp8.js";var Cf=["-h","--help"];function fn(P,G){let K=Object.entries(P.booleans??{}),Y=Object.entries(P.values??{}),Z=Object.entries(P.lists??{}),X=Object.fromEntries(K.map(([_e])=>[_e,!1])),ie={},ae=Object.fromEntries(Z.map(([_e])=>[_e,[]])),ge=[],ye=[],Pe=!1,Re=-1;for(let[_e,Ae]of G.entries()){if(_e<=Re)continue;if(Ae==="--"){ge.push(...G.slice(_e+1));break}if(Cf.includes(Ae)){Pe=!0;continue}let Ie=K.find(([,Ve])=>Ve.includes(Ae));if(Ie){X[Ie[0]]=!0;continue}let je=Y.find(([,Ve])=>Ve.includes(Ae));if(je){let Ve=G[_e+1];if(Ve===void 0||Ve.startsWith("-")){ye.push(`${Ae} requires a value`);continue}ie[je[0]]=Ve,Re=_e+1;continue}let Oe=Z.find(([,Ve])=>Ve.includes(Ae));if(Oe){let Ve=G.slice(_e+1),nn=Ve.findIndex((an)=>an.startsWith("-")),rn=Ve.slice(0,nn===-1?Ve.length:nn);if(rn.length===0){ye.push(`${Ae} requires at least one value`);continue}ae[Oe[0]]=[...ae[Oe[0]]??[],...rn],Re=_e+rn.length;continue}if(Ae.startsWith("-")){ye.push(`Unknown option for ${P.label}: ${Ae}`);continue}if(P.positionals==="tail"){ge.push(...G.slice(_e));break}ge.push(Ae)}if(P.positionals!=="list"&&P.positionals!=="tail")ye.push(...ge.map((_e)=>`Unexpected argument for ${P.label}: ${_e}`));return{flags:X,values:ie,lists:ae,positionals:ge,help:Pe,errors:ye}}function $n(P){for(let G of P)console.error(G);return P.length>0}import{readdirSync as Af,statSync as Xs,unlinkSync as _f}from"node:fs";import{basename as Qs,dirname as If,isAbsolute as Of,join as $f,relative as Df,resolve as Nf,sep as Lf}from"node:path";var Ws=(P)=>{let G=Date.now()-new Date(P).getTime();if(!Number.isFinite(G))return"";let K=Math.floor(G/60000),Y=Math.floor(K/60),Z=Math.floor(Y/24);if(Z>0)return`${Z}d ago`;if(Y>0)return`${Y}h ago`;if(K>0)return`${K}m ago`;return"just now"},Go=(P)=>{let G=(P??"").trim().split(/\s+/).filter((Z)=>Z&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(Z)),K=G[0]?.split("/").pop();if(!K)return null;let Y=G[1];return Y&&/^[a-z][a-z0-9-]*$/.test(Y)?`${K} ${Y}`:K};function Ys(P){let G=(Z)=>`${Z.sessionId}
2
2
  ${Go(Z.segment||Z.command)}`,K=P.filter((Z)=>Z.decision!=="allow"),Y=K.filter((Z)=>Z.sessionId).reduce((Z,X)=>Z.set(G(X),(Z.get(G(X))??0)+1),new Map);return new Set(K.filter((Z)=>Z.failureStage||(Y.get(G(Z))??0)>=2))}import{existsSync as xf,readdirSync as Pf,readFileSync as Sf}from"node:fs";import{join as Rf}from"node:path";function Wn(P,G){try{return Pf(P,{withFileTypes:!0,encoding:"utf8"}).flatMap((K)=>{let Y=Rf(P,K.name);if(K.isDirectory())return Wn(Y,G);if(K.name.endsWith(".jsonl"))return[Y];return[]})}catch{if(G&&xf(P))G.count++;return[]}}var Ef=["segment","reason","sessionId","decision","agent","ruleId","failureStage"];function Tf(P){if(!P||typeof P!=="object"||Array.isArray(P))return!1;let G=P;if(typeof G.ts!=="string"||typeof G.command!=="string")return!1;return Ef.every((K)=>G[K]===void 0||typeof G[K]==="string")}function Dt(P,G){try{return Sf(P,"utf-8").split(`
3
3
  `).filter(Boolean).flatMap((K)=>{try{let Y=JSON.parse(K);if(!Tf(Y)){if(G)G.count++;return[]}return[Y]}catch{if(G)G.count++;return[]}})}catch{if(G)G.count++;return[]}}function mn(P){return Array.from(P,(G)=>{let K=G.charCodeAt(0);if(K<=31||K>=127&&K<=159)return`\\x${K.toString(16).padStart(2,"0")}`;return G}).join("")}function jf(P,G){let K=se(P),Y=fn({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"]}},G);if($n(Y.errors))return null;if(Y.values.id!==void 0&&!/^[a-f0-9]{16}$/.test(Y.values.id))return console.error("--id must be 16 hexadecimal characters"),null;let Z=Y.values.limit===void 0?20:Zs(Y.values.limit);if(Z===null)return console.error("--limit must be a positive number"),null;let X=Y.values.since===void 0?Math.min(30,K):Zs(Y.values.since);if(X===null||X>K)return console.error(`--since must be a positive number of days no greater than ${K}`),null;let ie={limit:Z,limitExplicit:Y.values.limit!==void 0,since:X,sinceExplicit:Y.values.since!==void 0,all:Y.flags.all,json:Y.flags.json,suspect:Y.flags.suspect,pruneLegacy:Y.flags.pruneLegacy,dryRun:Y.flags.dryRun,id:Y.values.id,agent:Y.values.agent,rule:Y.values.rule,session:Y.values.session,project:Y.values.project===void 0?void 0:Nf(Y.values.project)};if(ie.id&&(ie.agent!==void 0||ie.rule!==void 0||ie.session!==void 0||ie.project!==void 0||ie.suspect||ie.sinceExplicit||ie.limitExplicit))return console.error("--id cannot be combined with --agent, --rule, --session, --project, --suspect, --since, or --limit"),null;if(ie.pruneLegacy&&(ie.id!==void 0||ie.agent!==void 0||ie.rule!==void 0||ie.session!==void 0||ie.project!==void 0||ie.suspect||ie.all||ie.sinceExplicit||ie.limitExplicit))return console.error("--prune-legacy cannot be combined with --id, --agent, --rule, --session, --project, --suspect, --all, --since, or --limit"),null;if(ie.dryRun&&!ie.pruneLegacy)return console.error("--dry-run requires --prune-legacy"),null;return ie}async function ea(P,G,K={}){let Y=jf(P,G);if(!Y)return 1;let Z=K.logsDir??U(P);if(Y.pruneLegacy)return Ff(Z,Y.json,Y.dryRun);if(!Z)return console.log(Y.json?"[]":Y.id?`No retained audit log entry found for id ${mn(Y.id)}.`:"No audit log entries found."),0;J(P,Z);let X={count:0},ie=Wn(Z,X).flatMap((Re)=>Dt(Re,X).map((_e)=>({entry:_e,file:Re})));if(X.count>0)console.error(`warning: ${X.count} audit log ${X.count===1?"source":"sources"} could not be read; these results are incomplete`);if(Y.id)return Bf(ie,Y,K.timeZone);let ae=Date.now()-Y.since*24*60*60*1000,ge=ie.filter((Re)=>Gf(Re,Y,Z,ae)),ye=Y.suspect?Ys(ge.map((Re)=>Re.entry)):null,Pe=(ye?ge.filter((Re)=>ye.has(Re.entry)):ge).sort((Re,_e)=>Date.parse(_e.entry.ts)-Date.parse(Re.entry.ts)).slice(0,Y.limit);if(Y.json)return console.log(JSON.stringify(Pe.map((Re)=>Re.entry),null,2)),0;if(Pe.length===0)return console.log("No audit log entries found."),0;for(let Re of Pe)console.log(Kf(Re.entry,K.timeZone));return 0}function Ff(P,G,K){let Y=P?Mf(P).map((ae)=>$f(P,ae)):[];if(K)return Hf(Y,G);let Z=[],X=0,ie=0;for(let ae of Y){let ge=Xs(ae,{throwIfNoEntry:!1})?.size??0,ye=Uf(ae);if(ye){Z.push(`${Qs(ae)}: ${ye}`);continue}X++,ie+=ge}if(G)return console.log(JSON.stringify({removedFiles:X,removedBytes:ie,failedFiles:Z.length})),Z.length===0?0:1;console.log(X===0&&Z.length===0?"No legacy audit log files found.":`Removed ${X} legacy audit log ${X===1?"file":"files"} (${na(ie)}).`);for(let ae of Z)console.error(`Could not remove ${mn(ae)}`);if(console.log("Nested v2 audit logs were not changed."),X>0)console.log("This deletion cannot be undone.");return Z.length===0?0:1}function Hf(P,G){let K=P.reduce((Y,Z)=>Y+(Xs(Z,{throwIfNoEntry:!1})?.size??0),0);if(G)return console.log(JSON.stringify({dryRun:!0,files:P.length,bytes:K})),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"} (${na(K)}).`),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 Mf(P){try{return Af(P,{withFileTypes:!0}).filter((G)=>G.isFile()&&G.name.endsWith(".jsonl")).map((G)=>G.name)}catch{return[]}}function Uf(P){try{return _f(P),null}catch(G){return G instanceof Error?G.message:String(G)}}function na(P){let G=["B","KiB","MiB","GiB"],K=Math.min(Math.floor(Math.log2(Math.max(P,1))/10),G.length-1);return`${Math.round(P/1024**K*10)/10} ${G[K]}`}function Bf(P,G,K){let Y=P.filter((X)=>X.entry.id===G.id);if(Y.length>1)return console.error(`Multiple audit log entries found for id ${mn(G.id??"")}.`),1;if(G.json)return console.log(JSON.stringify(Y.map((X)=>X.entry),null,2)),0;let Z=Y[0];if(!Z)return console.log(`No retained audit log entry found for id ${mn(G.id??"")}.`),0;return console.log(Jf(Z.entry,K)),0}function Gf(P,G,K,Y){if(!G.all&&P.entry.decision==="allow")return!1;if(Date.parse(P.entry.ts)<Y)return!1;if(G.agent!==void 0&&P.entry.agent!==G.agent)return!1;if(G.rule!==void 0&&P.entry.ruleId!==G.rule)return!1;if(G.session!==void 0&&!qf(P,K,G.session))return!1;if(G.project!==void 0&&!Vf(P.entry.cwd,G.project))return!1;return!0}function qf(P,G,K){if(P.entry.sessionId===K)return!0;return If(P.file)===G&&Qs(P.file,".jsonl")===K}function Vf(P,G){if(!P)return!1;let K=Df(G,P);return K!==".."&&!K.startsWith(`..${Lf}`)&&!Of(K)}function Kf(P,G){let K=mn(P.id??"-"),Y=mn(P.decision??"deny"),Z=P.cwd?` [${mn(P.cwd)}]`:"",X=P.segment||P.command,ie=X===P.command?"":"↳ ",ae=X.length>50?`${X.slice(0,50)}…`:X;return`${K.padEnd(16)} ${mn(ta(P.ts,G))} ${Y.padEnd(5)} ${mn(P.agent??"-").padEnd(15)} ${mn(P.ruleId??"-").padEnd(20)} ${ie}${mn(ae)}${Z}`}function Jf(P,G){let K=(Z)=>mn(Z===void 0||Z===null||Z===""?"-":Z),Y=P.shape?`${P.agent??"-"} (shape: ${P.shape})`:P.agent??"-";return[`id: ${K(P.id)}`,`ts: ${K(ta(P.ts,G))}`,`decision: ${K(P.decision)}`,`agent: ${K(Y)}`,`level: ${K(P.level)}`,`tool: ${K(P.toolName)}`,`rule: ${K(P.ruleId)}`,`intent: ${K(P.intent)}`,`stage: ${K(P.failureStage)}`,`error: ${K(P.errorCode)}`,`session: ${K(P.sessionId)}`,`cwd: ${K(P.cwd)}`,`version: ${K(P.v)}`,`truncated: ${K(P.truncated===!0?"yes":void 0)}`,`reason: ${K(P.reason)}`,`command: ${K(P.command)}`,`segment: ${K(P.segment)}`].join(`
4
4
  `)}function ta(P,G){let K=new Date(P);if(Number.isNaN(K.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:G}).format(K)}function Zs(P){let G=Number(P);return Number.isFinite(G)&&G>0?G:null}var ra={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 oa={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 ia={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 qo=["npx","--offline","--no-install","@deepseek-ai/dsh","--version"],sa=["cursor-agent","--version"],aa=[{id:"antigravity-cli",displayName:"Antigravity CLI",runtime:{flags:["-ac","--agy-cli"],description:"Run as Antigravity CLI PreToolUse hook",legacyTopLevelFlags:[]},install:{flag:"--agy-cli",artifactKind:"hook config",probeCommand:["agy","--version"]}},{id:"claude-code",displayName:"Claude Code",runtime:{displayName:"Coding CLI",flags:["-cc","--coding-cli"],legacyFlags:["--claude-code"],description:"Run as Coding CLI PreToolUse hook",legacyTopLevelFlags:["-cc","--claude-code"]},install:{flag:"--claude-code",artifactKind:"plugin",probeCommand:["claude","--version"]}},{id:"codex",displayName:"Codex",runtime:{flags:["-cx","--codex"],description:"Run as a Codex PreToolUse hook",legacyTopLevelFlags:[]},install:{flag:"--codex",artifactKind:"plugin",probeCommand:["codex","--version"]}},{id:"copilot-cli",displayName:"GitHub Copilot CLI",runtime:{flags:["-cp","--copilot-cli"],description:"Run as GitHub Copilot CLI PreToolUse hook",legacyTopLevelFlags:["-cp","--copilot-cli"]},install:{flag:"--copilot-cli",artifactKind:"plugin",probeCommand:["copilot","--binary-version"]}},{id:"gemini-cli",displayName:"Gemini CLI",runtime:{flags:["-gc","--gemini-cli"],description:"Run as Gemini CLI BeforeTool hook",legacyTopLevelFlags:["-gc","--gemini-cli"]},install:{flag:"--gemini-cli",artifactKind:"extension",probeCommand:["gemini","--version"]}},{id:"grok-build",displayName:"Grok Build",runtime:{flags:["-gb","--grok-build"],description:"Run as Grok Build PreToolUse hook",legacyTopLevelFlags:[]},install:{flag:"--grok-build",artifactKind:"hook config",probeCommand:["grok","--version"]}},{id:"hermes-agent",displayName:"Hermes Agent",runtime:{flags:["-ha","--hermes-agent"],description:"Run as Hermes Agent pre_tool_call hook",legacyTopLevelFlags:[]},install:{flag:"--hermes-agent",artifactKind:"plugin",probeCommand:["hermes","--version"]}},{id:"kimi-code",displayName:"Kimi Code",runtime:{flags:["-kc","--kimi-code"],description:"Run as Kimi Code PreToolUse hook",legacyTopLevelFlags:[]},install:{flag:"--kimi-code",artifactKind:"hook config",probeCommand:["kimi","--version"]}},{id:"openclaw",displayName:"OpenClaw",install:{flag:"--openclaw",artifactKind:"plugin",probeCommand:["openclaw","--version"]}},{id:"opencode",displayName:"OpenCode",install:{flag:"--opencode",artifactKind:"plugin",probeCommand:["opencode","--version"]}},{id:"pi",displayName:"Pi",install:{flag:"--pi",artifactKind:"package",probeCommand:["pi","--version"]}},{id:"cursor",displayName:"Cursor",runtime:{flags:["-cu","--cursor"],description:"Run as Cursor preToolUse hook",legacyTopLevelFlags:[]},install:{flag:"--cursor",artifactKind:"hook config",probeCommand:["cursor","--version"]}},{id:"deepseek-harness",displayName:"DeepSeek Harness",install:{flag:"--deepseek-harness",artifactKind:"package",probeCommand:qo}},{id:"devin",displayName:"Devin CLI",runtime:{flags:["-dv","--devin"],description:"Run as Devin CLI PreToolUse hook",legacyTopLevelFlags:[]},install:{flag:"--devin",artifactKind:"hook config",probeCommand:["devin","--version"]}},{id:"droid",displayName:"Factory Droid",runtime:{flags:["-fd","--droid"],description:"Run as Factory Droid PreToolUse hook",legacyTopLevelFlags:[]},install:{flag:"--droid",artifactKind:"hook config",probeCommand:["droid","--version"]}},{id:"amp",displayName:"Amp Code",install:{flag:"--amp",artifactKind:"plugin",probeCommand:["amp","--version"]}}],Vo=aa.slice().sort((P,G)=>P.displayName.localeCompare(G.displayName,"en")),Er=Vo.map((P)=>P.id).sort((P,G)=>Number(G==="claude-code")-Number(P==="claude-code")),er=Vo.filter((P)=>("runtime"in P)).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})),Sn=Vo.map((P)=>({id:P.id,...P.install})),zf=Object.fromEntries(aa.map((P)=>[P.id,P.displayName]));function ln(P){return zf[P]}var Wf=er.map((P)=>({flags:P.flags.join(", "),description:P.description})),Yf=er.flatMap((P)=>P.flags.map((G)=>`cc-safety-net hook ${G}`)),la={name:"hook",description:"Run as an agent CLI hook (reads JSON from stdin)",usage:"hook INTEGRATION_FLAG",options:[...Wf,{flags:"-h, --help",description:"Show this help"}],examples:Yf};var ca={name:"install",description:"Install CC Safety Net into a coding agent CLI",usage:"install [TARGET_FLAG]",options:[...Sn.map((P)=>({flags:P.flag,description:`Install ${ln(P.id)} ${P.artifactKind}`})),{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net install",...Sn.map((P)=>`cc-safety-net install ${P.flag}`)]},da={name:"uninstall",description:"Uninstall CC Safety Net from a coding agent CLI",usage:"uninstall [TARGET_FLAG]",options:[...Sn.map((P)=>({flags:P.flag,description:`Uninstall ${ln(P.id)} ${P.artifactKind}`})),{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net uninstall",...Sn.map((P)=>`cc-safety-net uninstall ${P.flag}`)]},ua={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 pa={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 Tr={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 Ko=[{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"}],Jo=["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"],Nt={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:"tool add <name...> [--cwd-arg <name>] [--project]",description:"Analyze community shell tools (user scope by default)"},{usage:"tool remove <name...> [--project]",description:"Stop analyzing declared tools"},{usage:"tool list",description:"List declared command tools in both scopes"},{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"},{flags:"--project",description:"Use project-scope rule config with rule tool"},{flags:"--cwd-arg",argument:"<name>",description:"Name the working-directory argument with rule tool add"},...Ko.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","cc-safety-net rule tool add ops_bash","cc-safety-net rule tool add ops_run_background --cwd-arg cwd --project",...Jo,"cc-safety-net rule update","cc-safety-net rule migrate --cleanup","cc-safety-net rule verify"]};var fa={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 ma={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 Ar=[fa,ra,pa,oa,Nt,Tr,ca,ua,da,la,ia,ma];function Zf(P){return P.aliases??[]}function _r(P){let G=P.toLowerCase();return Ar.find((K)=>K.name.toLowerCase()===G||Zf(K).some((Y)=>Y.toLowerCase()===G))}import{existsSync as qh}from"node:fs";import{basename as Xf}from"node:path";function Ir(P,G=7,K=U(P)){let Y=Date.now()-G*24*60*60*1000,Z=[],X=new Set,ie=0,ae,ge,ye,Pe;if(K)J(P,K);let Re={count:0},_e=K?Wn(K,Re):[];for(let Ie of _e)for(let je of Dt(Ie,Re)){if(je.decision==="allow")continue;let Oe=new Date(je.ts).getTime();if(Oe>=Y){if(ie++,X.add(je.sessionId??Xf(Ie,".jsonl")),ge===void 0||Oe<=ge)ae=je.ts,ge=Oe;if(Pe===void 0||Oe>Pe)ye=je.ts,Pe=Oe;Qf(Z,je,Oe)}}let Ae=Z.map((Ie)=>({timestamp:Ie.ts,command:Ie.command,reason:Ie.reason,relativeTime:Ws(new Date(Ie.ts))}));return{totalBlocked:ie,sessionCount:X.size,recentEntries:Ae,oldestEntry:ae,newestEntry:ye,unreadable:Re.count}}function Qf(P,G,K){let Y=P.findIndex((Z)=>K>new Date(Z.ts).getTime());if(Y===-1){if(P.length<3)P.push(G);return}if(P.splice(Y,0,G),P.length>3)P.pop()}import{dirname as um}from"node:path";import{dirname as em,join as nm,resolve as tm}from"node:path";var rm="config.json";function vn(P,G,K,Y){h(om(P),`${JSON.stringify(G,null,2)}
@@ -18,7 +18,7 @@ ${Go(Z.segment||Z.command)}`,K=P.filter((Z)=>Z.decision!=="allow"),Y=K.filter((Z
18
18
  `)}function $r(P){return Yn({rows:P})}function Oa(P){let G=[];return G.push("System Info"),G.push(Nm(P)),G.join(`
19
19
  `)}function Nm(P){let G=["Component","Version"],K=(X)=>{if(X===null)return Qe.dim("not found");return X},Z=[{label:"cc-safety-net",value:P.version},...Er.map((X)=>({label:ln(X),value:P.versions[X]??null})),{label:"Node.js",value:P.nodeVersion},{label:"npm",value:P.npmVersion},{label:"Bun",value:P.bunVersion},{label:"Platform",value:P.platform}].map((X)=>[X.label,K(X.value)]);return Yn({headers:G,rows:Z})}function $a(P){if(P.findings.length===0)return Qe.green(`
20
20
  No findings from inspected doctor facts.`);let G={error:P.findings.filter((X)=>X.severity==="error").length,warning:P.findings.filter((X)=>X.severity==="warning").length,info:P.findings.filter((X)=>X.severity==="info").length},K=["error","warning","info"].filter((X)=>G[X]>0).map((X)=>`${G[X]} ${X}`),Y=P.findings.length===1?"finding":"findings",Z=`
21
- ${P.findings.length} ${Y}: ${K.join(", ")}.`;if(G.error>0)return Qe.red(Z);if(G.warning>0)return Qe.yellow(Z);return Qe.blue(Z)}import{lstatSync as Lm}from"node:fs";import{dirname as Xo}from"node:path";function Qo(P,G){try{let K=Lm(G);if(K.isSymbolicLink())return{kind:P,path:G,status:"unsafe",issues:["symlink"]};if(!K.isDirectory())return{kind:P,path:G,status:"unsafe",issues:["not-directory"]};if(process.platform==="win32"||typeof process.getuid!=="function")return{kind:P,path:G,status:"unknown",issues:[]};let Y=[...K.uid!==process.getuid()?["ownership"]:[],...(K.mode&18)!==0?["permissions"]:[]];return{kind:P,path:G,status:Y.length>0?"unsafe":"safe",issues:Y}}catch(K){if(typeof K==="object"&&K!==null&&"code"in K&&K.code==="ENOENT")return{kind:P,path:G,status:"not-applicable",issues:[]};return{kind:P,path:G,status:"unknown",issues:[]}}}function Da(P,G){let K=U(P);return{directories:[Qo("policy",Xo(Xo(G))),Qo("config",Xo(G)),...K?[Qo("audit",K)]:[{kind:"audit",status:"unknown",issues:[]}]]}}import{spawn as jm}from"node:child_process";import{existsSync as Na}from"node:fs";import{delimiter as Fm,extname as Hm,join as Mm}from"node:path";import{stripVTControlCharacters as La}from"node:util";var Fa="2.6.17",Um=5000,Bm="_CC_SAFETY_NET_TEST_SPAWN_PLATFORM";function un(){return Fa}function ei(P,G){let K=P[G];if(K)return K;let Y=Object.keys(P).find((Z)=>Z.toLowerCase()===G.toLowerCase()&&!!P[Z]);return Y?P[Y]:K}function Gm(P){return(ei(P,"PATHEXT")||".COM;.EXE;.BAT;.CMD").split(";").filter((G)=>G.length>0)}function qm(P,G){let K=Hm(P)?[P]:[...Gm(G).map((Y)=>`${P}${Y}`),P];if(P.includes("/")||P.includes("\\"))return K.find((Y)=>Na(Y))??P;return(ei(G,"PATH")??"").split(Fm).flatMap((Y)=>K.map((Z)=>Mm(Y,Z))).find((Y)=>Na(Y))??P}function ja(P){if(!/[\s"&|<>^]/.test(P))return P;return`"${P.replace(/"/g,'""')}"`}function Zn(P,G){let[K,...Y]=P,Z=G[Bm]==="win32"?"win32":process.platform;if(!K||Z!=="win32")return{cmd:K??"",args:Y};let X=qm(K,G);if(!/\.(?:bat|cmd)$/i.test(X))return{cmd:X,args:Y};return{cmd:ei(G,"COMSPEC")??"cmd.exe",args:["/d","/c",["call",ja(X),...Y.map(ja)].join(" ")]}}var Ft=async(P,G=Um)=>{let K=await Vm(P,{timeoutMs:G});if(K.code!==0)return null;return La(K.stdout).trim()||La(K.stderr).trim()||null};function Vm(P,G){let[K,...Y]=P;if(!K)return Promise.resolve({code:null,stdout:"",stderr:""});return new Promise((Z)=>{try{let X=Zn([K,...Y],process.env),ie=jm(X.cmd,X.args,{stdio:["ignore","pipe","pipe"]}),ae=!1,ge="",ye="";ie.stdout.on("data",(_e)=>{ge+=_e.toString()}),ie.stderr.on("data",(_e)=>{ye+=_e.toString()});let Pe=(_e)=>{if(ae)return;ae=!0,clearTimeout(Re),Z(_e)},Re=setTimeout(()=>{ie.kill(),Pe({code:null,stdout:ge,stderr:ye})},G.timeoutMs);ie.on("close",(_e)=>{Pe({code:_e,stdout:ge,stderr:ye})}),ie.on("error",()=>{Pe({code:null,stdout:ge,stderr:ye})})}catch{Z({code:null,stdout:"",stderr:""})}})}function Dr(P){if(!P)return null;let G=/Claude Code\s+(\d+\.\d+\.\d+)/i.exec(P);if(G)return G[1]??null;let K=/v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)/i.exec(P);if(K)return K[1]??null;return P.split(`
21
+ ${P.findings.length} ${Y}: ${K.join(", ")}.`;if(G.error>0)return Qe.red(Z);if(G.warning>0)return Qe.yellow(Z);return Qe.blue(Z)}import{lstatSync as Lm}from"node:fs";import{dirname as Xo}from"node:path";function Qo(P,G){try{let K=Lm(G);if(K.isSymbolicLink())return{kind:P,path:G,status:"unsafe",issues:["symlink"]};if(!K.isDirectory())return{kind:P,path:G,status:"unsafe",issues:["not-directory"]};if(process.platform==="win32"||typeof process.getuid!=="function")return{kind:P,path:G,status:"unknown",issues:[]};let Y=[...K.uid!==process.getuid()?["ownership"]:[],...(K.mode&18)!==0?["permissions"]:[]];return{kind:P,path:G,status:Y.length>0?"unsafe":"safe",issues:Y}}catch(K){if(typeof K==="object"&&K!==null&&"code"in K&&K.code==="ENOENT")return{kind:P,path:G,status:"not-applicable",issues:[]};return{kind:P,path:G,status:"unknown",issues:[]}}}function Da(P,G){let K=U(P);return{directories:[Qo("policy",Xo(Xo(G))),Qo("config",Xo(G)),...K?[Qo("audit",K)]:[{kind:"audit",status:"unknown",issues:[]}]]}}import{spawn as jm}from"node:child_process";import{existsSync as Na}from"node:fs";import{delimiter as Fm,extname as Hm,join as Mm}from"node:path";import{stripVTControlCharacters as La}from"node:util";var Fa="2.6.18",Um=5000,Bm="_CC_SAFETY_NET_TEST_SPAWN_PLATFORM";function un(){return Fa}function ei(P,G){let K=P[G];if(K)return K;let Y=Object.keys(P).find((Z)=>Z.toLowerCase()===G.toLowerCase()&&!!P[Z]);return Y?P[Y]:K}function Gm(P){return(ei(P,"PATHEXT")||".COM;.EXE;.BAT;.CMD").split(";").filter((G)=>G.length>0)}function qm(P,G){let K=Hm(P)?[P]:[...Gm(G).map((Y)=>`${P}${Y}`),P];if(P.includes("/")||P.includes("\\"))return K.find((Y)=>Na(Y))??P;return(ei(G,"PATH")??"").split(Fm).flatMap((Y)=>K.map((Z)=>Mm(Y,Z))).find((Y)=>Na(Y))??P}function ja(P){if(!/[\s"&|<>^]/.test(P))return P;return`"${P.replace(/"/g,'""')}"`}function Zn(P,G){let[K,...Y]=P,Z=G[Bm]==="win32"?"win32":process.platform;if(!K||Z!=="win32")return{cmd:K??"",args:Y};let X=qm(K,G);if(!/\.(?:bat|cmd)$/i.test(X))return{cmd:X,args:Y};return{cmd:ei(G,"COMSPEC")??"cmd.exe",args:["/d","/c",["call",ja(X),...Y.map(ja)].join(" ")]}}var Ft=async(P,G=Um)=>{let K=await Vm(P,{timeoutMs:G});if(K.code!==0)return null;return La(K.stdout).trim()||La(K.stderr).trim()||null};function Vm(P,G){let[K,...Y]=P;if(!K)return Promise.resolve({code:null,stdout:"",stderr:""});return new Promise((Z)=>{try{let X=Zn([K,...Y],process.env),ie=jm(X.cmd,X.args,{stdio:["ignore","pipe","pipe"]}),ae=!1,ge="",ye="";ie.stdout.on("data",(_e)=>{ge+=_e.toString()}),ie.stderr.on("data",(_e)=>{ye+=_e.toString()});let Pe=(_e)=>{if(ae)return;ae=!0,clearTimeout(Re),Z(_e)},Re=setTimeout(()=>{ie.kill(),Pe({code:null,stdout:ge,stderr:ye})},G.timeoutMs);ie.on("close",(_e)=>{Pe({code:_e,stdout:ge,stderr:ye})}),ie.on("error",()=>{Pe({code:null,stdout:ge,stderr:ye})})}catch{Z({code:null,stdout:"",stderr:""})}})}function Dr(P){if(!P)return null;let G=/Claude Code\s+(\d+\.\d+\.\d+)/i.exec(P);if(G)return G[1]??null;let K=/v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)/i.exec(P);if(K)return K[1]??null;return P.split(`
22
22
  `)[0]?.trim()||null}async function Nr(P,G=Ft,K=process.cwd()){let Y=Promise.all(Sn.map(async(Re)=>[Re.id,Dr(await G([...Re.probeCommand]))])),[Z,X,ie,ae,ge,ye,Pe]=await Promise.all([Y,Y.then(async(Re)=>{let _e=Re.find(([je])=>je==="opencode")?.[1];if(!_e?.startsWith("2.")||!P(_e))return null;let Ae=["--param",`location[directory]=${K}`],Ie=["opencode","api","integration.list",...Ae];return await G(Ie,30000),G(["opencode","api","plugin.list",...Ae],30000)}),G(["codex","plugin","list"],30000),G(["amp","plugins","list"],30000),G(["node","--version"]),G(["npm","--version"]),G(["bun","--version"])]);return{version:Fa,versions:Object.fromEntries(Z),codexPluginListOutput:ie,ampPluginListOutput:ae,openCodePluginListOutput:X,nodeVersion:Dr(ge),npmVersion:Dr(ye),bunVersion:Dr(Pe),platform:`${process.platform} ${process.arch}`}}function ni(P,G){if(G==="dev")return!1;let K=P.split(".").map(Number),Y=G.split(".").map(Number),[Z=0,X=0,ie=0]=K,[ae=0,ge=0,ye=0]=Y;if(Z!==ae)return Z>ae;if(X!==ge)return X>ge;return ie>ye}async function Bn(){let P=un(),G=new AbortController,K=setTimeout(()=>G.abort(),3000);try{let Y=await fetch("https://registry.npmjs.org/cc-safety-net/latest",{signal:G.signal});if(!Y.ok)return{currentVersion:P,latestVersion:null,updateAvailable:!1,error:`npm registry returned ${Y.status}`};let Z=await Y.json(),X=ni(Z.version,P);return{currentVersion:P,latestVersion:Z.version,updateAvailable:X}}catch(Y){return{currentVersion:P,latestVersion:null,updateAvailable:!1,error:Y instanceof Error?Y.message:"Network error"}}finally{clearTimeout(K)}}import*as Ka from"node:readline";var Ba=(P)=>`\x1B[${P}B`,Km=(P)=>`\x1B[${P}A`;var Ha=["░","▒","▓","╱","╲","┃","━","┏","┓","┗","┛","╋"];function Jm(P){return new Promise((G)=>setTimeout(G,P))}function zm(P,G,K){if(!K)return G(P);if(K.aborted)return Promise.resolve();return new Promise((Y,Z)=>{let X=()=>K.removeEventListener("abort",ie),ie=()=>{X(),Y()};K.addEventListener("abort",ie,{once:!0}),G(P).then(()=>{X(),Y()},(ae)=>{X(),Z(ae)})})}function Lr(P){return Math.max(0,Math.min(1,P))}function Ht(P){return Math.max(0,Math.min(255,Math.round(P)))}function ti(P){return P<=0.0031308?12.92*P:1.055*P**0.4166666666666667-0.055}function Wm(P,G,K){let Y=K*Math.PI/180,Z=G*Math.cos(Y),X=G*Math.sin(Y),ie=(P+0.3963377774*Z+0.2158037573*X)**3,ae=(P-0.1055613458*Z-0.0638541728*X)**3,ge=(P-0.0894841775*Z-1.291485548*X)**3;return{blue:Ht(ti(Lr(-0.0041960863*ie-0.7034186147*ae+1.707614701*ge))*255),green:Ht(ti(Lr(-1.2684380046*ie+2.6097574011*ae-0.3413193965*ge))*255),red:Ht(ti(Lr(4.0767416621*ie-3.3077115913*ae+0.2309699292*ge))*255)}}function ri(P,G){let K=(G*P*180/Math.PI%360+360)%360;return Wm(0.72,0.15,K)}function Ga(P,G=0.1){let K=ri(G,P);return`\x1B[38;2;${K.red};${K.green};${K.blue}m`}function Ym(P,G){return{blue:Ht(P.blue+(255-P.blue)*G),green:Ht(P.green+(255-P.green)*G),red:Ht(P.red+(255-P.red)*G)}}function qa(P,G,K){let Y=Math.imul(P+2654435769,2246822507)^Math.imul(G+3266489909,668265263)^Math.imul(K+374761393,2654435761),Z=Y^Y>>>15,X=Math.imul(Z,739982445),ie=X^X>>>12,ae=Math.imul(ie,695872825);return((ae^ae>>>15)>>>0)/4294967296}function Zm(P,G,K){let Y=Math.floor(qa(P,G,K)*Ha.length);return Ha[Y]??"░"}function Ma(P){let G=Lr(P);return G*G*G*(G*(G*6-15)+10)}function Xm(P){if(P.length===0)return"";let G=[],K=!1,Y="";for(let Z of P){let X=`${Z.red};${Z.green};${Z.blue}`;if(Z.bold!==K)G.push(Z.bold?"\x1B[1m":"\x1B[22m"),K=Z.bold;if(X!==Y)G.push(`\x1B[38;2;${X}m`),Y=X;G.push(Z.character)}return`${G.join("")}\x1B[22m\x1B[39m`}function Qm(P,G,K,Y,Z){return P.map((X,ie)=>({...ri(K,Y+G+ie/Z),bold:!1,character:X}))}function eg(P,G,K,Y,Z,X,ie,ae){let ge=Math.max(1,Y*0.75),ye=Math.min(1,K/ge),Pe=Z*Ma(ye),Re=Math.max(0,(K-ge)/Math.max(1,Y-ge)),_e=(1-Ma(K/Y))*ae*2,Ae=0.35*Math.max(0,1-Re*2),Ie=ye>=1,je=Math.min(P.length,Math.ceil(Pe+2+1));return P.slice(0,je).map((Oe,Ve)=>{let nn=ri(X,ie+G+Ve/ae+_e),rn=Ve+qa(G,Ve,7919)*2-1;if(rn>Pe+2)return{...nn,bold:!1,character:" "};let an=Pe-rn,en=0.8*Math.exp(-(an*an)/12.5),on=Math.min(0.9,en+Ae),xn=!Ie&&rn>Pe-4;return{...Ym(nn,on),bold:on>0.3,character:xn?Zm(G,Ve,K):Oe}})}function Ua(P){return`\x1B[?2026h${P.map((G,K)=>`\x1B8${K>0?Ba(K):""}${Xm(G)}`).join("")}\x1B[?2026l`}async function oi(P,G={}){if(!P)return;let K=G.output??process.stdout,Y=G.sleep??Jm,Z=G.seed??0,X=P.split(`
23
23
  `).map((Pe)=>Array.from(Pe)),ie=Math.max(...X.map((Pe)=>Pe.length)),ae=12000*X.filter((Pe)=>Pe.length>0).length/40,ge=ie>0?Math.max(1,Math.ceil(ae/16.666666666666668)):0,ye=ge>0?ae/ge:0;K.write(`\x1B[?25l${X.length>1?`${`
24
24
  `.repeat(X.length-1)}${Km(X.length-1)}`:""}\x1B7`);try{for(let Pe=1;Pe<=ge;Pe+=1){if(G.signal?.aborted)break;K.write(Ua(X.map((Re,_e)=>eg(Re,_e,Pe,ge,ie,0.1,Z,3)))),await zm(ye,Y,G.signal)}}finally{if(K.write(Ua(X.map((Pe,Re)=>Qm(Pe,Re,0.1,Z,3)))),K.write("\x1B8"),X.length>1)K.write(Ba(X.length-1));K.write(`
@@ -227,7 +227,7 @@ def register(ctx):
227
227
  `));return{path:Z[0]??K??_n(Qi(P),Xi[0]),alreadyInstalled:Z.length>0}}function Jt(P){let G=[];for(let K of P.openCodeVersion?.startsWith("2.")?es(P.environment):ns(P.environment))if($h(K))try{let Y=Dh(K,"utf-8"),Z=gn(Y),X=JSON.parse(Z);if(os(X)){let ie=ts(P.openCodePluginListOutput);if(ie)return{platform:"opencode",status:"disabled",method:"opencode api plugin.list",configPath:K,errors:[...G,ie]};return{platform:"opencode",status:"configured",method:"plugin array",configPath:K,errors:G.length>0?G:void 0}}}catch(Y){G.push(`Failed to parse ${Nh(K)}: ${Y instanceof Error?Y.message:String(Y)}`)}return{platform:"opencode",status:"n/a",errors:G.length>0?G:void 0}}import{join as Yc}from"node:path";var Xc="dist/pi/index.js",Zc=new Set([Xc,"index.js"]),Lh=/[*?[\]{}]/;function is(P){let G=P.env.get("PI_CODING_AGENT_DIR");return Yc(G?Nn(G,P.home):Yc(P.home,".pi","agent"),"settings.json")}function ss(P){if(typeof P!=="string")return!1;return P==="npm:cc-safety-net"||P.startsWith("npm:cc-safety-net@")}function jh(P){if(!Array.isArray(P)||P.length===0)return!1;if(!P.every((Y)=>typeof Y==="string"))return!1;let G=(Y)=>P.some((Z)=>Z.startsWith(Y)&&Z.slice(1).replace(/^\.[/\\]/,"")===Xc);if(G("-"))return!1;if(G("+"))return!0;let K=P.filter((Y)=>!/^[-+!]/.test(Y));return(K.length===0||K.some((Y)=>Zc.has(Y)))&&!P.some((Y)=>Y.startsWith("!")&&(Zc.has(Y.slice(1))||Lh.test(Y)))}function Qc(P){let G=is(P.environment),K=yn(G);if(K.kind==="unreadable")return{platform:"pi",status:"not-inspected"};if(K.kind==="missing")return{platform:"pi",status:"n/a"};let Y=Fe(K.value,"packages");if(!Array.isArray(Y))return{platform:"pi",status:"n/a"};let Z=Y.find((ie)=>ss(typeof ie==="string"?ie:Fe(ie,"source")));if(Z===void 0)return{platform:"pi",status:"n/a"};let X=Fe(Z,"extensions");if(X!==void 0&&!jh(X))return{platform:"pi",status:"disabled",method:"package config",configPath:G,errors:["npm:cc-safety-net is installed but its extension is disabled in Pi settings"]};return{platform:"pi",status:"configured",method:"package config",configPath:G}}var Fh={amp:tl,"antigravity-cli":sl,"claude-code":ul,codex:fl,"copilot-cli":Il,cursor:Ml,"deepseek-harness":Bl,devin:Yl,droid:oc,"gemini-cli":ic,"grok-build":gc,"hermes-agent":Ec,"kimi-code":po,openclaw:Uc,opencode:Jt,pi:Qc};function zt(P,G,K){let Y={...K,cwd:G,environment:P};return Er.map((Z)=>Hh(Fh[Z](Y)))}function Hh(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 Mh}from"node:path";var Uh=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}]),Bh=Object.freeze({state:"ready",diagnostics:Object.freeze([]),ruleMetadata:Object.freeze({}),policy:Object.freeze({rules:Object.freeze([]),transparentWrappers:Object.freeze([]),commandTools:Object.freeze([]),safety:Object.freeze({level:"standard"}),worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:Object.freeze({}),destructiveCommandAllowPaths:Object.freeze([]),secretProtection:Object.freeze({enabled:!0,disabledRules:Object.freeze([]),denyPaths:Object.freeze([]),allowPaths:Object.freeze([])})})}),Gh={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 ed(P){let G=Mh(P.tmpdir,"cc-safety-net-self-test"),K=Uh.map((Y)=>{let Z=H(P,l("self-test",{command:Y.command},{kind:"command",shell:"auto"},{configCwd:G,executionCwd:G},Y.command),{guard:{dependencies:{loadPolicySnapshot:()=>Bh,getModes:()=>Gh,findPolicyMutation:()=>null}},audit:{agent:"self-test",getSessionId:()=>{return}}}),X=Y.expectBlocked?"blocked":"allowed",ie=Z.decision.kind==="deny"?"blocked":"allowed";return{command:Y.command,description:Y.description,expected:X,actual:ie,passed:X===ie,reason:Z.decision.kind==="deny"?Z.decision.reason:void 0,ruleId:Z.decision.kind==="deny"?Z.decision.ruleId:void 0}});return{passed:K.filter((Y)=>Y.passed).length,failed:K.filter((Y)=>!Y.passed).length,total:K.length,results:K}}function as(P){let G=fn({label:"doctor",booleans:{json:["--json"],skipUpdateCheck:["--skip-update-check"]}},P);if($n(G.errors))return null;return{json:G.flags.json,skipUpdateCheck:G.flags.skipUpdateCheck}}async function nd(P,G={}){let K=await tr(!G.json,()=>{let Y=Vh(P,G);return{ready:Y,finish:()=>Y}},()=>nr(),{loadingMessage:"Checking system status…"});if(G.json)console.log(JSON.stringify(K,null,2));else Kh(K);return K.engineSelfTest.failed>0||K.findings.some((Y)=>Y.severity==="error")?1:0}async function Vh(P,G){let K=G.cwd??process.cwd(),Y=await Nr((Oe)=>Jt({environment:P,cwd:K,openCodeVersion:Oe}).status!=="n/a",void 0,K),Z=zt(P,K,{ampPluginListOutput:Y.ampPluginListOutput,codexPluginListOutput:Y.codexPluginListOutput,copilotCliVersion:Y.versions["copilot-cli"],openCodeVersion:Y.versions.opencode,openCodePluginListOutput:Y.openCodePluginListOutput}),X=ba(P,K),ie=wa(P),ae=R(P,{cwd:K}),ge=ae.policy,ye=_(ge,P.env),Pe=q(ge,ye.capabilities),Re=Ir(P,7),_e=Za(P,K),Ae=[Lt(K),jt(P)].filter((Oe)=>qh(Oe)),Ie=G.skipUpdateCheck?{currentVersion:un(),latestVersion:null,updateAvailable:!1}:await Bn(),je={hooks:Z,engineSelfTest:ed(P),userConfig:X.userConfig,projectConfig:X.projectConfig,configState:Ke(ae),effectiveRules:X.effectiveRules,environment:ie,effectiveSafety:{selectedPreset:ge.safety.level,level:ye.effectiveLevel,capabilities:ye.capabilities,ruleOverrides:ge.destructiveCommandRuleOverrides,weakenedRuleOverrides:Object.entries(Pe).filter(([,Oe])=>Oe.source==="rule_override"&&Oe.override==="off"&&Oe.inheritedEnabled&&Oe.changesInherited).map(([Oe])=>Oe),ruleCounts:{stored:Object.keys(ge.destructiveCommandRuleOverrides).length,effective:Object.values(Pe).filter((Oe)=>Oe.changesInherited).length},...ae.policyScopes?{policyScopes:ae.policyScopes}:{}},..._e.length>0?{v2Leftovers:_e}:{},...Ae.length>0?{legacyConfigs:Ae}:{},posture:Da(P,X.userConfig.path),activity:Re,update:Ie,system:Y};return{...je,findings:Ca(je)}}function Kh(P){console.log(),console.log(Pa(P.hooks)),console.log(),console.log(Sa(P.engineSelfTest)),console.log(),console.log(Ra(P)),console.log(),console.log(Ea(P.environment)),console.log(),console.log(Ta(P)),console.log(),console.log(Aa(P.findings)),console.log(),console.log(_a(P.activity)),console.log(),console.log(Oa(P.system)),console.log(),console.log(Ia(P.update)),console.log($a(P))}import{existsSync as Jh}from"node:fs";var zh=/^[A-Za-z0-9_@%+=:,./-]+$/,td="Usage: cc-safety-net explain [--json] [--cwd <path>] <command>";function ls(P){let G=fn({label:"explain",booleans:{json:["--json"]},values:{cwd:["--cwd"]},positionals:"tail"},P);if($n(G.errors))return console.error(td),console.error("Pass -- before a command that starts with dashes."),null;if(G.values.cwd!==void 0&&!Jh(G.values.cwd))return console.error(`Error: --cwd path does not exist: ${G.values.cwd}`),null;let K=G.positionals.length===1?G.positionals[0]:G.positionals.map((Y)=>zh.test(Y)?Y:`'${Y.replaceAll("'","'\\''")}'`).join(" ");if(!K)return console.error("Error: No command provided"),console.error(td),null;return{json:G.flags.json,cwd:G.values.cwd,command:K}}function rd(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 od(P,G){let Y=G-18;return[`${P.dtl}${P.dh.repeat(G)}${P.dtr}`,`${P.dv} Command Analysis${" ".repeat(Y)}${P.dv}`,`${P.dbl}${P.dh.repeat(G)}${P.dbr}`]}function cs(P){return JSON.stringify(P)}function id(P,G=0){return`[${P.map((Y,Z)=>xa(Y,Z,G)).join(",")}]`}function mr(P,G,K=70){let Y=P.split(" "),Z=[],X="";for(let ie of Y)if(X&&X.length+ie.length+1>K)Z.push(X),X=ie;else X=X?`${X} ${ie}`:ie;if(X)Z.push(X);return Z.map((ie,ae)=>ae===0?ie:`${G}${ie}`)}function sd(P,G,K){let Y=[];switch(P.type){case"parse":return null;case"env-strip":return Y.push(""),Y.push(`STEP ${G} ${K.h} Strip environment variables`),Y.push(` Removed: ${P.envVars.map((Z)=>`${Z}=<redacted>`).join(", ")}`),Y.push(` Tokens: ${cs(P.output)}`),{lines:Y,incrementStep:!0};case"leading-tokens-stripped":return Y.push(""),Y.push(`STEP ${G} ${K.h} Strip wrappers`),Y.push(` Removed: ${P.removed.join(", ")}`),Y.push(` Tokens: ${cs(P.output)}`),{lines:Y,incrementStep:!0};case"shell-wrapper":return Y.push(""),Y.push(`STEP ${G} ${K.h} Detect shell wrapper`),Y.push(` Wrapper: ${P.wrapper} -c`),Y.push(` Inner: ${P.innerCommand}`),{lines:Y,incrementStep:!0};case"interpreter":{if(Y.push(""),Y.push(`STEP ${G} ${K.h} Detect interpreter`),Y.push(` Interpreter: ${P.interpreter}`),Y.push(` Code: ${P.codeArg}`),P.paranoidBlocked)Y.push(" Result: ✗ BLOCKED (paranoid mode)");return{lines:Y,incrementStep:!0}}case"busybox":return Y.push(""),Y.push(`STEP ${G} ${K.h} Busybox wrapper`),Y.push(` Subcommand: ${P.subcommand}`),{lines:Y,incrementStep:!0};case"transparent-wrapper":return Y.push(""),Y.push(`STEP ${G} ${K.h} Transparent wrapper`),Y.push(` Wrapper: ${P.wrapper}`),Y.push(` Tokens: ${cs(P.output)}`),{lines:Y,incrementStep:!0};case"recurse":return{lines:[],incrementStep:!1};case"rule-check":{if(Y.push(""),Y.push(`STEP ${G} ${K.h} Match rules`),Y.push(` Rule: ${P.rule}()`),P.matched)Y.push(" Result: MATCHED");else Y.push(" Result: No match");return{lines:Y,incrementStep:!0}}case"worktree-relaxation":return Y.push(""),Y.push(`STEP ${G} ${K.h} Worktree relaxation`),Y.push(` Mode: ${n.worktree.name}`),Y.push(` Git cwd: ${P.gitCwd}`),Y.push(" Result: Allowed local discard in linked worktree"),{lines:Y,incrementStep:!0};case"temp-root-relaxation":return Y.push(""),Y.push(`STEP ${G} ${K.h} Temp-root relaxation`),Y.push(` Git cwd: ${P.gitCwd}`),Y.push(" Result: Allowed git discard in a temp-root repository"),{lines:Y,incrementStep:!0};case"tmpdir-check":return null;case"fallback-scan":{if(P.embeddedCommandFound)return Y.push(""),Y.push(`STEP ${G} ${K.h} Fallback scan`),Y.push(` Found: ${P.embeddedCommandFound}`),{lines:Y,incrementStep:!0};return null}case"custom-rules-check":{if(P.rulesChecked){if(Y.push(""),Y.push(`STEP ${G} ${K.h} Custom rules`),P.matched)Y.push(" Result: MATCHED");else Y.push(" Result: No match");return{lines:Y,incrementStep:!0}}return null}case"cwd-change":return null;case"dangerous-text":{if(P.matched)return Y.push(""),Y.push(`STEP ${G} ${K.h} Dangerous text check`),Y.push(` Token: ${P.token}`),Y.push(" Result: MATCHED"),{lines:Y,incrementStep:!0};return null}case"strict-unparseable":return Y.push(""),Y.push(`STEP ${G} ${K.h} Strict mode check`),Y.push(` Command: ${P.rawCommand}`),Y.push(" Result: ✗ UNPARSEABLE"),{lines:Y,incrementStep:!0};case"segment-skipped":return null;case"error":return Y.push(""),Y.push(`ERROR: ${P.message}`),{lines:Y,incrementStep:!1};default:return P}}function ds(P,G){let K=rd(G?.asciiOnly??!1),Y=58,Z=[],X=1;Z.push(...od(K,58)),Z.push("");let ie=P.trace.steps.find((Ie)=>Ie.type==="error");if(ie&&ie.type==="error"){Z.push("ERROR"),Z.push(` ${ie.message}`),Z.push(""),Z.push("RESULT"),Z.push(` Status: ${P.result==="blocked"?Qe.red("BLOCKED"):Qe.green("ALLOWED")}`),Z.push(""),Z.push("CONFIG");let Ie=P.configSource??"none";return Z.push(` Path: ${Ie}`),Z.join(`
228
228
  `)}let ae=P.trace.steps.find((Ie)=>Ie.type==="parse");if(ae&&ae.type==="parse"){Z.push("INPUT"),Z.push(` ${ae.input}`),Z.push(""),Z.push(`STEP ${X} ${K.h} Split shell commands`),X++;for(let Ie=0;Ie<ae.segments.length;Ie++){let je=ae.segments[Ie];if(je){let Oe=Math.random();Z.push(` Segment ${Ie+1}: ${id(je,Oe)}`)}}}let ge=P.trace.segments,ye=ge.length>1;for(let Ie of ge){if(ye){Z.push("");let nn="";if(ae&&ae.type==="parse"){let Bo=ae.segments[Ie.index];if(Bo)nn=Bo.join(" ")}let rn=54,an=nn,en=` Segment ${Ie.index+1}: `,on=" ";if(nn){if(en.length+nn.length+on.length>rn){let kf=rn-en.length-on.length;an=`${nn.substring(0,kf-1)}…`}}let xn=nn?`${en}${an}${on}`:` Segment ${Ie.index+1} `,bf=nn?`${en}${Qe.cyan(an)}${on}`:xn,Js=58-xn.length,zs=Math.floor(Js/2),wf=Js-zs;Z.push(`${K.sh.repeat(zs)}${bf}${K.sh.repeat(wf)}`)}if(Ie.steps.find((nn)=>nn.type==="segment-skipped")){Z.push(""),Z.push(" (skipped — prior segment blocked)");continue}let Oe=!1,Ve=!1;for(let nn of Ie.steps){let rn=sd(nn,X,K);if(rn){if(Ve=!0,nn.type==="recurse"){Z.push("");let an=" RECURSING ",en=58-an.length-4;Z.push(` ${K.tl}${K.h}${an}${K.h.repeat(en)}`),Z.push(` ${K.v}`),Oe=!0;continue}for(let an of rn.lines)if(Oe)Z.push(` ${K.v} ${an}`);else Z.push(an);if(rn.incrementStep)X++}}if(Oe)Z.push(` ${K.v}`),Z.push(` ${K.bl}${K.h.repeat(56)}`);if(!Ve)Z.push(""),Z.push(` ${Qe.green("✓")} Allowed (no matching rules)`)}if(Z.push(""),Z.push("RESULT"),P.result==="blocked"){if(Z.push(` Status: ${Qe.red("BLOCKED")}`),P.customRule){if(Z.push(` Rule: ${P.customRule.id}`),P.customRule.rulebook)Z.push(` Rulebook: ${P.customRule.rulebook.name} ${P.customRule.rulebook.version}`);if(P.customRule.source)Z.push(` Source: ${P.customRule.source}`);if(P.customRule.override)Z.push(` Override: reason ${P.customRule.override.reason}`)}if(P.reason){let Ie=mr(P.reason," ");Z.push(` Reason: ${Ie[0]}`);for(let je=1;je<Ie.length;je++)Z.push(Ie[je]??"")}}else Z.push(` Status: ${Qe.green("ALLOWED")}`);Z.push(""),Z.push("CONFIG");let Pe=P.configSource??"none",Re=P.configValid?"":" (invalid)";Z.push(` Path: ${Pe}${Re}`);let _e=P.safetyPresetScope;Z.push(` Safety preset: ${P.selectedPreset??"standard"}${_e?` (${Or(_e)})`:""}`),Z.push(` Effective capabilities: ${P.effectiveLevel}`);let Ae=Object.entries(P.destructiveCommandRuleOverrides??{});if(Z.push(` Rule customizations: ${Ae.length}`),P.ruleActivation)Z.push(` Rule activation: ${P.ruleActivation.id} — ${P.ruleActivation.enabled?"on":"off"} via ${P.ruleActivation.source}`);return Z.join(`
229
229
  `)}function us(P){return JSON.stringify(P,null,2)}import{resolve as Xh}from"node:path";var ad=512,ld={maxTextLength:2048,maxListLength:128,maxObjectProperties:128,maxDepth:16},Wh=["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 ms(P){let G=0,K={allocateSegment(){return G++},getNextSegmentIndex(){return G},branch(){let Y=P.fork(),Z=ms(Y);return{trace:Z,adopt(){P.replaceSegmentEvents(Y.finish().events),G=Z.getNextSegmentIndex()}}},recordGlobal(Y){P.record({scope:"global",step:Y})},recordSegment(Y,Z=K.currentSegmentIndex){if(Z===void 0)return;P.record({scope:"segment",segmentIndex:Z,step:Y})}};return K}function gs(P=new Set){let G=[];return{record(K){if(G.length>=ad)return;ho(K.step,P,ld),G.push({...K,step:ps(K.step,ld,P)})},fork(){return gs(P)},replaceSegmentEvents(K){G.splice(0,G.length,...[...G.filter((Y)=>Y.scope==="global"),...K].slice(0,ad))},finish(){return{events:G}}}}function ho(P,G,K,Y=0,Z=new WeakSet){if(typeof P==="string"){let ae=P.slice(0,K.maxTextLength);if(!it(ae))return;for(let ge of xt(ae))for(let ye of ge.match(/[^\s"'()$]+/g)??[])G.add(cd(ye));return}if(!P||typeof P!=="object"||Y>=K.maxDepth||Z.has(P))return;if(Z.add(P),Array.isArray(P)){let ae=Math.min(P.length,K.maxListLength);for(let ge=0;ge<ae;ge++)ho(P[ge],G,K,Y+1,Z);return}let X=0,ie=new Set;for(let ae in P){if(!Object.hasOwn(P,ae))continue;if(X>=K.maxObjectProperties)break;X++,ho(ae,G,K);let ge=fs(ae,K,G);if(ie.has(ge))continue;ie.add(ge),ho(P[ae],G,K,Y+1,Z)}}function ps(P,G,K,Y=0,Z=new WeakSet){if(typeof P==="string")return fs(P,G,K);if(!P||typeof P!=="object")return P;if(Y>=G.maxDepth)return;if(Z.has(P))return;if(Z.add(P),Array.isArray(P)){let ae=[],ge=Math.min(P.length,G.maxListLength);for(let ye=0;ye<ge;ye++)ae.push(ps(P[ye],G,K,Y+1,Z));return ae}let X={},ie=0;for(let ae in P){if(!Object.hasOwn(P,ae))continue;if(ie>=G.maxObjectProperties)break;ie++;let ge=fs(ae,G,K);if(Object.hasOwn(X,ge))continue;Object.defineProperty(X,ge,{value:ps(P[ae],G,K,Y+1,Z),enumerable:!0,configurable:!0,writable:!0})}return X}function fs(P,G,K){let Y=P.slice(0,G.maxTextLength),Z=it(Y)?ot(Y):Y,X=K.size>0?Zh(Z,K):Z;return(Yh(X)?$e(X):X).slice(0,G.maxTextLength)}function Yh(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&&Wh.some((G)=>P.includes(G))||P.length>=49&&/\b[a-f0-9]{32}\.[A-Za-z0-9]{16}\b/.test(P)}function Zh(P,G){return P.replace(/[^\s"'()$]+/g,(K)=>G.has(cd(K))?"<redacted>":K)}function cd(P){let G=2166136261,K=2166136261;for(let Y=0;Y<P.length;Y++)G=Math.imul(G^P.charCodeAt(Y),16777619),K=Math.imul(K^P.charCodeAt(P.length-Y-1),16777619);return`${G>>>0}:${K>>>0}:${P.length}`}function gr(P,G={},K){let Y=Xh(G.cwd??process.cwd()),Z=G.policySnapshot??R(K,{cwd:Y,userConfigDir:G.userConfigDir}),X=_(Z.policy,K.env),ie=Je({policySnapshot:Z,effectiveCapabilities:X.capabilities,worktreeMode:X.worktreeMode}),ae={effectiveLevel:ie.effectiveLevel,selectedPreset:Z.policy.safety.level,...Z.policyScopes?{safetyPresetScope:Z.policyScopes.levelScope}:{},effectiveCapabilities:ie.effectiveCapabilities,destructiveCommandRuleOverrides:Z.policy.destructiveCommandRuleOverrides},{configSource:ge,configValid:ye}=ev(K,{cwd:Y,userConfigDir:G.userConfigDir});if(!P||!P.trim())return{trace:{steps:[{type:"error",message:"No command provided"}],segments:[]},result:"allowed",configSource:ge,configValid:ye,...ae};let Pe=v(P,"auto");if(Pe.status==="limited")throw new b;let Re=Pe.dialect==="powershell"?v(P,"posix"):Pe,_e=Pt(Re),Ae=gs(),Ie=ms(Ae);Ie.recordGlobal({type:"parse",input:P,segments:_e.map((xn)=>[...xn])});let je=l("Bash",{command:P},{kind:"command",shell:"auto"},{configCwd:Y,executionCwd:Y},P),Oe=j(je,{environment:K,trace:Ie,dependencies:{loadPolicySnapshot:()=>Z}}),Ve=Oe.decision.kind==="deny"?Oe.decision:null;if(Ve&&(Oe.stage==="policy-protection"||Oe.stage==="secret-protection"))return{trace:{steps:[],segments:[{index:0,steps:[{type:"rule-check",rule:Qh(Ve),matched:!0,reason:Ve.reason}]}]},result:"blocked",reason:T(Ve.reason),segment:T(dd(Ve,P)),ruleId:T(Ve.ruleId),configSource:ge,configValid:ye,...ae};let nn=Ie.getNextSegmentIndex();if(Ve&&nn>0&&nn<_e.length)Ie.recordSegment({type:"segment-skipped",index:nn,reason:"prior-segment-blocked"},nn);let rn=Ae.finish(),an=Ve?.ruleId??nv(je,Z,X,K),en=V.find((xn)=>xn.id===an&&xn.activationCapability),on=en?ie.policy.effectiveDestructiveCommandRules[en.id]:void 0;return{trace:rv(rn),result:Ve?"blocked":"allowed",reason:Ve?T(Ve.reason):void 0,segment:Ve?T(dd(Ve,P)):void 0,ruleId:Ve?T(Ve.ruleId):void 0,customRule:tv(ov(Ve?.ruleId,Z)),configSource:ge,configValid:ye,...ae,...en&&on?{ruleActivation:{id:en.id,...on}}:{}}}function dd(P,G){return P.evidence?.segment??G}function Qh(P){if(P.reason===Ze)return"policy-protection:findPolicyConfigMutationTargetInSemanticFacts";if(P.reason===Ye)return"policy-apply-protection:findPolicyApplyInvocationInSemanticFacts";if(P.reason===g)return"git-metadata-protection:findGitMetadataMutationTargetInSemanticFacts";return"secret-protection:findSensitiveTargetInSemanticFacts"}function ev(P,G){let K=A(G.cwd),Y=W(P,G),Z=ee(P,{cwd:G.cwd,userConfigDir:G.userConfigDir});try{if(r(Z.projectConfigTarget)!==null){if(Un(Z.projectConfigTarget).errors.length===0)return{configSource:K,configValid:!0};return{configSource:K,configValid:!1}}}catch(X){if(X instanceof o)return{configSource:K,configValid:!1};throw X}try{if(r(Z.userConfigTarget)!==null){let X=Un(Z.userConfigTarget);return{configSource:Y,configValid:X.errors.length===0}}return{configSource:null,configValid:!0}}catch(X){if(X instanceof o)return{configSource:Y,configValid:!1};throw X}}function nv(P,G,K,Y){let Z=G.policy,X=Me({...Z,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{...Z.destructiveCommandRuleOverrides,...Object.fromEntries(V.flatMap((ae)=>ae.activationCapability?[[ae.id,"on"]]:[]))}},G.state==="degraded"?{diagnostics:G.diagnostics,reason:G.reason}:void 0),ie=j(P,{environment:Y,dependencies:{loadPolicySnapshot:()=>X,getModes:()=>({...K,strict:!0,paranoidRm:!0,paranoidInterpreters:!0,capabilities:{fail_closed:{...K.capabilities.fail_closed,enabled:!0},paranoid_rm:{...K.capabilities.paranoid_rm,enabled:!0},paranoid_interpreters:{...K.capabilities.paranoid_interpreters,enabled:!0}}}),findSensitiveTarget:()=>null}});return ie.decision.kind==="deny"?ie.decision.ruleId:void 0}function tv(P){if(!P)return;return{id:T(P.id),...P.rulebook?{rulebook:{name:T(P.rulebook.name),version:T(P.rulebook.version)}}:{},...P.source?{source:T(P.source)}:{},...P.override?{override:{type:"reason",reason:T(P.override.reason)}}:{}}}function rv(P){let G=P.events.flatMap((Y)=>Y.scope==="global"?[Y.step]:[]),K=new Map;for(let Y of P.events){if(Y.scope!=="segment")continue;let Z=K.get(Y.segmentIndex)??{index:Y.segmentIndex,steps:[]};Z.steps.push(Y.step),K.set(Y.segmentIndex,Z)}return{steps:G,segments:[...K.values()]}}function ov(P,G){let K=P?.replace(/^custom\./,"");if(!K||!G.policy.rules.some((Y)=>Y.name===K))return;return G.ruleMetadata[K]??Object.freeze({id:K})}function ud(P){return new Promise((G)=>{process.stdout.write(`${P}
230
- `,()=>G())})}async function pd(P,G){let K=ls(G);if(!K)return 1;try{let Y=gr(K.command,{cwd:K.cwd},P),Z=!!process.env.NO_COLOR||!process.stdout.isTTY;return await ud(K.json?us(Y):ds(Y,{asciiOnly:Z})),0}catch(Y){let Z=iv(Y instanceof f?Y.cause:Y);if(Z===void 0)throw Y;if(K.json)return await ud(JSON.stringify({error:Z})),1;return console.error(Z),1}}function iv(P){if(P instanceof b)return P.message;if(P instanceof F)return P.message;if(P instanceof m)return P.message;if(P instanceof s&&a[P.kind].errorCode==="path-canonicalization-limit")return"Path canonicalization work limit exceeded.";return}var fd="2.6.17",Rn=" ",Ct="cc-safety-net";function md(P){return P.argument?`${P.flags} ${P.argument}`:P.flags}function sv(P){return Math.max(...P.map((G)=>md(G).length))}function av(P){return Math.max(...P.map((G)=>G.usage.length))}function lv(P){return Math.max(...P.map((G)=>`${Ct} ${G.usage}`.length))}function cv(P,G){let K=`${Ct} ${P.usage}`;return`${Rn}${K.padEnd(G+2)}${P.description}`}function In(P,G){return`${Rn}${P.padEnd(Math.max(40,P.length+2))}${G}`}function Wt(P,G=console.log){let K=[];if(K.push(`${Ct} ${P.name}`),K.push(""),K.push(`${Rn}${P.description}`),K.push(""),K.push("USAGE:"),K.push(`${Rn}${Ct} ${P.usage}`),K.push(""),P.subcommands&&P.subcommands.length>0){K.push("SUBCOMMANDS:");let Y=av(P.subcommands);for(let Z of P.subcommands)K.push(`${Rn}${Z.usage.padEnd(Y+2)}${Z.description}`);K.push("")}if(P.options.length>0){K.push("OPTIONS:");let Y=sv(P.options);for(let Z of P.options){let X=md(Z),ie=Z.default?`${Z.description} (default: ${Z.default})`:Z.description;K.push(`${Rn}${X.padEnd(Y+2)}${ie}`)}K.push("")}if(P.examples&&P.examples.length>0){K.push("EXAMPLES:");for(let Y of P.examples)K.push(`${Rn}${Y}`)}G(K.join(`
230
+ `,()=>G())})}async function pd(P,G){let K=ls(G);if(!K)return 1;try{let Y=gr(K.command,{cwd:K.cwd},P),Z=!!process.env.NO_COLOR||!process.stdout.isTTY;return await ud(K.json?us(Y):ds(Y,{asciiOnly:Z})),0}catch(Y){let Z=iv(Y instanceof f?Y.cause:Y);if(Z===void 0)throw Y;if(K.json)return await ud(JSON.stringify({error:Z})),1;return console.error(Z),1}}function iv(P){if(P instanceof b)return P.message;if(P instanceof F)return P.message;if(P instanceof m)return P.message;if(P instanceof s&&a[P.kind].errorCode==="path-canonicalization-limit")return"Path canonicalization work limit exceeded.";return}var fd="2.6.18",Rn=" ",Ct="cc-safety-net";function md(P){return P.argument?`${P.flags} ${P.argument}`:P.flags}function sv(P){return Math.max(...P.map((G)=>md(G).length))}function av(P){return Math.max(...P.map((G)=>G.usage.length))}function lv(P){return Math.max(...P.map((G)=>`${Ct} ${G.usage}`.length))}function cv(P,G){let K=`${Ct} ${P.usage}`;return`${Rn}${K.padEnd(G+2)}${P.description}`}function In(P,G){return`${Rn}${P.padEnd(Math.max(40,P.length+2))}${G}`}function Wt(P,G=console.log){let K=[];if(K.push(`${Ct} ${P.name}`),K.push(""),K.push(`${Rn}${P.description}`),K.push(""),K.push("USAGE:"),K.push(`${Rn}${Ct} ${P.usage}`),K.push(""),P.subcommands&&P.subcommands.length>0){K.push("SUBCOMMANDS:");let Y=av(P.subcommands);for(let Z of P.subcommands)K.push(`${Rn}${Z.usage.padEnd(Y+2)}${Z.description}`);K.push("")}if(P.options.length>0){K.push("OPTIONS:");let Y=sv(P.options);for(let Z of P.options){let X=md(Z),ie=Z.default?`${Z.description} (default: ${Z.default})`:Z.description;K.push(`${Rn}${X.padEnd(Y+2)}${ie}`)}K.push("")}if(P.examples&&P.examples.length>0){K.push("EXAMPLES:");for(let Y of P.examples)K.push(`${Rn}${Y}`)}G(K.join(`
231
231
  `))}function ys(){let P=lv(Ar),G=[];G.push(`${Ct} v${fd}`),G.push(""),G.push("Blocks destructive commands and secret access."),G.push(""),G.push("COMMANDS:");for(let K of Ar)G.push(cv(K,P));G.push(""),G.push("GLOBAL OPTIONS:"),G.push(`${Rn}-h, --help Show help (use with command for command-specific help)`),G.push(`${Rn}-V, --version Show version`),G.push(""),G.push("HELP:"),G.push(`${Rn}${Ct} help <command> Show help for a specific command`),G.push(`${Rn}${Ct} <command> --help Show help for a specific command`),G.push(""),G.push("ENVIRONMENT VARIABLES:"),G.push(In(`${n.level.name}=standard|strict|paranoid`,"Set session safety level")),G.push(In(`${n.worktree.name}=1`,"Allow local git discards in linked worktrees")),G.push(In(`${n.debug.name}=1`,"Print diagnostic messages to stderr")),G.push(In(`${n.auditScope.name}=all|blocked`,"Record all command decisions, or denials only")),G.push(In(`${n.projectTightenOnly.name}=1`,"Ignore project policy settings that weaken the user policy")),G.push(In("CC_SAFETY_NET_HOME","Override rule config home directory")),G.push(""),G.push("LEGACY ENVIRONMENT VARIABLES (STILL SUPPORTED):"),G.push(In(`${n.strict.name}=1`,"Force safety.overrides.fail_closed on")),G.push(In(`${n.paranoid.name}=1`,"Force paranoid_rm and paranoid_interpreters on")),G.push(In(`${n.paranoidRm.name}=1`,"Force safety.overrides.paranoid_rm on")),G.push(In(`${n.paranoidInterpreters.name}=1`,"Force safety.overrides.paranoid_interpreters on")),G.push(""),G.push("Documentation: https://ccsafetynet.com/docs"),console.log(G.join(`
232
232
  `))}function gd(){console.log(fd)}function yr(P,G=console.log){let K=_r(P);if(!K)return!1;if(K.name.toLowerCase()!==P.toLowerCase())return!1;return Wt(K,G),!0}import{existsSync as So,readFileSync as Cu}from"node:fs";import{join as Po}from"node:path";import*as Vn from"node:readline";function dv(P){return P==="install"?"Install":"Uninstall"}function uv(P){return P==="install"?"Installing":"Uninstalling"}function pv(P){return P==="install"?"into":"from"}function vd(P){return P?.available===!0}function fv(P,G){let K=new Set(G);return P.filter((Y)=>K.has(Y.target)).map((Y)=>Y.target)}function yd(P,G,K){if(P.every((Y)=>!Y.available))return G;return Array.from({length:P.length},(Y,Z)=>Z+1).map((Y)=>(G+Y*K+P.length)%P.length).find((Y)=>vd(P[Y]))}function mv(P,G,K){if(K.ctrl&&K.name==="c")return"interrupt";if(K.name==="escape"||G==="q")return"abort";if(P==="install"&&(G==="u"||G==="U"))return"update";if(K.name==="up"||G==="k")return"up";if(K.name==="down"||G==="j")return"down";if(K.name==="space"||G===" ")return"toggle";if(K.name==="return"||K.name==="enter")return"confirm";return null}function gv(P){return{cursor:P.findIndex((G)=>G.available),selected:[]}}function yv(P,G,K){if(K==="confirm"||K==="update"||K==="abort"||K==="interrupt")return{state:P,done:K};if(K==="up")return{state:{...P,cursor:yd(G,P.cursor,-1)}};if(K==="down")return{state:{...P,cursor:yd(G,P.cursor,1)}};let Y=G[P.cursor];if(!vd(Y))return{state:P};let Z=P.selected.includes(Y.target)?P.selected.filter((X)=>X!==Y.target):fv(G,[...P.selected,Y.target]);return{state:{...P,selected:Z}}}var bd="◉",wd="◯",kd=">",Cd=" ";function hv(P,G,K){return["",`${dv(P)} CC Safety Net ${pv(P)}:`,"",...G.map((Y,Z)=>{let X=K.selected.includes(Y.target),ie=Z===K.cursor,ae=X?bd:wd,ge=ie?kd:Cd,ye=Y.available?"":` (${Y.unavailableReason??"not installed"})`,Pe=`${ae} ${Y.label}${ye}`,Re=!Y.available?Qe.dim(Pe):X?Qe.green(Pe):ie?Qe.bold(Pe):Pe;return`${ge} ${Re}`}),"",P==="install"?"Space: select Enter: confirm u: update installed Up/Down: move q/Esc: cancel":G.some((Y)=>Y.available)?"Space: select Enter: confirm Up/Down: move q/Esc: cancel":`No selectable integrations found for ${P}. q/Esc: close`].join(`
233
233
  `)}var hd=["global-hook","plugin"];function vv(P,G,K={}){let Y=K.color!==!1?Qe.bold:(X)=>X;return["","Install the Kimi Code integration as:","",...[`Global hook — ${G?"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((X,ie)=>{let ae=ie===P,ge=`${ae?bd:wd} ${X}`;return`${ae?kd:Cd} ${ae?Y(ge):ge}`}),"","Enter: confirm Up/Down: move q/Esc: cancel"].join(`
@@ -1 +1 @@
1
- import"../chunks/index-cxqk4wed.js";import{bt}from"../chunks/index-p0tjjrnj.js";import"../chunks/index-7w6trghf.js";import"../chunks/index-823nnrjs.js";var t={name:"cc-safety-net",inject:["tools"],apply:bt};export{t as default};
1
+ import"../chunks/index-1p1q38x4.js";import{bt}from"../chunks/index-7nndhfn3.js";import"../chunks/index-tz7650sh.js";import"../chunks/index-8m4sxbp8.js";var t={name:"cc-safety-net",inject:["tools"],apply:bt};export{t as default};
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{x,Re}from"./chunks/index-cxqk4wed.js";import{Fe,Te,yt,Qe,et}from"./chunks/index-x65f5t9p.js";import"./chunks/index-823nnrjs.js";import{execFile as Af}from"node:child_process";var re=(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}}},Cc={pipe(){return re(this,arguments)}},Dt=function(){function e(){}return e.prototype=Cc,e}();var w=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 Q=(e)=>e;var Ss=(e)=>()=>e;var lt=Ss(void 0),ys=lt;function ze(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 ft(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 Ut=(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},Mt=new WeakSet;function Nt(e){return typeof e==="string"}function En(e){return typeof e==="number"}function Ts(e){return typeof e==="symbol"}function Sr(e){return Nt(e)||En(e)||Ts(e)}function pt(e){return typeof e==="function"}function bn(e){return e!==void 0}function wn(e){return e!=null}function Es(e){return!0}function In(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function yr(e){return typeof e==="object"&&e!==null||pt(e)}var C=w(2,(e,t)=>yr(e)&&(t in e));function bs(e){return e instanceof Error}var G="~effect/interfaces/Hash",R=(e)=>{switch(typeof e){case"number":return wr(e);case"bigint":return L(e.toString(10));case"boolean":return L(String(e));case"symbol":return L(String(e));case"string":return L(e);case"undefined":return L("undefined");case"function":case"object":if(e===null)return L("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return L("Invalid Date");return L(e.toISOString())}else if(e instanceof RegExp)return L(e.toString());else{if(Mt.has(e))return Tr(e);if(On.has(e))return On.get(e);let t=Fc(e,()=>{if(kc(e))return e[G]();else if(typeof e==="function")return Tr(e);else if(e instanceof DataView)return Er(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e)||ArrayBuffer.isView(e))return Er(e);else if(e instanceof Map)return _c(e);else if(e instanceof Set)return Ac(e);return Rc(e)});return On.set(e,t),t}default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},Tr=(e)=>{if(!vn.has(e))vn.set(e,wr(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return vn.get(e)},ee=w(2,(e,t)=>e*53^t),br=(e)=>e&3221225471|e>>>1&1073741824,kc=(e)=>C(e,G),wr=(e)=>{if(e!==e)return L("NaN");if(e===1/0)return L("Infinity");if(e===-1/0)return L("-Infinity");let t=e|0;if(t!==e)t^=e*4294967295;while(e>4294967295)t^=e/=4294967295;return br(t)},L=(e)=>{let t=5381,r=e.length;while(r)t=t*33^e.charCodeAt(--r);return br(t)},kn=(e,t)=>{let r=12289;for(let n of t)r^=ee(R(n),R(e[n]));return br(r)},Rc=(e)=>kn(e,Ut(e)),Rn=(e,t)=>(r)=>{let n=e;for(let o of r)n^=t(o);return br(n)},Er=Rn(6151,R),_c=Rn(L("Map"),([e,t])=>ee(R(e),R(t))),Ac=Rn(L("Set"),R),vn=new WeakMap,On=new WeakMap,Cn=new WeakSet;function Fc(e,t){if(Cn.has(e))return L("[Circular]");Cn.add(e);let r=t();return Cn.delete(e),r}var z="~effect/interfaces/Equal";function q(){if(arguments.length===1)return(e)=>He(e,arguments[0]);return He(arguments[0],arguments[1])}function He(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(Mt.has(e)||Mt.has(t))return!1;return Uc(e,t,Dc)}function Pc(e,t,r){let n=_n.has(e),o=An.has(t);if(n&&o)return!0;if(n||o)return!1;_n.add(e),An.add(t);let s=r();return _n.delete(e),An.delete(t),s}var _n=new WeakSet,An=new WeakSet;function Dc(e,t){if(R(e)!==R(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=Is(e),n=Is(t);if(r!==n)return!1;let o=r&&n;if(typeof e==="function"&&!o)return!1;return Pc(e,t,()=>{if(o)return e[z](t);else if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;return Mc(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 ws(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}return ws(e,t)}else if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;return $c(e,t)}else if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;return jc(e,t)}return Nc(e,t)})}function Uc(e,t,r){let n=Ir.get(e);if(!n)n=new WeakMap,Ir.set(e,n);else if(n.has(t))return n.get(t);let o=r(e,t);n.set(t,o);let s=Ir.get(t);if(!s)s=new WeakMap,Ir.set(t,s);return s.set(e,o),o}var Ir=new WeakMap;function Mc(e,t){for(let r=0;r<e.length;r++)if(!He(e[r],t[r]))return!1;return!0}function ws(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 Nc(e,t){let r=Ut(e),n=Ut(t);if(r.size!==n.size)return!1;for(let o of r)if(!n.has(o)||!He(e[o],t[o]))return!1;return!0}function Lc(e,t){return function(n,o){let s=Array.from(o);for(let[a,c]of n){let u=!1;for(let i=0;i<s.length;i++){let[f,g]=s[i];if(e(a,f)&&t(c,g)){s[i]=s[s.length-1],s.pop(),u=!0;break}}if(!u)return!1}return!0}}var $c=Lc(He,He);function Bc(e){return function(r,n){let o=Array.from(n);for(let s of r){let a=!1;for(let c=0;c<o.length;c++){let u=o[c];if(e(s,u)){o[c]=o[o.length-1],o.pop(),a=!0;break}}if(!a)return!1}return!0}}var jc=Bc(He),Is=(e)=>C(e,z);var Lt=Symbol.for("~effect/Redactable"),qc=(e)=>C(e,Lt);function ht(e){if(qc(e))return Fn(e);return e}function Fn(e){return e[Lt](globalThis[xt]?.context??Jc)}var xt="~effect/Fiber/currentFiber",vs=new Map,Jc={"~effect/Context":{},base:vs,depth:0,mapUnsafe:vs,pipe(){return re(this,arguments)}};function A(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,f)=>{let g=i?.constructor;return g&&g!==Object.prototype.constructor&&g.name?`${g.name}(${f})`:f},c=(i)=>{try{return Reflect.ownKeys(i)}catch{return["[ownKeys threw]"]}};function u(i,f=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 Kc;n.add(i);let g;if(Lt in i)g=u(Fn(i),f);else if(Array.isArray(i))g=!o||i.length<=1?`[${i.map((h)=>u(h,f)).join(",")}]`:`[
1
+ import{x,Re}from"./chunks/index-1p1q38x4.js";import{Fe,Te,yt,Qe,et}from"./chunks/index-03hfs9tb.js";import"./chunks/index-8m4sxbp8.js";import{execFile as Af}from"node:child_process";var re=(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}}},Cc={pipe(){return re(this,arguments)}},Dt=function(){function e(){}return e.prototype=Cc,e}();var w=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 Q=(e)=>e;var Ss=(e)=>()=>e;var lt=Ss(void 0),ys=lt;function ze(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 ft(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 Ut=(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},Mt=new WeakSet;function Nt(e){return typeof e==="string"}function En(e){return typeof e==="number"}function Ts(e){return typeof e==="symbol"}function Sr(e){return Nt(e)||En(e)||Ts(e)}function pt(e){return typeof e==="function"}function bn(e){return e!==void 0}function wn(e){return e!=null}function Es(e){return!0}function In(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function yr(e){return typeof e==="object"&&e!==null||pt(e)}var C=w(2,(e,t)=>yr(e)&&(t in e));function bs(e){return e instanceof Error}var G="~effect/interfaces/Hash",R=(e)=>{switch(typeof e){case"number":return wr(e);case"bigint":return L(e.toString(10));case"boolean":return L(String(e));case"symbol":return L(String(e));case"string":return L(e);case"undefined":return L("undefined");case"function":case"object":if(e===null)return L("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return L("Invalid Date");return L(e.toISOString())}else if(e instanceof RegExp)return L(e.toString());else{if(Mt.has(e))return Tr(e);if(On.has(e))return On.get(e);let t=Fc(e,()=>{if(kc(e))return e[G]();else if(typeof e==="function")return Tr(e);else if(e instanceof DataView)return Er(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e)||ArrayBuffer.isView(e))return Er(e);else if(e instanceof Map)return _c(e);else if(e instanceof Set)return Ac(e);return Rc(e)});return On.set(e,t),t}default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},Tr=(e)=>{if(!vn.has(e))vn.set(e,wr(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return vn.get(e)},ee=w(2,(e,t)=>e*53^t),br=(e)=>e&3221225471|e>>>1&1073741824,kc=(e)=>C(e,G),wr=(e)=>{if(e!==e)return L("NaN");if(e===1/0)return L("Infinity");if(e===-1/0)return L("-Infinity");let t=e|0;if(t!==e)t^=e*4294967295;while(e>4294967295)t^=e/=4294967295;return br(t)},L=(e)=>{let t=5381,r=e.length;while(r)t=t*33^e.charCodeAt(--r);return br(t)},kn=(e,t)=>{let r=12289;for(let n of t)r^=ee(R(n),R(e[n]));return br(r)},Rc=(e)=>kn(e,Ut(e)),Rn=(e,t)=>(r)=>{let n=e;for(let o of r)n^=t(o);return br(n)},Er=Rn(6151,R),_c=Rn(L("Map"),([e,t])=>ee(R(e),R(t))),Ac=Rn(L("Set"),R),vn=new WeakMap,On=new WeakMap,Cn=new WeakSet;function Fc(e,t){if(Cn.has(e))return L("[Circular]");Cn.add(e);let r=t();return Cn.delete(e),r}var z="~effect/interfaces/Equal";function q(){if(arguments.length===1)return(e)=>He(e,arguments[0]);return He(arguments[0],arguments[1])}function He(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(Mt.has(e)||Mt.has(t))return!1;return Uc(e,t,Dc)}function Pc(e,t,r){let n=_n.has(e),o=An.has(t);if(n&&o)return!0;if(n||o)return!1;_n.add(e),An.add(t);let s=r();return _n.delete(e),An.delete(t),s}var _n=new WeakSet,An=new WeakSet;function Dc(e,t){if(R(e)!==R(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=Is(e),n=Is(t);if(r!==n)return!1;let o=r&&n;if(typeof e==="function"&&!o)return!1;return Pc(e,t,()=>{if(o)return e[z](t);else if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;return Mc(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 ws(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}return ws(e,t)}else if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;return $c(e,t)}else if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;return jc(e,t)}return Nc(e,t)})}function Uc(e,t,r){let n=Ir.get(e);if(!n)n=new WeakMap,Ir.set(e,n);else if(n.has(t))return n.get(t);let o=r(e,t);n.set(t,o);let s=Ir.get(t);if(!s)s=new WeakMap,Ir.set(t,s);return s.set(e,o),o}var Ir=new WeakMap;function Mc(e,t){for(let r=0;r<e.length;r++)if(!He(e[r],t[r]))return!1;return!0}function ws(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 Nc(e,t){let r=Ut(e),n=Ut(t);if(r.size!==n.size)return!1;for(let o of r)if(!n.has(o)||!He(e[o],t[o]))return!1;return!0}function Lc(e,t){return function(n,o){let s=Array.from(o);for(let[a,c]of n){let u=!1;for(let i=0;i<s.length;i++){let[f,g]=s[i];if(e(a,f)&&t(c,g)){s[i]=s[s.length-1],s.pop(),u=!0;break}}if(!u)return!1}return!0}}var $c=Lc(He,He);function Bc(e){return function(r,n){let o=Array.from(n);for(let s of r){let a=!1;for(let c=0;c<o.length;c++){let u=o[c];if(e(s,u)){o[c]=o[o.length-1],o.pop(),a=!0;break}}if(!a)return!1}return!0}}var jc=Bc(He),Is=(e)=>C(e,z);var Lt=Symbol.for("~effect/Redactable"),qc=(e)=>C(e,Lt);function ht(e){if(qc(e))return Fn(e);return e}function Fn(e){return e[Lt](globalThis[xt]?.context??Jc)}var xt="~effect/Fiber/currentFiber",vs=new Map,Jc={"~effect/Context":{},base:vs,depth:0,mapUnsafe:vs,pipe(){return re(this,arguments)}};function A(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,f)=>{let g=i?.constructor;return g&&g!==Object.prototype.constructor&&g.name?`${g.name}(${f})`:f},c=(i)=>{try{return Reflect.ownKeys(i)}catch{return["[ownKeys threw]"]}};function u(i,f=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 Kc;n.add(i);let g;if(Lt in i)g=u(Fn(i),f);else if(Array.isArray(i))g=!o||i.length<=1?`[${i.map((h)=>u(h,f)).join(",")}]`:`[
2
2
  ${s(f+1)}${i.map((h)=>u(h,f+1)).join(`,
3
3
  `+s(f+1))}
4
4
  ${s(f)}]`;else if(i instanceof Date)g=Os(i);else if(!t?.ignoreToString&&C(i,"toString")&&typeof i.toString==="function"&&i.toString!==Object.prototype.toString&&i.toString!==Array.prototype.toString){let h=Gc(i);g=i instanceof Error&&i.cause?`${h} (cause: ${u(i.cause,f)})`:h}else if(Symbol.iterator in i)g=`${i.constructor.name}(${u(Array.from(i),f)})`;else{let h=c(i);if(!o||h.length<=1){let m=`{${h.map((p)=>`${$t(p)}:${u(i[p],f)}`).join(",")}}`;g=a(i,m)}else{let m=`{