cc-safety-net 2.6.13 → 2.6.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/amp/cc-safety-net/index.ts +42 -42
- package/dist/api.js +1 -1
- package/dist/bin/hook.js +42 -42
- package/dist/chunks/{index-z5fwe2yq.js → index-1x1d9s1m.js} +1 -1
- package/dist/chunks/{index-ry0wwdk0.js → index-aq50vwpd.js} +1 -1
- package/dist/chunks/{index-e25d8rb4.js → index-gj5qkg3c.js} +1 -1
- package/dist/chunks/{index-x95aj0ja.js → index-pgmgvnyg.js} +2 -2
- package/dist/chunks/{index-q29jqk43.js → index-rwp0taf5.js} +1 -1
- package/dist/chunks/index-z14g58a6.js +49 -0
- package/dist/cli.js +3 -3
- package/dist/deepseek-harness/index.js +1 -1
- package/dist/index.js +1 -1
- package/dist/openclaw/cc-safety-net/index.js +42 -42
- package/dist/openclaw/cc-safety-net/openclaw.plugin.json +1 -1
- package/dist/openclaw/cc-safety-net/package.json +1 -1
- package/dist/pi/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunks/index-rdxjms22.js +0 -49
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a,s,Me,nt,T,bt,rt,c,n,ot,P,S,me,vt,m,Ie,x,st,l,o,w,i,ae,r,g,he,B,wt,Ct,p,ye,be,Et,M,X,ce,C,kt,I,h,Ae,z,u,O,Q,at,ct,F,E,D,xe,ve,$e,le,d,e,Ue,Oe,je,Se,lt,ut,ue,De,de,Ge,ee,V,He,we,q,dt,K,te,ne,pe,pt,ft,k,A,We,mt,ze,R,Ve,Ne,qe,y,t,re,Ce,b,U,v,N,Rt,Ke,Je,f,j}from"./chunks/index-
|
|
1
|
+
import{a,s,Me,nt,T,bt,rt,c,n,ot,P,S,me,vt,m,Ie,x,st,l,o,w,i,ae,r,g,he,B,wt,Ct,p,ye,be,Et,M,X,ce,C,kt,I,h,Ae,z,u,O,Q,at,ct,F,E,D,xe,ve,$e,le,d,e,Ue,Oe,je,Se,lt,ut,ue,De,de,Ge,ee,V,He,we,q,dt,K,te,ne,pe,pt,ft,k,A,We,mt,ze,R,Ve,Ne,qe,y,t,re,Ce,b,U,v,N,Rt,Ke,Je,f,j}from"./chunks/index-z14g58a6.js";import{Qe}from"./chunks/index-gj5qkg3c.js";import{Ye,ke}from"./chunks/index-aq50vwpd.js";import{et}from"./chunks/index-1x1d9s1m.js";import"./chunks/index-rwp0taf5.js";import{ie,J,tt,H,W}from"./chunks/index-pgmgvnyg.js";var cf=["-h","--help"];function mn(_,L){let G=Object.entries(_.booleans??{}),Y=Object.entries(_.values??{}),Z=Object.entries(_.lists??{}),oe=Object.fromEntries(G.map(([Le])=>[Le,!1])),se={},fe=Object.fromEntries(Z.map(([Le])=>[Le,[]])),ge=[],Pe=[],Ee=!1,Re=-1;for(let[Le,_e]of L.entries()){if(Le<=Re)continue;if(_e==="--"){ge.push(...L.slice(Le+1));break}if(cf.includes(_e)){Ee=!0;continue}let Te=G.find(([,Ze])=>Ze.includes(_e));if(Te){oe[Te[0]]=!0;continue}let Be=Y.find(([,Ze])=>Ze.includes(_e));if(Be){let Ze=L[Le+1];if(Ze===void 0||Ze.startsWith("-")){Pe.push(`${_e} requires a value`);continue}se[Be[0]]=Ze,Re=Le+1;continue}let Fe=Z.find(([,Ze])=>Ze.includes(_e));if(Fe){let Ze=L.slice(Le+1),tn=Ze.findIndex((an)=>an.startsWith("-")),on=Ze.slice(0,tn===-1?Ze.length:tn);if(on.length===0){Pe.push(`${_e} requires at least one value`);continue}fe[Fe[0]]=[...fe[Fe[0]]??[],...on],Re=Le+on.length;continue}if(_e.startsWith("-")){Pe.push(`Unknown option for ${_.label}: ${_e}`);continue}if(_.positionals==="tail"){ge.push(...L.slice(Le));break}ge.push(_e)}if(_.positionals!=="list"&&_.positionals!=="tail")Pe.push(...ge.map((Le)=>`Unexpected argument for ${_.label}: ${Le}`));return{flags:oe,values:se,lists:fe,positionals:ge,help:Ee,errors:Pe}}function $n(_){for(let L of _)console.error(L);return _.length>0}import{readdirSync as yf,statSync as Ys,unlinkSync as hf}from"node:fs";import{basename as Zs,dirname as vf,isAbsolute as bf,join as wf,relative as kf,resolve as Cf,sep as xf}from"node:path";var Js=(_)=>{let L=Date.now()-new Date(_).getTime();if(!Number.isFinite(L))return"";let G=Math.floor(L/60000),Y=Math.floor(G/60),Z=Math.floor(Y/24);if(Z>0)return`${Z}d ago`;if(Y>0)return`${Y}h ago`;if(G>0)return`${G}m ago`;return"just now"},Go=(_)=>{let L=(_??"").trim().split(/\s+/).filter((Z)=>Z&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(Z)),G=L[0]?.split("/").pop();if(!G)return null;let Y=L[1];return Y&&/^[a-z][a-z0-9-]*$/.test(Y)?`${G} ${Y}`:G};function Ws(_){let L=(Z)=>`${Z.sessionId}
|
|
2
2
|
${Go(Z.segment||Z.command)}`,G=_.filter((Z)=>Z.decision!=="allow"),Y=G.filter((Z)=>Z.sessionId).reduce((Z,oe)=>Z.set(L(oe),(Z.get(L(oe))??0)+1),new Map);return new Set(G.filter((Z)=>Z.failureStage||(Y.get(L(Z))??0)>=2))}import{existsSync as df,readdirSync as uf,readFileSync as pf}from"node:fs";import{join as ff}from"node:path";function Yn(_,L){try{return uf(_,{withFileTypes:!0,encoding:"utf8"}).flatMap((G)=>{let Y=ff(_,G.name);if(G.isDirectory())return Yn(Y,L);if(G.name.endsWith(".jsonl"))return[Y];return[]})}catch{if(L&&df(_))L.count++;return[]}}var mf=["segment","reason","sessionId","decision","agent","ruleId","failureStage"];function gf(_){if(!_||typeof _!=="object"||Array.isArray(_))return!1;let L=_;if(typeof L.ts!=="string"||typeof L.command!=="string")return!1;return mf.every((G)=>L[G]===void 0||typeof L[G]==="string")}function Dt(_,L){try{return pf(_,"utf-8").split(`
|
|
3
3
|
`).filter(Boolean).flatMap((G)=>{try{let Y=JSON.parse(G);if(!gf(Y)){if(L)L.count++;return[]}return[Y]}catch{if(L)L.count++;return[]}})}catch{if(L)L.count++;return[]}}function gn(_){return Array.from(_,(L)=>{let G=L.charCodeAt(0);if(G<=31||G>=127&&G<=159)return`\\x${G.toString(16).padStart(2,"0")}`;return L}).join("")}function Sf(_,L){let G=ie(_),Y=mn({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"]}},L);if($n(Y.errors))return null;if(Y.values.id!==void 0&&!/^[a-f0-9]{16}$/.test(Y.values.id))return console.error("--id must be 16 hexadecimal characters"),null;let Z=Y.values.limit===void 0?20:zs(Y.values.limit);if(Z===null)return console.error("--limit must be a positive number"),null;let oe=Y.values.since===void 0?Math.min(30,G):zs(Y.values.since);if(oe===null||oe>G)return console.error(`--since must be a positive number of days no greater than ${G}`),null;let se={limit:Z,limitExplicit:Y.values.limit!==void 0,since:oe,sinceExplicit:Y.values.since!==void 0,all:Y.flags.all,json:Y.flags.json,suspect:Y.flags.suspect,pruneLegacy:Y.flags.pruneLegacy,dryRun:Y.flags.dryRun,id:Y.values.id,agent:Y.values.agent,rule:Y.values.rule,session:Y.values.session,project:Y.values.project===void 0?void 0:Cf(Y.values.project)};if(se.id&&(se.agent!==void 0||se.rule!==void 0||se.session!==void 0||se.project!==void 0||se.suspect||se.sinceExplicit||se.limitExplicit))return console.error("--id cannot be combined with --agent, --rule, --session, --project, --suspect, --since, or --limit"),null;if(se.pruneLegacy&&(se.id!==void 0||se.agent!==void 0||se.rule!==void 0||se.session!==void 0||se.project!==void 0||se.suspect||se.all||se.sinceExplicit||se.limitExplicit))return console.error("--prune-legacy cannot be combined with --id, --agent, --rule, --session, --project, --suspect, --all, --since, or --limit"),null;if(se.dryRun&&!se.pruneLegacy)return console.error("--dry-run requires --prune-legacy"),null;return se}async function Xs(_,L,G={}){let Y=Sf(_,L);if(!Y)return 1;let Z=G.logsDir??H(_);if(Y.pruneLegacy)return Pf(Z,Y.json,Y.dryRun);if(!Z)return console.log(Y.json?"[]":Y.id?`No retained audit log entry found for id ${gn(Y.id)}.`:"No audit log entries found."),0;J(_,Z);let oe={count:0},se=Yn(Z,oe).flatMap((Re)=>Dt(Re,oe).map((Le)=>({entry:Le,file:Re})));if(oe.count>0)console.error(`warning: ${oe.count} audit log ${oe.count===1?"source":"sources"} could not be read; these results are incomplete`);if(Y.id)return Tf(se,Y,G.timeZone);let fe=Date.now()-Y.since*24*60*60*1000,ge=se.filter((Re)=>If(Re,Y,Z,fe)),Pe=Y.suspect?Ws(ge.map((Re)=>Re.entry)):null,Ee=(Pe?ge.filter((Re)=>Pe.has(Re.entry)):ge).sort((Re,Le)=>Date.parse(Le.entry.ts)-Date.parse(Re.entry.ts)).slice(0,Y.limit);if(Y.json)return console.log(JSON.stringify(Ee.map((Re)=>Re.entry),null,2)),0;if(Ee.length===0)return console.log("No audit log entries found."),0;for(let Re of Ee)console.log($f(Re.entry,G.timeZone));return 0}function Pf(_,L,G){let Y=_?Rf(_).map((fe)=>wf(_,fe)):[];if(G)return Ef(Y,L);let Z=[],oe=0,se=0;for(let fe of Y){let ge=Ys(fe,{throwIfNoEntry:!1})?.size??0,Pe=_f(fe);if(Pe){Z.push(`${Zs(fe)}: ${Pe}`);continue}oe++,se+=ge}if(L)return console.log(JSON.stringify({removedFiles:oe,removedBytes:se,failedFiles:Z.length})),Z.length===0?0:1;console.log(oe===0&&Z.length===0?"No legacy audit log files found.":`Removed ${oe} legacy audit log ${oe===1?"file":"files"} (${Qs(se)}).`);for(let fe of Z)console.error(`Could not remove ${gn(fe)}`);if(console.log("Nested v2 audit logs were not changed."),oe>0)console.log("This deletion cannot be undone.");return Z.length===0?0:1}function Ef(_,L){let G=_.reduce((Y,Z)=>Y+(Ys(Z,{throwIfNoEntry:!1})?.size??0),0);if(L)return console.log(JSON.stringify({dryRun:!0,files:_.length,bytes:G})),0;if(console.log(_.length===0?"No legacy audit log files found.":`Would remove ${_.length} legacy audit log ${_.length===1?"file":"files"} (${Qs(G)}).`),console.log("Nested v2 audit logs are not included."),_.length>0)console.log("Run the same command without --dry-run to delete them.");return 0}function Rf(_){try{return yf(_,{withFileTypes:!0}).filter((L)=>L.isFile()&&L.name.endsWith(".jsonl")).map((L)=>L.name)}catch{return[]}}function _f(_){try{return hf(_),null}catch(L){return L instanceof Error?L.message:String(L)}}function Qs(_){let L=["B","KiB","MiB","GiB"],G=Math.min(Math.floor(Math.log2(Math.max(_,1))/10),L.length-1);return`${Math.round(_/1024**G*10)/10} ${L[G]}`}function Tf(_,L,G){let Y=_.filter((oe)=>oe.entry.id===L.id);if(Y.length>1)return console.error(`Multiple audit log entries found for id ${gn(L.id??"")}.`),1;if(L.json)return console.log(JSON.stringify(Y.map((oe)=>oe.entry),null,2)),0;let Z=Y[0];if(!Z)return console.log(`No retained audit log entry found for id ${gn(L.id??"")}.`),0;return console.log(Df(Z.entry,G)),0}function If(_,L,G,Y){if(!L.all&&_.entry.decision==="allow")return!1;if(Date.parse(_.entry.ts)<Y)return!1;if(L.agent!==void 0&&_.entry.agent!==L.agent)return!1;if(L.rule!==void 0&&_.entry.ruleId!==L.rule)return!1;if(L.session!==void 0&&!Af(_,G,L.session))return!1;if(L.project!==void 0&&!Of(_.entry.cwd,L.project))return!1;return!0}function Af(_,L,G){if(_.entry.sessionId===G)return!0;return vf(_.file)===L&&Zs(_.file,".jsonl")===G}function Of(_,L){if(!_)return!1;let G=kf(L,_);return G!==".."&&!G.startsWith(`..${xf}`)&&!bf(G)}function $f(_,L){let G=gn(_.id??"-"),Y=gn(_.decision??"deny"),Z=_.cwd?` [${gn(_.cwd)}]`:"",oe=_.segment||_.command,se=oe===_.command?"":"↳ ",fe=oe.length>50?`${oe.slice(0,50)}…`:oe;return`${G.padEnd(16)} ${gn(ea(_.ts,L))} ${Y.padEnd(5)} ${gn(_.agent??"-").padEnd(15)} ${gn(_.ruleId??"-").padEnd(20)} ${se}${gn(fe)}${Z}`}function Df(_,L){let G=(Z)=>gn(Z===void 0||Z===null||Z===""?"-":Z),Y=_.shape?`${_.agent??"-"} (shape: ${_.shape})`:_.agent??"-";return[`id: ${G(_.id)}`,`ts: ${G(ea(_.ts,L))}`,`decision: ${G(_.decision)}`,`agent: ${G(Y)}`,`level: ${G(_.level)}`,`tool: ${G(_.toolName)}`,`rule: ${G(_.ruleId)}`,`intent: ${G(_.intent)}`,`stage: ${G(_.failureStage)}`,`error: ${G(_.errorCode)}`,`session: ${G(_.sessionId)}`,`cwd: ${G(_.cwd)}`,`version: ${G(_.v)}`,`truncated: ${G(_.truncated===!0?"yes":void 0)}`,`reason: ${G(_.reason)}`,`command: ${G(_.command)}`,`segment: ${G(_.segment)}`].join(`
|
|
4
4
|
`)}function ea(_,L){let G=new Date(_);if(Number.isNaN(G.getTime()))return _;return new Intl.DateTimeFormat("sv-SE",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23",timeZone:L}).format(G)}function zs(_){let L=Number(_);return Number.isFinite(L)&&L>0?L:null}var na={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 ta={name:"explain",description:"Show step-by-step analysis trace of how a command would be analyzed",usage:"explain [options] <command>",argument:"<command>",options:[{flags:"--json",description:"Output analysis as JSON"},{flags:"--cwd",argument:"<path>",description:"Use custom working directory"},{flags:"-h, --help",description:"Show this help"}],examples:['cc-safety-net explain "git reset --hard"','cc-safety-net explain --json "rm -rf /"','cc-safety-net explain --cwd /tmp "git status"']};var ra={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 Bo=["npx","--offline","--no-install","@deepseek-ai/dsh","--version"],oa=["cursor-agent","--version"],ia=[{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:Bo}},{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"]}}],qo=ia.slice().sort((_,L)=>_.displayName.localeCompare(L.displayName,"en")),Rr=qo.map((_)=>_.id).sort((_,L)=>Number(L==="claude-code")-Number(_==="claude-code")),Qt=qo.filter((_)=>("runtime"in _)).map((_)=>({id:_.id,displayName:"displayName"in _.runtime?_.runtime.displayName:_.displayName,flags:_.runtime.flags,legacyFlags:"legacyFlags"in _.runtime?_.runtime.legacyFlags:[],description:_.runtime.description,legacyTopLevelFlags:_.runtime.legacyTopLevelFlags})),En=qo.map((_)=>({id:_.id,..._.install})),Nf=Object.fromEntries(ia.map((_)=>[_.id,_.displayName]));function cn(_){return Nf[_]}var Lf=Qt.map((_)=>({flags:_.flags.join(", "),description:_.description})),jf=Qt.flatMap((_)=>_.flags.map((L)=>`cc-safety-net hook ${L}`)),sa={name:"hook",description:"Run as an agent CLI hook (reads JSON from stdin)",usage:"hook INTEGRATION_FLAG",options:[...Lf,{flags:"-h, --help",description:"Show this help"}],examples:jf};var aa={name:"install",description:"Install CC Safety Net into a coding agent CLI",usage:"install [TARGET_FLAG]",options:[...En.map((_)=>({flags:_.flag,description:`Install ${cn(_.id)} ${_.artifactKind}`})),{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net install",...En.map((_)=>`cc-safety-net install ${_.flag}`)]},la={name:"uninstall",description:"Uninstall CC Safety Net from a coding agent CLI",usage:"uninstall [TARGET_FLAG]",options:[...En.map((_)=>({flags:_.flag,description:`Uninstall ${cn(_.id)} ${_.artifactKind}`})),{flags:"-h, --help",description:"Show this help"}],examples:["cc-safety-net uninstall",...En.map((_)=>`cc-safety-net uninstall ${_.flag}`)]},ca={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 da={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 Vo=[{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"}],Ko=["cc-safety-net rule add project-rules","cc-safety-net rule add acme/safety-rules","cc-safety-net rule add acme/safety-rules --only aws gcloud","cc-safety-net rule add acme/safety-rules --ref v2 --only aws","cc-safety-net rule add --only terraform aws"],Nt={name:"rule",description:"Manage CC Safety Net rule config and rulebook sources",usage:"rule <subcommand>",subcommands:[{usage:"init [--example]",description:"Create inert rule config"},{usage:"add [source] [--ref <ref>] [--only <rulebook...>]",description:"Add rulebook sources and sync"},{usage:"remove <source>",description:"Remove a rulebook source and sync"},{usage:"update [source]",description:"Re-fetch and vendor remote rulebooks"},{usage:"sync",description:"Deprecated: migrate lock and cache leftovers"},{usage:"list",description:"List active rulebooks"},{usage:"wrapper add <command>",description:"Trust a transparent command wrapper"},{usage:"wrapper remove <command>",description:"Remove a transparent command wrapper"},{usage:"wrapper list",description:"List transparent command wrappers"},{usage:"tool add <name...> [--cwd-arg <name>] [--project]",description:"Analyze community shell tools (user scope by default)"},{usage:"tool remove <name...> [--project]",description:"Stop analyzing declared tools"},{usage:"tool list",description:"List declared command tools in both scopes"},{usage:"migrate [--cleanup]",description:"Migrate legacy inline rules"},{usage:"doc",description:"Print the rulebook authoring guide"},{usage:"verify",description:"Validate rule config files"}],options:[{flags:"-g, --global",description:"Use user-scope rule config"},{flags:"--cleanup",description:"Delete legacy files after rule migrate verifies them"},{flags:"--delete-source",description:"Delete clean local source directory on remove"},{flags:"--example",description:"Create an inactive example rulebook with rule init"},{flags:"--project",description:"Use project-scope rule config with rule tool"},{flags:"--cwd-arg",argument:"<name>",description:"Name the working-directory argument with rule tool add"},...Vo.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",...Ko,"cc-safety-net rule update","cc-safety-net rule migrate --cleanup","cc-safety-net rule verify"]};var ua={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 pa={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 Tr=[ua,na,da,ta,Nt,_r,aa,ca,la,sa,ra,pa];function Hf(_){return _.aliases??[]}function Ir(_){let L=_.toLowerCase();return Tr.find((G)=>G.name.toLowerCase()===L||Hf(G).some((Y)=>Y.toLowerCase()===L))}import{existsSync as Ah}from"node:fs";import{basename as Ff}from"node:path";function Ar(_,L=7,G=H(_)){let Y=Date.now()-L*24*60*60*1000,Z=[],oe=new Set,se=0,fe,ge,Pe,Ee;if(G)J(_,G);let Re={count:0},Le=G?Yn(G,Re):[];for(let Te of Le)for(let Be of Dt(Te,Re)){if(Be.decision==="allow")continue;let Fe=new Date(Be.ts).getTime();if(Fe>=Y){if(se++,oe.add(Be.sessionId??Ff(Te,".jsonl")),ge===void 0||Fe<=ge)fe=Be.ts,ge=Fe;if(Ee===void 0||Fe>Ee)Pe=Be.ts,Ee=Fe;Mf(Z,Be,Fe)}}let _e=Z.map((Te)=>({timestamp:Te.ts,command:Te.command,reason:Te.reason,relativeTime:Js(new Date(Te.ts))}));return{totalBlocked:se,sessionCount:oe.size,recentEntries:_e,oldestEntry:fe,newestEntry:Pe,unreadable:Re.count}}function Mf(_,L,G){let Y=_.findIndex((Z)=>G>new Date(Z.ts).getTime());if(Y===-1){if(_.length<3)_.push(L);return}if(_.splice(Y,0,L),_.length>3)_.pop()}import{dirname as Xf}from"node:path";import{dirname as Uf,join as Gf,resolve as Bf}from"node:path";var qf="config.json";function bn(_,L,G,Y){g(Vf(_),`${JSON.stringify(L,null,2)}
|
|
@@ -18,7 +18,7 @@ ${Go(Z.segment||Z.command)}`,G=_.filter((Z)=>Z.decision!=="allow"),Y=G.filter((Z
|
|
|
18
18
|
`)}function $r(_){return Zn({rows:_})}function Ia(_){let L=[];return L.push("System Info"),L.push(Cm(_)),L.join(`
|
|
19
19
|
`)}function Cm(_){let L=["Component","Version"],G=(oe)=>{if(oe===null)return en.dim("not found");return oe},Z=[{label:"cc-safety-net",value:_.version},...Rr.map((oe)=>({label:cn(oe),value:_.versions[oe]??null})),{label:"Node.js",value:_.nodeVersion},{label:"npm",value:_.npmVersion},{label:"Bun",value:_.bunVersion},{label:"Platform",value:_.platform}].map((oe)=>[oe.label,G(oe.value)]);return Zn({headers:L,rows:Z})}function Aa(_){if(_.findings.length===0)return en.green(`
|
|
20
20
|
No findings from inspected doctor facts.`);let L={error:_.findings.filter((oe)=>oe.severity==="error").length,warning:_.findings.filter((oe)=>oe.severity==="warning").length,info:_.findings.filter((oe)=>oe.severity==="info").length},G=["error","warning","info"].filter((oe)=>L[oe]>0).map((oe)=>`${L[oe]} ${oe}`),Y=_.findings.length===1?"finding":"findings",Z=`
|
|
21
|
-
${_.findings.length} ${Y}: ${G.join(", ")}.`;if(L.error>0)return en.red(Z);if(L.warning>0)return en.yellow(Z);return en.blue(Z)}import{lstatSync as xm}from"node:fs";import{dirname as Zo}from"node:path";function Xo(_,L){try{let G=xm(L);if(G.isSymbolicLink())return{kind:_,path:L,status:"unsafe",issues:["symlink"]};if(!G.isDirectory())return{kind:_,path:L,status:"unsafe",issues:["not-directory"]};if(process.platform==="win32"||typeof process.getuid!=="function")return{kind:_,path:L,status:"unknown",issues:[]};let Y=[...G.uid!==process.getuid()?["ownership"]:[],...(G.mode&18)!==0?["permissions"]:[]];return{kind:_,path:L,status:Y.length>0?"unsafe":"safe",issues:Y}}catch(G){if(typeof G==="object"&&G!==null&&"code"in G&&G.code==="ENOENT")return{kind:_,path:L,status:"not-applicable",issues:[]};return{kind:_,path:L,status:"unknown",issues:[]}}}function Oa(_,L){let G=H(_);return{directories:[Xo("policy",Zo(Zo(L))),Xo("config",Zo(L)),...G?[Xo("audit",G)]:[{kind:"audit",status:"unknown",issues:[]}]]}}import{spawn as Sm}from"node:child_process";import{existsSync as $a}from"node:fs";import{delimiter as Pm,extname as Em,join as Rm}from"node:path";import{stripVTControlCharacters as Da}from"node:util";var La="2.6.
|
|
21
|
+
${_.findings.length} ${Y}: ${G.join(", ")}.`;if(L.error>0)return en.red(Z);if(L.warning>0)return en.yellow(Z);return en.blue(Z)}import{lstatSync as xm}from"node:fs";import{dirname as Zo}from"node:path";function Xo(_,L){try{let G=xm(L);if(G.isSymbolicLink())return{kind:_,path:L,status:"unsafe",issues:["symlink"]};if(!G.isDirectory())return{kind:_,path:L,status:"unsafe",issues:["not-directory"]};if(process.platform==="win32"||typeof process.getuid!=="function")return{kind:_,path:L,status:"unknown",issues:[]};let Y=[...G.uid!==process.getuid()?["ownership"]:[],...(G.mode&18)!==0?["permissions"]:[]];return{kind:_,path:L,status:Y.length>0?"unsafe":"safe",issues:Y}}catch(G){if(typeof G==="object"&&G!==null&&"code"in G&&G.code==="ENOENT")return{kind:_,path:L,status:"not-applicable",issues:[]};return{kind:_,path:L,status:"unknown",issues:[]}}}function Oa(_,L){let G=H(_);return{directories:[Xo("policy",Zo(Zo(L))),Xo("config",Zo(L)),...G?[Xo("audit",G)]:[{kind:"audit",status:"unknown",issues:[]}]]}}import{spawn as Sm}from"node:child_process";import{existsSync as $a}from"node:fs";import{delimiter as Pm,extname as Em,join as Rm}from"node:path";import{stripVTControlCharacters as Da}from"node:util";var La="2.6.14",_m=5000,Tm="_CC_SAFETY_NET_TEST_SPAWN_PLATFORM";function pn(){return La}function Qo(_,L){let G=_[L];if(G)return G;let Y=Object.keys(_).find((Z)=>Z.toLowerCase()===L.toLowerCase()&&!!_[Z]);return Y?_[Y]:G}function Im(_){return(Qo(_,"PATHEXT")||".COM;.EXE;.BAT;.CMD").split(";").filter((L)=>L.length>0)}function Am(_,L){let G=Em(_)?[_]:[...Im(L).map((Y)=>`${_}${Y}`),_];if(_.includes("/")||_.includes("\\"))return G.find((Y)=>$a(Y))??_;return(Qo(L,"PATH")??"").split(Pm).flatMap((Y)=>G.map((Z)=>Rm(Y,Z))).find((Y)=>$a(Y))??_}function Na(_){if(!/[\s"&|<>^]/.test(_))return _;return`"${_.replace(/"/g,'""')}"`}function Xn(_,L){let[G,...Y]=_,Z=L[Tm]==="win32"?"win32":process.platform;if(!G||Z!=="win32")return{cmd:G??"",args:Y};let oe=Am(G,L);if(!/\.(?:bat|cmd)$/i.test(oe))return{cmd:oe,args:Y};return{cmd:Qo(L,"COMSPEC")??"cmd.exe",args:["/d","/c",["call",Na(oe),...Y.map(Na)].join(" ")]}}var Ht=async(_,L=_m)=>{let G=await Om(_,{timeoutMs:L});if(G.code!==0)return null;return Da(G.stdout).trim()||Da(G.stderr).trim()||null};function Om(_,L){let[G,...Y]=_;if(!G)return Promise.resolve({code:null,stdout:"",stderr:""});return new Promise((Z)=>{try{let oe=Xn([G,...Y],process.env),se=Sm(oe.cmd,oe.args,{stdio:["ignore","pipe","pipe"]}),fe=!1,ge="",Pe="";se.stdout.on("data",(Le)=>{ge+=Le.toString()}),se.stderr.on("data",(Le)=>{Pe+=Le.toString()});let Ee=(Le)=>{if(fe)return;fe=!0,clearTimeout(Re),Z(Le)},Re=setTimeout(()=>{se.kill(),Ee({code:null,stdout:ge,stderr:Pe})},L.timeoutMs);se.on("close",(Le)=>{Ee({code:Le,stdout:ge,stderr:Pe})}),se.on("error",()=>{Ee({code:null,stdout:ge,stderr:Pe})})}catch{Z({code:null,stdout:"",stderr:""})}})}function Dr(_){if(!_)return null;let L=/Claude Code\s+(\d+\.\d+\.\d+)/i.exec(_);if(L)return L[1]??null;let G=/v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)/i.exec(_);if(G)return G[1]??null;return _.split(`
|
|
22
22
|
`)[0]?.trim()||null}async function Nr(_,L=Ht,G=process.cwd()){let Y=Promise.all(En.map(async(Re)=>[Re.id,Dr(await L([...Re.probeCommand]))])),[Z,oe,se,fe,ge,Pe,Ee]=await Promise.all([Y,Y.then(async(Re)=>{let Le=Re.find(([Be])=>Be==="opencode")?.[1];if(!Le?.startsWith("2.")||!_(Le))return null;let _e=["--param",`location[directory]=${G}`],Te=["opencode","api","integration.list",..._e];return await L(Te,30000),L(["opencode","api","plugin.list",..._e],30000)}),L(["codex","plugin","list"],30000),L(["amp","plugins","list"],30000),L(["node","--version"]),L(["npm","--version"]),L(["bun","--version"])]);return{version:La,versions:Object.fromEntries(Z),codexPluginListOutput:se,ampPluginListOutput:fe,openCodePluginListOutput:oe,nodeVersion:Dr(ge),npmVersion:Dr(Pe),bunVersion:Dr(Ee),platform:`${process.platform} ${process.arch}`}}function ei(_,L){if(L==="dev")return!1;let G=_.split(".").map(Number),Y=L.split(".").map(Number),[Z=0,oe=0,se=0]=G,[fe=0,ge=0,Pe=0]=Y;if(Z!==fe)return Z>fe;if(oe!==ge)return oe>ge;return se>Pe}async function Gn(){let _=pn(),L=new AbortController,G=setTimeout(()=>L.abort(),3000);try{let Y=await fetch("https://registry.npmjs.org/cc-safety-net/latest",{signal:L.signal});if(!Y.ok)return{currentVersion:_,latestVersion:null,updateAvailable:!1,error:`npm registry returned ${Y.status}`};let Z=await Y.json(),oe=ei(Z.version,_);return{currentVersion:_,latestVersion:Z.version,updateAvailable:oe}}catch(Y){return{currentVersion:_,latestVersion:null,updateAvailable:!1,error:Y instanceof Error?Y.message:"Network error"}}finally{clearTimeout(G)}}import*as qa from"node:readline";var Ma=(_)=>`\x1B[${_}B`,$m=(_)=>`\x1B[${_}A`;var ja=["░","▒","▓","╱","╲","┃","━","┏","┓","┗","┛","╋"];function Dm(_){return new Promise((L)=>setTimeout(L,_))}function Nm(_,L,G){if(!G)return L(_);if(G.aborted)return Promise.resolve();return new Promise((Y,Z)=>{let oe=()=>G.removeEventListener("abort",se),se=()=>{oe(),Y()};G.addEventListener("abort",se,{once:!0}),L(_).then(()=>{oe(),Y()},(fe)=>{oe(),Z(fe)})})}function Lr(_){return Math.max(0,Math.min(1,_))}function Ft(_){return Math.max(0,Math.min(255,Math.round(_)))}function ni(_){return _<=0.0031308?12.92*_:1.055*_**0.4166666666666667-0.055}function Lm(_,L,G){let Y=G*Math.PI/180,Z=L*Math.cos(Y),oe=L*Math.sin(Y),se=(_+0.3963377774*Z+0.2158037573*oe)**3,fe=(_-0.1055613458*Z-0.0638541728*oe)**3,ge=(_-0.0894841775*Z-1.291485548*oe)**3;return{blue:Ft(ni(Lr(-0.0041960863*se-0.7034186147*fe+1.707614701*ge))*255),green:Ft(ni(Lr(-1.2684380046*se+2.6097574011*fe-0.3413193965*ge))*255),red:Ft(ni(Lr(4.0767416621*se-3.3077115913*fe+0.2309699292*ge))*255)}}function ti(_,L){let G=(L*_*180/Math.PI%360+360)%360;return Lm(0.72,0.15,G)}function Ua(_,L=0.1){let G=ti(L,_);return`\x1B[38;2;${G.red};${G.green};${G.blue}m`}function jm(_,L){return{blue:Ft(_.blue+(255-_.blue)*L),green:Ft(_.green+(255-_.green)*L),red:Ft(_.red+(255-_.red)*L)}}function Ga(_,L,G){let Y=Math.imul(_+2654435769,2246822507)^Math.imul(L+3266489909,668265263)^Math.imul(G+374761393,2654435761),Z=Y^Y>>>15,oe=Math.imul(Z,739982445),se=oe^oe>>>12,fe=Math.imul(se,695872825);return((fe^fe>>>15)>>>0)/4294967296}function Hm(_,L,G){let Y=Math.floor(Ga(_,L,G)*ja.length);return ja[Y]??"░"}function Ha(_){let L=Lr(_);return L*L*L*(L*(L*6-15)+10)}function Fm(_){if(_.length===0)return"";let L=[],G=!1,Y="";for(let Z of _){let oe=`${Z.red};${Z.green};${Z.blue}`;if(Z.bold!==G)L.push(Z.bold?"\x1B[1m":"\x1B[22m"),G=Z.bold;if(oe!==Y)L.push(`\x1B[38;2;${oe}m`),Y=oe;L.push(Z.character)}return`${L.join("")}\x1B[22m\x1B[39m`}function Mm(_,L,G,Y,Z){return _.map((oe,se)=>({...ti(G,Y+L+se/Z),bold:!1,character:oe}))}function Um(_,L,G,Y,Z,oe,se,fe){let ge=Math.max(1,Y*0.75),Pe=Math.min(1,G/ge),Ee=Z*Ha(Pe),Re=Math.max(0,(G-ge)/Math.max(1,Y-ge)),Le=(1-Ha(G/Y))*fe*2,_e=0.35*Math.max(0,1-Re*2),Te=Pe>=1,Be=Math.min(_.length,Math.ceil(Ee+2+1));return _.slice(0,Be).map((Fe,Ze)=>{let tn=ti(oe,se+L+Ze/fe+Le),on=Ze+Ga(L,Ze,7919)*2-1;if(on>Ee+2)return{...tn,bold:!1,character:" "};let an=Ee-on,nn=0.8*Math.exp(-(an*an)/12.5),sn=Math.min(0.9,nn+_e),Sn=!Te&&on>Ee-4;return{...jm(tn,sn),bold:sn>0.3,character:Sn?Hm(L,Ze,G):Fe}})}function Fa(_){return`\x1B[?2026h${_.map((L,G)=>`\x1B8${G>0?Ma(G):""}${Fm(L)}`).join("")}\x1B[?2026l`}async function ri(_,L={}){if(!_)return;let G=L.output??process.stdout,Y=L.sleep??Dm,Z=L.seed??0,oe=_.split(`
|
|
23
23
|
`).map((Ee)=>Array.from(Ee)),se=Math.max(...oe.map((Ee)=>Ee.length)),fe=12000*oe.filter((Ee)=>Ee.length>0).length/40,ge=se>0?Math.max(1,Math.ceil(fe/16.666666666666668)):0,Pe=ge>0?fe/ge:0;G.write(`\x1B[?25l${oe.length>1?`${`
|
|
24
24
|
`.repeat(oe.length-1)}${$m(oe.length-1)}`:""}\x1B7`);try{for(let Ee=1;Ee<=ge;Ee+=1){if(L.signal?.aborted)break;G.write(Fa(oe.map((Re,Le)=>Um(Re,Le,Ee,ge,se,0.1,Z,3)))),await Nm(Pe,Y,L.signal)}}finally{if(G.write(Fa(oe.map((Ee,Re)=>Mm(Ee,Re,0.1,Z,3)))),G.write("\x1B8"),oe.length>1)G.write(Ma(oe.length-1));G.write(`
|
|
@@ -227,7 +227,7 @@ def register(ctx):
|
|
|
227
227
|
`));return{path:Z[0]??G??In(Zi(_),Yi[0]),alreadyInstalled:Z.length>0}}function Jt(_){let L=[];for(let G of _.openCodeVersion?.startsWith("2.")?Xi(_.environment):Qi(_.environment))if(wh(G))try{let Y=kh(G,"utf-8"),Z=yn(Y),oe=JSON.parse(Z);if(ts(oe)){let se=es(_.openCodePluginListOutput);if(se)return{platform:"opencode",status:"disabled",method:"opencode api plugin.list",configPath:G,errors:[...L,se]};return{platform:"opencode",status:"configured",method:"plugin array",configPath:G,errors:L.length>0?L:void 0}}}catch(Y){L.push(`Failed to parse ${Ch(G)}: ${Y instanceof Error?Y.message:String(Y)}`)}return{platform:"opencode",status:"n/a",errors:L.length>0?L:void 0}}import{join as Wc}from"node:path";var Yc="dist/pi/index.js",zc=new Set([Yc,"index.js"]),xh=/[*?[\]{}]/;function rs(_){let L=_.env.get("PI_CODING_AGENT_DIR");return Wc(L?Nn(L,_.home):Wc(_.home,".pi","agent"),"settings.json")}function os(_){if(typeof _!=="string")return!1;return _==="npm:cc-safety-net"||_.startsWith("npm:cc-safety-net@")}function Sh(_){if(!Array.isArray(_)||_.length===0)return!1;if(!_.every((Y)=>typeof Y==="string"))return!1;let L=(Y)=>_.some((Z)=>Z.startsWith(Y)&&Z.slice(1).replace(/^\.[/\\]/,"")===Yc);if(L("-"))return!1;if(L("+"))return!0;let G=_.filter((Y)=>!/^[-+!]/.test(Y));return(G.length===0||G.some((Y)=>zc.has(Y)))&&!_.some((Y)=>Y.startsWith("!")&&(zc.has(Y.slice(1))||xh.test(Y)))}function Zc(_){let L=rs(_.environment),G=vn(L);if(G.kind==="unreadable")return{platform:"pi",status:"not-inspected"};if(G.kind==="missing")return{platform:"pi",status:"n/a"};let Y=Xe(G.value,"packages");if(!Array.isArray(Y))return{platform:"pi",status:"n/a"};let Z=Y.find((se)=>os(typeof se==="string"?se:Xe(se,"source")));if(Z===void 0)return{platform:"pi",status:"n/a"};let oe=Xe(Z,"extensions");if(oe!==void 0&&!Sh(oe))return{platform:"pi",status:"disabled",method:"package config",configPath:L,errors:["npm:cc-safety-net is installed but its extension is disabled in Pi settings"]};return{platform:"pi",status:"configured",method:"package config",configPath:L}}var Ph={amp:el,"antigravity-cli":ol,"claude-code":cl,codex:ul,"copilot-cli":Tl,cursor:Hl,"deepseek-harness":Ml,devin:Wl,droid:tc,"gemini-cli":rc,"grok-build":fc,"hermes-agent":Pc,"kimi-code":po,openclaw:Fc,opencode:Jt,pi:Zc};function Wt(_,L,G){let Y={...G,cwd:L,environment:_};return Rr.map((Z)=>Eh(Ph[Z](Y)))}function Eh(_){if(_.status==="not-inspected")return{platform:_.platform,detected:!1,configured:!1,inspectionStatus:"not-inspected"};return{platform:_.platform,detected:_.status!=="n/a",configured:_.status==="configured",inspectionStatus:_.status!=="n/a"?"verified":_.errors&&_.errors.length>0?"failed":"not-applicable",method:_.method,configPath:_.configPath,configPaths:_.configPaths,errors:_.errors}}import{join as Rh}from"node:path";var _h=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}]),Th=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([])})})}),Ih={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 Xc(_){let L=Rh(_.tmpdir,"cc-safety-net-self-test"),G=_h.map((Y)=>{let Z=W(_,l("self-test",{command:Y.command},{kind:"command",shell:"auto"},{configCwd:L,executionCwd:L},Y.command),{guard:{dependencies:{loadPolicySnapshot:()=>Th,getModes:()=>Ih,findPolicyMutation:()=>null}},audit:{agent:"self-test",getSessionId:()=>{return}}}),oe=Y.expectBlocked?"blocked":"allowed",se=Z.decision.kind==="deny"?"blocked":"allowed";return{command:Y.command,description:Y.description,expected:oe,actual:se,passed:oe===se,reason:Z.decision.kind==="deny"?Z.decision.reason:void 0,ruleId:Z.decision.kind==="deny"?Z.decision.ruleId:void 0}});return{passed:G.filter((Y)=>Y.passed).length,failed:G.filter((Y)=>!Y.passed).length,total:G.length,results:G}}function is(_){let L=mn({label:"doctor",booleans:{json:["--json"],skipUpdateCheck:["--skip-update-check"]}},_);if($n(L.errors))return null;return{json:L.flags.json,skipUpdateCheck:L.flags.skipUpdateCheck}}async function Qc(_,L={}){let G=await nr(!L.json,()=>{let Y=Oh(_,L);return{ready:Y,finish:()=>Y}},()=>er(),{loadingMessage:"Checking system status…"});if(L.json)console.log(JSON.stringify(G,null,2));else $h(G);return G.engineSelfTest.failed>0||G.findings.some((Y)=>Y.severity==="error")?1:0}async function Oh(_,L){let G=L.cwd??process.cwd(),Y=await Nr((Fe)=>Jt({environment:_,cwd:G,openCodeVersion:Fe}).status!=="n/a",void 0,G),Z=Wt(_,G,{ampPluginListOutput:Y.ampPluginListOutput,codexPluginListOutput:Y.codexPluginListOutput,copilotCliVersion:Y.versions["copilot-cli"],openCodeVersion:Y.versions.opencode,openCodePluginListOutput:Y.openCodePluginListOutput}),oe=ha(_,G),se=va(_),fe=R(_,{cwd:G}),ge=fe.policy,Pe=P(ge,_.env),Ee=K(ge,Pe.capabilities),Re=Ar(_,7),Le=za(_,G),_e=[Lt(G),jt(_)].filter((Fe)=>Ah(Fe)),Te=L.skipUpdateCheck?{currentVersion:pn(),latestVersion:null,updateAvailable:!1}:await Gn(),Be={hooks:Z,engineSelfTest:Xc(_),userConfig:oe.userConfig,projectConfig:oe.projectConfig,configState:Ve(fe),effectiveRules:oe.effectiveRules,environment:se,effectiveSafety:{selectedPreset:ge.safety.level,level:Pe.effectiveLevel,capabilities:Pe.capabilities,ruleOverrides:ge.destructiveCommandRuleOverrides,weakenedRuleOverrides:Object.entries(Ee).filter(([,Fe])=>Fe.source==="rule_override"&&Fe.override==="off"&&Fe.inheritedEnabled&&Fe.changesInherited).map(([Fe])=>Fe),ruleCounts:{stored:Object.keys(ge.destructiveCommandRuleOverrides).length,effective:Object.values(Ee).filter((Fe)=>Fe.changesInherited).length},...fe.policyScopes?{policyScopes:fe.policyScopes}:{}},...Le.length>0?{v2Leftovers:Le}:{},..._e.length>0?{legacyConfigs:_e}:{},posture:Oa(_,oe.userConfig.path),activity:Re,update:Te,system:Y};return{...Be,findings:wa(Be)}}function $h(_){console.log(),console.log(Ca(_.hooks)),console.log(),console.log(xa(_.engineSelfTest)),console.log(),console.log(Sa(_)),console.log(),console.log(Pa(_.environment)),console.log(),console.log(Ea(_)),console.log(),console.log(Ra(_.findings)),console.log(),console.log(_a(_.activity)),console.log(),console.log(Ia(_.system)),console.log(),console.log(Ta(_.update)),console.log(Aa(_))}import{existsSync as Dh}from"node:fs";var Nh=/^[A-Za-z0-9_@%+=:,./-]+$/,ed="Usage: cc-safety-net explain [--json] [--cwd <path>] <command>";function ss(_){let L=mn({label:"explain",booleans:{json:["--json"]},values:{cwd:["--cwd"]},positionals:"tail"},_);if($n(L.errors))return console.error(ed),console.error("Pass -- before a command that starts with dashes."),null;if(L.values.cwd!==void 0&&!Dh(L.values.cwd))return console.error(`Error: --cwd path does not exist: ${L.values.cwd}`),null;let G=L.positionals.length===1?L.positionals[0]:L.positionals.map((Y)=>Nh.test(Y)?Y:`'${Y.replaceAll("'","'\\''")}'`).join(" ");if(!G)return console.error("Error: No command provided"),console.error(ed),null;return{json:L.flags.json,cwd:L.values.cwd,command:G}}function nd(_){if(_)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(_,L){let Y=L-18;return[`${_.dtl}${_.dh.repeat(L)}${_.dtr}`,`${_.dv} Command Analysis${" ".repeat(Y)}${_.dv}`,`${_.dbl}${_.dh.repeat(L)}${_.dbr}`]}function as(_){return JSON.stringify(_)}function rd(_,L=0){return`[${_.map((Y,Z)=>ka(Y,Z,L)).join(",")}]`}function fr(_,L,G=70){let Y=_.split(" "),Z=[],oe="";for(let se of Y)if(oe&&oe.length+se.length+1>G)Z.push(oe),oe=se;else oe=oe?`${oe} ${se}`:se;if(oe)Z.push(oe);return Z.map((se,fe)=>fe===0?se:`${L}${se}`)}function od(_,L,G){let Y=[];switch(_.type){case"parse":return null;case"env-strip":return Y.push(""),Y.push(`STEP ${L} ${G.h} Strip environment variables`),Y.push(` Removed: ${_.envVars.map((Z)=>`${Z}=<redacted>`).join(", ")}`),Y.push(` Tokens: ${as(_.output)}`),{lines:Y,incrementStep:!0};case"leading-tokens-stripped":return Y.push(""),Y.push(`STEP ${L} ${G.h} Strip wrappers`),Y.push(` Removed: ${_.removed.join(", ")}`),Y.push(` Tokens: ${as(_.output)}`),{lines:Y,incrementStep:!0};case"shell-wrapper":return Y.push(""),Y.push(`STEP ${L} ${G.h} Detect shell wrapper`),Y.push(` Wrapper: ${_.wrapper} -c`),Y.push(` Inner: ${_.innerCommand}`),{lines:Y,incrementStep:!0};case"interpreter":{if(Y.push(""),Y.push(`STEP ${L} ${G.h} Detect interpreter`),Y.push(` Interpreter: ${_.interpreter}`),Y.push(` Code: ${_.codeArg}`),_.paranoidBlocked)Y.push(" Result: ✗ BLOCKED (paranoid mode)");return{lines:Y,incrementStep:!0}}case"busybox":return Y.push(""),Y.push(`STEP ${L} ${G.h} Busybox wrapper`),Y.push(` Subcommand: ${_.subcommand}`),{lines:Y,incrementStep:!0};case"transparent-wrapper":return Y.push(""),Y.push(`STEP ${L} ${G.h} Transparent wrapper`),Y.push(` Wrapper: ${_.wrapper}`),Y.push(` Tokens: ${as(_.output)}`),{lines:Y,incrementStep:!0};case"recurse":return{lines:[],incrementStep:!1};case"rule-check":{if(Y.push(""),Y.push(`STEP ${L} ${G.h} Match rules`),Y.push(` Rule: ${_.rule}()`),_.matched)Y.push(" Result: MATCHED");else Y.push(" Result: No match");return{lines:Y,incrementStep:!0}}case"worktree-relaxation":return Y.push(""),Y.push(`STEP ${L} ${G.h} Worktree relaxation`),Y.push(` Mode: ${n.worktree.name}`),Y.push(` Git cwd: ${_.gitCwd}`),Y.push(" Result: Allowed local discard in linked worktree"),{lines:Y,incrementStep:!0};case"temp-root-relaxation":return Y.push(""),Y.push(`STEP ${L} ${G.h} Temp-root relaxation`),Y.push(` Git cwd: ${_.gitCwd}`),Y.push(" Result: Allowed git discard in a temp-root repository"),{lines:Y,incrementStep:!0};case"tmpdir-check":return null;case"fallback-scan":{if(_.embeddedCommandFound)return Y.push(""),Y.push(`STEP ${L} ${G.h} Fallback scan`),Y.push(` Found: ${_.embeddedCommandFound}`),{lines:Y,incrementStep:!0};return null}case"custom-rules-check":{if(_.rulesChecked){if(Y.push(""),Y.push(`STEP ${L} ${G.h} Custom rules`),_.matched)Y.push(" Result: MATCHED");else Y.push(" Result: No match");return{lines:Y,incrementStep:!0}}return null}case"cwd-change":return null;case"dangerous-text":{if(_.matched)return Y.push(""),Y.push(`STEP ${L} ${G.h} Dangerous text check`),Y.push(` Token: ${_.token}`),Y.push(" Result: MATCHED"),{lines:Y,incrementStep:!0};return null}case"strict-unparseable":return Y.push(""),Y.push(`STEP ${L} ${G.h} Strict mode check`),Y.push(` Command: ${_.rawCommand}`),Y.push(" Result: ✗ UNPARSEABLE"),{lines:Y,incrementStep:!0};case"segment-skipped":return null;case"error":return Y.push(""),Y.push(`ERROR: ${_.message}`),{lines:Y,incrementStep:!1};default:return _}}function ls(_,L){let G=nd(L?.asciiOnly??!1),Y=58,Z=[],oe=1;Z.push(...td(G,58)),Z.push("");let se=_.trace.steps.find((Te)=>Te.type==="error");if(se&&se.type==="error"){Z.push("ERROR"),Z.push(` ${se.message}`),Z.push(""),Z.push("RESULT"),Z.push(` Status: ${_.result==="blocked"?en.red("BLOCKED"):en.green("ALLOWED")}`),Z.push(""),Z.push("CONFIG");let Te=_.configSource??"none";return Z.push(` Path: ${Te}`),Z.join(`
|
|
228
228
|
`)}let fe=_.trace.steps.find((Te)=>Te.type==="parse");if(fe&&fe.type==="parse"){Z.push("INPUT"),Z.push(` ${fe.input}`),Z.push(""),Z.push(`STEP ${oe} ${G.h} Split shell commands`),oe++;for(let Te=0;Te<fe.segments.length;Te++){let Be=fe.segments[Te];if(Be){let Fe=Math.random();Z.push(` Segment ${Te+1}: ${rd(Be,Fe)}`)}}}let ge=_.trace.segments,Pe=ge.length>1;for(let Te of ge){if(Pe){Z.push("");let tn="";if(fe&&fe.type==="parse"){let Uo=fe.segments[Te.index];if(Uo)tn=Uo.join(" ")}let on=54,an=tn,nn=` Segment ${Te.index+1}: `,sn=" ";if(tn){if(nn.length+tn.length+sn.length>on){let lf=on-nn.length-sn.length;an=`${tn.substring(0,lf-1)}…`}}let Sn=tn?`${nn}${an}${sn}`:` Segment ${Te.index+1} `,sf=tn?`${nn}${en.cyan(an)}${sn}`:Sn,Vs=58-Sn.length,Ks=Math.floor(Vs/2),af=Vs-Ks;Z.push(`${G.sh.repeat(Ks)}${sf}${G.sh.repeat(af)}`)}if(Te.steps.find((tn)=>tn.type==="segment-skipped")){Z.push(""),Z.push(" (skipped — prior segment blocked)");continue}let Fe=!1,Ze=!1;for(let tn of Te.steps){let on=od(tn,oe,G);if(on){if(Ze=!0,tn.type==="recurse"){Z.push("");let an=" RECURSING ",nn=58-an.length-4;Z.push(` ${G.tl}${G.h}${an}${G.h.repeat(nn)}`),Z.push(` ${G.v}`),Fe=!0;continue}for(let an of on.lines)if(Fe)Z.push(` ${G.v} ${an}`);else Z.push(an);if(on.incrementStep)oe++}}if(Fe)Z.push(` ${G.v}`),Z.push(` ${G.bl}${G.h.repeat(56)}`);if(!Ze)Z.push(""),Z.push(` ${en.green("✓")} Allowed (no matching rules)`)}if(Z.push(""),Z.push("RESULT"),_.result==="blocked"){if(Z.push(` Status: ${en.red("BLOCKED")}`),_.customRule){if(Z.push(` Rule: ${_.customRule.id}`),_.customRule.rulebook)Z.push(` Rulebook: ${_.customRule.rulebook.name} ${_.customRule.rulebook.version}`);if(_.customRule.source)Z.push(` Source: ${_.customRule.source}`);if(_.customRule.override)Z.push(` Override: reason ${_.customRule.override.reason}`)}if(_.reason){let Te=fr(_.reason," ");Z.push(` Reason: ${Te[0]}`);for(let Be=1;Be<Te.length;Be++)Z.push(Te[Be]??"")}}else Z.push(` Status: ${en.green("ALLOWED")}`);Z.push(""),Z.push("CONFIG");let Ee=_.configSource??"none",Re=_.configValid?"":" (invalid)";Z.push(` Path: ${Ee}${Re}`);let Le=_.safetyPresetScope;Z.push(` Safety preset: ${_.selectedPreset??"standard"}${Le?` (${Or(Le)})`:""}`),Z.push(` Effective capabilities: ${_.effectiveLevel}`);let _e=Object.entries(_.destructiveCommandRuleOverrides??{});if(Z.push(` Rule customizations: ${_e.length}`),_.ruleActivation)Z.push(` Rule activation: ${_.ruleActivation.id} — ${_.ruleActivation.enabled?"on":"off"} via ${_.ruleActivation.source}`);return Z.join(`
|
|
229
229
|
`)}function cs(_){return JSON.stringify(_,null,2)}import{resolve as Fh}from"node:path";var id=512,sd={maxTextLength:2048,maxListLength:128,maxObjectProperties:128,maxDepth:16},Lh=["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 ps(_){let L=0,G={allocateSegment(){return L++},getNextSegmentIndex(){return L},branch(){let Y=_.fork(),Z=ps(Y);return{trace:Z,adopt(){_.replaceSegmentEvents(Y.finish().events),L=Z.getNextSegmentIndex()}}},recordGlobal(Y){_.record({scope:"global",step:Y})},recordSegment(Y,Z=G.currentSegmentIndex){if(Z===void 0)return;_.record({scope:"segment",segmentIndex:Z,step:Y})}};return G}function fs(_=new Set){let L=[];return{record(G){if(L.length>=id)return;ho(G.step,_,sd),L.push({...G,step:ds(G.step,sd,_)})},fork(){return fs(_)},replaceSegmentEvents(G){L.splice(0,L.length,...[...L.filter((Y)=>Y.scope==="global"),...G].slice(0,id))},finish(){return{events:L}}}}function ho(_,L,G,Y=0,Z=new WeakSet){if(typeof _==="string"){let fe=_.slice(0,G.maxTextLength);if(!rt(fe))return;for(let ge of bt(fe))for(let Pe of ge.match(/[^\s"'()$]+/g)??[])L.add(ad(Pe));return}if(!_||typeof _!=="object"||Y>=G.maxDepth||Z.has(_))return;if(Z.add(_),Array.isArray(_)){let fe=Math.min(_.length,G.maxListLength);for(let ge=0;ge<fe;ge++)ho(_[ge],L,G,Y+1,Z);return}let oe=0,se=new Set;for(let fe in _){if(!Object.hasOwn(_,fe))continue;if(oe>=G.maxObjectProperties)break;oe++,ho(fe,L,G);let ge=us(fe,G,L);if(se.has(ge))continue;se.add(ge),ho(_[fe],L,G,Y+1,Z)}}function ds(_,L,G,Y=0,Z=new WeakSet){if(typeof _==="string")return us(_,L,G);if(!_||typeof _!=="object")return _;if(Y>=L.maxDepth)return;if(Z.has(_))return;if(Z.add(_),Array.isArray(_)){let fe=[],ge=Math.min(_.length,L.maxListLength);for(let Pe=0;Pe<ge;Pe++)fe.push(ds(_[Pe],L,G,Y+1,Z));return fe}let oe={},se=0;for(let fe in _){if(!Object.hasOwn(_,fe))continue;if(se>=L.maxObjectProperties)break;se++;let ge=us(fe,L,G);if(Object.hasOwn(oe,ge))continue;Object.defineProperty(oe,ge,{value:ds(_[fe],L,G,Y+1,Z),enumerable:!0,configurable:!0,writable:!0})}return oe}function us(_,L,G){let Y=_.slice(0,L.maxTextLength),Z=rt(Y)?nt(Y):Y,oe=G.size>0?Hh(Z,G):Z;return(jh(oe)?Me(oe):oe).slice(0,L.maxTextLength)}function jh(_){return _.includes("PRIVATE KEY")||_.includes("://")||_.includes("eyJ")||_.includes(":")&&/(?:authorization|cookie|x-api-key|api-key|(?:^|\s)(?:-u|--user)(?:\s|=))/i.test(_)||_.length>=14&&Lh.some((L)=>_.includes(L))||_.length>=49&&/\b[a-f0-9]{32}\.[A-Za-z0-9]{16}\b/.test(_)}function Hh(_,L){return _.replace(/[^\s"'()$]+/g,(G)=>L.has(ad(G))?"<redacted>":G)}function ad(_){let L=2166136261,G=2166136261;for(let Y=0;Y<_.length;Y++)L=Math.imul(L^_.charCodeAt(Y),16777619),G=Math.imul(G^_.charCodeAt(_.length-Y-1),16777619);return`${L>>>0}:${G>>>0}:${_.length}`}function mr(_,L={},G){let Y=Fh(L.cwd??process.cwd()),Z=L.policySnapshot??R(G,{cwd:Y,userConfigDir:L.userConfigDir}),oe=P(Z.policy,G.env),se=qe({policySnapshot:Z,effectiveCapabilities:oe.capabilities,worktreeMode:oe.worktreeMode}),fe={effectiveLevel:se.effectiveLevel,selectedPreset:Z.policy.safety.level,...Z.policyScopes?{safetyPresetScope:Z.policyScopes.levelScope}:{},effectiveCapabilities:se.effectiveCapabilities,destructiveCommandRuleOverrides:Z.policy.destructiveCommandRuleOverrides},{configSource:ge,configValid:Pe}=Uh(G,{cwd:Y,userConfigDir:L.userConfigDir});if(!_||!_.trim())return{trace:{steps:[{type:"error",message:"No command provided"}],segments:[]},result:"allowed",configSource:ge,configValid:Pe,...fe};let Ee=y(_,"auto");if(Ee.status==="limited")throw new b;let Re=Ee.dialect==="powershell"?y(_,"posix"):Ee,Le=Rt(Re),_e=fs(),Te=ps(_e);Te.recordGlobal({type:"parse",input:_,segments:Le.map((Sn)=>[...Sn])});let Be=l("Bash",{command:_},{kind:"command",shell:"auto"},{configCwd:Y,executionCwd:Y},_),Fe=j(Be,{environment:G,trace:Te,dependencies:{loadPolicySnapshot:()=>Z}}),Ze=Fe.decision.kind==="deny"?Fe.decision:null;if(Ze&&(Fe.stage==="policy-protection"||Fe.stage==="secret-protection"))return{trace:{steps:[],segments:[{index:0,steps:[{type:"rule-check",rule:Mh(Ze),matched:!0,reason:Ze.reason}]}]},result:"blocked",reason:T(Ze.reason),segment:T(ld(Ze,_)),ruleId:T(Ze.ruleId),configSource:ge,configValid:Pe,...fe};let tn=Te.getNextSegmentIndex();if(Ze&&tn>0&&tn<Le.length)Te.recordSegment({type:"segment-skipped",index:tn,reason:"prior-segment-blocked"},tn);let on=_e.finish(),an=Ze?.ruleId??Gh(Be,Z,oe,G),nn=q.find((Sn)=>Sn.id===an&&Sn.activationCapability),sn=nn?se.policy.effectiveDestructiveCommandRules[nn.id]:void 0;return{trace:qh(on),result:Ze?"blocked":"allowed",reason:Ze?T(Ze.reason):void 0,segment:Ze?T(ld(Ze,_)):void 0,ruleId:Ze?T(Ze.ruleId):void 0,customRule:Bh(Vh(Ze?.ruleId,Z)),configSource:ge,configValid:Pe,...fe,...nn&&sn?{ruleActivation:{id:nn.id,...sn}}:{}}}function ld(_,L){return _.evidence?.segment??L}function Mh(_){if(_.reason===Je)return"policy-protection:findPolicyConfigMutationTargetInSemanticFacts";if(_.reason===Ke)return"policy-apply-protection:findPolicyApplyInvocationInSemanticFacts";if(_.reason===v)return"git-metadata-protection:findGitMetadataMutationTargetInSemanticFacts";return"secret-protection:findSensitiveTargetInSemanticFacts"}function Uh(_,L){let G=I(L.cwd),Y=z(_,L),Z=Q(_,{cwd:L.cwd,userConfigDir:L.userConfigDir});try{if(r(Z.projectConfigTarget)!==null){if(Un(Z.projectConfigTarget).errors.length===0)return{configSource:G,configValid:!0};return{configSource:G,configValid:!1}}}catch(oe){if(oe instanceof o)return{configSource:G,configValid:!1};throw oe}try{if(r(Z.userConfigTarget)!==null){let oe=Un(Z.userConfigTarget);return{configSource:Y,configValid:oe.errors.length===0}}return{configSource:null,configValid:!0}}catch(oe){if(oe instanceof o)return{configSource:Y,configValid:!1};throw oe}}function Gh(_,L,G,Y){let Z=L.policy,oe=Ne({...Z,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{...Z.destructiveCommandRuleOverrides,...Object.fromEntries(q.flatMap((fe)=>fe.activationCapability?[[fe.id,"on"]]:[]))}},L.state==="degraded"?{diagnostics:L.diagnostics,reason:L.reason}:void 0),se=j(_,{environment:Y,dependencies:{loadPolicySnapshot:()=>oe,getModes:()=>({...G,strict:!0,paranoidRm:!0,paranoidInterpreters:!0,capabilities:{fail_closed:{...G.capabilities.fail_closed,enabled:!0},paranoid_rm:{...G.capabilities.paranoid_rm,enabled:!0},paranoid_interpreters:{...G.capabilities.paranoid_interpreters,enabled:!0}}}),findSensitiveTarget:()=>null}});return se.decision.kind==="deny"?se.decision.ruleId:void 0}function Bh(_){if(!_)return;return{id:T(_.id),..._.rulebook?{rulebook:{name:T(_.rulebook.name),version:T(_.rulebook.version)}}:{},..._.source?{source:T(_.source)}:{},..._.override?{override:{type:"reason",reason:T(_.override.reason)}}:{}}}function qh(_){let L=_.events.flatMap((Y)=>Y.scope==="global"?[Y.step]:[]),G=new Map;for(let Y of _.events){if(Y.scope!=="segment")continue;let Z=G.get(Y.segmentIndex)??{index:Y.segmentIndex,steps:[]};Z.steps.push(Y.step),G.set(Y.segmentIndex,Z)}return{steps:L,segments:[...G.values()]}}function Vh(_,L){let G=_?.replace(/^custom\./,"");if(!G||!L.policy.rules.some((Y)=>Y.name===G))return;return L.ruleMetadata[G]??Object.freeze({id:G})}function cd(_){return new Promise((L)=>{process.stdout.write(`${_}
|
|
230
|
-
`,()=>L())})}async function dd(_,L){let G=ss(L);if(!G)return 1;try{let Y=mr(G.command,{cwd:G.cwd},_),Z=!!process.env.NO_COLOR||!process.stdout.isTTY;return await cd(G.json?cs(Y):ls(Y,{asciiOnly:Z})),0}catch(Y){let Z=Kh(Y instanceof f?Y.cause:Y);if(Z===void 0)throw Y;if(G.json)return await cd(JSON.stringify({error:Z})),1;return console.error(Z),1}}function Kh(_){if(_ instanceof b)return _.message;if(_ instanceof U)return _.message;if(_ instanceof m)return _.message;if(_ instanceof s&&a[_.kind].errorCode==="path-canonicalization-limit")return"Path canonicalization work limit exceeded.";return}var ud="2.6.
|
|
230
|
+
`,()=>L())})}async function dd(_,L){let G=ss(L);if(!G)return 1;try{let Y=mr(G.command,{cwd:G.cwd},_),Z=!!process.env.NO_COLOR||!process.stdout.isTTY;return await cd(G.json?cs(Y):ls(Y,{asciiOnly:Z})),0}catch(Y){let Z=Kh(Y instanceof f?Y.cause:Y);if(Z===void 0)throw Y;if(G.json)return await cd(JSON.stringify({error:Z})),1;return console.error(Z),1}}function Kh(_){if(_ instanceof b)return _.message;if(_ instanceof U)return _.message;if(_ instanceof m)return _.message;if(_ instanceof s&&a[_.kind].errorCode==="path-canonicalization-limit")return"Path canonicalization work limit exceeded.";return}var ud="2.6.14",Rn=" ",Pt="cc-safety-net";function pd(_){return _.argument?`${_.flags} ${_.argument}`:_.flags}function Jh(_){return Math.max(..._.map((L)=>pd(L).length))}function Wh(_){return Math.max(..._.map((L)=>L.usage.length))}function zh(_){return Math.max(..._.map((L)=>`${Pt} ${L.usage}`.length))}function Yh(_,L){let G=`${Pt} ${_.usage}`;return`${Rn}${G.padEnd(L+2)}${_.description}`}function An(_,L){return`${Rn}${_.padEnd(Math.max(40,_.length+2))}${L}`}function zt(_,L=console.log){let G=[];if(G.push(`${Pt} ${_.name}`),G.push(""),G.push(`${Rn}${_.description}`),G.push(""),G.push("USAGE:"),G.push(`${Rn}${Pt} ${_.usage}`),G.push(""),_.subcommands&&_.subcommands.length>0){G.push("SUBCOMMANDS:");let Y=Wh(_.subcommands);for(let Z of _.subcommands)G.push(`${Rn}${Z.usage.padEnd(Y+2)}${Z.description}`);G.push("")}if(_.options.length>0){G.push("OPTIONS:");let Y=Jh(_.options);for(let Z of _.options){let oe=pd(Z),se=Z.default?`${Z.description} (default: ${Z.default})`:Z.description;G.push(`${Rn}${oe.padEnd(Y+2)}${se}`)}G.push("")}if(_.examples&&_.examples.length>0){G.push("EXAMPLES:");for(let Y of _.examples)G.push(`${Rn}${Y}`)}L(G.join(`
|
|
231
231
|
`))}function ms(){let _=zh(Tr),L=[];L.push(`${Pt} v${ud}`),L.push(""),L.push("Blocks destructive commands and secret access."),L.push(""),L.push("COMMANDS:");for(let G of Tr)L.push(Yh(G,_));L.push(""),L.push("GLOBAL OPTIONS:"),L.push(`${Rn}-h, --help Show help (use with command for command-specific help)`),L.push(`${Rn}-V, --version Show version`),L.push(""),L.push("HELP:"),L.push(`${Rn}${Pt} help <command> Show help for a specific command`),L.push(`${Rn}${Pt} <command> --help Show help for a specific command`),L.push(""),L.push("ENVIRONMENT VARIABLES:"),L.push(An(`${n.level.name}=standard|strict|paranoid`,"Set session safety level")),L.push(An(`${n.worktree.name}=1`,"Allow local git discards in linked worktrees")),L.push(An(`${n.debug.name}=1`,"Print diagnostic messages to stderr")),L.push(An(`${n.auditScope.name}=all|blocked`,"Record all command decisions, or denials only")),L.push(An(`${n.projectTightenOnly.name}=1`,"Ignore project policy settings that weaken the user policy")),L.push(An("CC_SAFETY_NET_HOME","Override rule config home directory")),L.push(""),L.push("LEGACY ENVIRONMENT VARIABLES (STILL SUPPORTED):"),L.push(An(`${n.strict.name}=1`,"Force safety.overrides.fail_closed on")),L.push(An(`${n.paranoid.name}=1`,"Force paranoid_rm and paranoid_interpreters on")),L.push(An(`${n.paranoidRm.name}=1`,"Force safety.overrides.paranoid_rm on")),L.push(An(`${n.paranoidInterpreters.name}=1`,"Force safety.overrides.paranoid_interpreters on")),L.push(""),L.push("Documentation: https://ccsafetynet.com/docs"),console.log(L.join(`
|
|
232
232
|
`))}function fd(){console.log(ud)}function gr(_,L=console.log){let G=Ir(_);if(!G)return!1;if(G.name.toLowerCase()!==_.toLowerCase())return!1;return zt(G,L),!0}import{existsSync as Po,readFileSync as bu}from"node:fs";import{join as So}from"node:path";import*as Vn from"node:readline";function Zh(_){return _==="install"?"Install":"Uninstall"}function Xh(_){return _==="install"?"Installing":"Uninstalling"}function Qh(_){return _==="install"?"into":"from"}function yd(_){return _?.available===!0}function ev(_,L){let G=new Set(L);return _.filter((Y)=>G.has(Y.target)).map((Y)=>Y.target)}function md(_,L,G){if(_.every((Y)=>!Y.available))return L;return Array.from({length:_.length},(Y,Z)=>Z+1).map((Y)=>(L+Y*G+_.length)%_.length).find((Y)=>yd(_[Y]))}function nv(_,L,G){if(G.ctrl&&G.name==="c")return"interrupt";if(G.name==="escape"||L==="q")return"abort";if(_==="install"&&(L==="u"||L==="U"))return"update";if(G.name==="up"||L==="k")return"up";if(G.name==="down"||L==="j")return"down";if(G.name==="space"||L===" ")return"toggle";if(G.name==="return"||G.name==="enter")return"confirm";return null}function tv(_){return{cursor:_.findIndex((L)=>L.available),selected:[]}}function rv(_,L,G){if(G==="confirm"||G==="update"||G==="abort"||G==="interrupt")return{state:_,done:G};if(G==="up")return{state:{..._,cursor:md(L,_.cursor,-1)}};if(G==="down")return{state:{..._,cursor:md(L,_.cursor,1)}};let Y=L[_.cursor];if(!yd(Y))return{state:_};let Z=_.selected.includes(Y.target)?_.selected.filter((oe)=>oe!==Y.target):ev(L,[..._.selected,Y.target]);return{state:{..._,selected:Z}}}var hd="◉",vd="◯",bd=">",wd=" ";function ov(_,L,G){return["",`${Zh(_)} CC Safety Net ${Qh(_)}:`,"",...L.map((Y,Z)=>{let oe=G.selected.includes(Y.target),se=Z===G.cursor,fe=oe?hd:vd,ge=se?bd:wd,Pe=Y.available?"":` (${Y.unavailableReason??"not installed"})`,Ee=`${fe} ${Y.label}${Pe}`,Re=!Y.available?en.dim(Ee):oe?en.green(Ee):se?en.bold(Ee):Ee;return`${ge} ${Re}`}),"",_==="install"?"Space: select Enter: confirm u: update installed Up/Down: move q/Esc: cancel":L.some((Y)=>Y.available)?"Space: select Enter: confirm Up/Down: move q/Esc: cancel":`No selectable integrations found for ${_}. q/Esc: close`].join(`
|
|
233
233
|
`)}var gd=["global-hook","plugin"];function iv(_,L,G={}){let Y=G.color!==!1?en.bold:(oe)=>oe;return["","Install the Kimi Code integration as:","",...[`Global hook — ${L?"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((oe,se)=>{let fe=se===_,ge=`${fe?hd:vd} ${oe}`;return`${fe?bd:wd} ${fe?Y(ge):ge}`}),"","Enter: confirm Up/Down: move q/Esc: cancel"].join(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../chunks/index-
|
|
1
|
+
import"../chunks/index-z14g58a6.js";import{yt}from"../chunks/index-1x1d9s1m.js";import"../chunks/index-rwp0taf5.js";import"../chunks/index-pgmgvnyg.js";var t={name:"cc-safety-net",inject:["tools"],apply:yt};export{t as default};
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{x,Ee}from"./chunks/index-
|
|
1
|
+
import{x,Ee}from"./chunks/index-z14g58a6.js";import{Le,ke,gt,Ze,Xe}from"./chunks/index-aq50vwpd.js";import"./chunks/index-pgmgvnyg.js";import{execFile as Af}from"node:child_process";var re=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let r=e;for(let n=0,o=t.length;n<o;n++)r=t[n](r);return r}}},Cc={pipe(){return re(this,arguments)}},Dt=function(){function e(){}return e.prototype=Cc,e}();var w=function(e,t){if(typeof e==="function")return function(){return e(arguments)?t.apply(this,arguments):(r)=>t(r,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(r,n){if(arguments.length>=2)return t(r,n);return function(o){return t(o,r)}};case 3:return function(r,n,o){if(arguments.length>=3)return t(r,n,o);return function(s){return t(s,r,n)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let r=arguments;return function(n){return t(n,...r)}}}};var Q=(e)=>e;var Ss=(e)=>()=>e;var lt=Ss(void 0),ys=lt;function ze(e){let t=new WeakMap;return(r)=>{let n=t.get(r);if(n!==void 0)return n;let o=e(r);return t.set(r,o),o}}function ft(e){let t=new WeakMap;return(r)=>{let n=t.get(r);if(n!==void 0)return n;let o=e(r);return t.set(r,o),t.set(o,o),o}}var Ut=(e)=>{let t=new Set(Reflect.ownKeys(e));if(e.constructor===Object)return t;if(e instanceof Error)t.delete("stack");let r=Object.getPrototypeOf(e),n=r;while(n!==null&&n!==Object.prototype){let o=Reflect.ownKeys(n);for(let s=0;s<o.length;s++)t.add(o[s]);n=Object.getPrototypeOf(n)}if(t.has("constructor")&&typeof e.constructor==="function"&&r===e.constructor.prototype)t.delete("constructor");return t},Mt=new WeakSet;function Nt(e){return typeof e==="string"}function En(e){return typeof e==="number"}function Ts(e){return typeof e==="symbol"}function Sr(e){return Nt(e)||En(e)||Ts(e)}function pt(e){return typeof e==="function"}function bn(e){return e!==void 0}function wn(e){return e!=null}function Es(e){return!0}function In(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function yr(e){return typeof e==="object"&&e!==null||pt(e)}var C=w(2,(e,t)=>yr(e)&&(t in e));function bs(e){return e instanceof Error}var G="~effect/interfaces/Hash",R=(e)=>{switch(typeof e){case"number":return wr(e);case"bigint":return L(e.toString(10));case"boolean":return L(String(e));case"symbol":return L(String(e));case"string":return L(e);case"undefined":return L("undefined");case"function":case"object":if(e===null)return L("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return L("Invalid Date");return L(e.toISOString())}else if(e instanceof RegExp)return L(e.toString());else{if(Mt.has(e))return Tr(e);if(On.has(e))return On.get(e);let t=Fc(e,()=>{if(kc(e))return e[G]();else if(typeof e==="function")return Tr(e);else if(e instanceof DataView)return Er(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e)||ArrayBuffer.isView(e))return Er(e);else if(e instanceof Map)return _c(e);else if(e instanceof Set)return Ac(e);return Rc(e)});return On.set(e,t),t}default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},Tr=(e)=>{if(!vn.has(e))vn.set(e,wr(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return vn.get(e)},ee=w(2,(e,t)=>e*53^t),br=(e)=>e&3221225471|e>>>1&1073741824,kc=(e)=>C(e,G),wr=(e)=>{if(e!==e)return L("NaN");if(e===1/0)return L("Infinity");if(e===-1/0)return L("-Infinity");let t=e|0;if(t!==e)t^=e*4294967295;while(e>4294967295)t^=e/=4294967295;return br(t)},L=(e)=>{let t=5381,r=e.length;while(r)t=t*33^e.charCodeAt(--r);return br(t)},kn=(e,t)=>{let r=12289;for(let n of t)r^=ee(R(n),R(e[n]));return br(r)},Rc=(e)=>kn(e,Ut(e)),Rn=(e,t)=>(r)=>{let n=e;for(let o of r)n^=t(o);return br(n)},Er=Rn(6151,R),_c=Rn(L("Map"),([e,t])=>ee(R(e),R(t))),Ac=Rn(L("Set"),R),vn=new WeakMap,On=new WeakMap,Cn=new WeakSet;function Fc(e,t){if(Cn.has(e))return L("[Circular]");Cn.add(e);let r=t();return Cn.delete(e),r}var z="~effect/interfaces/Equal";function q(){if(arguments.length===1)return(e)=>He(e,arguments[0]);return He(arguments[0],arguments[1])}function He(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let r=typeof e;if(r!==typeof t)return!1;if(r==="number"&&e!==e&&t!==t)return!0;if(r!=="object"&&r!=="function")return!1;if(Mt.has(e)||Mt.has(t))return!1;return Uc(e,t,Dc)}function Pc(e,t,r){let n=_n.has(e),o=An.has(t);if(n&&o)return!0;if(n||o)return!1;_n.add(e),An.add(t);let s=r();return _n.delete(e),An.delete(t),s}var _n=new WeakSet,An=new WeakSet;function Dc(e,t){if(R(e)!==R(t))return!1;else if(e instanceof Date){if(!(t instanceof Date))return!1;let s=e.getTime(),a=t.getTime();return s===a||Number.isNaN(s)&&Number.isNaN(a)}else if(e instanceof RegExp){if(!(t instanceof RegExp))return!1;return e.toString()===t.toString()}let r=Is(e),n=Is(t);if(r!==n)return!1;let o=r&&n;if(typeof e==="function"&&!o)return!1;return Pc(e,t,()=>{if(o)return e[z](t);else if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;return Mc(e,t)}else if(ArrayBuffer.isView(e)){let s=e instanceof DataView;if(!ArrayBuffer.isView(t)||e.byteLength!==t.byteLength||s!==t instanceof DataView)return!1;if(s){let a=t;return ws(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}return ws(e,t)}else if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;return $c(e,t)}else if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;return jc(e,t)}return Nc(e,t)})}function Uc(e,t,r){let n=Ir.get(e);if(!n)n=new WeakMap,Ir.set(e,n);else if(n.has(t))return n.get(t);let o=r(e,t);n.set(t,o);let s=Ir.get(t);if(!s)s=new WeakMap,Ir.set(t,s);return s.set(e,o),o}var Ir=new WeakMap;function Mc(e,t){for(let r=0;r<e.length;r++)if(!He(e[r],t[r]))return!1;return!0}function ws(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Nc(e,t){let r=Ut(e),n=Ut(t);if(r.size!==n.size)return!1;for(let o of r)if(!n.has(o)||!He(e[o],t[o]))return!1;return!0}function Lc(e,t){return function(n,o){let s=Array.from(o);for(let[a,c]of n){let u=!1;for(let i=0;i<s.length;i++){let[f,g]=s[i];if(e(a,f)&&t(c,g)){s[i]=s[s.length-1],s.pop(),u=!0;break}}if(!u)return!1}return!0}}var $c=Lc(He,He);function Bc(e){return function(r,n){let o=Array.from(n);for(let s of r){let a=!1;for(let c=0;c<o.length;c++){let u=o[c];if(e(s,u)){o[c]=o[o.length-1],o.pop(),a=!0;break}}if(!a)return!1}return!0}}var jc=Bc(He),Is=(e)=>C(e,z);var Lt=Symbol.for("~effect/Redactable"),qc=(e)=>C(e,Lt);function ht(e){if(qc(e))return Fn(e);return e}function Fn(e){return e[Lt](globalThis[xt]?.context??Jc)}var xt="~effect/Fiber/currentFiber",vs=new Map,Jc={"~effect/Context":{},base:vs,depth:0,mapUnsafe:vs,pipe(){return re(this,arguments)}};function A(e,t){let r=t?.space??0,n=new WeakSet,o=!r?"":typeof r==="number"?" ".repeat(r):r,s=(i)=>o.repeat(i),a=(i,f)=>{let g=i?.constructor;return g&&g!==Object.prototype.constructor&&g.name?`${g.name}(${f})`:f},c=(i)=>{try{return Reflect.ownKeys(i)}catch{return["[ownKeys threw]"]}};function u(i,f=0){if(typeof i==="string")return JSON.stringify(i);if(typeof i==="number"||i==null||typeof i==="boolean"||typeof i==="symbol")return String(i);if(typeof i==="bigint")return String(i)+"n";if(typeof i==="object"||typeof i==="function"){if(n.has(i))return Kc;n.add(i);let g;if(Lt in i)g=u(Fn(i),f);else if(Array.isArray(i))g=!o||i.length<=1?`[${i.map((h)=>u(h,f)).join(",")}]`:`[
|
|
2
2
|
${s(f+1)}${i.map((h)=>u(h,f+1)).join(`,
|
|
3
3
|
`+s(f+1))}
|
|
4
4
|
${s(f)}]`;else if(i instanceof Date)g=Os(i);else if(!t?.ignoreToString&&C(i,"toString")&&typeof i.toString==="function"&&i.toString!==Object.prototype.toString&&i.toString!==Array.prototype.toString){let h=Gc(i);g=i instanceof Error&&i.cause?`${h} (cause: ${u(i.cause,f)})`:h}else if(Symbol.iterator in i)g=`${i.constructor.name}(${u(Array.from(i),f)})`;else{let h=c(i);if(!o||h.length<=1){let m=`{${h.map((p)=>`${$t(p)}:${u(i[p],f)}`).join(",")}}`;g=a(i,m)}else{let m=`{
|