cc-safety-net 2.7.5 → 2.7.7

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,4 +1,4 @@
1
- import{l,a,te,Ve,p,h,et,E,H,g,G}from"./index-dm4v8s9a.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 U,readFileSync as j,rmdirSync as V,statSync as C,unlinkSync as B,utimesSync as K,writeFileSync as X}from"node:fs";import{join as s}from"node:path";function ue(t,e={}){return et(p(t,e),t.home).policy.audit.retention_days}var A=86400000,Y=".last-prune",Z=/^\d{4}-\d{2}$/,J=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,L=(t)=>Math.floor(t/A);function ee(t,e,r=()=>new Date){try{let n=r().getTime();if(!C(e,{throwIfNoEntry:!1})?.isDirectory())return;let o=s(e,Y),c=C(o,{throwIfNoEntry:!1})?.mtimeMs;if(c!==void 0&&L(c)===L(n))return;let i=n-ue(t)*A,d=new Date(n).toISOString().slice(0,7);for(let u of v(e)){if(u.isDirectory()){Q(s(e,u.name),i,d);continue}if(u.isFile()&&u.name.endsWith(".jsonl"))q(s(e,u.name),i)}X(o,"",{mode:384}),K(o,n/1000,n/1000)}catch{}}function Q(t,e,r){for(let n of v(t)){if(!n.isDirectory()||!Z.test(n.name))continue;let o=s(t,n.name);for(let c of v(o)){if(!c.isFile())continue;let i=J.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;T(s(o,c.name))}if(n.name!==r)O(o)}O(t)}function q(t,e){try{let r=D(t);if(r.mtimeMs>=e)return;let n=j(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;T(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 U(t,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function T(t){try{B(t)}catch{}}function O(t){try{V(t)}catch{}}var ae="2.7.5",ce=1e4,de=2000,se=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 u=W(t);if(!u)return;try{let f=(i.now??(()=>new Date))().toISOString(),_=m(te(r),i.failureStage?Number.POSITIVE_INFINITY:ce),N=m(te(n),de),w=i.toolName?m(te(i.toolName),se):void 0,y=c===null?void 0:m(te(c),le),F=S(u,fe(y?.value??null),f.slice(0,7));oe(F,{recursive:!0,mode:448});let R=S(F,`${f.slice(0,10)}-${d}.jsonl`),P={ts:f,id:(i.createId??Ve)(),v:ae,sessionId:d,decision:i.decision??"deny",agent:i.agent,shape:i.shape,level:i.level,configFallback:i.configFallback,toolName:w?.value,command:_.value,segment:N.value,..._.truncated||N.truncated||w?.truncated||y?.truncated?{truncated:!0}:{},reason:o,ruleId:i.ruleId,intent:i.intent,failureStage:i.failureStage,errorCode:i.errorCode,cwd:y?.value??null};re(R,`${JSON.stringify(P)}
1
+ import{l,a,te,Ve,p,h,et,E,H,g,G}from"./index-769a735t.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 U,readFileSync as j,rmdirSync as V,statSync as C,unlinkSync as B,utimesSync as K,writeFileSync as X}from"node:fs";import{join as s}from"node:path";function ue(t,e={}){return et(p(t,e),t.home).policy.audit.retention_days}var A=86400000,Y=".last-prune",Z=/^\d{4}-\d{2}$/,J=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,L=(t)=>Math.floor(t/A);function ee(t,e,r=()=>new Date){try{let n=r().getTime();if(!C(e,{throwIfNoEntry:!1})?.isDirectory())return;let o=s(e,Y),c=C(o,{throwIfNoEntry:!1})?.mtimeMs;if(c!==void 0&&L(c)===L(n))return;let i=n-ue(t)*A,d=new Date(n).toISOString().slice(0,7);for(let u of v(e)){if(u.isDirectory()){Q(s(e,u.name),i,d);continue}if(u.isFile()&&u.name.endsWith(".jsonl"))q(s(e,u.name),i)}X(o,"",{mode:384}),K(o,n/1000,n/1000)}catch{}}function Q(t,e,r){for(let n of v(t)){if(!n.isDirectory()||!Z.test(n.name))continue;let o=s(t,n.name);for(let c of v(o)){if(!c.isFile())continue;let i=J.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;T(s(o,c.name))}if(n.name!==r)O(o)}O(t)}function q(t,e){try{let r=D(t);if(r.mtimeMs>=e)return;let n=j(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;T(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 U(t,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function T(t){try{B(t)}catch{}}function O(t){try{V(t)}catch{}}var ae="2.7.7",ce=1e4,de=2000,se=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 u=W(t);if(!u)return;try{let f=(i.now??(()=>new Date))().toISOString(),_=m(te(r),i.failureStage?Number.POSITIVE_INFINITY:ce),N=m(te(n),de),w=i.toolName?m(te(i.toolName),se):void 0,y=c===null?void 0:m(te(c),le),F=S(u,fe(y?.value??null),f.slice(0,7));oe(F,{recursive:!0,mode:448});let R=S(F,`${f.slice(0,10)}-${d}.jsonl`),P={ts:f,id:(i.createId??Ve)(),v:ae,sessionId:d,decision:i.decision??"deny",agent:i.agent,shape:i.shape,level:i.level,configFallback:i.configFallback,toolName:w?.value,command:_.value,segment:N.value,..._.truncated||N.truncated||w?.truncated||y?.truncated?{truncated:!0}:{},reason:o,ruleId:i.ruleId,intent:i.intent,failureStage:i.failureStage,errorCode:i.errorCode,cwd:y?.value??null};re(R,`${JSON.stringify(P)}
3
3
  `,{encoding:"utf-8",mode:384}),ee(t,u,i.now)}catch{}}function m(t,e){return{value:t.slice(0,e),truncated:t.length>e}}function ut(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 W(t){let e=ut(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=b(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?b(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 b(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 Me(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 z(t,e,r){try{let n=G(e,{environment:t,...r.guard});return M(t,e,n,r),n}catch(n){if(!(n instanceof g))throw n;throw M(t,e,n.evaluation,r,!(n.cause instanceof h),{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 a)return l[t.kind].errorCode;if(t instanceof h)return"tool-input-limit";if(t instanceof E)return"structural-shell-syntax-limit";if(t instanceof H)return"unparseable-command";return"unexpected-error"}
4
4
  export{ue,ee,ut,W,Me,z};
@@ -1,2 +1,2 @@
1
- import{re,S,Mt,d}from"./index-dm4v8s9a.js";import{Q,Ne,ve,Le}from"./index-a1hayde0.js";var ct=new Map([["bash","posix"],["powershell","powershell"]]),u={agent:"pi",debugLabel:"pi tool_call",extract:(o,e,t)=>C(o,e,t),getSessionId:(o,e)=>e.sessionManager.getSessionId(),allow:void 0,block:(o)=>p(o),includeEvidenceOnError:(o)=>o.route.kind==="command"};function kt(o){o.on("tool_call",s)}var s=m();function m(o={}){return Le(u,o)}function C(o,e,t){if(!o||typeof o!=="object")return;let l=o;if(l.type!==void 0&&l.type!=="tool_call")return;if(typeof l.toolName!=="string"||l.toolName.trim()==="")return a(e);if(typeof e.cwd!=="string"||e.cwd.trim()==="")return Ne(null,{toolName:l.toolName});let n=Mt(".",[e.cwd],t);if(!n)return ve({directory:"session",problem:"unusable",cwd:e.cwd},{toolName:l.toolName});let i=ct.get(l.toolName);if(!l.input||typeof l.input!=="object")return i?a(e,l.toolName):void 0;if(!i)return d(l.toolName,l.input,{kind:S(l.toolName)},{configCwd:n,executionCwd:n},null);let r=l.input.command;if(typeof r!=="string"||r.trim()==="")return a(e,l.toolName);return d(l.toolName,l.input,{kind:"command",shell:i},{configCwd:n,executionCwd:n},r)}function a(o,e){return Q(typeof o.cwd==="string"&&o.cwd.trim()?o.cwd:null,{toolName:e})}function p(o){return{block:!0,reason:re(o)}}
1
+ import{re,S,Mt,d}from"./index-769a735t.js";import{Q,Ne,ve,Le}from"./index-ssmnsasm.js";var ct=new Map([["bash","posix"],["powershell","powershell"]]),u={agent:"pi",debugLabel:"pi tool_call",extract:(o,e,t)=>C(o,e,t),getSessionId:(o,e)=>e.sessionManager.getSessionId(),allow:void 0,block:(o)=>p(o),includeEvidenceOnError:(o)=>o.route.kind==="command"};function kt(o){o.on("tool_call",s)}var s=m();function m(o={}){return Le(u,o)}function C(o,e,t){if(!o||typeof o!=="object")return;let l=o;if(l.type!==void 0&&l.type!=="tool_call")return;if(typeof l.toolName!=="string"||l.toolName.trim()==="")return a(e);if(typeof e.cwd!=="string"||e.cwd.trim()==="")return Ne(null,{toolName:l.toolName});let n=Mt(".",[e.cwd],t);if(!n)return ve({directory:"session",problem:"unusable",cwd:e.cwd},{toolName:l.toolName});let i=ct.get(l.toolName);if(!l.input||typeof l.input!=="object")return i?a(e,l.toolName):void 0;if(!i)return d(l.toolName,l.input,{kind:S(l.toolName)},{configCwd:n,executionCwd:n},null);let r=l.input.command;if(typeof r!=="string"||r.trim()==="")return a(e,l.toolName);return d(l.toolName,l.input,{kind:"command",shell:i},{configCwd:n,executionCwd:n},r)}function a(o,e){return Q(typeof o.cwd==="string"&&o.cwd.trim()?o.cwd:null,{toolName:e})}function p(o){return{block:!0,reason:re(o)}}
2
2
  export{ct,kt};
@@ -1,2 +1,2 @@
1
- import{Fe,ne,q,I,_t,c,r,$e,k,g}from"./index-dm4v8s9a.js";import{Me,z}from"./index-r6tk9ysc.js";function Q(n,o={}){return{malformed:!0,denial:q(o),cwd:n}}function Ne(n,o={}){return{malformed:!0,denial:ne(o),cwd:n}}function ve(n,o){return{malformed:!0,denial:I(n,o),cwd:n.cwd}}function Le(n,o={}){return(e,i)=>{try{return p(e,i,n,o)}catch(a){return console.error("CC Safety Net error:",a),n.block(ne())}}}function p(n,o,e,i){let a=c();if(e.cancelled?.(o))return e.block(ne());let t=e.extract(n,o,a.paths);if(!t)return e.allow;let d=()=>e.getSessionId(n,o);if("malformed"in t)return Me(a,t.denial,d,{agent:e.agent,toolName:t.denial.toolName,cwd:t.cwd}),e.block(t.denial);let u=(l,s)=>{let m=Fe(l,{includeEvidence:s});return m?e.block(m):e.allow};try{let l=z(a,t,{guard:{auditAllowed:$e(a.env),policyOptions:i.policyOptions,dependencies:i.guardDependencies},audit:{agent:e.agent,getSessionId:d}});return u(l,!0)}catch(l){if(!(l instanceof g))throw l;if(k(r.debug,a.env))console.error(`CC Safety Net debug: ${e.debugLabel} analysis failed: ${_t(l.cause)}`);return u(l.evaluation,e.includeEvidenceOnError(t))}}
1
+ import{Fe,ne,q,I,_t,c,r,$e,k,g}from"./index-769a735t.js";import{Me,z}from"./index-hqqx476d.js";function Q(n,o={}){return{malformed:!0,denial:q(o),cwd:n}}function Ne(n,o={}){return{malformed:!0,denial:ne(o),cwd:n}}function ve(n,o){return{malformed:!0,denial:I(n,o),cwd:n.cwd}}function Le(n,o={}){return(e,i)=>{try{return p(e,i,n,o)}catch(a){return console.error("CC Safety Net error:",a),n.block(ne())}}}function p(n,o,e,i){let a=c();if(e.cancelled?.(o))return e.block(ne());let t=e.extract(n,o,a.paths);if(!t)return e.allow;let d=()=>e.getSessionId(n,o);if("malformed"in t)return Me(a,t.denial,d,{agent:e.agent,toolName:t.denial.toolName,cwd:t.cwd}),e.block(t.denial);let u=(l,s)=>{let m=Fe(l,{includeEvidence:s});return m?e.block(m):e.allow};try{let l=z(a,t,{guard:{auditAllowed:$e(a.env),policyOptions:i.policyOptions,dependencies:i.guardDependencies},audit:{agent:e.agent,getSessionId:d}});return u(l,!0)}catch(l){if(!(l instanceof g))throw l;if(k(r.debug,a.env))console.error(`CC Safety Net debug: ${e.debugLabel} analysis failed: ${_t(l.cause)}`);return u(l.evaluation,e.includeEvidenceOnError(t))}}
2
2
  export{Q,Ne,ve,Le};
@@ -1,2 +1,2 @@
1
- import{Fe,ne,q,I,re,c,$e,Lt,h,S,ye,Pe,d,g}from"./index-dm4v8s9a.js";import{le}from"./index-e4b0v62z.js";import{Me,z}from"./index-r6tk9ysc.js";import{join as v,resolve as w}from"node:path";function Be(){return{"cc-safety-net":{description:"Operate CC Safety Net: explain blocks, rules, integrations, diagnostics",template:le.slice(le.indexOf("# CC Safety Net"))}}}var x=new Set(["powershell","pwsh"]),O=new Set(["fish","nu"]),it="bash",Oe="shell";function Et(e={}){return async({directory:o,homeDir:a})=>{let n=w(o),r;return{config:async(t)=>{r=t;let s=Be(),u=t.command??{};t.command={...s,...u}},"tool.execute.before":async(t,s)=>{st({configCwd:n,homeDir:a,tool:t.tool,sessionID:t.sessionID,toolInput:s.args,route:k(t.tool,at(r?.shell)),guardDependencies:e})}}}}function st({configCwd:e,homeDir:o,expandHomeWorkdir:a=!1,tool:n,sessionID:r,toolInput:t,route:s,guardDependencies:u={}}){let l=o===void 0?c():{...c(),home:o},m=(i,E,T=e)=>{Me(l,i,()=>r,{agent:"opencode",toolName:E,cwd:T}),y(i)};if(typeof n!=="string"||n.trim()==="")m(q());let p;try{p=ye(t)}catch(i){if(!(i instanceof h))throw i;m(ne({toolName:n}),n)}if(!Pe(e)){m(I({directory:"session",problem:"unusable",cwd:e},{command:p,toolName:n}),n);return}let f=P(e,t,a?l.home:void 0,()=>s.kind==="unknown"&&Lt(l,e,n));if(f===null){m(q({command:p,toolName:n}),n);return}if(typeof f!=="string"){m(I(f,{command:p,toolName:n}),n,f.cwd);return}let D=d(n,t,s,{configCwd:e,executionCwd:f},p??null);try{let i=z(l,D,{guard:{auditAllowed:$e(l.env),dependencies:u},audit:{agent:"opencode",getSessionId:()=>r}});C(i)}catch(i){if(!(i instanceof g))throw i;if(i.stage==="policy-protection"||i.stage==="config-load"||i.stage==="secret-protection")throw i.cause;C(i.evaluation);return}}function at(e,o=process.platform,a=process.env.SHELL){let r=(typeof e==="string"?e:a)?.trim().split(/[\\/]/).at(-1)?.toLowerCase().replace(/\.exe$/,"");if(typeof e!=="string"&&o==="win32"&&(!r||O.has(r)))return"powershell";if(!r)return"auto";if(x.has(r))return"powershell";return r==="cmd"?"auto":"posix"}function k(e,o){if(e===it)return{kind:"command",shell:o};return{kind:S(e)}}function P(e,o,a,n){if(!o||typeof o!=="object"||Array.isArray(o))return e;if(!Object.hasOwn(o,"workdir")||n())return e;let r=o.workdir;if(typeof r!=="string"||r.trim()==="")return null;let t=process.platform==="win32"?A(r):r,s=t.startsWith("~/")||process.platform==="win32"&&t.startsWith("~\\"),u=a===void 0?t:t==="~"?a:s?v(a,t.slice(2)):t,l=w(e,u);return Pe(l)?l:{directory:"requested",problem:"unusable",cwd:r}}function A(e){return e.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(a,n)=>`${n.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:[\\/]|$)/,(a,n)=>`${n.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:[\\/]|$)/,(a,n)=>`${n.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:[\\/]|$)/,(a,n)=>`${n.toUpperCase()}:/`)}function C(e){let o=Fe(e,{includeEvidence:!0});if(o)y(o)}function y(e){throw Error(re(e))}
1
+ import{Fe,ne,q,I,re,c,$e,Lt,h,S,ye,Pe,d,g}from"./index-769a735t.js";import{le}from"./index-e4b0v62z.js";import{Me,z}from"./index-hqqx476d.js";import{join as v,resolve as w}from"node:path";function Be(){return{"cc-safety-net":{description:"Operate CC Safety Net: explain blocks, rules, integrations, diagnostics",template:le.slice(le.indexOf("# CC Safety Net"))}}}var x=new Set(["powershell","pwsh"]),O=new Set(["fish","nu"]),it="bash",Oe="shell";function Et(e={}){return async({directory:o,homeDir:a})=>{let n=w(o),r;return{config:async(t)=>{r=t;let s=Be(),u=t.command??{};t.command={...s,...u}},"tool.execute.before":async(t,s)=>{st({configCwd:n,homeDir:a,tool:t.tool,sessionID:t.sessionID,toolInput:s.args,route:k(t.tool,at(r?.shell)),guardDependencies:e})}}}}function st({configCwd:e,homeDir:o,expandHomeWorkdir:a=!1,tool:n,sessionID:r,toolInput:t,route:s,guardDependencies:u={}}){let l=o===void 0?c():{...c(),home:o},m=(i,E,T=e)=>{Me(l,i,()=>r,{agent:"opencode",toolName:E,cwd:T}),y(i)};if(typeof n!=="string"||n.trim()==="")m(q());let p;try{p=ye(t)}catch(i){if(!(i instanceof h))throw i;m(ne({toolName:n}),n)}if(!Pe(e)){m(I({directory:"session",problem:"unusable",cwd:e},{command:p,toolName:n}),n);return}let f=P(e,t,a?l.home:void 0,()=>s.kind==="unknown"&&Lt(l,e,n));if(f===null){m(q({command:p,toolName:n}),n);return}if(typeof f!=="string"){m(I(f,{command:p,toolName:n}),n,f.cwd);return}let D=d(n,t,s,{configCwd:e,executionCwd:f},p??null);try{let i=z(l,D,{guard:{auditAllowed:$e(l.env),dependencies:u},audit:{agent:"opencode",getSessionId:()=>r}});C(i)}catch(i){if(!(i instanceof g))throw i;if(i.stage==="policy-protection"||i.stage==="config-load"||i.stage==="secret-protection")throw i.cause;C(i.evaluation);return}}function at(e,o=process.platform,a=process.env.SHELL){let r=(typeof e==="string"?e:a)?.trim().split(/[\\/]/).at(-1)?.toLowerCase().replace(/\.exe$/,"");if(typeof e!=="string"&&o==="win32"&&(!r||O.has(r)))return"powershell";if(!r)return"auto";if(x.has(r))return"powershell";return r==="cmd"?"auto":"posix"}function k(e,o){if(e===it)return{kind:"command",shell:o};return{kind:S(e)}}function P(e,o,a,n){if(!o||typeof o!=="object"||Array.isArray(o))return e;if(!Object.hasOwn(o,"workdir")||n())return e;let r=o.workdir;if(typeof r!=="string"||r.trim()==="")return null;let t=process.platform==="win32"?A(r):r,s=t.startsWith("~/")||process.platform==="win32"&&t.startsWith("~\\"),u=a===void 0?t:t==="~"?a:s?v(a,t.slice(2)):t,l=w(e,u);return Pe(l)?l:{directory:"requested",problem:"unusable",cwd:r}}function A(e){return e.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(a,n)=>`${n.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:[\\/]|$)/,(a,n)=>`${n.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:[\\/]|$)/,(a,n)=>`${n.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:[\\/]|$)/,(a,n)=>`${n.toUpperCase()}:/`)}function C(e){let o=Fe(e,{includeEvidence:!0});if(o)y(o)}function y(e){throw Error(re(e))}
2
2
  export{Be,it,Oe,Et,st,at};
package/dist/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import{l,a,qe,dt,A,Pt,pt,c,r,ft,O,k,xe,At,i,R,s,de,o,v,Se,V,It,Ot,m,we,Ce,Dt,j,oe,pe,T,Nt,D,x,fe,K,p,L,ie,mt,gt,U,P,M,Ee,ke,Ke,me,f,e,Je,je,Ye,Re,ht,yt,ge,Ue,he,Ze,J,Y,Xe,Te,h,He,S,vt,d,Z,xt,X,se,ae,be,St,wt,_,N,Qe,Ct,tt,w,nt,Ge,_e,C,t,ce,Ae,E,H,y,F,Ft,rt,ot,g,G}from"./chunks/index-dm4v8s9a.js";import{ct}from"./chunks/index-kzz5h21y.js";import{it,Oe}from"./chunks/index-eg9by26f.js";import{b,B,u,We,n,De,lt,Rt,ze}from"./chunks/index-edtb8nxp.js";import"./chunks/index-a1hayde0.js";import{ue,ee,ut,W,z}from"./chunks/index-r6tk9ysc.js";var vf=["-h","--help"];function fn(I,q){let Q=Object.entries(I.booleans??{}),ne=Object.entries(I.values??{}),te=Object.entries(I.lists??{}),re=Object.fromEntries(Q.map(([Le])=>[Le,!1])),le={},ye=Object.fromEntries(te.map(([Le])=>[Le,[]])),ve=[],Pe=[],Ie=!1,$e=-1;for(let[Le,Fe]of q.entries()){if(Le<=$e)continue;if(Fe==="--"){ve.push(...q.slice(Le+1));break}if(vf.includes(Fe)){Ie=!0;continue}let Ne=Q.find(([,tn])=>tn.includes(Fe));if(Ne){re[Ne[0]]=!0;continue}let Be=ne.find(([,tn])=>tn.includes(Fe));if(Be){let tn=q[Le+1];if(tn===void 0||tn.startsWith("-")){Pe.push(`${Fe} requires a value`);continue}le[Be[0]]=tn,$e=Le+1;continue}let Me=te.find(([,tn])=>tn.includes(Fe));if(Me){let tn=q.slice(Le+1),en=tn.findIndex((ln)=>ln.startsWith("-")),on=tn.slice(0,en===-1?tn.length:en);if(on.length===0){Pe.push(`${Fe} requires at least one value`);continue}ye[Me[0]]=[...ye[Me[0]]??[],...on],$e=Le+on.length;continue}if(Fe.startsWith("-")){Pe.push(`Unknown option for ${I.label}: ${Fe}`);continue}if(I.positionals==="tail"){ve.push(...q.slice(Le));break}ve.push(Fe)}if(I.positionals!=="list"&&I.positionals!=="tail")Pe.push(...ve.map((Le)=>`Unexpected argument for ${I.label}: ${Le}`));return{flags:re,values:le,lists:ye,positionals:ve,help:Ie,errors:Pe}}function In(I){for(let q of I)console.error(q);return I.length>0}import{readdirSync as Sf,statSync as Qs,unlinkSync as Rf}from"node:fs";import{basename as ea,dirname as Ef,isAbsolute as Tf,join as Af,relative as _f,resolve as If,sep as Of}from"node:path";var Ys=(I)=>{let q=Date.now()-new Date(I).getTime();if(!Number.isFinite(q))return"";let Q=Math.floor(q/60000),ne=Math.floor(Q/60),te=Math.floor(ne/24);if(te>0)return`${te}d ago`;if(ne>0)return`${ne}h ago`;if(Q>0)return`${Q}m ago`;return"just now"},Jo=(I)=>{let q=(I??"").trim().split(/\s+/).filter((te)=>te&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(te)),Q=q[0]?.split("/").pop();if(!Q)return null;let ne=q[1];return ne&&/^[a-z][a-z0-9-]*$/.test(ne)?`${Q} ${ne}`:Q};function Zs(I){let q=(te)=>`${te.sessionId}
1
+ import{l,a,qe,dt,A,Pt,pt,c,r,ft,O,k,xe,At,i,R,s,de,o,v,Se,V,It,Ot,m,we,Ce,Dt,j,oe,pe,T,Nt,D,x,fe,K,p,L,ie,mt,gt,U,P,M,Ee,ke,Ke,me,f,e,Je,je,Ye,Re,ht,yt,ge,Ue,he,Ze,J,Y,Xe,Te,h,He,S,vt,d,Z,xt,X,se,ae,be,St,wt,_,N,Qe,Ct,tt,w,nt,Ge,_e,C,t,ce,Ae,E,H,y,F,Ft,rt,ot,g,G}from"./chunks/index-769a735t.js";import{ct}from"./chunks/index-jharmezb.js";import{it,Oe}from"./chunks/index-ta894pns.js";import{b,B,u,We,n,De,lt,Rt,ze}from"./chunks/index-39xnzexq.js";import"./chunks/index-ssmnsasm.js";import{ue,ee,ut,W,z}from"./chunks/index-hqqx476d.js";var vf=["-h","--help"];function fn(I,q){let Q=Object.entries(I.booleans??{}),ne=Object.entries(I.values??{}),te=Object.entries(I.lists??{}),re=Object.fromEntries(Q.map(([Le])=>[Le,!1])),le={},ye=Object.fromEntries(te.map(([Le])=>[Le,[]])),ve=[],Pe=[],Ie=!1,$e=-1;for(let[Le,Fe]of q.entries()){if(Le<=$e)continue;if(Fe==="--"){ve.push(...q.slice(Le+1));break}if(vf.includes(Fe)){Ie=!0;continue}let Ne=Q.find(([,tn])=>tn.includes(Fe));if(Ne){re[Ne[0]]=!0;continue}let Be=ne.find(([,tn])=>tn.includes(Fe));if(Be){let tn=q[Le+1];if(tn===void 0||tn.startsWith("-")){Pe.push(`${Fe} requires a value`);continue}le[Be[0]]=tn,$e=Le+1;continue}let Me=te.find(([,tn])=>tn.includes(Fe));if(Me){let tn=q.slice(Le+1),en=tn.findIndex((ln)=>ln.startsWith("-")),on=tn.slice(0,en===-1?tn.length:en);if(on.length===0){Pe.push(`${Fe} requires at least one value`);continue}ye[Me[0]]=[...ye[Me[0]]??[],...on],$e=Le+on.length;continue}if(Fe.startsWith("-")){Pe.push(`Unknown option for ${I.label}: ${Fe}`);continue}if(I.positionals==="tail"){ve.push(...q.slice(Le));break}ve.push(Fe)}if(I.positionals!=="list"&&I.positionals!=="tail")Pe.push(...ve.map((Le)=>`Unexpected argument for ${I.label}: ${Le}`));return{flags:re,values:le,lists:ye,positionals:ve,help:Ie,errors:Pe}}function In(I){for(let q of I)console.error(q);return I.length>0}import{readdirSync as Sf,statSync as Qs,unlinkSync as Rf}from"node:fs";import{basename as ea,dirname as Ef,isAbsolute as Tf,join as Af,relative as _f,resolve as If,sep as Of}from"node:path";var Ys=(I)=>{let q=Date.now()-new Date(I).getTime();if(!Number.isFinite(q))return"";let Q=Math.floor(q/60000),ne=Math.floor(Q/60),te=Math.floor(ne/24);if(te>0)return`${te}d ago`;if(ne>0)return`${ne}h ago`;if(Q>0)return`${Q}m ago`;return"just now"},Jo=(I)=>{let q=(I??"").trim().split(/\s+/).filter((te)=>te&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(te)),Q=q[0]?.split("/").pop();if(!Q)return null;let ne=q[1];return ne&&/^[a-z][a-z0-9-]*$/.test(ne)?`${Q} ${ne}`:Q};function Zs(I){let q=(te)=>`${te.sessionId}
2
2
  ${Jo(te.segment||te.command)}`,Q=I.filter((te)=>te.decision!=="allow"),ne=Q.filter((te)=>te.sessionId).reduce((te,re)=>te.set(q(re),(te.get(q(re))??0)+1),new Map);return new Set(Q.filter((te)=>te.failureStage||(ne.get(q(te))??0)>=2))}import{existsSync as bf,readdirSync as wf,readFileSync as kf}from"node:fs";import{join as Cf}from"node:path";function Jn(I,q){try{return wf(I,{withFileTypes:!0,encoding:"utf8"}).flatMap((Q)=>{let ne=Cf(I,Q.name);if(Q.isDirectory())return Jn(ne,q);if(Q.name.endsWith(".jsonl"))return[ne];return[]})}catch{if(q&&bf(I))q.count++;return[]}}var xf=["segment","reason","sessionId","decision","agent","ruleId","failureStage"];function Pf(I){if(!I||typeof I!=="object"||Array.isArray(I))return!1;let q=I;if(typeof q.ts!=="string"||typeof q.command!=="string")return!1;return xf.every((Q)=>q[Q]===void 0||typeof q[Q]==="string")}function Ht(I,q){try{return kf(I,"utf-8").split(`
3
3
  `).filter(Boolean).flatMap((Q)=>{try{let ne=JSON.parse(Q);if(!Pf(ne)){if(q)q.count++;return[]}return[ne]}catch{if(q)q.count++;return[]}})}catch{if(q)q.count++;return[]}}function mn(I){return Array.from(I,(q)=>{let Q=q.charCodeAt(0);if(Q<=31||Q>=127&&Q<=159)return`\\x${Q.toString(16).padStart(2,"0")}`;return q}).join("")}function $f(I,q){let Q=ue(I),ne=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"]}},q);if(In(ne.errors))return null;if(ne.values.id!==void 0&&!/^[a-f0-9]{16}$/.test(ne.values.id))return console.error("--id must be 16 hexadecimal characters"),null;let te=ne.values.limit===void 0?20:Xs(ne.values.limit);if(te===null)return console.error("--limit must be a positive number"),null;let re=ne.values.since===void 0?Math.min(30,Q):Xs(ne.values.since);if(re===null||re>Q)return console.error(`--since must be a positive number of days no greater than ${Q}`),null;let le={limit:te,limitExplicit:ne.values.limit!==void 0,since:re,sinceExplicit:ne.values.since!==void 0,all:ne.flags.all,json:ne.flags.json,suspect:ne.flags.suspect,pruneLegacy:ne.flags.pruneLegacy,dryRun:ne.flags.dryRun,id:ne.values.id,agent:ne.values.agent,rule:ne.values.rule,session:ne.values.session,project:ne.values.project===void 0?void 0:If(ne.values.project)};if(le.id&&(le.agent!==void 0||le.rule!==void 0||le.session!==void 0||le.project!==void 0||le.suspect||le.sinceExplicit||le.limitExplicit))return console.error("--id cannot be combined with --agent, --rule, --session, --project, --suspect, --since, or --limit"),null;if(le.pruneLegacy&&(le.id!==void 0||le.agent!==void 0||le.rule!==void 0||le.session!==void 0||le.project!==void 0||le.suspect||le.all||le.sinceExplicit||le.limitExplicit))return console.error("--prune-legacy cannot be combined with --id, --agent, --rule, --session, --project, --suspect, --all, --since, or --limit"),null;if(le.dryRun&&!le.pruneLegacy)return console.error("--dry-run requires --prune-legacy"),null;return le}async function na(I,q,Q={}){let ne=$f(I,q);if(!ne)return 1;let te=Q.logsDir??W(I);if(ne.pruneLegacy)return Df(te,ne.json,ne.dryRun);if(!te)return console.log(ne.json?"[]":ne.id?`No retained audit log entry found for id ${mn(ne.id)}.`:"No audit log entries found."),0;ee(I,te);let re={count:0},le=Jn(te,re).flatMap(($e)=>Ht($e,re).map((Le)=>({entry:Le,file:$e})));if(re.count>0)console.error(`warning: ${re.count} audit log ${re.count===1?"source":"sources"} could not be read; these results are incomplete`);if(ne.id)return Ff(le,ne,Q.timeZone);let ye=Date.now()-ne.since*24*60*60*1000,ve=le.filter(($e)=>Hf($e,ne,te,ye)),Pe=ne.suspect?Zs(ve.map(($e)=>$e.entry)):null,Ie=(Pe?ve.filter(($e)=>Pe.has($e.entry)):ve).sort(($e,Le)=>Date.parse(Le.entry.ts)-Date.parse($e.entry.ts)).slice(0,ne.limit);if(ne.json)return console.log(JSON.stringify(Ie.map(($e)=>$e.entry),null,2)),0;if(Ie.length===0)return console.log("No audit log entries found."),0;for(let $e of Ie)console.log(Bf($e.entry,Q.timeZone));return 0}function Df(I,q,Q){let ne=I?Lf(I).map((ye)=>Af(I,ye)):[];if(Q)return Nf(ne,q);let te=[],re=0,le=0;for(let ye of ne){let ve=Qs(ye,{throwIfNoEntry:!1})?.size??0,Pe=jf(ye);if(Pe){te.push(`${ea(ye)}: ${Pe}`);continue}re++,le+=ve}if(q)return console.log(JSON.stringify({removedFiles:re,removedBytes:le,failedFiles:te.length})),te.length===0?0:1;console.log(re===0&&te.length===0?"No legacy audit log files found.":`Removed ${re} legacy audit log ${re===1?"file":"files"} (${ta(le)}).`);for(let ye of te)console.error(`Could not remove ${mn(ye)}`);if(console.log("Nested v2 audit logs were not changed."),re>0)console.log("This deletion cannot be undone.");return te.length===0?0:1}function Nf(I,q){let Q=I.reduce((ne,te)=>ne+(Qs(te,{throwIfNoEntry:!1})?.size??0),0);if(q)return console.log(JSON.stringify({dryRun:!0,files:I.length,bytes:Q})),0;if(console.log(I.length===0?"No legacy audit log files found.":`Would remove ${I.length} legacy audit log ${I.length===1?"file":"files"} (${ta(Q)}).`),console.log("Nested v2 audit logs are not included."),I.length>0)console.log("Run the same command without --dry-run to delete them.");return 0}function Lf(I){try{return Sf(I,{withFileTypes:!0}).filter((q)=>q.isFile()&&q.name.endsWith(".jsonl")).map((q)=>q.name)}catch{return[]}}function jf(I){try{return Rf(I),null}catch(q){return q instanceof Error?q.message:String(q)}}function ta(I){let q=["B","KiB","MiB","GiB"],Q=Math.min(Math.floor(Math.log2(Math.max(I,1))/10),q.length-1);return`${Math.round(I/1024**Q*10)/10} ${q[Q]}`}function Ff(I,q,Q){let ne=I.filter((re)=>re.entry.id===q.id);if(ne.length>1)return console.error(`Multiple audit log entries found for id ${mn(q.id??"")}.`),1;if(q.json)return console.log(JSON.stringify(ne.map((re)=>re.entry),null,2)),0;let te=ne[0];if(!te)return console.log(`No retained audit log entry found for id ${mn(q.id??"")}.`),0;return console.log(Gf(te.entry,Q)),0}function Hf(I,q,Q,ne){if(!q.all&&I.entry.decision==="allow")return!1;if(Date.parse(I.entry.ts)<ne)return!1;if(q.agent!==void 0&&I.entry.agent!==q.agent)return!1;if(q.rule!==void 0&&I.entry.ruleId!==q.rule)return!1;if(q.session!==void 0&&!Mf(I,Q,q.session))return!1;if(q.project!==void 0&&!Uf(I.entry.cwd,q.project))return!1;return!0}function Mf(I,q,Q){if(I.entry.sessionId===Q)return!0;return Ef(I.file)===q&&ea(I.file,".jsonl")===Q}function Uf(I,q){if(!I)return!1;let Q=_f(q,I);return Q!==".."&&!Q.startsWith(`..${Of}`)&&!Tf(Q)}function Bf(I,q){let Q=mn(I.id??"-"),ne=mn(I.decision??"deny"),te=I.cwd?` [${mn(I.cwd)}]`:"",re=I.segment||I.command,le=re===I.command?"":"↳ ",ye=re.length>50?`${re.slice(0,50)}…`:re;return`${Q.padEnd(16)} ${mn(ra(I.ts,q))} ${ne.padEnd(5)} ${mn(I.agent??"-").padEnd(15)} ${mn(I.ruleId??"-").padEnd(20)} ${le}${mn(ye)}${te}`}function Gf(I,q){let Q=(te)=>mn(te===void 0||te===null||te===""?"-":te),ne=I.shape?`${I.agent??"-"} (shape: ${I.shape})`:I.agent??"-";return[`id: ${Q(I.id)}`,`ts: ${Q(ra(I.ts,q))}`,`decision: ${Q(I.decision)}`,`agent: ${Q(ne)}`,`level: ${Q(I.level)}`,`tool: ${Q(I.toolName)}`,`rule: ${Q(I.ruleId)}`,`intent: ${Q(I.intent)}`,`stage: ${Q(I.failureStage)}`,`error: ${Q(I.errorCode)}`,`session: ${Q(I.sessionId)}`,`cwd: ${Q(I.cwd)}`,`version: ${Q(I.v)}`,`truncated: ${Q(I.truncated===!0?"yes":void 0)}`,`reason: ${Q(I.reason)}`,`command: ${Q(I.command)}`,`segment: ${Q(I.segment)}`].join(`
4
4
  `)}function ra(I,q){let Q=new Date(I);if(Number.isNaN(Q.getTime()))return I;return new Intl.DateTimeFormat("sv-SE",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23",timeZone:q}).format(Q)}function Xs(I){let q=Number(I);return Number.isFinite(q)&&q>0?q:null}var oa={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 ia={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:"--shell",argument:"<auto|posix|powershell>",description:"Parse the command as this shell (default: auto)"},{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"',"cc-safety-net explain --shell posix 'rmdir /s /q d:\\'"]};var sa={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 zo=["npx","--offline","--no-install","@deepseek-ai/dsh","--version"],aa=["cursor-agent","--version"],la=[{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:zo}},{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"]}}],Wo=la.slice().sort((I,q)=>I.displayName.localeCompare(q.displayName,"en")),Or=Wo.map((I)=>I.id).sort((I,q)=>Number(q==="claude-code")-Number(I==="claude-code")),ir=Wo.filter((I)=>("runtime"in I)).map((I)=>({id:I.id,displayName:"displayName"in I.runtime?I.runtime.displayName:I.displayName,flags:I.runtime.flags,legacyFlags:"legacyFlags"in I.runtime?I.runtime.legacyFlags:[],description:I.runtime.description,legacyTopLevelFlags:I.runtime.legacyTopLevelFlags})),xn=Wo.map((I)=>({id:I.id,...I.install})),qf=Object.fromEntries(la.map((I)=>[I.id,I.displayName]));function cn(I){return qf[I]}var Vf=ir.map((I)=>({flags:I.flags.join(", "),description:I.description})),Kf=ir.flatMap((I)=>I.flags.map((q)=>`cc-safety-net hook ${q}`)),ca={name:"hook",description:"Run as an agent CLI hook (reads JSON from stdin)",usage:"hook INTEGRATION_FLAG",options:[...Vf,{flags:"-h, --help",description:"Show this help"}],examples:Kf};var da={name:"install",description:"Install CC Safety Net into a coding agent CLI",usage:"install [TARGET_FLAG]",options:[...xn.map((I)=>({flags:I.flag,description:`Install ${cn(I.id)} ${I.artifactKind}`})),{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net install",...xn.map((I)=>`cc-safety-net install ${I.flag}`)]},ua={name:"uninstall",description:"Uninstall CC Safety Net from a coding agent CLI",usage:"uninstall [TARGET_FLAG]",options:[...xn.map((I)=>({flags:I.flag,description:`Uninstall ${cn(I.id)} ${I.artifactKind}`})),{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net uninstall",...xn.map((I)=>`cc-safety-net uninstall ${I.flag}`)]},pa={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 fa={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 $r={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 Yo=[{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"}],Zo=["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"],Mt={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> | --no-cwd-arg] [--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"},{flags:"--no-cwd-arg",description:"Read no working-directory argument with rule tool add, for a remote tool"},...Yo.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","cc-safety-net rule tool add phone_shell --no-cwd-arg",...Zo,"cc-safety-net rule update","cc-safety-net rule migrate --cleanup","cc-safety-net rule verify"]};var ma={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 ga={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 Dr=[ma,oa,fa,ia,Mt,$r,da,pa,ua,ca,sa,ga];function Jf(I){return I.aliases??[]}function Nr(I){let q=I.toLowerCase();return Dr.find((Q)=>Q.name.toLowerCase()===q||Jf(Q).some((ne)=>ne.toLowerCase()===q))}import{existsSync as Dy}from"node:fs";import{basename as zf}from"node:path";function Lr(I,q=7,Q=W(I)){let ne=Date.now()-q*24*60*60*1000,te=[],re=new Set,le=0,ye,ve,Pe,Ie;if(Q)ee(I,Q);let $e={count:0},Le=Q?Jn(Q,$e):[];for(let Ne of Le)for(let Be of Ht(Ne,$e)){if(Be.decision==="allow")continue;let Me=new Date(Be.ts).getTime();if(Me>=ne){if(le++,re.add(Be.sessionId??zf(Ne,".jsonl")),ve===void 0||Me<=ve)ye=Be.ts,ve=Me;if(Ie===void 0||Me>Ie)Pe=Be.ts,Ie=Me;Wf(te,Be,Me)}}let Fe=te.map((Ne)=>({timestamp:Ne.ts,command:Ne.command,reason:Ne.reason,relativeTime:Ys(new Date(Ne.ts))}));return{totalBlocked:le,sessionCount:re.size,recentEntries:Fe,oldestEntry:ye,newestEntry:Pe,unreadable:$e.count}}function Wf(I,q,Q){let ne=I.findIndex((te)=>Q>new Date(te.ts).getTime());if(ne===-1){if(I.length<3)I.push(q);return}if(I.splice(ne,0,q),I.length>3)I.pop()}import{dirname as am}from"node:path";import{dirname as Yf,join as Zf,resolve as Xf}from"node:path";var Qf="config.json";function yn(I,q,Q,ne){v(em(I),`${JSON.stringify(q,null,2)}
@@ -18,7 +18,7 @@ ${Jo(te.segment||te.command)}`,Q=I.filter((te)=>te.decision!=="allow"),ne=Q.filt
18
18
  `)}function Fr(I){return zn({rows:I})}function $a(I){let q=[];return q.push("System Info"),q.push(Im(I)),q.join(`
19
19
  `)}function Im(I){let q=["Component","Version"],Q=(re)=>{if(re===null)return Ve.dim("not found");return re},te=[{label:"cc-safety-net",value:I.version},...Or.map((re)=>({label:cn(re),value:I.versions[re]??null})),{label:"Node.js",value:I.nodeVersion},{label:"npm",value:I.npmVersion},{label:"Bun",value:I.bunVersion},{label:"Platform",value:I.platform}].map((re)=>[re.label,Q(re.value)]);return zn({headers:q,rows:te})}function Da(I){if(I.findings.length===0)return Ve.green(`
20
20
  No findings from inspected doctor facts.`);let q={error:I.findings.filter((re)=>re.severity==="error").length,warning:I.findings.filter((re)=>re.severity==="warning").length,info:I.findings.filter((re)=>re.severity==="info").length},Q=["error","warning","info"].filter((re)=>q[re]>0).map((re)=>`${q[re]} ${re}`),ne=I.findings.length===1?"finding":"findings",te=`
21
- ${I.findings.length} ${ne}: ${Q.join(", ")}.`;if(q.error>0)return Ve.red(te);if(q.warning>0)return Ve.yellow(te);return Ve.blue(te)}import{lstatSync as Om}from"node:fs";import{dirname as ti}from"node:path";function ri(I,q){try{let Q=Om(q);if(Q.isSymbolicLink())return{kind:I,path:q,status:"unsafe",issues:["symlink"]};if(!Q.isDirectory())return{kind:I,path:q,status:"unsafe",issues:["not-directory"]};if(process.platform==="win32"||typeof process.getuid!=="function")return{kind:I,path:q,status:"unknown",issues:[]};let ne=[...Q.uid!==process.getuid()?["ownership"]:[],...(Q.mode&18)!==0?["permissions"]:[]];return{kind:I,path:q,status:ne.length>0?"unsafe":"safe",issues:ne}}catch(Q){if(typeof Q==="object"&&Q!==null&&"code"in Q&&Q.code==="ENOENT")return{kind:I,path:q,status:"not-applicable",issues:[]};return{kind:I,path:q,status:"unknown",issues:[]}}}function Na(I,q){let Q=W(I);return{directories:[ri("policy",ti(ti(q))),ri("config",ti(q)),...Q?[ri("audit",Q)]:[{kind:"audit",status:"unknown",issues:[]}]]}}import{spawn as $m}from"node:child_process";import{existsSync as La}from"node:fs";import{delimiter as Dm,extname as Nm,join as Lm}from"node:path";import{stripVTControlCharacters as ja}from"node:util";var Ha="2.7.5",jm=5000,Fm="_CC_SAFETY_NET_TEST_SPAWN_PLATFORM";function un(){return Ha}function oi(I,q){let Q=I[q];if(Q)return Q;let ne=Object.keys(I).find((te)=>te.toLowerCase()===q.toLowerCase()&&!!I[te]);return ne?I[ne]:Q}function Hm(I){return(oi(I,"PATHEXT")||".COM;.EXE;.BAT;.CMD").split(";").filter((q)=>q.length>0)}function Mm(I,q){let Q=Nm(I)?[I]:[...Hm(q).map((ne)=>`${I}${ne}`),I];if(I.includes("/")||I.includes("\\"))return Q.find((ne)=>La(ne))??I;return(oi(q,"PATH")??"").split(Dm).flatMap((ne)=>Q.map((te)=>Lm(ne,te))).find((ne)=>La(ne))??I}function Fa(I){if(!/[\s"&|<>^]/.test(I))return I;return`"${I.replace(/"/g,'""')}"`}function Wn(I,q){let[Q,...ne]=I,te=q[Fm]==="win32"?"win32":process.platform;if(!Q||te!=="win32")return{cmd:Q??"",args:ne};let re=Mm(Q,q);if(!/\.(?:bat|cmd)$/i.test(re))return{cmd:re,args:ne};return{cmd:oi(q,"COMSPEC")??"cmd.exe",args:["/d","/c",["call",Fa(re),...ne.map(Fa)].join(" ")]}}var Gt=async(I,q=jm)=>{let Q=await Um(I,{timeoutMs:q});if(Q.code!==0)return null;return ja(Q.stdout).trim()||ja(Q.stderr).trim()||null};function Um(I,q){let[Q,...ne]=I;if(!Q)return Promise.resolve({code:null,stdout:"",stderr:""});return new Promise((te)=>{try{let re=Wn([Q,...ne],process.env),le=$m(re.cmd,re.args,{stdio:["ignore","pipe","pipe"]}),ye=!1,ve="",Pe="";le.stdout.on("data",(Le)=>{ve+=Le.toString()}),le.stderr.on("data",(Le)=>{Pe+=Le.toString()});let Ie=(Le)=>{if(ye)return;ye=!0,clearTimeout($e),te(Le)},$e=setTimeout(()=>{le.kill(),Ie({code:null,stdout:ve,stderr:Pe})},q.timeoutMs);le.on("close",(Le)=>{Ie({code:Le,stdout:ve,stderr:Pe})}),le.on("error",()=>{Ie({code:null,stdout:ve,stderr:Pe})})}catch{te({code:null,stdout:"",stderr:""})}})}function Hr(I){if(!I)return null;let q=/Claude Code\s+(\d+\.\d+\.\d+)/i.exec(I);if(q)return q[1]??null;let Q=/v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)/i.exec(I);if(Q)return Q[1]??null;return I.split(`
21
+ ${I.findings.length} ${ne}: ${Q.join(", ")}.`;if(q.error>0)return Ve.red(te);if(q.warning>0)return Ve.yellow(te);return Ve.blue(te)}import{lstatSync as Om}from"node:fs";import{dirname as ti}from"node:path";function ri(I,q){try{let Q=Om(q);if(Q.isSymbolicLink())return{kind:I,path:q,status:"unsafe",issues:["symlink"]};if(!Q.isDirectory())return{kind:I,path:q,status:"unsafe",issues:["not-directory"]};if(process.platform==="win32"||typeof process.getuid!=="function")return{kind:I,path:q,status:"unknown",issues:[]};let ne=[...Q.uid!==process.getuid()?["ownership"]:[],...(Q.mode&18)!==0?["permissions"]:[]];return{kind:I,path:q,status:ne.length>0?"unsafe":"safe",issues:ne}}catch(Q){if(typeof Q==="object"&&Q!==null&&"code"in Q&&Q.code==="ENOENT")return{kind:I,path:q,status:"not-applicable",issues:[]};return{kind:I,path:q,status:"unknown",issues:[]}}}function Na(I,q){let Q=W(I);return{directories:[ri("policy",ti(ti(q))),ri("config",ti(q)),...Q?[ri("audit",Q)]:[{kind:"audit",status:"unknown",issues:[]}]]}}import{spawn as $m}from"node:child_process";import{existsSync as La}from"node:fs";import{delimiter as Dm,extname as Nm,join as Lm}from"node:path";import{stripVTControlCharacters as ja}from"node:util";var Ha="2.7.7",jm=5000,Fm="_CC_SAFETY_NET_TEST_SPAWN_PLATFORM";function un(){return Ha}function oi(I,q){let Q=I[q];if(Q)return Q;let ne=Object.keys(I).find((te)=>te.toLowerCase()===q.toLowerCase()&&!!I[te]);return ne?I[ne]:Q}function Hm(I){return(oi(I,"PATHEXT")||".COM;.EXE;.BAT;.CMD").split(";").filter((q)=>q.length>0)}function Mm(I,q){let Q=Nm(I)?[I]:[...Hm(q).map((ne)=>`${I}${ne}`),I];if(I.includes("/")||I.includes("\\"))return Q.find((ne)=>La(ne))??I;return(oi(q,"PATH")??"").split(Dm).flatMap((ne)=>Q.map((te)=>Lm(ne,te))).find((ne)=>La(ne))??I}function Fa(I){if(!/[\s"&|<>^]/.test(I))return I;return`"${I.replace(/"/g,'""')}"`}function Wn(I,q){let[Q,...ne]=I,te=q[Fm]==="win32"?"win32":process.platform;if(!Q||te!=="win32")return{cmd:Q??"",args:ne};let re=Mm(Q,q);if(!/\.(?:bat|cmd)$/i.test(re))return{cmd:re,args:ne};return{cmd:oi(q,"COMSPEC")??"cmd.exe",args:["/d","/c",["call",Fa(re),...ne.map(Fa)].join(" ")]}}var Gt=async(I,q=jm)=>{let Q=await Um(I,{timeoutMs:q});if(Q.code!==0)return null;return ja(Q.stdout).trim()||ja(Q.stderr).trim()||null};function Um(I,q){let[Q,...ne]=I;if(!Q)return Promise.resolve({code:null,stdout:"",stderr:""});return new Promise((te)=>{try{let re=Wn([Q,...ne],process.env),le=$m(re.cmd,re.args,{stdio:["ignore","pipe","pipe"]}),ye=!1,ve="",Pe="";le.stdout.on("data",(Le)=>{ve+=Le.toString()}),le.stderr.on("data",(Le)=>{Pe+=Le.toString()});let Ie=(Le)=>{if(ye)return;ye=!0,clearTimeout($e),te(Le)},$e=setTimeout(()=>{le.kill(),Ie({code:null,stdout:ve,stderr:Pe})},q.timeoutMs);le.on("close",(Le)=>{Ie({code:Le,stdout:ve,stderr:Pe})}),le.on("error",()=>{Ie({code:null,stdout:ve,stderr:Pe})})}catch{te({code:null,stdout:"",stderr:""})}})}function Hr(I){if(!I)return null;let q=/Claude Code\s+(\d+\.\d+\.\d+)/i.exec(I);if(q)return q[1]??null;let Q=/v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)/i.exec(I);if(Q)return Q[1]??null;return I.split(`
22
22
  `)[0]?.trim()||null}async function Mr(I,q=Gt,Q=process.cwd()){let ne=Promise.all(xn.map(async($e)=>[$e.id,Hr(await q([...$e.probeCommand]))])),[te,re,le,ye,ve,Pe,Ie]=await Promise.all([ne,ne.then(async($e)=>{let Le=$e.find(([Be])=>Be==="opencode")?.[1];if(!Le?.startsWith("2.")||!I(Le))return null;let Fe=["--param",`location[directory]=${Q}`],Ne=["opencode","api","integration.list",...Fe];return await q(Ne,30000),q(["opencode","api","plugin.list",...Fe],30000)}),q(["codex","plugin","list"],30000),q(["amp","plugins","list"],30000),q(["node","--version"]),q(["npm","--version"]),q(["bun","--version"])]);return{version:Ha,versions:Object.fromEntries(te),codexPluginListOutput:le,ampPluginListOutput:ye,openCodePluginListOutput:re,nodeVersion:Hr(ve),npmVersion:Hr(Pe),bunVersion:Hr(Ie),platform:`${process.platform} ${process.arch}`}}function ii(I,q){if(q==="dev")return!1;let Q=I.split(".").map(Number),ne=q.split(".").map(Number),[te=0,re=0,le=0]=Q,[ye=0,ve=0,Pe=0]=ne;if(te!==ye)return te>ye;if(re!==ve)return re>ve;return le>Pe}async function Mn(){let I=un(),q=new AbortController,Q=setTimeout(()=>q.abort(),3000);try{let ne=await fetch("https://registry.npmjs.org/cc-safety-net/latest",{signal:q.signal});if(!ne.ok)return{currentVersion:I,latestVersion:null,updateAvailable:!1,error:`npm registry returned ${ne.status}`};let te=await ne.json(),re=ii(te.version,I);return{currentVersion:I,latestVersion:te.version,updateAvailable:re}}catch(ne){return{currentVersion:I,latestVersion:null,updateAvailable:!1,error:ne instanceof Error?ne.message:"Network error"}}finally{clearTimeout(Q)}}import*as Ja from"node:readline";var Ga=(I)=>`\x1B[${I}B`,Bm=(I)=>`\x1B[${I}A`;var Ma=["░","▒","▓","╱","╲","┃","━","┏","┓","┗","┛","╋"];function Gm(I){return new Promise((q)=>setTimeout(q,I))}function qm(I,q,Q){if(!Q)return q(I);if(Q.aborted)return Promise.resolve();return new Promise((ne,te)=>{let re=()=>Q.removeEventListener("abort",le),le=()=>{re(),ne()};Q.addEventListener("abort",le,{once:!0}),q(I).then(()=>{re(),ne()},(ye)=>{re(),te(ye)})})}function Ur(I){return Math.max(0,Math.min(1,I))}function qt(I){return Math.max(0,Math.min(255,Math.round(I)))}function si(I){return I<=0.0031308?12.92*I:1.055*I**0.4166666666666667-0.055}function Vm(I,q,Q){let ne=Q*Math.PI/180,te=q*Math.cos(ne),re=q*Math.sin(ne),le=(I+0.3963377774*te+0.2158037573*re)**3,ye=(I-0.1055613458*te-0.0638541728*re)**3,ve=(I-0.0894841775*te-1.291485548*re)**3;return{blue:qt(si(Ur(-0.0041960863*le-0.7034186147*ye+1.707614701*ve))*255),green:qt(si(Ur(-1.2684380046*le+2.6097574011*ye-0.3413193965*ve))*255),red:qt(si(Ur(4.0767416621*le-3.3077115913*ye+0.2309699292*ve))*255)}}function ai(I,q){let Q=(q*I*180/Math.PI%360+360)%360;return Vm(0.72,0.15,Q)}function qa(I,q=0.1){let Q=ai(q,I);return`\x1B[38;2;${Q.red};${Q.green};${Q.blue}m`}function Km(I,q){return{blue:qt(I.blue+(255-I.blue)*q),green:qt(I.green+(255-I.green)*q),red:qt(I.red+(255-I.red)*q)}}function Va(I,q,Q){let ne=Math.imul(I+2654435769,2246822507)^Math.imul(q+3266489909,668265263)^Math.imul(Q+374761393,2654435761),te=ne^ne>>>15,re=Math.imul(te,739982445),le=re^re>>>12,ye=Math.imul(le,695872825);return((ye^ye>>>15)>>>0)/4294967296}function Jm(I,q,Q){let ne=Math.floor(Va(I,q,Q)*Ma.length);return Ma[ne]??"░"}function Ua(I){let q=Ur(I);return q*q*q*(q*(q*6-15)+10)}function zm(I){if(I.length===0)return"";let q=[],Q=!1,ne="";for(let te of I){let re=`${te.red};${te.green};${te.blue}`;if(te.bold!==Q)q.push(te.bold?"\x1B[1m":"\x1B[22m"),Q=te.bold;if(re!==ne)q.push(`\x1B[38;2;${re}m`),ne=re;q.push(te.character)}return`${q.join("")}\x1B[22m\x1B[39m`}function Wm(I,q,Q,ne,te){return I.map((re,le)=>({...ai(Q,ne+q+le/te),bold:!1,character:re}))}function Ym(I,q,Q,ne,te,re,le,ye){let ve=Math.max(1,ne*0.75),Pe=Math.min(1,Q/ve),Ie=te*Ua(Pe),$e=Math.max(0,(Q-ve)/Math.max(1,ne-ve)),Le=(1-Ua(Q/ne))*ye*2,Fe=0.35*Math.max(0,1-$e*2),Ne=Pe>=1,Be=Math.min(I.length,Math.ceil(Ie+2+1));return I.slice(0,Be).map((Me,tn)=>{let en=ai(re,le+q+tn/ye+Le),on=tn+Va(q,tn,7919)*2-1;if(on>Ie+2)return{...en,bold:!1,character:" "};let ln=Ie-on,nn=0.8*Math.exp(-(ln*ln)/12.5),sn=Math.min(0.9,nn+Fe),Sn=!Ne&&on>Ie-4;return{...Km(en,sn),bold:sn>0.3,character:Sn?Jm(q,tn,Q):Me}})}function Ba(I){return`\x1B[?2026h${I.map((q,Q)=>`\x1B8${Q>0?Ga(Q):""}${zm(q)}`).join("")}\x1B[?2026l`}async function li(I,q={}){if(!I)return;let Q=q.output??process.stdout,ne=q.sleep??Gm,te=q.seed??0,re=I.split(`
23
23
  `).map((Ie)=>Array.from(Ie)),le=Math.max(...re.map((Ie)=>Ie.length)),ye=12000*re.filter((Ie)=>Ie.length>0).length/40,ve=le>0?Math.max(1,Math.ceil(ye/16.666666666666668)):0,Pe=ve>0?ye/ve:0;Q.write(`\x1B[?25l${re.length>1?`${`
24
24
  `.repeat(re.length-1)}${Bm(re.length-1)}`:""}\x1B7`);try{for(let Ie=1;Ie<=ve;Ie+=1){if(q.signal?.aborted)break;Q.write(Ba(re.map(($e,Le)=>Ym($e,Le,Ie,ve,le,0.1,te,3)))),await qm(Pe,ne,q.signal)}}finally{if(Q.write(Ba(re.map((Ie,$e)=>Wm(Ie,$e,0.1,te,3)))),Q.write("\x1B8"),re.length>1)Q.write(Ga(re.length-1));Q.write(`
@@ -227,7 +227,7 @@ def register(ctx):
227
227
  `));return{path:te[0]??Q??Tn(Qi(I),Xi[0]),alreadyInstalled:te.length>0}}function Xt(I){let q=[];for(let Q of I.openCodeVersion?.startsWith("2.")?es(I.environment):ns(I.environment))if(xy(Q))try{let ne=Py(Q,"utf-8"),te=gn(ne),re=JSON.parse(te);if(os(re)){let le=ts(I.openCodePluginListOutput);if(le)return{platform:"opencode",status:"disabled",method:"opencode api plugin.list",configPath:Q,errors:[...q,le]};return{platform:"opencode",status:"configured",method:"plugin array",configPath:Q,errors:q.length>0?q:void 0}}}catch(ne){q.push(`Failed to parse ${Sy(Q)}: ${ne instanceof Error?ne.message:String(ne)}`)}return{platform:"opencode",status:"n/a",errors:q.length>0?q:void 0}}import{join as Wc}from"node:path";var Zc="dist/pi/index.js",Yc=new Set([Zc,"index.js"]),Ry=/[*?[\]{}]/;function is(I){let q=I.env.get("PI_CODING_AGENT_DIR");return Wc(q?B(q,I.home):Wc(I.home,".pi","agent"),"settings.json")}function ss(I){if(typeof I!=="string")return!1;return I==="npm:cc-safety-net"||I.startsWith("npm:cc-safety-net@")}function Ey(I){if(!Array.isArray(I)||I.length===0)return!1;if(!I.every((ne)=>typeof ne==="string"))return!1;let q=(ne)=>I.some((te)=>te.startsWith(ne)&&te.slice(1).replace(/^\.[/\\]/,"")===Zc);if(q("-"))return!1;if(q("+"))return!0;let Q=I.filter((ne)=>!/^[-+!]/.test(ne));return(Q.length===0||Q.some((ne)=>Yc.has(ne)))&&!I.some((ne)=>ne.startsWith("!")&&(Yc.has(ne.slice(1))||Ry.test(ne)))}function Xc(I){let q=is(I.environment),Q=b(q);if(Q.kind==="unreadable")return{platform:"pi",status:"not-inspected"};if(Q.kind==="missing")return{platform:"pi",status:"n/a"};let ne=n(Q.value,"packages");if(!Array.isArray(ne))return{platform:"pi",status:"n/a"};let te=ne.find((le)=>ss(typeof le==="string"?le:n(le,"source")));if(te===void 0)return{platform:"pi",status:"n/a"};let re=n(te,"extensions");if(re!==void 0&&!Ey(re))return{platform:"pi",status:"disabled",method:"package config",configPath:q,errors:["npm:cc-safety-net is installed but its extension is disabled in Pi settings"]};return{platform:"pi",status:"configured",method:"package config",configPath:q}}var Ty={amp:rl,"antigravity-cli":al,"claude-code":pl,codex:ml,"copilot-cli":Ol,cursor:Ul,"deepseek-harness":Rt,devin:Wl,droid:rc,"gemini-cli":oc,"grok-build":mc,"hermes-agent":Rc,"kimi-code":ho,openclaw:Mc,opencode:Xt,pi:Xc};function Qt(I,q,Q){let ne={...Q,cwd:q,environment:I};return Or.map((te)=>Ay(Ty[te](ne)))}function Ay(I){if(I.status==="not-inspected")return{platform:I.platform,detected:!1,configured:!1,inspectionStatus:"not-inspected"};return{platform:I.platform,detected:I.status!=="n/a",configured:I.status==="configured",inspectionStatus:I.status!=="n/a"?"verified":I.errors&&I.errors.length>0?"failed":"not-applicable",method:I.method,configPath:I.configPath,configPaths:I.configPaths,errors:I.errors}}import{join as _y}from"node:path";var Iy=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}]),Oy=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([])})})}),$y={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 Qc(I){let q=_y(I.tmpdir,"cc-safety-net-self-test"),Q=Iy.map((ne)=>{let te=z(I,d("self-test",{command:ne.command},{kind:"command",shell:"auto"},{configCwd:q,executionCwd:q},ne.command),{guard:{dependencies:{loadPolicySnapshot:()=>Oy,getModes:()=>$y,findPolicyMutation:()=>null}},audit:{agent:"self-test",getSessionId:()=>{return}}}),re=ne.expectBlocked?"blocked":"allowed",le=te.decision.kind==="deny"?"blocked":"allowed";return{command:ne.command,description:ne.description,expected:re,actual:le,passed:re===le,reason:te.decision.kind==="deny"?te.decision.reason:void 0,ruleId:te.decision.kind==="deny"?te.decision.ruleId:void 0}});return{passed:Q.filter((ne)=>ne.passed).length,failed:Q.filter((ne)=>!ne.passed).length,total:Q.length,results:Q}}function as(I){let q=fn({label:"doctor",booleans:{json:["--json"],skipUpdateCheck:["--skip-update-check"]}},I);if(In(q.errors))return null;return{json:q.flags.json,skipUpdateCheck:q.flags.skipUpdateCheck}}async function ed(I,q={}){let Q=await ar(!q.json,()=>{let ne=Ny(I,q);return{ready:ne,finish:()=>ne}},()=>sr(),{loadingMessage:"Checking system status…"});if(q.json)console.log(JSON.stringify(Q,null,2));else Ly(Q);return Q.engineSelfTest.failed>0||Q.findings.some((ne)=>ne.severity==="error")?1:0}async function Ny(I,q){let Q=q.cwd??process.cwd(),ne=await Mr((Me)=>Xt({environment:I,cwd:Q,openCodeVersion:Me}).status!=="n/a",void 0,Q),te=Qt(I,Q,{ampPluginListOutput:ne.ampPluginListOutput,codexPluginListOutput:ne.codexPluginListOutput,copilotCliVersion:ne.versions["copilot-cli"],openCodeVersion:ne.versions.opencode,openCodePluginListOutput:ne.openCodePluginListOutput}),re=wa(I,Q),le=ka(I),ye=w(I,{cwd:Q}),ve=ye.policy,Pe=O(ve,I.env),Ie=X(ve,Pe.capabilities),$e=Lr(I,7),Le=Xa(I,Q),Fe=[Ut(Q),Bt(I)].filter((Me)=>Dy(Me)),Ne=q.skipUpdateCheck?{currentVersion:un(),latestVersion:null,updateAvailable:!1}:await Mn(),Be={hooks:te,engineSelfTest:Qc(I),userConfig:re.userConfig,projectConfig:re.projectConfig,configState:nt(ye),effectiveRules:re.effectiveRules,environment:le,effectiveSafety:{selectedPreset:ve.safety.level,level:Pe.effectiveLevel,capabilities:Pe.capabilities,ruleOverrides:ve.destructiveCommandRuleOverrides,weakenedRuleOverrides:Object.entries(Ie).filter(([,Me])=>Me.source==="rule_override"&&Me.override==="off"&&Me.inheritedEnabled&&Me.changesInherited).map(([Me])=>Me),ruleCounts:{stored:Object.keys(ve.destructiveCommandRuleOverrides).length,effective:Object.values(Ie).filter((Me)=>Me.changesInherited).length},...ye.policyScopes?{policyScopes:ye.policyScopes}:{}},...Le.length>0?{v2Leftovers:Le}:{},...Fe.length>0?{legacyConfigs:Fe}:{},posture:Na(I,re.userConfig.path),activity:$e,update:Ne,system:ne};return{...Be,findings:xa(Be)}}function Ly(I){console.log(),console.log(Sa(I.hooks)),console.log(),console.log(Ra(I.engineSelfTest)),console.log(),console.log(Ea(I)),console.log(),console.log(Ta(I.environment)),console.log(),console.log(Aa(I)),console.log(),console.log(_a(I.findings)),console.log(),console.log(Ia(I.activity)),console.log(),console.log($a(I.system)),console.log(),console.log(Oa(I.update)),console.log(Da(I))}import{existsSync as jy}from"node:fs";var Fy=/^[A-Za-z0-9_@%+=:,./-]+$/,ls="Usage: cc-safety-net explain [--json] [--cwd <path>] [--shell <auto|posix|powershell>] <command>",Hy=["auto","posix","powershell"];function cs(I){let q=fn({label:"explain",booleans:{json:["--json"]},values:{cwd:["--cwd"],shell:["--shell"]},positionals:"tail"},I);if(In(q.errors))return console.error(ls),console.error("Pass -- before a command that starts with dashes."),null;if(q.values.cwd!==void 0&&!jy(q.values.cwd))return console.error(`Error: --cwd path does not exist: ${q.values.cwd}`),null;let Q=Hy.find((te)=>te===q.values.shell);if(q.values.shell!==void 0&&!Q)return console.error(`Error: --shell must be auto, posix, or powershell, got: ${q.values.shell}`),console.error(ls),null;let ne=q.positionals.length===1?q.positionals[0]:q.positionals.map((te)=>Fy.test(te)?te:`'${te.replaceAll("'",Q==="powershell"?"''":"'\\''")}'`).join(" ");if(!ne)return console.error("Error: No command provided"),console.error(ls),null;return{json:q.flags.json,cwd:q.values.cwd,shell:Q,command:ne}}function nd(I){if(I)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 td(I,q){let ne=q-18;return[`${I.dtl}${I.dh.repeat(q)}${I.dtr}`,`${I.dv} Command Analysis${" ".repeat(ne)}${I.dv}`,`${I.dbl}${I.dh.repeat(q)}${I.dbr}`]}function ds(I){return JSON.stringify(I)}function rd(I,q=0){return`[${I.map((ne,te)=>Pa(ne,te,q)).join(",")}]`}function br(I,q,Q=70){let ne=I.split(" "),te=[],re="";for(let le of ne)if(re&&re.length+le.length+1>Q)te.push(re),re=le;else re=re?`${re} ${le}`:le;if(re)te.push(re);return te.map((le,ye)=>ye===0?le:`${q}${le}`)}function od(I,q,Q){let ne=[];switch(I.type){case"parse":return null;case"env-strip":return ne.push(""),ne.push(`STEP ${q} ${Q.h} Strip environment variables`),ne.push(` Removed: ${I.envVars.map((te)=>`${te}=<redacted>`).join(", ")}`),ne.push(` Tokens: ${ds(I.output)}`),{lines:ne,incrementStep:!0};case"leading-tokens-stripped":return ne.push(""),ne.push(`STEP ${q} ${Q.h} Strip wrappers`),ne.push(` Removed: ${I.removed.join(", ")}`),ne.push(` Tokens: ${ds(I.output)}`),{lines:ne,incrementStep:!0};case"shell-wrapper":return ne.push(""),ne.push(`STEP ${q} ${Q.h} Detect shell wrapper`),ne.push(` Wrapper: ${I.wrapper} -c`),ne.push(` Inner: ${I.innerCommand}`),{lines:ne,incrementStep:!0};case"interpreter":{if(ne.push(""),ne.push(`STEP ${q} ${Q.h} Detect interpreter`),ne.push(` Interpreter: ${I.interpreter}`),ne.push(` Code: ${I.codeArg}`),I.paranoidBlocked)ne.push(" Result: ✗ BLOCKED (paranoid mode)");return{lines:ne,incrementStep:!0}}case"busybox":return ne.push(""),ne.push(`STEP ${q} ${Q.h} Busybox wrapper`),ne.push(` Subcommand: ${I.subcommand}`),{lines:ne,incrementStep:!0};case"transparent-wrapper":return ne.push(""),ne.push(`STEP ${q} ${Q.h} Transparent wrapper`),ne.push(` Wrapper: ${I.wrapper}`),ne.push(` Tokens: ${ds(I.output)}`),{lines:ne,incrementStep:!0};case"recurse":return{lines:[],incrementStep:!1};case"script-file":return ne.push(""),ne.push(`STEP ${q} ${Q.h} Read script file`),ne.push(` Path: ${I.path}`),ne.push(` Size: ${I.bytes} bytes`),{lines:ne,incrementStep:!0};case"rule-check":{if(ne.push(""),ne.push(`STEP ${q} ${Q.h} Match rules`),ne.push(` Rule: ${I.rule}()`),I.matched)ne.push(" Result: MATCHED");else ne.push(" Result: No match");return{lines:ne,incrementStep:!0}}case"worktree-relaxation":return ne.push(""),ne.push(`STEP ${q} ${Q.h} Worktree relaxation`),ne.push(` Mode: ${r.worktree.name}`),ne.push(` Git cwd: ${I.gitCwd}`),ne.push(" Result: Allowed local discard in linked worktree"),{lines:ne,incrementStep:!0};case"temp-root-relaxation":return ne.push(""),ne.push(`STEP ${q} ${Q.h} Temp-root relaxation`),ne.push(` Git cwd: ${I.gitCwd}`),ne.push(" Result: Allowed git discard in a temp-root repository"),{lines:ne,incrementStep:!0};case"tmpdir-check":return null;case"fallback-scan":{if(I.embeddedCommandFound)return ne.push(""),ne.push(`STEP ${q} ${Q.h} Fallback scan`),ne.push(` Found: ${I.embeddedCommandFound}`),{lines:ne,incrementStep:!0};return null}case"custom-rules-check":{if(I.rulesChecked){if(ne.push(""),ne.push(`STEP ${q} ${Q.h} Custom rules`),I.matched)ne.push(" Result: MATCHED");else ne.push(" Result: No match");return{lines:ne,incrementStep:!0}}return null}case"cwd-change":return null;case"dangerous-text":{if(I.matched)return ne.push(""),ne.push(`STEP ${q} ${Q.h} Dangerous text check`),ne.push(` Token: ${I.token}`),ne.push(" Result: MATCHED"),{lines:ne,incrementStep:!0};return null}case"strict-unparseable":return ne.push(""),ne.push(`STEP ${q} ${Q.h} Strict mode check`),ne.push(` Command: ${I.rawCommand}`),ne.push(" Result: ✗ UNPARSEABLE"),{lines:ne,incrementStep:!0};case"segment-skipped":return null;case"error":return ne.push(""),ne.push(`ERROR: ${I.message}`),{lines:ne,incrementStep:!1};default:return I}}function us(I,q){let Q=nd(q?.asciiOnly??!1),ne=58,te=[],re=1;te.push(...td(Q,58)),te.push("");let le=I.trace.steps.find((Ne)=>Ne.type==="error");if(le&&le.type==="error"){te.push("ERROR"),te.push(` ${le.message}`),te.push(""),te.push("RESULT"),te.push(` Status: ${I.result==="blocked"?Ve.red("BLOCKED"):Ve.green("ALLOWED")}`),te.push(""),te.push("CONFIG");let Ne=I.configSource??"none";return te.push(` Path: ${Ne}`),te.join(`
228
228
  `)}let ye=I.trace.steps.find((Ne)=>Ne.type==="parse");if(ye&&ye.type==="parse"){te.push("INPUT"),te.push(` ${ye.input}`),te.push(""),te.push(`STEP ${re} ${Q.h} Split shell commands`),re++;for(let Ne=0;Ne<ye.segments.length;Ne++){let Be=ye.segments[Ne];if(Be){let Me=Math.random();te.push(` Segment ${Ne+1}: ${rd(Be,Me)}`)}}}let ve=I.trace.segments,Pe=ve.length>1;for(let Ne of ve){if(Pe){te.push("");let en="";if(ye&&ye.type==="parse"){let Ko=ye.segments[Ne.index];if(Ko)en=Ko.join(" ")}let on=54,ln=en,nn=` Segment ${Ne.index+1}: `,sn=" ";if(en){if(nn.length+en.length+sn.length>on){let yf=on-nn.length-sn.length;ln=`${en.substring(0,yf-1)}…`}}let Sn=en?`${nn}${ln}${sn}`:` Segment ${Ne.index+1} `,jt=en?`${nn}${Ve.cyan(ln)}${sn}`:Sn,zs=58-Sn.length,Ws=Math.floor(zs/2),hf=zs-Ws;te.push(`${Q.sh.repeat(Ws)}${jt}${Q.sh.repeat(hf)}`)}if(Ne.steps.find((en)=>en.type==="segment-skipped")){te.push(""),te.push(" (skipped — prior segment blocked)");continue}let Me=!1,tn=!1;for(let en of Ne.steps){let on=od(en,re,Q);if(on){if(tn=!0,en.type==="recurse"){te.push("");let ln=" RECURSING ",nn=58-ln.length-4;te.push(` ${Q.tl}${Q.h}${ln}${Q.h.repeat(nn)}`),te.push(` ${Q.v}`),Me=!0;continue}for(let ln of on.lines)if(Me)te.push(` ${Q.v} ${ln}`);else te.push(ln);if(on.incrementStep)re++}}if(Me)te.push(` ${Q.v}`),te.push(` ${Q.bl}${Q.h.repeat(56)}`);if(!tn)te.push(""),te.push(` ${Ve.green("✓")} Allowed (no matching rules)`)}if(te.push(""),te.push("RESULT"),I.result==="blocked"){if(te.push(` Status: ${Ve.red("BLOCKED")}`),I.customRule){if(te.push(` Rule: ${I.customRule.id}`),I.customRule.rulebook)te.push(` Rulebook: ${I.customRule.rulebook.name} ${I.customRule.rulebook.version}`);if(I.customRule.source)te.push(` Source: ${I.customRule.source}`);if(I.customRule.override)te.push(` Override: reason ${I.customRule.override.reason}`)}if(I.reason){let Ne=br(I.reason," ");te.push(` Reason: ${Ne[0]}`);for(let Be=1;Be<Ne.length;Be++)te.push(Ne[Be]??"")}}else te.push(` Status: ${Ve.green("ALLOWED")}`);te.push(""),te.push("CONFIG");let Ie=I.configSource??"none",$e=I.configValid?"":" (invalid)";te.push(` Path: ${Ie}${$e}`);let Le=I.safetyPresetScope;te.push(` Safety preset: ${I.selectedPreset??"standard"}${Le?` (${jr(Le)})`:""}`),te.push(` Effective capabilities: ${I.effectiveLevel}`);let Fe=Object.entries(I.destructiveCommandRuleOverrides??{});if(te.push(` Rule customizations: ${Fe.length}`),I.ruleActivation)te.push(` Rule activation: ${I.ruleActivation.id} — ${I.ruleActivation.enabled?"on":"off"} via ${I.ruleActivation.source}`);return te.join(`
229
229
  `)}function ps(I){return JSON.stringify(I,null,2)}import{resolve as Gy}from"node:path";var id=512,sd={maxTextLength:2048,maxListLength:128,maxObjectProperties:128,maxDepth:16},My=["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 gs(I){let q=0,Q={allocateSegment(){return q++},getNextSegmentIndex(){return q},branch(){let ne=I.fork(),te=gs(ne);return{trace:te,adopt(){I.replaceSegmentEvents(ne.finish().events),q=te.getNextSegmentIndex()}}},recordGlobal(ne){I.record({scope:"global",step:ne})},recordSegment(ne,te=Q.currentSegmentIndex){if(te===void 0)return;I.record({scope:"segment",segmentIndex:te,step:ne})}};return Q}function hs(I=new Set){let q=[];return{record(Q){if(q.length>=id)return;ko(Q.step,I,sd),q.push({...Q,step:fs(Q.step,sd,I)})},fork(){return hs(I)},replaceSegmentEvents(Q){q.splice(0,q.length,...[...q.filter((ne)=>ne.scope==="global"),...Q].slice(0,id))},finish(){return{events:q}}}}function ko(I,q,Q,ne=0,te=new WeakSet){if(typeof I==="string"){let ye=I.slice(0,Q.maxTextLength);if(!pt(ye))return;for(let ve of Pt(ye))for(let Pe of ve.match(/[^\s"'()$]+/g)??[])q.add(ad(Pe));return}if(!I||typeof I!=="object"||ne>=Q.maxDepth||te.has(I))return;if(te.add(I),Array.isArray(I)){let ye=Math.min(I.length,Q.maxListLength);for(let ve=0;ve<ye;ve++)ko(I[ve],q,Q,ne+1,te);return}let re=0,le=new Set;for(let ye in I){if(!Object.hasOwn(I,ye))continue;if(re>=Q.maxObjectProperties)break;re++,ko(ye,q,Q);let ve=ms(ye,Q,q);if(le.has(ve))continue;le.add(ve),ko(I[ye],q,Q,ne+1,te)}}function fs(I,q,Q,ne=0,te=new WeakSet){if(typeof I==="string")return ms(I,q,Q);if(!I||typeof I!=="object")return I;if(ne>=q.maxDepth)return;if(te.has(I))return;if(te.add(I),Array.isArray(I)){let ye=[],ve=Math.min(I.length,q.maxListLength);for(let Pe=0;Pe<ve;Pe++)ye.push(fs(I[Pe],q,Q,ne+1,te));return ye}let re={},le=0;for(let ye in I){if(!Object.hasOwn(I,ye))continue;if(le>=q.maxObjectProperties)break;le++;let ve=ms(ye,q,Q);if(Object.hasOwn(re,ve))continue;Object.defineProperty(re,ve,{value:fs(I[ye],q,Q,ne+1,te),enumerable:!0,configurable:!0,writable:!0})}return re}function ms(I,q,Q){let ne=I.slice(0,q.maxTextLength),te=pt(ne)?dt(ne):ne,re=Q.size>0?By(te,Q):te;return(Uy(re)?qe(re):re).slice(0,q.maxTextLength)}function Uy(I){return I.includes("PRIVATE KEY")||I.includes("://")||I.includes("eyJ")||I.includes(":")&&/(?:authorization|cookie|x-api-key|api-key|(?:^|\s)(?:-u|--user)(?:\s|=))/i.test(I)||I.length>=14&&My.some((q)=>I.includes(q))||I.length>=49&&/\b[a-f0-9]{32}\.[A-Za-z0-9]{16}\b/.test(I)}function By(I,q){return I.replace(/[^\s"'()$]+/g,(Q)=>q.has(ad(Q))?"<redacted>":Q)}function ad(I){let q=2166136261,Q=2166136261;for(let ne=0;ne<I.length;ne++)q=Math.imul(q^I.charCodeAt(ne),16777619),Q=Math.imul(Q^I.charCodeAt(I.length-ne-1),16777619);return`${q>>>0}:${Q>>>0}:${I.length}`}function wr(I,q={},Q){let ne=Gy(q.cwd??process.cwd()),te=q.policySnapshot??w(Q,{cwd:ne,userConfigDir:q.userConfigDir}),re=O(te.policy,Q.env),le=_e({policySnapshot:te,effectiveCapabilities:re.capabilities,worktreeMode:re.worktreeMode}),ye={effectiveLevel:le.effectiveLevel,selectedPreset:te.policy.safety.level,...te.policyScopes?{safetyPresetScope:te.policyScopes.levelScope}:{},effectiveCapabilities:le.effectiveCapabilities,destructiveCommandRuleOverrides:te.policy.destructiveCommandRuleOverrides},{configSource:ve,configValid:Pe}=Vy(Q,{cwd:ne,userConfigDir:q.userConfigDir});if(!I||!I.trim())return{trace:{steps:[{type:"error",message:"No command provided"}],segments:[]},result:"allowed",configSource:ve,configValid:Pe,...ye};let Ie=q.shell??"auto",$e=C(I,Ie);if($e.status==="limited")throw new E;let Le=$e.dialect==="powershell"?C(I,"posix"):$e,Fe=Ft(Le),Ne=hs(),Be=gs(Ne);Be.recordGlobal({type:"parse",input:I,segments:Fe.map((jt)=>[...jt])});let Me=d("Bash",{command:I},{kind:"command",shell:Ie},{configCwd:ne,executionCwd:ne},I),tn=G(Me,{environment:Q,trace:Be,dependencies:{loadPolicySnapshot:()=>te}}),en=tn.decision.kind==="deny"?tn.decision:null;if(en&&(tn.stage==="policy-protection"||tn.stage==="secret-protection"))return{trace:{steps:[],segments:[{index:0,steps:[{type:"rule-check",rule:qy(en),matched:!0,reason:en.reason}]}]},result:"blocked",reason:A(en.reason),segment:A(ld(en,I)),ruleId:A(en.ruleId),configSource:ve,configValid:Pe,...ye};let on=Be.getNextSegmentIndex();if(en&&on>0&&on<Fe.length)Be.recordSegment({type:"segment-skipped",index:on,reason:"prior-segment-blocked"},on);let ln=Ne.finish(),nn=en?.ruleId??Ky(Me,te,re,Q),sn=Z.find((jt)=>jt.id===nn&&jt.activationCapability),Sn=sn?le.policy.effectiveDestructiveCommandRules[sn.id]:void 0;return{trace:zy(ln),result:en?"blocked":"allowed",reason:en?A(en.reason):void 0,segment:en?A(ld(en,I)):void 0,ruleId:en?A(en.ruleId):void 0,customRule:Jy(Wy(en?.ruleId,te)),configSource:ve,configValid:Pe,...ye,...sn&&Sn?{ruleActivation:{id:sn.id,...Sn}}:{}}}function ld(I,q){return I.evidence?.segment??q}function qy(I){if(I.reason===ot)return"policy-protection:findPolicyConfigMutationTargetInSemanticFacts";if(I.reason===rt)return"policy-apply-protection:findPolicyApplyInvocationInSemanticFacts";if(I.reason===y)return"git-metadata-protection:findGitMetadataMutationTargetInSemanticFacts";return"secret-protection:findSensitiveTargetInSemanticFacts"}function Vy(I,q){let Q=D(q.cwd),ne=K(I,q),te=ie(I,{cwd:q.cwd,userConfigDir:q.userConfigDir});try{if(o(te.projectConfigTarget)!==null){if(Hn(te.projectConfigTarget).errors.length===0)return{configSource:Q,configValid:!0};return{configSource:Q,configValid:!1}}}catch(re){if(re instanceof i)return{configSource:Q,configValid:!1};throw re}try{if(o(te.userConfigTarget)!==null){let re=Hn(te.userConfigTarget);return{configSource:ne,configValid:re.errors.length===0}}return{configSource:null,configValid:!0}}catch(re){if(re instanceof i)return{configSource:ne,configValid:!1};throw re}}function Ky(I,q,Q,ne){let te=q.policy,re=Ge({...te,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{...te.destructiveCommandRuleOverrides,...Object.fromEntries(Z.flatMap((ye)=>ye.activationCapability?[[ye.id,"on"]]:[]))}},q.state==="degraded"?{diagnostics:q.diagnostics,reason:q.reason}:void 0),le=G(I,{environment:ne,dependencies:{loadPolicySnapshot:()=>re,getModes:()=>({...Q,strict:!0,paranoidRm:!0,paranoidInterpreters:!0,capabilities:{fail_closed:{...Q.capabilities.fail_closed,enabled:!0},paranoid_rm:{...Q.capabilities.paranoid_rm,enabled:!0},paranoid_interpreters:{...Q.capabilities.paranoid_interpreters,enabled:!0}}}),findSensitiveTarget:()=>null}});return le.decision.kind==="deny"?le.decision.ruleId:void 0}function Jy(I){if(!I)return;return{id:A(I.id),...I.rulebook?{rulebook:{name:A(I.rulebook.name),version:A(I.rulebook.version)}}:{},...I.source?{source:A(I.source)}:{},...I.override?{override:{type:"reason",reason:A(I.override.reason)}}:{}}}function zy(I){let q=I.events.flatMap((ne)=>ne.scope==="global"?[ne.step]:[]),Q=new Map;for(let ne of I.events){if(ne.scope!=="segment")continue;let te=Q.get(ne.segmentIndex)??{index:ne.segmentIndex,steps:[]};te.steps.push(ne.step),Q.set(ne.segmentIndex,te)}return{steps:q,segments:[...Q.values()]}}function Wy(I,q){let Q=I?.replace(/^custom\./,"");if(!Q||!q.policy.rules.some((ne)=>ne.name===Q))return;return q.ruleMetadata[Q]??Object.freeze({id:Q})}function cd(I){return new Promise((q)=>{process.stdout.write(`${I}
230
- `,()=>q())})}async function dd(I,q){let Q=cs(q);if(!Q)return 1;try{let ne=wr(Q.command,{cwd:Q.cwd,shell:Q.shell},I),te=!!process.env.NO_COLOR||!process.stdout.isTTY;return await cd(Q.json?ps(ne):us(ne,{asciiOnly:te})),0}catch(ne){let te=Yy(ne instanceof g?ne.cause:ne);if(te===void 0)throw ne;if(Q.json)return await cd(JSON.stringify({error:te})),1;return console.error(te),1}}function Yy(I){if(I instanceof E)return I.message;if(I instanceof H)return I.message;if(I instanceof h)return I.message;if(I instanceof a&&l[I.kind].errorCode==="path-canonicalization-limit")return"Path canonicalization work limit exceeded.";return}var ud="2.7.5",Pn=" ",bt="cc-safety-net";function pd(I){return I.argument?`${I.flags} ${I.argument}`:I.flags}function Zy(I){return Math.max(...I.map((q)=>pd(q).length))}function Xy(I){return Math.max(...I.map((q)=>q.usage.length))}function Qy(I){return Math.max(...I.map((q)=>`${bt} ${q.usage}`.length))}function ev(I,q){let Q=`${bt} ${I.usage}`;return`${Pn}${Q.padEnd(q+2)}${I.description}`}function An(I,q){return`${Pn}${I.padEnd(Math.max(40,I.length+2))}${q}`}function er(I,q=console.log){let Q=[];if(Q.push(`${bt} ${I.name}`),Q.push(""),Q.push(`${Pn}${I.description}`),Q.push(""),Q.push("USAGE:"),Q.push(`${Pn}${bt} ${I.usage}`),Q.push(""),I.subcommands&&I.subcommands.length>0){Q.push("SUBCOMMANDS:");let ne=Xy(I.subcommands);for(let te of I.subcommands)Q.push(`${Pn}${te.usage.padEnd(ne+2)}${te.description}`);Q.push("")}if(I.options.length>0){Q.push("OPTIONS:");let ne=Zy(I.options);for(let te of I.options){let re=pd(te),le=te.default?`${te.description} (default: ${te.default})`:te.description;Q.push(`${Pn}${re.padEnd(ne+2)}${le}`)}Q.push("")}if(I.examples&&I.examples.length>0){Q.push("EXAMPLES:");for(let ne of I.examples)Q.push(`${Pn}${ne}`)}q(Q.join(`
230
+ `,()=>q())})}async function dd(I,q){let Q=cs(q);if(!Q)return 1;try{let ne=wr(Q.command,{cwd:Q.cwd,shell:Q.shell},I),te=!!process.env.NO_COLOR||!process.stdout.isTTY;return await cd(Q.json?ps(ne):us(ne,{asciiOnly:te})),0}catch(ne){let te=Yy(ne instanceof g?ne.cause:ne);if(te===void 0)throw ne;if(Q.json)return await cd(JSON.stringify({error:te})),1;return console.error(te),1}}function Yy(I){if(I instanceof E)return I.message;if(I instanceof H)return I.message;if(I instanceof h)return I.message;if(I instanceof a&&l[I.kind].errorCode==="path-canonicalization-limit")return"Path canonicalization work limit exceeded.";return}var ud="2.7.7",Pn=" ",bt="cc-safety-net";function pd(I){return I.argument?`${I.flags} ${I.argument}`:I.flags}function Zy(I){return Math.max(...I.map((q)=>pd(q).length))}function Xy(I){return Math.max(...I.map((q)=>q.usage.length))}function Qy(I){return Math.max(...I.map((q)=>`${bt} ${q.usage}`.length))}function ev(I,q){let Q=`${bt} ${I.usage}`;return`${Pn}${Q.padEnd(q+2)}${I.description}`}function An(I,q){return`${Pn}${I.padEnd(Math.max(40,I.length+2))}${q}`}function er(I,q=console.log){let Q=[];if(Q.push(`${bt} ${I.name}`),Q.push(""),Q.push(`${Pn}${I.description}`),Q.push(""),Q.push("USAGE:"),Q.push(`${Pn}${bt} ${I.usage}`),Q.push(""),I.subcommands&&I.subcommands.length>0){Q.push("SUBCOMMANDS:");let ne=Xy(I.subcommands);for(let te of I.subcommands)Q.push(`${Pn}${te.usage.padEnd(ne+2)}${te.description}`);Q.push("")}if(I.options.length>0){Q.push("OPTIONS:");let ne=Zy(I.options);for(let te of I.options){let re=pd(te),le=te.default?`${te.description} (default: ${te.default})`:te.description;Q.push(`${Pn}${re.padEnd(ne+2)}${le}`)}Q.push("")}if(I.examples&&I.examples.length>0){Q.push("EXAMPLES:");for(let ne of I.examples)Q.push(`${Pn}${ne}`)}q(Q.join(`
231
231
  `))}function ys(){let I=Qy(Dr),q=[];q.push(`${bt} v${ud}`),q.push(""),q.push("Blocks destructive commands and secret access."),q.push(""),q.push("COMMANDS:");for(let Q of Dr)q.push(ev(Q,I));q.push(""),q.push("GLOBAL OPTIONS:"),q.push(`${Pn}-h, --help Show help (use with command for command-specific help)`),q.push(`${Pn}-V, --version Show version`),q.push(""),q.push("HELP:"),q.push(`${Pn}${bt} help <command> Show help for a specific command`),q.push(`${Pn}${bt} <command> --help Show help for a specific command`),q.push(""),q.push("ENVIRONMENT VARIABLES:"),q.push(An(`${r.level.name}=standard|strict|paranoid`,"Set session safety level")),q.push(An(`${r.worktree.name}=1`,"Allow local git discards in linked worktrees")),q.push(An(`${r.debug.name}=1`,"Print diagnostic messages to stderr")),q.push(An(`${r.auditScope.name}=all|blocked`,"Record all command decisions, or denials only")),q.push(An(`${r.projectTightenOnly.name}=1`,"Ignore project policy settings that weaken the user policy")),q.push(An("CC_SAFETY_NET_HOME","Override rule config home directory")),q.push(""),q.push("LEGACY ENVIRONMENT VARIABLES (STILL SUPPORTED):"),q.push(An(`${r.strict.name}=1`,"Force safety.overrides.fail_closed on")),q.push(An(`${r.paranoid.name}=1`,"Force paranoid_rm and paranoid_interpreters on")),q.push(An(`${r.paranoidRm.name}=1`,"Force safety.overrides.paranoid_rm on")),q.push(An(`${r.paranoidInterpreters.name}=1`,"Force safety.overrides.paranoid_interpreters on")),q.push(""),q.push("Documentation: https://ccsafetynet.com/docs"),console.log(q.join(`
232
232
  `))}function fd(){console.log(ud)}function kr(I,q=console.log){let Q=Nr(I);if(!Q)return!1;if(Q.name.toLowerCase()!==I.toLowerCase())return!1;return er(Q,q),!0}import{existsSync as Ao,readFileSync as bu}from"node:fs";import{join as To}from"node:path";import*as Gn from"node:readline";function nv(I){return I==="install"?"Install":"Uninstall"}function tv(I){return I==="install"?"Installing":"Uninstalling"}function rv(I){return I==="install"?"into":"from"}function hd(I){return I?.available===!0}function ov(I,q){let Q=new Set(q);return I.filter((ne)=>Q.has(ne.target)).map((ne)=>ne.target)}function md(I,q,Q){if(I.every((ne)=>!ne.available))return q;return Array.from({length:I.length},(ne,te)=>te+1).map((ne)=>(q+ne*Q+I.length)%I.length).find((ne)=>hd(I[ne]))}function iv(I,q,Q){if(Q.ctrl&&Q.name==="c")return"interrupt";if(Q.name==="escape"||q==="q")return"abort";if(I==="install"&&(q==="u"||q==="U"))return"update";if(Q.name==="up"||q==="k")return"up";if(Q.name==="down"||q==="j")return"down";if(Q.name==="space"||q===" ")return"toggle";if(Q.name==="return"||Q.name==="enter")return"confirm";return null}function sv(I){return{cursor:I.findIndex((q)=>q.available),selected:[]}}function av(I,q,Q){if(Q==="confirm"||Q==="update"||Q==="abort"||Q==="interrupt")return{state:I,done:Q};if(Q==="up")return{state:{...I,cursor:md(q,I.cursor,-1)}};if(Q==="down")return{state:{...I,cursor:md(q,I.cursor,1)}};let ne=q[I.cursor];if(!hd(ne))return{state:I};let te=I.selected.includes(ne.target)?I.selected.filter((re)=>re!==ne.target):ov(q,[...I.selected,ne.target]);return{state:{...I,selected:te}}}var yd="◉",vd="◯",bd=">",wd=" ";function lv(I,q,Q){return["",`${nv(I)} CC Safety Net ${rv(I)}:`,"",...q.map((ne,te)=>{let re=Q.selected.includes(ne.target),le=te===Q.cursor,ye=re?yd:vd,ve=le?bd:wd,Pe=ne.available?"":` (${ne.unavailableReason??"not installed"})`,Ie=`${ye} ${ne.label}${Pe}`,$e=!ne.available?Ve.dim(Ie):re?Ve.green(Ie):le?Ve.bold(Ie):Ie;return`${ve} ${$e}`}),"",I==="install"?"Space: select Enter: confirm u: update installed Up/Down: move q/Esc: cancel":q.some((ne)=>ne.available)?"Space: select Enter: confirm Up/Down: move q/Esc: cancel":`No selectable integrations found for ${I}. q/Esc: close`].join(`
233
233
  `)}var gd=["global-hook","plugin"];function cv(I,q,Q={}){let ne=Q.color!==!1?Ve.bold:(re)=>re;return["","Install the Kimi Code integration as:","",...[`Global hook — ${q?"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((re,le)=>{let ye=le===I,ve=`${ye?yd:vd} ${re}`;return`${ye?bd:wd} ${ye?ne(ve):ve}`}),"","Enter: confirm Up/Down: move q/Esc: cancel"].join(`
@@ -1 +1 @@
1
- import"../chunks/index-dm4v8s9a.js";import{Tt}from"../chunks/index-edtb8nxp.js";import"../chunks/index-a1hayde0.js";import"../chunks/index-r6tk9ysc.js";var t={name:"cc-safety-net",inject:["tools"],apply:Tt};export{t as default};
1
+ import"../chunks/index-769a735t.js";import{Tt}from"../chunks/index-39xnzexq.js";import"../chunks/index-ssmnsasm.js";import"../chunks/index-hqqx476d.js";var t={name:"cc-safety-net",inject:["tools"],apply:Tt};export{t as default};
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{S,Ie}from"./chunks/index-dm4v8s9a.js";import{Be,Oe,Et,st,at}from"./chunks/index-eg9by26f.js";import"./chunks/index-r6tk9ysc.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,x]=s[i];if(e(a,f)&&t(c,x)){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 x=i?.constructor;return x&&x!==Object.prototype.constructor&&x.name?`${x.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 x;if(Lt in i)x=u(Fn(i),f);else if(Array.isArray(i))x=!o||i.length<=1?`[${i.map((h)=>u(h,f)).join(",")}]`:`[
1
+ import{S,Ie}from"./chunks/index-769a735t.js";import{Be,Oe,Et,st,at}from"./chunks/index-ta894pns.js";import"./chunks/index-hqqx476d.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,x]=s[i];if(e(a,f)&&t(c,x)){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 x=i?.constructor;return x&&x!==Object.prototype.constructor&&x.name?`${x.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 x;if(Lt in i)x=u(Fn(i),f);else if(Array.isArray(i))x=!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)x=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);x=i instanceof Error&&i.cause?`${h} (cause: ${u(i.cause,f)})`:h}else if(Symbol.iterator in i)x=`${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(",")}}`;x=a(i,m)}else{let m=`{