@useanvil/claude-code 0.0.0-stage → 0.8.0

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.
@@ -0,0 +1,37 @@
1
+ "use strict";var Re=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var bt=Object.prototype.hasOwnProperty;var xt=(a,e)=>{for(var t in e)Re(a,t,{get:e[t],enumerable:!0})},yt=(a,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of wt(e))!bt.call(a,n)&&n!==t&&Re(a,n,{get:()=>e[n],enumerable:!(s=kt(e,n))||s.enumerable});return a};var $t=a=>yt(Re({},"__esModule",{value:!0}),a);var cs={};xt(cs,{readCmd:()=>Ct,readPowerShell:()=>St});module.exports=$t(cs);var it=require("buffer");function St(a,e){return ot(a,e,(t,s)=>new xe(s,t).program())}function Ct(a,e){return ot(a,e,(t,s)=>gt(s,t))}var at=64*1024,we=32,jt=128*1024,Wt=4*at,Pt=64*1024,Q="Unknown",ve=`[ -n "$${Q}" ]`,X="\uFDD0",ie="\uFDD1",ge='eval "$PowerShellUnread"',ne=class extends Error{constructor(t,s=!1){super(t);this.why=t;this.fatal=s}};function g(a){throw new ne(a)}function ae(a){throw new ne(a,!0)}function oe(a,e){return a.unread.push(e),ge}function Ke(a,e,t){return a.unread.length=e,a.drive=null,oe(a,t)}function ot(a,e,t){if(a.length>at)return{kind:"unreadable",why:"longer than 64 KB"};if(a.includes(X)||a.includes(ie)||a.includes("\0")||a.includes(""))return{kind:"unreadable",why:"holds control characters"};let s=a.replace(/\r\n?/g,`
2
+ `),n={cwd:e.cwd,drive:ke(e.cwd),depth:0,functions:new Set,vars:new Map,marks:[],maybe:0,unread:[],aliases:new Map,work:0};try{let r=t(n,s).trim();return r.length>jt?{kind:"unreadable",why:"too long once translated"}:{kind:"shell",text:r===""?"true":r,unread:[...n.unread]}}catch(r){if(r instanceof ne)return{kind:"unreadable",why:r.why};if(r instanceof RangeError)return{kind:"unreadable",why:"nests too deeply"};throw r}}var p=a=>({t:"lit",s:a}),L=a=>({t:"var",n:a}),K={t:"home"},j=[L(Q)];function W(...a){let e=[];for(let t of a)for(let s of t){let n=e[e.length-1];s.t==="lit"&&s.s===""||(s.t==="lit"&&n?.t==="lit"?e[e.length-1]=p(n.s+s.s):e.push(s))}return e}var se=class{out=[];buf="";text(e){this.buf+=e}add(e){for(let t of e)t.t==="lit"?this.buf+=t.s:(this.flush(),this.out.push(t))}word(){return this.flush(),this.out}flush(){this.buf!==""&&this.out.push(p(this.buf)),this.buf=""}};function w(a){let e="";for(let t of a){if(t.t!=="lit")return null;e+=t.s}return e}function M(a){return(a.includes("\0")||a.includes(""))&&g("a NUL character"),a.split(/([\v\f\r])/).map(e=>/^[\v\f\r]$/.test(e)?lt[e]:e===""?"":`'${e.replace(/'/g,"'\\''")}'`).join("")||"''"}var lt={"\v":"$'\\v'","\f":"$'\\f'","\r":"$'\\r'"};function c(a){let e=[...a];if(e.length===0)return"''";let t="";if(e[0].t==="home"){let r=e[1];if(r===void 0)return"~";if(r.t==="lit"&&(r.s.startsWith("\\")||r.s.startsWith("/"))&&(t="~/",e=r.s.length>1?[p(r.s.slice(1)),...e.slice(2)]:e.slice(2),e.length===0))return t}e=e.map(r=>r.t==="home"?L("HOME"):r);let s=w(e);if(s!==null)return t+M(s);let n='"';for(let r=0;r<e.length;r++){let i=e[r];if(i.t==="lit")(i.s.includes("\0")||i.s.includes(""))&&g("a NUL character"),n+=i.s.replace(/[\\"$`]/g,o=>`\\${o}`).replace(/[\v\f\r]/g,o=>`"${lt[o]}"`);else if(i.t==="var"){let o=e[r+1];n+=o?.t==="lit"&&/^[A-Za-z0-9_]/.test(o.s)?`\${${i.n}}`:`$${i.n}`}else i.t==="sub"&&(n+=`$( ${i.code} )`)}return`${t}${n}"`}var ct=/^[A-Za-z0-9_.,:/@%+=-]+$/;function B(a){let e=w(a);return e!==null&&ct.test(e)?e:c(a)}var je={words:[]},T={words:[j]};function Y(a){return{words:[[p(a)]],text:a}}function C(a,e=!1){let t=w(a),s=t===null?{words:[a]}:{words:[a],text:t};return e?{...s,path:!0}:s}function Z(a){return a===""?je:{words:[[{t:"sub",code:a}]]}}function de(a){return a.reduce((e,t)=>e+t.words.length,0)>Pt&&ae("too long once translated"),{words:a.flatMap(e=>e.words)}}function Ze(a,e){a.work+=e.length,a.work>Wt&&ae("too much text read again as code")}function P(a){let e=a.flatMap(t=>t.words.flatMap(s=>s.filter(n=>n.t==="sub")));return e.length===0?T:a.some(t=>t.unread)?{words:[e],computed:!0,unread:!0}:{words:[e],computed:!0}}function Et(a,e,t=[]){return{words:[[...t.flatMap(n=>n.words.flatMap(r=>r.filter(i=>i.t==="sub"))),{t:"sub",code:oe(a,e)}]],unread:!0}}function k(a){return a.words.length===1?a.words[0]:W(...a.words.flatMap((e,t)=>t>0?[[p(" ")],e]:[e]))}function O(a){let e=a.flatMap(t=>t.words.flatMap(s=>s.filter(n=>n.t==="sub")));return e.length>0?`true ${c(e)}`:""}function Se(a,e){let t=e.flatMap(s=>s.words.flatMap(n=>n.filter(r=>r.t==="sub"&&!a.includes(`$( ${r.code} )`))));return t.length>0?`true ${c(t)}; ${a}`:a}function pe(a){let e=a.words.length===1&&a.computed!==!0?a.words[0]:null;return e?.length===1&&e[0].t==="sub"?e[0].code:null}function Ne(a){let e=a[a.length-1];if(e?.t!=="lit")return null;let t=Math.max(e.s.lastIndexOf("\\"),e.s.lastIndexOf("/")),s=t>=0?e.s.slice(t+1):a.length===1?e.s:"";return s===""||/[*?]/.test(s)?null:be(s)}function Vt(a){let e=c(a),t=a[a.length-1];return ut(a)||e.endsWith("/")||t?.t==="lit"&&/[\\/]$/.test(t.s)?e:`${e}/`}function ut(a){let e=a[a.length-1];return e?.t!=="lit"?!1:/[*?[]/.test(e.s.split(/[\\/]/).pop()??"")}function It(a){let e=w(a);return e!==null&&/^[A-Za-z0-9_.*?-]+$/.test(e)?e:c(a)}function At(a){if(["where-object","select-object","sort-object","get-unique"].includes(a.name))return!0;if(a.name!=="foreach-object")return!1;let e=x(b["foreach-object"],a.elem.args),t=s=>s===""||s===`printf '%s\\n' "$psitem"`;return[...e.values.values(),...e.extra].every(s=>s.block!==void 0?t(s.block.code):s.text!==void 0)}function Ye(a){let e=a[a.length-1];return e?.t==="lit"&&/(^|[:\\/])win32_process$/i.test(e.s)}function Rt(a,e){return(t,s)=>t==="cmd"?$e(a,e,s):Lt(a,e,s)}function _e(a,e){return(t,s)=>oe(a,`${s}: ${e}`)}function Ge(a,e){let t="";for(let s of a)if(s.t==="lit")t+=s.s;else if(s.t==="home"||s.t==="var"&&ht.has(s.n))t+=ye(e,s);else return null;return t}function Ee(a,e,t,s){return y(e===null?`${a}; ${oe(t,`${s}: a command line the line does not show`)}`:`${a}; ${re($e(e,t,s))}`)}function De(a,e,t){let s=["schtasks",...a.map(c)].join(" "),n=a.map(o=>w(o)?.toLowerCase()??"");if(n.some(o=>o==="/xml"||o==="-xml"))return y(`${s}; ${oe(e,"a scheduled task from XML")}`);let r=n.findIndex(o=>o==="/tr"||o==="-tr");if(r<0)return s;let i=a[r+1];return Ee(s,i===void 0?null:t(i),e,"a scheduled task")}function Be(a,e,t){let s=["wmic",...a.map(c)].join(" "),n=a.map(o=>w(o)?.toLowerCase()??""),r=n.findIndex((o,l)=>o==="call"&&n[l+1]==="create"&&(n[l-1]==="process"||n[l-1]==="win32_process"));if(r<0)return s;let i=a[r+2];return Ee(s,i===void 0?null:t(i),e,"a process wmic starts")}function Lt(a,e,t){Ze(e,a),++e.depth>we&&ae("nests too deeply");let s=e.unread.length;try{return new xe(a.replace(/\r\n?/g,`
3
+ `),e).program()}catch(n){if(!(n instanceof ne)||n.fatal)throw n;return Ke(e,s,`${t}: ${n.why}`)}finally{e.depth--}}var Ot=[["help","h",!1],["?","?",!1],["login","l",!1],["mta","mta",!1],["sta","sta",!1],["noexit","noe",!1],["noprofile","nop",!1],["nologo","nol",!1],["noninteractive","noni",!1],["socketservermode","so",!1],["servermode","s",!1],["namedpipeservermode","nam",!1],["sshservermode","sshs",!1],["interactive","i",!1],["configurationfile","configurationfile",!0],["configurationname","config",!0],["custompipename","custompipename",!0],["command","c",!0],["windowstyle","w",!0],["file","f",!0],["executionpolicy","ex",!0],["ep","ep",!0],["encodedcommand","e",!0],["ec","e",!0],["encodedarguments","encodeda",!0],["ea","ea",!0],["settingsfile","settings",!0],["version","v",!0],["workingdirectory","wo",!0],["wd","wd",!0],["outputformat","o",!0],["of","o",!0],["inputformat","in",!0],["if","if",!0],["psconsolefile","psconsolefile",!0]],Tt={ep:"executionpolicy",ec:"encodedcommand",ea:"encodedarguments",wd:"workingdirectory",of:"outputformat",if:"inputformat"};function Mt(a){if(a.length<2||!(I(a[0]??"")||a[0]==="/"))return null;let e=a.slice(1);I(e[0]??"")&&(e=e.slice(1)),e=e.toLowerCase();for(let[t,s,n]of Ot)if(t.startsWith(e)&&e.length>=s.length)return{name:Tt[t]??t,value:n};return"unknown"}var Le={currentusercurrenthost:[K,p("/Documents/PowerShell/Microsoft.PowerShell_profile.ps1")],currentuserallhosts:[K,p("/Documents/PowerShell/profile.ps1")],alluserscurrenthost:[p("C:\\Program Files\\PowerShell\\7\\Microsoft.PowerShell_profile.ps1")],allusersallhosts:[p("C:\\Program Files\\PowerShell\\7\\profile.ps1")]},ht=new Set(["PWD","TMPDIR","CLAUDE_PROJECT_DIR"]);function Nt(a){return a!==void 0&&["invoke-webrequest","invoke-restmethod","curl","wget"].includes(a.name)}var _t="'\u2018\u2019\u201A\u201B",Dt='"\u201C\u201D\u201E',Bt="-\u2013\u2014\u2015",G=a=>a!==""&&_t.includes(a),H=a=>a!==""&&Dt.includes(a),te=a=>G(a)||H(a),I=a=>a!==""&&Bt.includes(a),U=a=>a>="0"&&a<="9"&&a.length===1;function q(a){if(a===" "||a===" ")return!0;if(a==="")return!1;let e=a.charCodeAt(0);return e===11||e===12||e===160||e===133||e===5760||e>=8192&&e<=8202||e===8239||e===8287||e===12288||e===65279}function D(a){if(a==="")return!1;let e=a.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122?!0:e>127&&new RegExp("\\p{L}","u").test(a)}var R=a=>D(a)||U(a)||a==="_";function le(a){return a===""||q(a)||a===`
4
+ `||a===";"||a==="|"||a==="&"||a==="("||a===")"||a==="{"||a==="}"||a===","||a===">"||a==="<"}var zt={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
5
+ `,r:"\r",t:" ",v:"\v"};function ke(a){if(!a)return null;let e=/^([A-Za-z]:)(?:[\\/]|$)/.exec(a);if(e)return e[1].toUpperCase();let t=/^(\\\\[^\\/]+\\[^\\/]+)/.exec(a);return t?t[1]:null}var Ft={"%":"foreach-object","?":"where-object",ac:"add-content",cat:"get-content",cd:"set-location",chdir:"set-location",clc:"clear-content",clear:"clear-host",cls:"clear-host",cli:"clear-item",clv:"clear-variable",compare:"compare-object",copy:"copy-item",cp:"copy-item",cpi:"copy-item",cvpa:"convert-path",del:"remove-item",diff:"compare-object",dir:"get-childitem",echo:"write-output",erase:"remove-item",fl:"format-list",foreach:"foreach-object",ft:"format-table",fw:"format-wide",gal:"get-alias",gc:"get-content",gcb:"get-clipboard",gci:"get-childitem",gcm:"get-command",gdr:"get-psdrive",ghy:"get-history",gi:"get-item",gjb:"get-job",gl:"get-location",gm:"get-member",gmo:"get-module",gp:"get-itemproperty",gpv:"get-itempropertyvalue",gps:"get-process",group:"group-object",gsv:"get-service",gu:"get-unique",gv:"get-variable",gwmi:"get-wmiobject",h:"get-history",history:"get-history",icm:"invoke-command",iex:"invoke-expression",ihy:"invoke-history",ii:"invoke-item",ipmo:"import-module",irm:"invoke-restmethod",iwr:"invoke-webrequest",kill:"stop-process",ls:"get-childitem",man:"get-help",md:"mkdir",measure:"measure-object",mi:"move-item",move:"move-item",mv:"move-item",nal:"new-alias",ni:"new-item",nv:"new-variable",oh:"out-host",popd:"pop-location",ps:"get-process",pushd:"push-location",pwd:"get-location",r:"invoke-history",rd:"remove-item",ren:"rename-item",ri:"remove-item",rm:"remove-item",rmdir:"remove-item",rni:"rename-item",rv:"remove-variable",rvpa:"resolve-path",sajb:"start-job",sal:"set-alias",saps:"start-process",sc:"set-content",select:"select-object",set:"set-variable",si:"set-item",sl:"set-location",sleep:"start-sleep",sls:"select-string",sort:"sort-object",sp:"set-itemproperty",spps:"stop-process",start:"start-process",sv:"set-variable",tee:"tee-object",type:"get-content",where:"where-object",write:"write-output",help:"get-help",gin:"get-computerinfo",gtz:"get-timezone",rjb:"remove-job",wjb:"wait-job",rcjb:"receive-job",spjb:"stop-job",epcsv:"export-csv",ipcsv:"import-csv",ogv:"out-gridview",fc:"format-custom",fhx:"format-hex"},qt=new Set(["select-object","sort-object","group-object","format-table","format-list","format-wide","format-custom","format-hex","out-string","out-host","convertto-json","convertfrom-json","convertto-csv","convertfrom-csv","convertto-xml","convertto-html","convertfrom-stringdata","convertto-securestring","convertfrom-securestring","get-unique","out-gridview","measure-object","compare-object","get-member"]),Ut=new Set(["get-date","get-command","get-help","get-service","get-variable","get-module","get-psdrive","get-random","get-filehash","start-sleep","import-module","read-host","clear-host","get-clipboard","wait-process","get-ciminstance","get-wmiobject","get-alias","get-history","get-job","wait-job","receive-job","remove-job","stop-job","get-host","get-culture","get-uiculture","get-executionpolicy","get-timezone","get-computerinfo","get-psreadlineoption","get-psprovider","get-pscallstack","get-event","get-eventlog","get-winevent","get-hotfix","get-netipaddress","get-netadapter","get-volume","get-disk","get-partition","get-psrepository","find-module","get-installedmodule","get-package","get-counter","get-acl","get-authenticodesignature","test-connection","test-netconnection","resolve-dnsname","get-credential","write-progress","set-strictmode","out-default","get-error","get-scheduledtask","get-localuser","get-localgroup","get-printer","get-itempropertyvalue","import-csv","import-clixml","import-powershelldatafile","get-tpm","get-mpcomputerstatus","set-psdebug","new-guid","new-timespan","get-verb","test-json","get-winsystemlocale","get-uptime","select-xml"]),dt={verbose:"s",debug:"s",erroraction:"v",warningaction:"v",informationaction:"v",progressaction:"v",errorvariable:"v",warningvariable:"v",informationvariable:"v",outvariable:"v",outbuffer:"v",pipelinevariable:"v"},Qt={vb:"verbose",db:"debug",ea:"erroraction",wa:"warningaction",infa:"informationaction",proga:"progressaction",ev:"errorvariable",wv:"warningvariable",iv:"informationvariable",ov:"outvariable",ob:"outbuffer",pv:"pipelinevariable"},V={path:"v",literalpath:"v"},E={pspath:"literalpath",lp:"literalpath"},J={filter:"v",include:"v",exclude:"v",credential:"v"},b={"remove-item":{params:{...V,...J,recurse:"s",force:"s",stream:"v"},positions:["path"],aliases:E,prefer:["force","recurse","path","literalpath"],sp:!0},"clear-content":{params:{...V,...J,force:"s",stream:"v"},positions:["path"],aliases:E,prefer:["force","path"],sp:!0},"set-content":{params:{...V,...J,value:"v",force:"s",passthru:"s",nonewline:"s",encoding:"v",stream:"v",asbytestream:"s"},positions:["path","value"],aliases:E,prefer:["force","path","value"],sp:!0},"out-file":{params:{filepath:"v",literalpath:"v",encoding:"v",append:"s",force:"s",noclobber:"s",width:"v",nonewline:"s",inputobject:"v"},positions:["filepath","encoding"],aliases:{...E,path:"filepath",nooverwrite:"noclobber"},prefer:["force","filepath","append"],sp:!0},"tee-object":{params:{filepath:"v",literalpath:"v",append:"s",variable:"v",inputobject:"v",encoding:"v"},positions:["filepath"],aliases:{...E,path:"filepath"},prefer:["filepath","append"]},"new-item":{params:{path:"v",name:"v",itemtype:"v",value:"v",force:"s",credential:"v"},positions:["path"],aliases:{type:"itemtype",target:"value"},prefer:["itemtype","force","value","path","name"],sp:!0},mkdir:{params:{path:"v",name:"v",value:"v",force:"s",credential:"v"},positions:["path"],prefer:["force","path"],sp:!0},"copy-item":{params:{...V,...J,destination:"v",container:"s",force:"s",recurse:"s",passthru:"s",tosession:"v",fromsession:"v"},positions:["path","destination"],aliases:E,prefer:["force","recurse","destination","path"],sp:!0},"move-item":{params:{...V,...J,destination:"v",force:"s",passthru:"s"},positions:["path","destination"],aliases:E,prefer:["force","destination","path"],sp:!0},"rename-item":{params:{...V,newname:"v",force:"s",passthru:"s",credential:"v"},positions:["path","newname"],aliases:E,prefer:["force","newname","path"],sp:!0},"get-content":{params:{...V,...J,readcount:"v",totalcount:"v",tail:"v",delimiter:"v",raw:"s",encoding:"v",asbytestream:"s",wait:"s",stream:"v",force:"s"},positions:["path"],aliases:{...E,first:"totalcount",head:"totalcount",last:"tail"},prefer:["path"]},"select-string":{params:{pattern:"v",...V,inputobject:"v",simplematch:"s",casesensitive:"s",quiet:"s",list:"s",notmatch:"s",allmatches:"s",encoding:"v",context:"v",include:"v",exclude:"v",raw:"s",noemphasis:"s",culture:"v"},positions:["pattern","path"],aliases:E,prefer:["pattern","path"]},"get-childitem":{params:{...V,...J,recurse:"s",depth:"v",force:"s",name:"s",attributes:"v",directory:"s",file:"s",hidden:"s",readonly:"s",system:"s",followsymlink:"s"},positions:["path","filter"],aliases:{...E,s:"recurse",ad:"directory",d:"directory",af:"file",ah:"hidden",h:"hidden",ar:"readonly",as:"system"},prefer:["path","recurse"]},"read-only-path":{params:{...V,...J,pathtype:"v",isvalid:"s",relative:"s",name:"v",force:"s",olderthan:"v",newerthan:"v"},positions:["path"],aliases:E,prefer:["path"]},"join-path":{params:{path:"v",childpath:"v",additionalchildpath:"v",resolve:"s",credential:"v"},positions:["path","childpath","additionalchildpath"],prefer:["path","childpath"]},"split-path":{params:{...V,parent:"s",leaf:"s",leafbase:"s",extension:"s",qualifier:"s",noqualifier:"s",isabsolute:"s",resolve:"s",credential:"v"},positions:["path"],aliases:E,prefer:["path","parent","leaf"]},"set-location":{params:{...V,passthru:"s",stackname:"v"},positions:["path"],aliases:E,prefer:["path"]},"write-output":{params:{inputobject:"v",noenumerate:"s"},positions:["inputobject"]},"write-host":{params:{object:"v",nonewline:"s",separator:"v",foregroundcolor:"v",backgroundcolor:"v"},positions:["object"]},"write-message":{params:{message:"v",messagedata:"v",category:"v",errorid:"v",targetobject:"v",exception:"v",errorrecord:"v",recommendedaction:"v",categoryactivity:"v",categoryreason:"v",categorytargetname:"v",categorytargettype:"v",tags:"v"},positions:["message"],aliases:{msg:"message"}},"start-process":{params:{filepath:"v",argumentlist:"v",credential:"v",workingdirectory:"v",loaduserprofile:"s",nonewwindow:"s",passthru:"s",redirectstandarderror:"v",redirectstandardinput:"v",redirectstandardoutput:"v",verb:"v",windowstyle:"v",wait:"s",usenewenvironment:"s",environment:"v"},positions:["filepath","argumentlist"],aliases:{path:"filepath",args:"argumentlist",lup:"loaduserprofile",nnw:"nonewwindow",rse:"redirectstandarderror",rsi:"redirectstandardinput",rso:"redirectstandardoutput"},prefer:["filepath","argumentlist","verb","workingdirectory","redirectstandardoutput","wait"],sp:!0},"invoke-expression":{params:{command:"v"},positions:["command"]},"invoke-command":{params:{scriptblock:"v",computername:"v",session:"v",argumentlist:"v",filepath:"v",credential:"v",port:"v",usessl:"s",configurationname:"v",applicationname:"v",throttlelimit:"v",asjob:"s",hidecomputername:"s",jobname:"v",inputobject:"v",nonewscope:"s",hostname:"v",username:"v",keyfilepath:"v",sshtransport:"s",subsystem:"v",vmid:"v",vmname:"v",containerid:"v",runasadministrator:"s",connectionuri:"v",authentication:"v",enablenetworkaccess:"s",insessionname:"v",sessionname:"v",sessionoption:"v"},positions:["scriptblock","argumentlist"],aliases:{cn:"computername",args:"argumentlist",command:"scriptblock",uri:"connectionuri",cu:"connectionuri",psconfigurationname:"configurationname"},prefer:["scriptblock","computername","filepath","session"]},"invoke-webrequest":{params:{uri:"v",method:"v",body:"v",outfile:"v",infile:"v",headers:"v",contenttype:"v",usebasicparsing:"s",useragent:"v",websession:"v",sessionvariable:"v",credential:"v",usedefaultcredentials:"s",certificatethumbprint:"v",certificate:"v",disablekeepalive:"s",timeoutsec:"v",maximumredirection:"v",proxy:"v",proxycredential:"v",proxyusedefaultcredentials:"s",transferencoding:"v",passthru:"s",form:"v",authentication:"v",token:"v",skipcertificatecheck:"s",sslprotocol:"v",resume:"s",preserveauthorizationonredirect:"s",skipheadervalidation:"s",allowunencryptedauthentication:"s",maximumretrycount:"v",retryintervalsec:"v",custommethod:"v",noproxy:"s",httpversion:"v",skiphttperrorcheck:"s",statuscodevariable:"v",responseheadersvariable:"v",followrellink:"s",maximumfollowrellink:"v",connectiontimeoutseconds:"v",operationtimeoutseconds:"v",allowinsecureredirect:"s",preservehttpmethodonredirect:"s",unixsocket:"v"},positions:["uri"],aliases:{url:"uri",sv:"sessionvariable",cm:"custommethod",rhv:"responseheadersvariable",fl:"followrellink",ml:"maximumfollowrellink"},prefer:["outfile","method","body","uri","infile","headers"]},"stop-process":{params:{id:"v",name:"v",inputobject:"v",passthru:"s",force:"s"},positions:["id"],aliases:{processname:"name"},prefer:["force","name","id"],sp:!0},"get-process":{params:{name:"v",id:"v",inputobject:"v",computername:"v",module:"s",fileversioninfo:"s",includeusername:"s"},positions:["name"],aliases:{processname:"name",pid:"id"},prefer:["name","id"]},"expand-archive":{params:{...V,destinationpath:"v",force:"s",passthru:"s"},positions:["path","destinationpath"],aliases:E,prefer:["destinationpath","path","force"],sp:!0},"compress-archive":{params:{...V,destinationpath:"v",compressionlevel:"v",update:"s",force:"s",passthru:"s"},positions:["path","destinationpath"],aliases:E,prefer:["destinationpath","path","force"],sp:!0},"set-variable":{params:{name:"v",value:"v",scope:"v",option:"v",visibility:"v",force:"s",passthru:"s",include:"v",exclude:"v",description:"v"},positions:["name","value"],prefer:["name","value"],sp:!0},"remove-variable":{params:{name:"v",scope:"v",include:"v",exclude:"v",force:"s"},positions:["name"],prefer:["name"],sp:!0},"foreach-object":{params:{process:"v",begin:"v",end:"v",remainingscripts:"v",membername:"v",argumentlist:"v",parallel:"v",throttlelimit:"v",timeoutseconds:"v",asjob:"s",usenewrunspace:"s",inputobject:"v"},positions:["process"],aliases:{args:"argumentlist"},prefer:["process","parallel"]},"where-object":{params:{filterscript:"v",property:"v",value:"v",inputobject:"v"},positions:["filterscript"],prefer:["filterscript"]},"script-runner":{params:{expression:"v",scriptblock:"v",name:"v",credential:"v",filepath:"v",initializationscript:"v",workingdirectory:"v",inputobject:"v",argumentlist:"v",streamingbuffer:"v",throttlelimit:"v"},positions:["scriptblock"],aliases:{command:"scriptblock",args:"argumentlist"},prefer:["scriptblock","expression"]},"get-nettcpconnection":{params:{localaddress:"v",localport:"v",remoteaddress:"v",remoteport:"v",state:"v",appliedsetting:"v",owningprocess:"v",createdfromtemplate:"v"},positions:["localaddress"]},"restart-computer":{params:{computername:"v",force:"s",wait:"s",timeout:"v",for:"v",delay:"v",credential:"v",protocol:"v",wsmanauthentication:"v"},positions:["computername"],aliases:{cn:"computername"},sp:!0},"new-object":{params:{typename:"v",comobject:"v",argumentlist:"v",property:"v",strict:"s"},positions:["typename","argumentlist"],aliases:{args:"argumentlist"},prefer:["comobject","typename"]},"scheduled-task":{params:{taskname:"v",taskpath:"v",action:"v",trigger:"v",settings:"v",principal:"v",user:"v",password:"v",runlevel:"v",inputobject:"v",xml:"v",description:"v",force:"s",cimsession:"v"},positions:["taskname"],prefer:["taskname"],sp:!0},"new-scheduledtaskaction":{params:{execute:"v",argument:"v",workingdirectory:"v",id:"v",cimsession:"v",throttlelimit:"v",asjob:"s"},positions:["execute","argument"],prefer:["execute","argument"]},"new-scheduledtask":{params:{action:"v",trigger:"v",settings:"v",principal:"v",description:"v",cimsession:"v",throttlelimit:"v",asjob:"s"},positions:["action","trigger","settings","principal","description"],prefer:["action"]},"invoke-cimmethod":{params:{classname:"v",methodname:"v",arguments:"v",inputobject:"v",query:"v",querydialect:"v",cimclass:"v",namespace:"v",computername:"v",cimsession:"v",operationtimeoutsec:"v",resourceuri:"v"},positions:["classname","arguments","methodname"],aliases:{class:"classname",name:"methodname",args:"arguments"},prefer:["classname","methodname","arguments"],sp:!0},"invoke-wmimethod":{params:{class:"v",name:"v",argumentlist:"v",path:"v",inputobject:"v",computername:"v",namespace:"v",credential:"v",asjob:"s",impersonation:"v",authentication:"v",locale:"v",enableallprivileges:"s",authority:"v",throttlelimit:"v"},positions:["class","name","argumentlist"],aliases:{args:"argumentlist"},prefer:["class","name","argumentlist"],sp:!0},"set-item":{params:{...V,...J,value:"v",force:"s",passthru:"s"},positions:["path","value"],aliases:E,prefer:["path","value","force"],sp:!0},"set-alias":{params:{name:"v",value:"v",description:"v",option:"v",passthru:"s",scope:"v",force:"s"},positions:["name","value"],prefer:["name","value"],sp:!0},"item-property":{params:{...V,...J,name:"v",value:"v",propertytype:"v",force:"s",passthru:"s"},positions:["path","name","value"],aliases:{...E,type:"propertytype",pspropertyname:"name"},prefer:["path","name","value"],sp:!0}};function Kt(a,e){let t=e.toLowerCase(),s={...dt,...a.sp?{whatif:"s",confirm:"s"}:{},...a.params},n={...Qt,...a.sp?{wi:"whatif",cf:"confirm"}:{},...a.aliases??{}};if(t in s)return t;if(t in n)return n[t];let r=new Set;for(let o of Object.keys(s))o.startsWith(t)&&r.add(o);for(let[o,l]of Object.entries(n))o.startsWith(t)&&r.add(l);if(r.size===0)return null;if(r.size===1)return[...r][0];for(let o of a.prefer??[])if(r.has(o))return o;return[...r].filter(o=>o in a.params)[0]??[...r].find(o=>o!=="whatif"&&o!=="confirm")??[...r][0]}function Zt(a){if(a===null)return!0;if(a.bool!==void 0)return a.bool;let e=a.text?.toLowerCase();return!(e==="false"||e==="0"||e==="$false")}function x(a,e){let t={...dt,...a.sp?{whatif:"s",confirm:"s"}:{},...a.params},s=new Map,n=new Map,r=[],i=!1,o=!1;for(let h=0;h<e.length;h++){let d=e[h];if(d.t==="splat"){i=!0;continue}if(d.t==="stop"){r.push(...Ae(d.text).map(S=>C(S)));continue}if(d.t==="pos"||o){d.t==="pos"&&d.val.text==="--"&&!o?o=!0:d.t==="pos"?r.push(d.val):r.push(Y(d.text));continue}let f=Kt(a,d.name);if(f!==null){if(t[f]==="s"){n.set(f,Zt(d.colon?d.val:null));continue}if(d.colon&&d.val!==null)s.set(f,d.val);else{let S=e[h+1];S?.t==="pos"?(s.set(f,S.val),h++):s.set(f,T)}}}let l=[],u=0;for(let h of r){for(;u<a.positions.length&&s.has(a.positions[u]);)u++;u<a.positions.length?s.set(a.positions[u++],h):l.push(h)}return{values:s,switches:n,extra:l,splat:i}}function F(a,e){return a.switches.get(e)===!0||a.splat&&!a.switches.has(e)}function _(a){return a.switches.get("whatif")===!0}var Ce=a=>`if ${ve}; then ${a||"true"}; fi`,y=a=>`{ ${a}; }`,re=a=>a===""?"true":/; | && | \|\| | \| /.test(a)?y(a):a,Ht=new Set(["if","switch","foreach","for","while","do","function","filter","workflow","configuration","class","enum","try","trap","return","exit","throw","break","continue","param","begin","process","end","dynamicparam","clean","using","data"]),et=new Set(["script","global","local","private","using","workflow","variable"]),tt=new Set(["eq","ne","gt","ge","lt","le","like","notlike","match","notmatch","contains","notcontains","in","notin","replace","split","join","is","isnot","as","and","or","xor","band","bor","bxor","shl","shr","f"]);function Xt(a){let e=a.toLowerCase();return tt.has(e)?!0:(e.startsWith("c")||e.startsWith("i"))&&tt.has(e.slice(1))&&!["f","and","or","xor","is","isnot","as","band","bor","bxor","shl","shr"].includes(e.slice(1))}var Ve={userprofile:[K],home:[K],temp:[L("TMPDIR")],tmp:[L("TMPDIR")],systemroot:[p("C:\\Windows")],windir:[p("C:\\Windows")],systemdrive:[p("C:")],programfiles:[p("C:\\Program Files")],programw6432:[p("C:\\Program Files")],"programfiles(x86)":[p("C:\\Program Files (x86)")],programdata:[p("C:\\ProgramData")],allusersprofile:[p("C:\\ProgramData")],appdata:[K,p("/AppData/Roaming")],localappdata:[K,p("/AppData/Local")],claude_project_dir:[L("CLAUDE_PROJECT_DIR")],public:[p("C:\\Users\\Public")],comspec:[p("C:\\Windows\\System32\\cmd.exe")]};function ee(a){let e=a.toUpperCase().replace(/[^A-Z0-9_]/g,"_");return/^[A-Z_]/.test(e)?e:`_${e}`}function st(a){return Ve[a.toLowerCase()]??[L(ee(a))]}function fe(a){let e=a.toLowerCase().replace(/[^a-z0-9_]/g,"_");return/^[a-z_]/.test(e)&&e!=="_"?e:`v_${e}`}function me(a){return`fn_${a.toLowerCase().replace(/[^a-z0-9_]/g,"_")}`}function be(a){return(a.split(/[\\/]/).pop()??a).toLowerCase().replace(/\.(exe|cmd|bat|com)$/,"")}function We(a){return/[\\/]/.test(a)&&!/\.(exe|cmd|bat|com)$/i.test(a)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(a)}var nt=new Set(["delete","kill","moveto","copyto","replace","encrypt","decrypt","stop","start","restart","invoke","invokereturnasis","create","open","openwrite","appendtext","createtext","setaccesscontrol","setattributes","terminate","uninstall","change","pause","resume","write","writeline"]),Jt=new Set(["tostring","tolower","toupper","tolowerinvariant","toupperinvariant","trim","trimstart","trimend","split","replace","substring","contains","startswith","endswith","indexof","lastindexof","indexofany","padleft","padright","join","format","gettype","equals","count","length","keys","values","containskey","containsvalue","where","foreach","toarray","getenumerator","tochararray","normalize","compareto","clone","gethashcode","getvalue","adddays","addhours","addminutes","addseconds","addmilliseconds","addmonths","addyears","addticks","toshortdatestring","tolongdatestring","toshorttimestring","tolongtimestring","touniversaltime","tolocaltime","tofiletime","tofiletimeutc","subtract","match","matches","ismatch","item","get_item","getbytes","getstring","getnewclosure","waitforexit","getproperty","getmembers","getfiles","getdirectories","exists","tobase64string","frombase64string","getfolderpath","getelementsbytagname","selectsinglenode","selectnodes","groups","nextmatch","result","getresult","getawaiter"]),Yt=new Set(["add","insert","remove","removeat","clear","addrange","push","pop","peek","enqueue","dequeue","append","appendline","appendformat","sort","reverse","set_item","removeall","insertrange","removerange","dispose","close","flush"]),Oe=new Set(["io.path","math","datetime","datetimeoffset","guid","convert","string","int","int16","int32","int64","uint32","uint64","long","double","decimal","single","float","bool","boolean","char","byte","text.encoding","regex","text.regularexpressions.regex","uri","bitconverter","timespan","version","array","web.httputility","net.webutility","threading.thread","diagnostics.stopwatch","security.principal.windowsidentity","runtime.interopservices.runtimeinformation","linq.enumerable","globalization.cultureinfo","text.utf8encoding","net.dns","net.ipaddress","xml","xml.xmldocument","enum","type","numerics.biginteger","object","security.cryptography.sha256","security.cryptography.sha1","security.cryptography.md5","security.cryptography.randomnumbergenerator","environment+specialfolder","io.searchoption","net.securityprotocoltype","consolecolor","stringcomparison","text.normalizationform","io.directoryinfo","io.fileinfo","management.automation.wildcardpattern","management.automation.language.parser","collections.generic.list","psobject","pscustomobject","hashtable","collections.hashtable","collections.arraylist","text.stringbuilder","ordered","datetimekind","random","net.http.httpmethod","io.fileattributes","char[]","string[]","byte[]","int[]","object[]","console","net.servicepointmanager","diagnostics.process","net.webclient","net.http.httpclient"]),Gt=new Set(["diagnostics.process.start","console.setout","console.seterror","console.setin"]),es=new Set(["net.servicepointmanager.securityprotocol","console.outputencoding","console.inputencoding"]),xe=class a{constructor(e,t){this.src=e;this.sh=t}pos=0;pending=[];bumped=[];backgrounded=!1;exprDepth=0;parsed=0;lastPure=null;closed=!1;inputUsed=!1;program(){return this.statements("").join("; ")}peek(e=0){return this.src[this.pos+e]??""}eof(){return this.pos>=this.src.length}enter(){++this.sh.depth>we&&ae("nests too deeply")}leave(){this.sh.depth--}exprIn(){++this.exprDepth>4*we&&ae("nests too deeply")}unread(e){return oe(this.sh,e)}unreadVal(e,t=[]){return Et(this.sh,e,t)}skip(e=!1){for(;;){let t=this.peek();if(q(t))this.pos++;else if(t==="`"&&this.peek(1)===`
6
+ `)this.pos+=2;else if(e&&t===`
7
+ `)this.pos++;else if(t==="#"){let s=this.src.indexOf(`
8
+ `,this.pos);this.pos=s<0?this.src.length:s}else if(t==="<"&&this.peek(1)==="#"){let s=this.src.indexOf("#>",this.pos+2);s<0&&g("an unclosed <# comment"),this.pos=s+2}else return}}wordAhead(){let e=this.pos;for(;D(this.src[e]??"");)e++;return this.src.slice(this.pos,e).toLowerCase()}keyword(){let e=this.wordAhead();if(!Ht.has(e))return null;let t=this.src[this.pos+e.length]??"";return t===""||q(t)||t===`
9
+ `||"({;})".includes(t)||t==="$"&&["return","exit","throw"].includes(e)?(this.pos+=e.length,e):null}expect(e,t){this.peek()!==e&&g(`a missing ${e} ${t}`),this.pos++}statements(e){let t=[],s=0;for(;;){for(this.skip(!0);this.peek()===";";)this.pos++,this.skip(!0);if(this.eof()){e!==""&&g(`a missing ${e}`);break}let n=this.peek();if(e!==""&&n===e)break;(n===")"||n==="}")&&g(`an unmatched ${n}`),this.backgrounded=!1,this.closed=!1;let r=this.pos,i=this.statement();this.pos===r&&g(`unexpected ${JSON.stringify(n)}`),s++,i!==""&&t.push(i),this.skip(!1);let o=this.peek();this.eof()||o===`
10
+ `||o===";"||e!==""&&o===e||this.backgrounded||this.closed||g(`unexpected ${JSON.stringify(o)} after a statement`)}return this.parsed=s,t}statement(){this.enter(),this.pending.push([]),this.bumped.push([]);let e;try{e=this.statementBody()}finally{this.leave()}let t=this.pending.pop().filter(n=>!n.used),s=[...new Set(this.bumped.pop())].map(n=>`${n}="$${Q}"`);return(t.length>0||s.length>0)&&(this.lastPure=null),[e,...s,...t.map(n=>Ce(n.code))].filter(n=>n!=="").join("; ")}statementBody(){if(this.peek()===":"&&D(this.peek(1))){for(this.pos++;R(this.peek());)this.pos++;this.skip(!1)}for(;this.peek()==="["&&this.attributeBeforeParam();)this.skip(!0);let e=this.pos,t=this.keyword();if(t!==null){let n=this.keywordStatement(t);if(n!==null)return this.lastPure=null,this.closed=!["return","exit","throw","break","continue","using"].includes(t),n;this.pos=e}let s=this.chain("out");return this.lastPure=s.val,this.closed=!1,s.text}attributeBeforeParam(){let e=this.pos;return this.skipBrackets(),this.skip(!0),this.wordAhead()==="param"||this.peek()==="["?!0:(this.pos=e,!1)}skipBrackets(){let e=this.pos,t=this.sh.unread.length,s=0;do{let n=this.peek();(this.eof()||n===`
11
+ `)&&g("an unclosed ["),G(n)?this.singleQuoted():H(n)?this.doubleQuoted():(n==="["||n==="("?s++:(n==="]"||n===")")&&s--,this.pos++)}while(s>0);return this.sh.unread.length=t,this.src.slice(e+1,this.pos-1)}keywordStatement(e){switch(e){case"if":return this.ifStatement();case"while":return this.whileStatement();case"do":return this.doStatement();case"for":return this.forStatement();case"foreach":return this.foreachStatement();case"switch":return this.switchStatement();case"function":case"filter":return this.functionStatement();case"try":return this.tryStatement();case"trap":return this.skip(!0),this.peek()==="["&&this.skipBrackets(),this.skip(!0),Ce(this.body(!0));case"return":case"exit":case"throw":return this.flowStatement(e);case"break":case"continue":if(this.skip(!1),D(this.peek()))for(;R(this.peek());)this.pos++;return e;case"param":return this.skip(!1),this.peek()==="("?this.paramList():null;case"begin":case"process":case"end":case"dynamicparam":case"clean":{if(this.skip(!0),this.peek()!=="{")return null;let t=this.body(!1);return t==="true"?"":y(t)}case"using":for(;!this.eof()&&this.peek()!==`
12
+ `&&this.peek()!==";";)this.pos++;return"";case"data":{for(this.skip(!1);I(this.peek());){for(this.pos++;!this.eof()&&!q(this.peek())&&this.peek()!=="{";)this.pos++;for(this.skip(!1);!this.eof()&&this.peek()!=="{"&&this.peek()!==`
13
+ `;)this.pos++}return this.peek()==="{"?y(this.body(!1)):null}case"enum":{for(;!this.eof()&&this.peek()!=="{";)this.pos++;return this.skipBraces(),""}case"class":case"workflow":case"configuration":{for(;!this.eof()&&this.peek()!=="{";)this.pos++;return this.skipBraces(),this.unread(e==="class"?"a class definition":`a ${e}`)}default:return null}}skipBraces(){let e=this.sh.unread.length,t=0;do{let s=this.peek();this.eof()&&g("a missing }"),G(s)?this.singleQuoted():H(s)?this.doubleQuoted():s==="#"||s==="<"&&this.peek(1)==="#"?this.skip(!1):(s==="{"?t++:s==="}"&&t--,this.pos++)}while(t>0);this.sh.unread.length=e}body(e){this.skip(!0),this.expect("{","opening a body"),this.enter(),e&&this.sh.maybe++;let t;try{t=this.statements("}").join("; ")}finally{e&&this.sh.maybe--,this.leave()}return this.pos++,t||"true"}condition(){this.skip(!0),this.expect("(","before a condition"),this.skip(!0);let e=this.peek()===")"?null:this.chain("cond");return this.skip(!0),this.expect(")","after a condition"),e?.text?e.multi?y(e.text):e.text:ve}ifStatement(){let e=`if ${this.condition()}; then ${this.body(!0)}`;for(;;){let t=this.pos;this.skip(!0);let s=this.wordAhead();if(s==="elseif"){this.pos+=6,e+=`; elif ${this.condition()}; then ${this.body(!0)}`;continue}if(s==="else"){this.pos+=4,e+=`; else ${this.body(!0)}`;break}this.pos=t;break}return`${e}; fi`}whileStatement(){return`while ${this.condition()}; do ${this.body(!0)}; done`}doStatement(){let e=this.body(!0);this.skip(!0);let t=this.wordAhead();t!=="while"&&t!=="until"&&g("a do loop without while or until"),this.pos+=t.length;let s=this.condition();return`while :; do ${e}; ${s===ve?"true":s}; done`}forStatement(){this.skip(!0),this.expect("(","after for");let e=(i,o)=>{if(this.skip(!0),this.peek()===i)return"";let l=this.chain(o);return this.skip(!0),l.multi?y(l.text):l.text},t=e(";","out");this.expect(";","in a for loop");let s=e(";","cond");this.expect(";","in a for loop"),this.sh.maybe++;let n=e(")","out");this.sh.maybe--,this.expect(")","closing a for loop");let r=this.body(!0);return[t,`while ${s||ve}; do ${r}${n?`; ${n}`:""}; done`].filter(Boolean).join("; ")}foreachStatement(){if(this.skip(!1),I(this.peek()))for(this.pos++;D(this.peek());)this.pos++;this.skip(!0),this.expect("(","after foreach"),this.skip(!0),this.peek()!=="$"&&g("a foreach without a variable");let t=this.dollar(!1)?.target;t?.k!=="var"&&g("a foreach over something other than a variable"),this.skip(!0),this.wordAhead()!=="in"&&g("a foreach without in"),this.pos+=2,this.skip(!0);let s=this.chain("out");this.skip(!0),this.expect(")","closing foreach");let n=s.val!==null?s.val.words:[[{t:"sub",code:s.text}]];this.setVar(t.name,null);let r=this.body(!0);return`for ${t.name} in ${n.length>0?n.map(c).join(" "):"''"}; do ${r}; done`}switchStatement(){let e=[];for(this.skip(!1);I(this.peek());){this.pos++;let s=this.wordAhead();if(this.pos+=s.length,this.skip(!1),"file".startsWith(s)&&s.length>0){let n=this.argValue();e.push(`cat ${c(this.fixPath(k(n)))}`),this.skip(!1)}}if(this.peek()==="("){let s=this.condition();(!s.startsWith("[ -n ")||s.includes("$("))&&e.push(s)}this.skip(!0),this.expect("{","opening a switch");let t=[];for(;;){for(this.skip(!0);this.peek()===";";)this.pos++,this.skip(!0);if(this.peek()==="}")break;this.eof()&&g("a missing } closing a switch");let s=this.argValue();s.block&&(s.block.used=!0);let n=O([s]);this.skip(!0);let r=this.body(!0);t.push(Ce([s.block?.code??"",n,r].filter(i=>i&&i!=="true").join("; ")||"true"))}return this.pos++,[...e,...t].join("; ")}tryStatement(){let e=[y(this.body(!1))];for(;;){let t=this.pos;this.skip(!0);let s=this.wordAhead();if(s==="catch"){for(this.pos+=5,this.skip(!0);this.peek()==="[";)this.skipBrackets(),this.skip(!0),this.peek()===","&&(this.pos++,this.skip(!0));e.push(Ce(this.body(!0)));continue}if(s==="finally"){this.pos+=7,e.push(y(this.body(!1)));break}this.pos=t;break}return e.join("; ")}flowStatement(e){this.skip(!1);let t=this.peek(),n=this.eof()||t===`
14
+ `||t===";"||t==="}"||t===")"||t==="|"&&this.peek(1)==="|"||t==="&"&&this.peek(1)==="&"?null:this.chain("out");if(e==="exit"){let r=n?.val?.text,i=n?.val?O([n.val]):n?.text??"",o=r!==void 0&&/^-?\d+$/.test(r)?`exit ${r}`:"exit";return i?y(`${i}; ${o}`):o}if(e==="throw"){let r=n?.val?O([n.val]):n?.text??"";return r?y(`${r}; exit 1`):"exit 1"}return n?.text?y(`${n.text}; return`):"return"}functionStatement(){this.skip(!1);let e=this.pos;for(;!this.eof()&&!q(this.peek())&&!`({
15
+ `.includes(this.peek());)this.pos++;let t=this.src.slice(e,this.pos);t===""&&g("a function without a name");let s=t.indexOf(":");s>=0&&et.has(t.slice(0,s).toLowerCase())&&(t=t.slice(s+1)),this.skip(!0);let n=this.peek()==="("?this.paramList():"";this.sh.functions.add(t.toLowerCase());let r=this.body(!0);return`${me(t)}() { ${[n,r].filter(i=>i&&i!=="true").join("; ")||"true"}; }`}paramList(){this.expect("(","opening parameters");let e=[];for(;this.skip(!0),this.peek()!==")";){if(this.eof()&&g("a missing ) closing parameters"),this.peek()===","){this.pos++;continue}if(this.peek()==="["){this.skipBrackets();continue}if(this.peek()!=="$"&&g("a parameter list"),this.dollar(!1),this.skip(!0),this.peek()==="="){this.pos++,this.skip(!0);let t=this.expression(!0),s=O([t.val]);s&&e.push(s)}}return this.pos++,e.join("; ")}chain(e){let t=this.pipelineOrAssignment(e);for(;;){let s=this.pos;this.skip(!1);let n=this.peek()+this.peek(1);if(n!=="&&"&&n!=="||"){this.pos=s;break}this.pos+=2,this.skip(!0);let r=this.wordAhead(),i=["throw","exit","return","break","continue"].includes(r)&&this.keyword()!==null?this.keywordPipe(r):this.pipelineOrAssignment("out");t={text:`${t.multi?y(t.text||"true"):t.text||"true"} ${n} ${i.multi?y(i.text||"true"):i.text||"true"}`,val:null,multi:!1}}return this.skip(!1),this.peek()==="&"&&this.peek(1)!=="&"&&(this.pos++,this.backgrounded=!0,t={text:`{ ${t.text||"true"} & }`,val:null,multi:!1}),t}keywordPipe(e){return{text:e==="break"||e==="continue"?e:this.flowStatement(e),val:null,multi:!1}}pipelineOrAssignment(e){if(this.expressionStart()){let t=this.expression(!1);this.skip(!1);let s=this.assignOp();if(s!==null){let n=this.assignment(t,s);return{text:n,val:null,multi:n.includes("; ")}}return this.pipeline({kind:"expr",ex:t,redirects:this.redirects()},e)}return this.pipeline(this.command(),e)}expressionStart(){let e=this.peek(),t=this.peek(1);if(e==="$"||e==="("||e==="["||e==="{"||te(e)||e==="!"||e===","||I(e))return!0;if(e==="@")return t==="("||t==="{"||te(t);if(e==="+")return U(t)||t==="+";if(e===".")return U(t);if(U(e)){let s=Me(this.src,this.pos);return s>this.pos&&ns(this.src[s]??"")}return!1}assignOp(){let e=this.peek(),t=this.peek(1);return e==="="&&t!=="="?(this.pos++,"="):"+-*/%".includes(e)&&e!==""&&t==="="?(this.pos+=2,`${e}=`):I(e)&&t==="="?(this.pos+=2,"-="):e==="?"&&t==="?"&&this.peek(2)==="="?(this.pos+=3,"??="):null}assignment(e,t){this.skip(!0);let s=this.assignedValue();return this.assign(e.target??g("an assignment to an expression"),t,s.val,s.code)}assignedValue(){let e=this.pos,t=this.keyword();if(t!==null&&["if","switch","foreach","for","while","do","try"].includes(t)){let n=this.keywordStatement(t)??"";return{val:Z(n),code:n}}this.pos=e;let s=this.chain("out");return s.val!==null?{val:s.val,code:""}:{val:Z(s.text),code:s.text}}assign(e,t,s,n){let r=()=>n||O([s]);switch(e.k){case"var":{let i=e.name;if(t==="=")return this.setVar(i,pe(s)===null?s:null),s.words.length>1?`${i}=${c([{t:"sub",code:`printf '%s\\n' ${s.words.map(c).join(" ")}`}])}`:`${i}=${s.words.length===0?"":B(s.words[0])}`;if(t==="+="&&s.words.length<=1){let o=this.known(i);return this.setVar(i,o!==null&&o.words.length>1?de([o,s]):null),`${i}=${c(W([L(i)],s.words[0]??[]))}`}return this.setVar(i,null),[r(),`${i}="$${Q}"`].filter(Boolean).join("; ")}case"env":{let i=s.words.length===0?null:k(s);return t==="+="?`export ${e.name}=${c(W([L(e.name)],i??[]))}`:t!=="="?[O([s]),`export ${e.name}="$${Q}"`].filter(Boolean).join("; "):i===null||w(i)===""?`unset ${e.name}`:`export ${e.name}=${B(i)}`}case"file":return`printf '%s\\n'${s.words.length>0?` ${s.words.map(c).join(" ")}`:" ''"} ${t==="+="?">>":">"} ${c(this.fixPath([p(e.path)]))}`;case"null":case"member":return e.k==="member"&&e.base!==null&&this.setVar(e.base,null),r();case"list":return[r(),...e.items.map(i=>i.k==="var"?`${i.name}="$${Q}"`:"")].filter(Boolean).join("; ");case"static":return es.has(`${e.type}.${e.member}`)?r():[r(),this.unread(`setting a .NET property ([${e.type}]::${e.member})`)].filter(Boolean).join("; ");case"function":return s.block?(s.block.used=!0,this.sh.functions.add(e.name),`${me(e.name)}() { ${s.block.code||"true"}; }`):(this.sh.functions.add(e.name),[r(),`${me(e.name)}() { ${this.unread("a function made from a value")}; }`].filter(Boolean).join("; "));default:return g("an assignment to an expression")}}setVar(e,t){this.sh.vars.set(e,this.sh.maybe>0?null:t)}known(e){return this.sh.vars.get(e)??null}notShown(e){if(e.length!==1)return!1;let t=r=>r.t==="sub"||r.t==="var"&&(r.n==="psitem"||r.n===Q),s=e[0];if(t(s))return!0;let n=s.t==="var"?this.known(s.n):null;return n!==null&&n.words.length>0&&n.words.every(r=>r.length>0&&r.every(t))}pipeline(e,t){let s=[e];for(;;){let n=this.pos;if(this.skip(!1),this.peek()===`
16
+ `&&this.skip(!0),this.peek()==="|"&&this.peek(1)!=="|"){this.pos++,this.skip(!0),s.push(this.command());continue}this.pos=n;break}return this.translate(s,t)}translate(e,t){let s=e[0];if(e.length===1&&s.kind==="expr")return this.expressionStatement(s,t);let n=[],r=null,i={k:"none"},o=[],l=null;for(let f of e){if(f.kind==="expr"){let A=f.ex.val;r=this.valueText(A,f.redirects)||`printf '%s\\n' ${A.words.length>0?A.words.map(c).join(" "):"''"}`,i={k:"value",val:A};continue}let S=this.resolve(f),m=this.stage(S,i,o);S.shadowed!==void 0&&(m={text:y(`${m.text}; ${this.stage(S.shadowed,i,o).text}`)}),l=m,r!==null&&!m.used&&n.push(r),r===null&&m.used&&i.k==="cmd"&&n.pop(),r=null,o.push(S);let z=m.text+this.redirectText(f.redirects);m.value!==void 0&&f.redirects.length===0?(r=z,i={k:"value",val:m.value}):(n.push(z),i={k:"cmd",calls:[...o]})}r!==null&&n.push(r);let u=n.map(f=>n.length>1&&f.includes("; ")&&!/^(\{|if |while |for )/.test(f)?y(f):f),h=u.join(" | "),d=e.length===1&&l?.value!==void 0&&e[0].redirects.length===0?l.value:null;return{text:h,val:d,multi:u.length===1&&h.includes("; ")&&!h.startsWith("{ ")}}expressionStatement(e,t){let s=e.ex.val,n=this.redirectText(e.redirects);if(t==="cond"){let i=pe(s);return{text:i!==null&&n===""&&!i.includes("; ")?i:`[ -n ${s.words.length>0?c(k(s)):"''"} ]${n}`,val:n===""?s:null,multi:!1}}let r=this.valueText(s,e.redirects);return{text:r,val:n===""?s:null,multi:r.includes("; ")&&!r.startsWith("{ ")}}valueText(e,t){let s=this.redirectText(t),n=pe(e);if(n!==null)return s===""?n:`${y(n)}${s}`;let r=e.unread&&!e.computed&&e.words.length===1?e.words[0]:null,i=r?.[r.length-1];if(r&&i?.t==="sub"&&i.code===ge){let l=`true ${c(r.slice(0,-1))}; ${ge}`;return s===""?l:`${y(l)}${s}`}return e.words.filter(l=>!(l.length===1&&l[0].t==="var"&&l[0].n===Q)).length===0?s===""?O([e]):`true${s}`:`printf '%s\\n' ${e.words.map(c).join(" ")}${s}`}redirectText(e){let t="";for(let s of e){if(s.target===null){let[u,h]=[s.op[0]===">"?"1":s.op[0],s.op[s.op.length-1]];t+=u==="*"?" 2>&1":u==="1"?` >&${h}`:` ${u}>&${h}`;continue}let n=s.target,r=n.words.length===0?"/dev/null":c(this.fixPath(k(n))),i=s.op.endsWith(">>"),o=s.op.replace(/>+$/,""),l=i?">>":">";o==="*"?t+=` ${l} ${r} 2>&1`:t+=` ${o===""||o==="1"?"":o}${l} ${r}`}return t}redirects(){let e=[];for(;;){let t=this.pos;this.skip(!1);let s=this.redirect();if(s===null)return this.pos=t,e;e.push(s)}}redirect(){let e=this.peek(),t=this.pos,s="";if((/^[1-6*]$/.test(e)||e==="*")&&this.peek(1)===">")s=e,t++;else if(e!==">")return null;t++;let n=`${s}>`;if(this.src[t]===">"&&(n+=">",t++),this.src[t]==="&"){let i=this.src[t+1];return i!=="1"&&i!=="2"&&g("a redirection"),this.pos=t+2,{op:`${s||"1"}>&${i}`,target:null}}this.pos=t,this.skip(!1),le(this.peek())&&g("a redirection without a file");let r=this.argValue();return{op:n,target:r}}command(){let e="plain",t,s=this.peek();s==="&"&&this.peek(1)!=="&"?(this.pos++,this.skip(!1),e="call",t=this.argValue()):s==="."&&(q(this.peek(1))||this.peek(1)==="{"||this.peek(1)==="$"||te(this.peek(1)))?(this.pos++,this.skip(!1),e="dot",t=this.argValue()):((le(s)||I(s))&&g(`a command expected at ${JSON.stringify(s||"the end")}`),t=this.genericToken());let n=[],r=[];for(;;){this.skip(!1);let i=this.peek();if(this.eof()||i===`
17
+ `||i===";"||i===")"||i==="}"||i==="|"||i==="&")break;i==="<"&&g("the < operator");let o=this.redirect();if(o!==null){r.push(o);continue}if(i==="-"&&this.src.startsWith("--%",this.pos)&&(q(this.peek(3))||this.peek(3)===""||this.peek(3)===`
18
+ `)){this.pos+=3;let u=this.pos;for(;!this.eof()&&this.peek()!==`
19
+ `&&this.peek()!=="|";)this.pos++;n.push({t:"stop",text:this.src.slice(u,this.pos).trim()});continue}if(I(i)){let u=this.paramToken();if(u!==null){n.push(u);continue}}if(i==="@"&&R(this.peek(1))){for(this.pos++;R(this.peek());)this.pos++;n.push({t:"splat"});continue}i===","&&g("a stray comma");let l=this.pos;n.push({t:"pos",val:this.argList()}),this.pos===l&&g(`unexpected ${JSON.stringify(i)}`)}return{kind:"cmd",invocation:e,name:t,args:n,redirects:r}}paramToken(){let e=this.pos,t=this.peek(1);if(!(D(t)||t==="_"||t==="?"))return null;let s=this.pos+1;for(;R(this.src[s]??"")||this.src[s]==="?"||this.src[s]==="-";)s++;let n=this.src.slice(this.pos+1,s),r=this.src[s]??"";if(r===":"){this.pos=s+1,this.skip(!1);let i=le(this.peek())?null:this.argList();return{t:"param",name:n,text:`-${n}`,val:i,colon:!0}}return le(r)||r==="`"&&this.src[s+1]===`
20
+ `?(this.pos=s,{t:"param",name:n,text:`-${n}`,val:null,colon:!1}):(this.pos=e,null)}argList(){let e=[this.argValue()];for(;;){let t=this.pos;if(this.skip(!1),this.peek()!==","){this.pos=t;break}this.pos++,this.skip(!0),e.push(this.argValue())}return e.length===1?e[0]:de(e)}argValue(){let e=this.peek(),t=this.peek(1);if(e==="(")return this.postfix({val:this.parenValue(),target:null}).val;if(e==="@"&&t==="(")return this.postfix({val:this.arraySub(),target:null}).val;if(e==="@"&&t==="{")return this.hashtable();if(e==="@"&&te(t)&&this.hereAhead())return this.hereString();if(e==="{")return this.scriptBlock();if(e==="$"){let s=this.pos,n=this.dollar(!1);if(n!==null){let r=this.peek(),i=this.peek(1);return r==="."&&(D(i)||i==="_"||te(i)||i==="$"||i==="(")||r==="["||r===":"&&i===":"?this.postfix(n).val:le(r)||r==="`"&&this.peek(1)===`
21
+ `?n.val:this.genericToken(k(n.val))}this.pos=s}return this.genericToken()}genericToken(e=[]){let t=new se;for(t.add(e);;){let r=this.peek();if(le(r))break;if(r==="`"){let i=this.peek(1);if(i===""&&g("a backtick with nothing after it"),i===`
22
+ `)break;this.escapeInto(t)}else if(r==="$"){let i=this.pos,o=this.dollar(!0);o!==null?t.add(k(o.val)):(this.pos=i+1,t.text("$"))}else G(r)?t.add(this.singleQuoted()):H(r)?t.add(this.doubleQuoted()):r===X?t.add([this.mark()]):(t.text(r),this.pos++)}let s=t.word(),n=s[0];return n?.t==="lit"&&(n.s==="~"||n.s.startsWith("~\\")||n.s.startsWith("~/"))&&(s=[K,...n.s.length>1?[p(n.s.slice(1))]:[],...s.slice(1)]),s.length===0?Y(""):C(s)}escapeInto(e){let t=this.escape();typeof t=="string"?e.text(t):e.add([t])}controlChar(e){let t=e.charCodeAt(0);return t>1&&e!==X&&e!==ie?e:{t:"sub",code:this.unread(t===0?"a NUL character":"an escape for a control character")}}escape(){let e=this.peek(1);if(e==="u"&&this.peek(2)==="{"){let t=this.src.indexOf("}",this.pos+3),s=t>0?this.src.slice(this.pos+3,t):"",n=/^[0-9a-fA-F]{1,6}$/.test(s)?parseInt(s,16):-1;return(n<0||n>1114111||n>=55296&&n<=57343)&&g("a bad `u{} escape"),this.pos=t+1,this.controlChar(String.fromCodePoint(n))}return this.pos+=2,this.controlChar(zt[e]??e)}mark(){let e=He(this.src,this.pos,this.sh);return this.pos=this.src.indexOf(ie,this.pos)+1,e}singleQuoted(){this.pos++;let e=new se;for(;;){this.eof()&&g("an unclosed string");let t=this.peek();if(G(t)){if(G(this.peek(1))){e.text("'"),this.pos+=2;continue}return this.pos++,e.word()}t===X?e.add([this.mark()]):(e.text(t),this.pos++)}}doubleQuoted(){return this.pos++,this.expandable(e=>!(!H(e)||H(this.peek(1))))}expandable(e,t=-1){let s=new se;for(;;){if(t>=0?this.pos>=t:this.eof()){if(t>=0)break;g("an unclosed string")}let n=this.peek();if(t<0&&e(n)){this.pos++;break}if(t<0&&H(n)&&H(this.peek(1)))s.text('"'),this.pos+=2;else if(n==="`"&&this.peek(1)!=="")this.escapeInto(s);else if(n==="$"){let r=this.pos,i=this.dollar(!0);i!==null?s.add(k(i.val)):(this.pos=r+1,s.text("$"))}else n===X?s.add([this.mark()]):(s.text(n),this.pos++)}return s.word()}hereAhead(){let e=this.pos+2;for(;q(this.src[e]??"");)e++;return this.src[e]===`
23
+ `}hereString(){let e=this.peek(1),t=G(e);for(this.pos+=2;q(this.peek());)this.pos++;this.pos++;let s=this.pos,n=-1;for(let o=s;;){if((t?G(this.src[o]??""):H(this.src[o]??""))&&this.src[o+1]==="@"){n=o;break}let l=this.src.indexOf(`
24
+ `,o);l<0&&g("an unclosed here-string"),o=l+1}let r=n>s?n-1:s,i;if(t){let o=new se;for(this.pos=s;this.pos<r;)this.peek()===X?o.add([this.mark()]):o.text(this.src[this.pos++]);let l=o.word();i=l.length===0?Y(""):C(l)}else this.pos=s,i=C(this.expandable(()=>!1,r)),this.pos!==r&&g("a here-string");return this.pos=n+2,i}dollar(e){let t=this.peek(1);if(t==="(")return this.pos+=2,{val:this.subValue(),target:null};if(t==="{"){let i=this.pos+2,o="";for(;i<this.src.length&&this.src[i]!=="}";)this.src[i]==="`"&&i+1<this.src.length&&i++,o+=this.src[i],i++;i>=this.src.length&&g("an unclosed ${"),this.pos=i+1;let l=o.indexOf(":");return l>0?this.variable(o.slice(0,l),o.slice(l+1)):this.variable(null,o)}if(t==="$"||t==="?"||t==="^")return this.pos+=2,{val:T,target:{k:"other"}};if(!R(t))return e?null:(this.pos++,{val:Y("$"),target:null});let s=this.pos+1;for(;R(this.src[s]??"");)s++;let n=null,r=this.src.slice(this.pos+1,s);if(this.src[s]===":"&&R(this.src[s+1]??"")){n=r;let i=s+1;for(;R(this.src[i]??"");)i++;r=this.src.slice(s+1,i),s=i}return this.pos=s,this.variable(n,r)}variable(e,t){let s=e?.toLowerCase()??null;if(s==="env")return{val:C(st(t),["userprofile","home","temp","tmp"].includes(t.toLowerCase())),target:{k:"env",name:ee(t)}};if(s===null||et.has(s)){let n=t.toLowerCase();switch(n){case"null":return{val:je,target:{k:"null"}};case"true":case"false":return{val:{words:[[p(n==="true"?"True":"False")]],text:n==="true"?"True":"False",bool:n==="true"},target:{k:"other"}};case"home":return{val:C([K],!0),target:{k:"other"}};case"pwd":return{val:C([L("PWD")],!0),target:{k:"other"}};case"profile":return{val:{...C(Le.currentusercurrenthost,!0),profile:!0},target:{k:"other"}};case"_":case"psitem":return{val:C([L("psitem")]),target:{k:"var",name:"psitem"}};case"executioncontext":return{val:this.unreadVal("$ExecutionContext (it can run code it builds)"),target:{k:"other"}};default:{let r=fe(t),i=this.known(r);if(i!==null&&i.words.length!==1)return{val:i,target:{k:"var",name:r}};let o=i?.wmiProcess?{wmiProcess:!0}:i?.action!==void 0?{action:i.action}:{};return{val:{...C([L(r)]),...o},target:{k:"var",name:r}}}}}if(s==="function")return{val:T,target:{k:"function",name:t.toLowerCase()}};if(s.length===1&&D(s)){let n=`${s.toUpperCase()}:${t}`;return{val:Z(`cat ${M(n)}`),target:{k:"file",path:n}}}return{val:T,target:{k:"other"}}}subValue(){this.enter();try{let e=this.statements(")"),t=this.parsed===1?this.lastPure:null;return this.pos++,t??Z(e.join("; "))}finally{this.leave()}}arraySub(){return this.pos+=2,this.subValue()}parenValue(){this.pos++,this.enter();try{if(this.skip(!0),this.peek()===")")return this.pos++,je;let e=this.pos;if(this.keyword()!==null){this.pos=e;let r=this.statements(")").join("; ");return this.pos++,Z(r)}let s=this.chain("out");if(this.skip(!0),this.peek()===")")return this.pos++,s.val??Z(s.text);let n=this.statements(")");return this.pos++,Z([s.text,...n].filter(Boolean).join("; "))}finally{this.leave()}}hashtable(){this.pos+=2,this.enter();let e=[],t=[];try{for(;;){for(this.skip(!0);this.peek()===";";)this.pos++,this.skip(!0);if(this.peek()==="}"){this.pos++;break}this.eof()&&g("a missing } closing a hashtable");let s,n=this.peek();if(te(n)||n==="$"||n==="("){let l=this.unary();t.push(l.val),s=l.val.text??""}else{let l=this.pos;for(;!this.eof()&&!q(this.peek())&&this.peek()!=="="&&this.peek()!==`
25
+ `&&this.peek()!=="}"&&this.peek()!==";";)this.pos++;s=this.src.slice(l,this.pos),s===""&&g("a hashtable key")}this.skip(!1),this.expect("=","in a hashtable"),this.skip(!0);let r=this.pos,i=this.keyword(),o;if(i!==null&&["if","switch","foreach","for","while","do","try"].includes(i))o=Z(this.keywordStatement(i)??"");else{this.pos=r;let l=this.chain("out");o=l.val??Z(l.text)}e.push([s,o])}}finally{this.leave()}return{...P([...t,...e.map(([,s])=>s)]),hash:e}}scriptBlock(){let e=this.body(!0),t={code:e==="true"?"":e,used:!1};return this.pending[this.pending.length-1]?.push(t),{words:[j],block:t}}expression(e){this.exprIn();try{let t=this.unary(),s=[t],n=[];for(;;){let r=this.pos;this.skip(!1);let i=this.binaryOp(e);if(i===null){this.pos=r;break}if(this.skip(!0),i==="?"){let o=this.expression(e);this.skip(!0),this.expect(":","in a ?: expression"),this.skip(!0);let l=this.expression(e);s.push(o,l),n.push("?",":");continue}s.push(this.unary()),n.push(i)}if(n.length===0)return t;if(n.every(r=>r===",")){let r=s.map(i=>i.target);return{val:de(s.map(i=>i.val)),target:r.every(i=>i!==null)?{k:"list",items:r}:null}}return n.every(r=>r==="+")&&s.some(r=>r.val.text!==void 0&&!/^-?[\d.]+$/.test(r.val.text))&&s.every(r=>r.val.words.length===1)?{val:C(W(...s.map(r=>r.val.words[0]))),target:null}:{val:P(s.map(r=>r.val)),target:null}}finally{this.exprDepth--}}binaryOp(e){let t=this.peek(),s=this.peek(1);if(I(t)&&D(s)){let n=this.pos+1;for(;D(this.src[n]??"");)n++;let r=this.src.slice(this.pos+1,n);return!Xt(r)||R(this.src[n]??"")?null:(this.pos=n,r.toLowerCase())}return t===","&&!e?(this.pos++,","):t==="."&&s==="."?(this.pos+=2,".."):t==="?"&&s==="?"&&this.peek(2)!=="="?(this.pos+=2,"??"):t==="?"&&q(s)?(this.pos++,"?"):"+*/%".includes(t)&&t!==""||I(t)?s==="="||t==="+"&&s==="+"||I(t)&&I(s)?null:(this.pos++,t):null}unary(){this.exprIn();try{let e=this.peek(),t=this.peek(1);if(e==="!")return this.pos++,this.skip(!1),{val:P([this.unary().val]),target:null};if(e===",")return this.pos++,this.skip(!0),{val:de([this.unary().val]),target:null};if(e==="+"&&t==="+"||I(e)&&I(t)){this.pos+=2;let s=this.unary();return s.target?.k==="var"&&this.bump(s.target.name),{val:T,target:null}}if(I(e)){if(D(t)){let s=this.pos+1;for(;D(this.src[s]??"");)s++;let n=this.src.slice(this.pos+1,s).toLowerCase();if(["not","bnot","split","join"].includes(n)&&!R(this.src[s]??""))return this.pos=s,this.skip(!1),{val:P([this.unary().val]),target:null};g(`an unexpected -${n} in an expression`)}if(U(t)||t==="."&&U(this.peek(2))){let s=Me(this.src,this.pos+1),n=this.src.slice(this.pos,s);return this.pos=s,{val:Y(n),target:null}}return this.pos++,this.skip(!1),{val:P([this.unary().val]),target:null}}if(e==="+")return this.pos++,this.skip(!1),this.unary();if(e==="["){let s=rt(this.skipBrackets());if(this.peek()===":"&&this.peek(1)===":")return this.postfix(this.staticMember(s));if(this.peek()==="["||this.operandAhead()){let n=this.unary(),r=n.val;if(s==="scriptblock")return{val:this.unreadVal("a script block made from text",[r]),target:null};if((s==="wmiclass"||s==="management.managementclass")&&Ye(k(r)))return{val:{words:r.words,wmiProcess:!0},target:null};let i={words:r.words,...r.text!==void 0?{text:r.text}:{},...r.computed?{computed:!0}:{},...r.unread?{unread:!0}:{}};return{val:r.block?r:i,target:n.target}}return{val:T,target:null}}return this.postfix(this.primary())}finally{this.exprDepth--}}bump(e){this.setVar(e,null),this.bumped[this.bumped.length-1]?.push(e)}operandAhead(){let e=this.peek();return e==="$"||e==="("||e==="@"||te(e)||U(e)||e==="{"||e===X||(e==="-"||e==="!")&&(this.peek(1)==="$"||this.peek(1)==="(")}primary(){let e=this.peek(),t=this.peek(1);if(e==="$")return this.dollar(!1)??g("a stray $");if(e==="(")return{val:this.parenValue(),target:null};if(e==="@"&&t==="(")return{val:this.arraySub(),target:null};if(e==="@"&&t==="{")return{val:this.hashtable(),target:null};if(e==="@"&&te(t)&&this.hereAhead())return{val:this.hereString(),target:null};if(e==="{")return{val:this.scriptBlock(),target:null};if(G(e)){let s=this.singleQuoted();return{val:s.length===0?Y(""):C(s),target:null}}if(H(e))return{val:C(this.doubleQuoted()),target:null};if(e===X)return{val:C([this.mark()]),target:null};if(U(e)||e==="."&&U(t)){let s=Me(this.src,this.pos);(s<=this.pos||R(this.src[s]??""))&&g("a malformed number");let n=this.src.slice(this.pos,s);return this.pos=s,{val:Y(n),target:null}}return g(`an unexpected ${JSON.stringify(e||"end")} in an expression`)}postfix(e){let t=e;for(;;){let s=this.peek(),n=this.peek(1);if(s==="."&&n!=="."&&(D(n)||n==="_"||te(n)||n==="$"||n==="(")||s==="?"&&n==="."){this.pos+=s==="?"?2:1;let r=this.memberName(),i=r.val===null?[]:[r.val];if(this.peek()==="("){let o=this.callArgs();t={val:this.instanceCall(t,r.name,[...i,...o]),target:null}}else if(t.val.profile===!0&&r.name!==null&&Le[r.name]!==void 0)t={val:C(Le[r.name],!0),target:null};else{let o=t.target?.k==="var"?t.target.name:null;t={val:t.val.path===!0&&r.name!==null&&["fullname","path","providerpath","pspath"].includes(r.name)||t.val.unread===!0&&i.length===0?t.val:P([t.val,...i]),target:{k:"member",base:o}}}continue}if(s===":"&&n===":"){this.pos+=2;let r=this.memberName(),i=[t.val,...r.val===null?[]:[r.val],...this.peek()==="("?this.callArgs():[]];t={val:t.val.unread?P(i):this.unreadVal("a static member of a value",i),target:null};continue}if(s==="["||s==="?"&&n==="["){this.pos+=s==="?"?2:1,this.skip(!0);let r=this.expression(!1);this.skip(!0),this.expect("]","closing an index");let i=t.target?.k==="var"?t.target.name:null;t={val:P([t.val,r.val]),target:{k:"member",base:i}};continue}if(s==="+"&&n==="+"||s==="-"&&n==="-"){let r=this.src[this.pos+2]??"";if(R(r)||r==="$")break;this.pos+=2,t.target?.k==="var"&&this.bump(t.target.name),t={val:T,target:null};continue}break}return t}memberName(){let e=this.peek();if(G(e)){let s=this.singleQuoted();return{name:w(s)?.toLowerCase()??null,val:w(s)===null?C(s):null}}if(H(e)){let s=this.doubleQuoted();return{name:w(s)?.toLowerCase()??null,val:w(s)===null?C(s):null}}if(e==="$")return{name:null,val:this.dollar(!1)?.val??null};if(e==="(")return{name:null,val:this.parenValue()};let t=this.pos;for(;R(this.peek());)this.pos++;return{name:this.src.slice(t,this.pos).toLowerCase(),val:null}}callArgs(){this.pos++;let e=[];if(this.skip(!0),this.peek()===")")return this.pos++,e;for(;;){if(this.skip(!0),e.push(this.expression(!0).val),this.skip(!0),this.peek()===","){this.pos++;continue}return this.expect(")","closing a method call"),e}}instanceCall(e,t,s){return e.val.unread?s.some(n=>n.words.some(r=>r.some(i=>i.t==="sub")))?P([e.val,...s]):e.val:e.val.wmiProcess&&t==="create"?Z(Se(this.processCreate(s[0]),s.slice(1))):t===null?this.unreadVal("a method chosen at run time",[e.val,...s]):Jt.has(t)?P([e.val,...s]):Yt.has(t)&&e.target?.k==="var"?(this.setVar(e.target.name,null),P([e.val,...s])):this.unreadVal(`a .NET method call (.${t}())`,[e.val,...s])}staticMember(e){this.pos+=2;let t=this.memberName(),s=this.peek()==="("?this.callArgs():null;return t.name===null?{val:this.unreadVal(`a .NET member chosen at run time ([${e}])`,[...t.val===null?[]:[t.val],...s??[]]),target:null}:s!==null?{val:this.staticCall(e,t.name,s),target:null}:e==="environment+specialfolder"?{val:Y(t.name),target:{k:"static",type:e,member:t.name}}:{val:T,target:{k:"static",type:e,member:t.name}}}staticCall(e,t,s){let n=`${e}.${t}`,r=l=>c(this.dotnetPath(s[l])),i=l=>s[l]&&s[l].words.length>0?s[l].words.map(c).join(" "):"''",o=l=>Z(Se(l,s));switch(n){case"io.file.delete":return o(`rm ${r(0)}`);case"io.directory.delete":return o(`${s.length>1&&s[1].bool!==!1?"rm -r":"rmdir"} ${r(0)}`);case"io.file.writealltext":case"io.file.writeallbytes":return o(`printf '%s' ${i(1)} > ${r(0)}`);case"io.file.writealllines":return o(`printf '%s\\n' ${i(1)} > ${r(0)}`);case"io.file.appendalltext":return o(`printf '%s' ${i(1)} >> ${r(0)}`);case"io.file.appendalllines":return o(`printf '%s\\n' ${i(1)} >> ${r(0)}`);case"io.file.readalltext":case"io.file.readalllines":case"io.file.readallbytes":case"io.file.readlines":case"io.file.opentext":case"io.file.openread":return o(`cat ${r(0)}`);case"io.file.move":case"io.directory.move":case"io.file.replace":return o(`mv ${r(0)} ${r(1)}`);case"io.file.copy":return o(`cp ${r(0)} ${r(1)}`);case"io.file.create":case"io.file.createtext":return o(`: > ${r(0)}`);case"io.directory.createdirectory":return o(`mkdir -p ${r(0)}`);case"io.file.createsymboliclink":case"io.directory.createsymboliclink":return o(`ln -s ${r(1)} ${r(0)}`);case"io.directory.getfiles":case"io.directory.getdirectories":case"io.directory.enumeratefiles":case"io.directory.enumeratedirectories":case"io.directory.getfilesystementries":case"io.directory.enumeratefilesystementries":return o(`ls ${r(0)}`);case"io.compression.zipfile.extracttodirectory":return o(`unzip ${r(0)} -d ${r(1)}`);case"io.compression.zipfile.createfromdirectory":return o(`zip ${r(1)} ${r(0)}`);case"environment.setenvironmentvariable":{let l=s[0]?.text;if(l===void 0)return this.unreadVal("setting an environment variable whose name is unknown",s);let u=s[1];return u===void 0||u.words.length===0||u.text===""?o(`unset ${ee(l)}`):o(`export ${ee(l)}=${B(k(u))}`)}case"environment.getenvironmentvariable":{let l=s[0]?.text;return l===void 0||O(s)!==""?P(s):C(st(l))}case"environment.getfolderpath":return O(s)!==""?P(s):this.folderPath(s[0]?.text);case"environment.exit":case"environment.failfast":return o("exit");case"io.directory.getcurrentdirectory":return this.sh.cwd!==null?C([p(this.sh.cwd)],!0):T;default:break}return(e==="io.file"||e==="io.directory")&&["exists","getattributes","getlastwritetime","getcreationtime","getlastaccesstime","getlastwritetimeutc","getcreationtimeutc","getparent","getdirectoryroot","getlogicaldrives"].includes(t)||e==="environment"&&!["setenvironmentvariable"].includes(t)||t==="new"&&(Oe.has(e)||Te(e))||Oe.has(e)&&t!=="new"&&!Gt.has(n)&&!(e==="diagnostics.process"&&t==="start")||Te(e)?P(s):e==="scriptblock"?this.unreadVal("a script block made from text ([scriptblock]::Create)",s):this.unreadVal(`a .NET call ([${e}]::${t})`,s)}folderPath(e){let t=e?.toLowerCase(),s=n=>C(n,!0);switch(t){case"userprofile":return s([K]);case"applicationdata":return s(Ve.appdata);case"localapplicationdata":return s(Ve.localappdata);case"desktop":case"desktopdirectory":return s([K,p("/Desktop")]);case"mydocuments":case"personal":return s([K,p("/Documents")]);case"windows":return s([p("C:\\Windows")]);case"system":return s([p("C:\\Windows\\System32")]);case"programfiles":return s([p("C:\\Program Files")]);case"commonapplicationdata":return s([p("C:\\ProgramData")]);default:return T}}dotnetPath(e){if(e===void 0||e.words.length===0)return j;let t=k(e),s=t[0];if(s?.t!=="lit")return t;let n=s.s;if(/^[A-Za-z]:[\\/]/.test(n)||n.startsWith("\\\\")||n.startsWith("//"))return t;let r=ke(this.sh.cwd);return n.startsWith("\\")||n.startsWith("/")?r===null?j:W([p(r)],t):this.sh.cwd===null?j:W([p(`${this.sh.cwd.replace(/[\\/]+$/,"")}\\`)],t)}fixPath(e){return ce(e,this.sh.drive)}resolve(e){let t=k(e.name),s=w(t);if(s===null&&e.name.words.length===1&&t.length===1&&t[0].t==="var"){let n=this.known(t[0].n);n?.text!==void 0&&(s=n.text)}return s===null?{name:"",kind:"program",prog:t,elem:e}:this.resolveName(s,e,0)}resolveName(e,t,s){let n=e.lastIndexOf("\\"),i=(n>0&&/^[A-Za-z][\w.]*$/.test(e.slice(0,n))&&/^[a-z]+-[a-z]+$/i.test(e.slice(n+1))?e.slice(n+1):e).toLowerCase(),o=s<8?this.sh.aliases.get(i):void 0;if(o!==void 0){let l=this.resolveName(o,t,s+1),u=this.defaultCall(e,i,t);return u.kind==="program"?l:{...l,shadowed:u}}return this.defaultCall(e,i,t)}defaultCall(e,t,s){let n=Ft[t];return n!==void 0?{name:n,kind:"cmdlet",prog:[p(t)],elem:s}:this.sh.functions.has(t)?{name:t,kind:"function",prog:[p(me(t))],elem:s}:/^[a-z]+-[a-z0-9]+$/i.test(t)||t==="mkdir"?{name:t,kind:"cmdlet",prog:[p(t)],elem:s}:{name:We(e)?e:be(e),kind:"program",prog:[p(e)],elem:s}}stage(e,t,s){let n=e.elem;if(n.invocation!=="plain"&&n.name.block)return n.name.block.used=!0,{text:y(n.name.block.code||"true")};let r=n.name.words.length===1?n.name.words[0]:null,i=r?.length===1&&r[0].t==="var"?this.known(r[0].n)?.block:void 0;if(n.invocation!=="plain"&&i!==void 0)return{text:y(i.code||"true")};let o=[n.name,...n.args.flatMap(h=>h.t==="pos"?[h.val]:h.t==="param"&&h.val!==null?[h.val]:[])],l;e.name===""?l=this.unknownCommand(e):e.kind==="function"?l={text:[me(e.name),...this.nativeArgs(n.args)].join(" ")}:l=e.kind==="program"?this.programStage(e,t):this.cmdlet(e,t,s);let u=Se(l.text,o);return u===l.text?l:{...l,text:y(u)}}unknownCommand(e){let t=e.elem;return t.name.unread?{text:[c(k(t.name)),...this.nativeArgs(t.args)].join(" ")}:{text:this.unknownProgram(k(t.name),pe(t.name)!==null,this.nativeArgs(t.args))}}unknownProgram(e,t,s){let n=Ne(e);return n!==null?[B([p(n)]),...s].join(" "):y(`${[c(t?e:j),...s].join(" ")}; ${this.unread("a command named by a value the line does not show")}`)}nativeArgs(e){let t=[];for(let s of e)s.t==="param"?s.colon&&s.val!==null?t.push(c(W([p(`${s.text}:`)],k(s.val)))):t.push(M(s.text.replace(/^[\u2013\u2014\u2015]/,"-"))):s.t==="pos"?t.push(...s.val.words.map(c)):s.t==="splat"?t.push(c(j)):t.push(...Ae(s.text).map(c));return t}argWords(e){let t=[];for(let s of e)s.t==="param"?t.push(s.colon&&s.val!==null?W([p(`${s.text}:`)],k(s.val)):[p(s.text)]):s.t==="pos"?t.push(...s.val.block?[[{t:"sub",code:s.val.block.code}]]:s.val.words):s.t==="splat"?t.push(j):t.push(...Ae(s.text));return t}programStage(e,t){let s=e.elem,n=e.name,r=this.argWords(s.args),i=w(e.prog)?.toLowerCase();if((i==="curl"||i==="wget")&&s.args.some(o=>o.t==="param"&&["uri","method","body","outfile","usebasicparsing","headers","infile","contenttype","useragent","sessionvariable","websession","timeoutsec"].includes(o.name.toLowerCase())))return this.webRequest(x(b["invoke-webrequest"],s.args));if(s.invocation==="dot")return{text:`source ${c(this.scriptWord(w(e.prog)??""))}`};switch(n){case"cmd":return this.inputUsed=!1,{text:qe(r,this.sh,this.feed(t)),used:this.inputUsed};case"powershell":case"pwsh":{let o=s.args.find(u=>u.t==="pos"&&u.val.block!==void 0)?.val.block;return o!==void 0?(o.used=!0,{text:y(o.code||"true")}):(this.inputUsed=!1,{text:this.cli(r,this.feed(t),n==="pwsh"),used:this.inputUsed})}case"taskkill":return{text:Fe(r)};case"schtasks":return{text:De(r,this.sh,o=>this.knownText(C(o)))};case"wmic":return{text:Be(r,this.sh,o=>this.knownText(C(o)))};default:break}return We(n)?{text:[c(this.scriptWord(n)),...this.nativeArgs(s.args)].join(" ")}:{text:[B([p(n)]),...this.nativeArgs(s.args)].join(" ")}}feed(e){return e.k==="none"?null:(t,s)=>e.k==="cmd"?this.pipedCode(e,s):(this.inputUsed=!0,this.codeFrom(e.val,s,t,!0))}scriptWord(e){if(e==="")return j;let t=e.replace(/\\/g,"/");return[p(/^([A-Za-z]:)?\/|^\.{1,2}\/|^~/.test(t)?t:`./${t}`)]}cli(e,t,s){let n=!1,r=i=>n&&t!==null?`${i}; ${t("ps","powershell -NoExit reading its input")}`:i;for(let i=0;i<e.length;i++){let o=w(e[i]),l=o===null?null:Mt(o);if(l===null||l==="unknown")return r(s&&o!==null?this.scriptRun(e[i],e.slice(i+1),t):this.psCommand(e.slice(i),t));if(l.name==="command")return r(this.psCommand(e.slice(i+1),t));if(l.name==="file")return r(e[i+1]===void 0?"true":this.scriptRun(e[i+1],e.slice(i+2),t));if(l.name==="noexit")n=!0;else if(l.name==="encodedcommand"){let u=w(e[i+1]??[])?.replace(/\s/g,"")??null;if(u===null||u.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(u))return r(this.unread("an encoded command that is not base64"));let h=it.Buffer.from(u,"base64").toString("utf16le");return/[\u0000\u0001\uFDD0\uFDD1]/.test(h)?r(this.unread("an encoded command holding control characters")):r(re(this.nested(h,"an encoded command")))}else l.value&&i++}return t!==null?t("ps","powershell reading its input"):"true"}scriptRun(e,t,s){let n=w(e);return n==="-"?s!==null?s("ps","powershell -File - reading its input"):"true":n!==null?[c(this.scriptWord(n)),...t.map(c)].join(" "):y(`${[c(e),...t.map(c)].join(" ")}; ${this.unread("a script named by a value the line does not show")}`)}psCommand(e,t){return e.length===0?"true":e.length===1&&w(e[0])==="-"?t!==null?t("ps","powershell -Command - reading its input"):"true":this.codeFrom({words:[W(...e.flatMap((s,n)=>n>0?[[p(" ")],s]:[s]))]},"powershell -Command")}nested(e,t){Ze(this.sh,e),this.enter();let s=this.sh.unread.length;try{return new a(e.replace(/\r\n?/g,`
26
+ `),this.sh).program()}catch(n){if(!(n instanceof ne)||n.fatal)throw n;return Ke(this.sh,s,`${t}: ${n.why}`)}finally{this.leave()}}cmdlet(e,t,s){let n=e.elem,r=e.name;switch(r){case"remove-item":return this.removeItem(n,t);case"clear-content":return this.clearContent(n,t);case"set-content":case"add-content":case"out-file":case"tee-object":return this.writeContent(r,n,t);case"new-item":return this.newItem(n,t);case"mkdir":return this.mkdir(n,t);case"copy-item":case"move-item":return this.copyMove(r,n,t);case"rename-item":return this.renameItem(n,t);case"get-content":return this.pathCommand("cat",x(b["get-content"],n.args),t);case"select-string":return this.selectString(n);case"get-childitem":return this.pathCommand("ls",x(b["get-childitem"],n.args),t);case"get-item":case"resolve-path":case"get-itemproperty":case"convert-path":case"test-path":return this.readOnlyPath(r,n,t);case"join-path":return this.joinPath(n);case"split-path":return this.splitPath(n);case"get-location":return{text:"pwd",value:C([L("PWD")],!0)};case"set-location":case"push-location":return this.setLocation(n);case"pop-location":return this.sh.drive=null,{text:'cd "$OLDPWD"'};case"write-output":case"write-host":return this.write(r,n);case"write-error":case"write-warning":case"write-verbose":case"write-debug":case"write-information":{let i=x(b["write-message"],n.args);return{text:["echo",...[...i.values.get("message")?.words??[],...i.values.get("messagedata")?.words??[],...i.extra.flatMap(l=>l.words)].map(c)].join(" ")}}case"start-process":return this.startProcess(n);case"invoke-expression":return this.invokeExpression(n,t);case"invoke-command":return this.invokeCommand(n);case"invoke-webrequest":case"invoke-restmethod":return this.webRequest(x(b["invoke-webrequest"],n.args));case"stop-process":return this.stopProcess(n,t,s);case"restart-computer":return{text:"reboot"};case"stop-computer":return{text:"shutdown"};case"expand-archive":case"compress-archive":return this.archive(r,n);case"foreach-object":case"where-object":return this.blockStage(r,n,t);case"measure-command":case"start-job":case"start-threadjob":case"trace-command":return this.runsBlock(n);case"set-variable":case"new-variable":return this.setVariable(n);case"remove-variable":case"clear-variable":{let o=(x(b["remove-variable"],n.args).values.get("name")?.words??[]).map(w).filter(l=>l!==null);return{text:o.length>0?o.map(l=>r==="remove-variable"?`unset ${fe(l)}`:`${fe(l)}=`).join("; "):"true"}}case"new-object":return this.newObject(n);case"get-process":return this.getProcess(n);case"out-null":return{text:t.k==="none"?"true":"cat > /dev/null"};case"get-nettcpconnection":return this.tcpConnections(n);case"register-scheduledtask":case"set-scheduledtask":case"unregister-scheduledtask":case"start-scheduledtask":return this.scheduledTask(r,n,t);case"new-scheduledtaskaction":case"new-scheduledtask":return this.taskValue(r,n);case"format-volume":case"clear-disk":case"initialize-disk":case"remove-partition":return{text:["mkfs",...this.nativeArgs(n.args)].join(" ")};case"add-type":return{text:this.unread("Add-Type (compiles and loads code)")};case"invoke-item":return{text:this.unread("Invoke-Item (opens a file with whatever program it is associated with)")};case"set-alias":case"new-alias":{let i=x(b["set-alias"],n.args),o=i.values.get("name")?.text,l=i.values.get("value")?.text;return o===void 0||l===void 0||o===""||l===""?{text:this.unread("an alias whose name or command the line does not show")}:(this.sh.aliases.set(o.toLowerCase(),l),{text:"true"})}case"invoke-history":return{text:this.unread("a command re-run from history")};case"invoke-wmimethod":case"invoke-cimmethod":{let i=r==="invoke-wmimethod",o=x(b[r],n.args);if(_(o))return this.whatIfStandIn(n);let l=i?o.values.get("class")??o.values.get("path"):o.values.get("classname"),u=o.values.get(i?"name":"methodname")?.text?.toLowerCase();if(l===void 0||!Ye(k(l))||u!=="create")return{text:this.unread(`${i?"Invoke-WmiMethod":"Invoke-CimMethod"} (it can start a process)`)};let h=o.values.get(i?"argumentlist":"arguments"),d=h?.words[0];return{text:this.processCreate(i?d===void 0?void 0:C(d):this.hashValue(h,"commandline"))}}case"set-item":case"new-itemproperty":case"set-itemproperty":return this.setItem(r,e);default:break}return qt.has(r)?this.standIn(n,t,!0):Ut.has(r)?this.standIn(n,t,!1):this.passThrough(e)}setItem(e,t){let s=t.elem,n=x(b[e==="set-item"?"set-item":"item-property"],s.args);if(_(n))return this.whatIfStandIn(s);let r=this.paths(n)[0],i=r?.[0]?.t==="lit"?r[0].s.toLowerCase():"";if(/^(function|alias):/.test(i))return{text:this.unread("a function or alias defined through a provider")};let o=n.values.get("value"),l=/^env:[\\/]?(.+)$/i.exec(w(r??[])??"");if(l&&e==="set-item")return{text:o&&o.words.length>0&&o.text!==""?`export ${ee(l[1])}=${B(k(o))}`:`unset ${ee(l[1])}`};let u=r?ze(r):null;if(u!==null){let h=n.values.get("name");return{text:["reg","add",M(u),...h?["'/v'",c(k(h))]:[],...o?["'/d'",c(k(o))]:[],"'/f'"].join(" ")}}return this.passThrough(t)}passThrough(e){return{text:[B([p(e.name)]),...this.nativeArgs(e.elem.args)].join(" ")}}standIn(e,t,s){let n=e.args.flatMap(o=>o.t==="pos"?[o.val]:o.t==="param"&&o.val!==null?[o.val]:[]),r=O(n),i=s&&t.k!=="none";return r===""?{text:i?"cat":"true"}:{text:i?y(`${r}; cat`):r}}paths(e,t=["path","literalpath"]){let s=[];for(let n of t)s.push(...e.values.get(n)?.words??[]);for(let n of e.extra)s.push(...n.words);return s.map(n=>this.fixPath(n))}inputPaths(e,t,s){let n=this.paths(e,s);return n.length>0?{paths:n,used:!1,xargs:!1}:t.k==="value"?{paths:t.val.words.map(r=>this.fixPath(r)),used:!0,xargs:!1}:t.k==="cmd"?{paths:[],used:!1,xargs:!0}:{paths:e.splat?[j]:[],used:!1,xargs:!1}}whatIfStandIn(e){return this.standIn(e,{k:"none"},!1)}removeItem(e,t){let s=x(b["remove-item"],e.args);if(_(s))return this.whatIfStandIn(e);let n=F(s,"recurse"),r=`${n?" -r":""}${F(s,"force")?" -f":""}`,{paths:i,used:o,xargs:l}=this.inputPaths(s,t);if(l){let f=t.k==="cmd"?this.listedItems(t.calls):null;return f===null?{text:`xargs rm${r}`}:{text:`rm${n||f.recurse?" -r":""}${F(s,"force")?" -f":""} ${f.items.join(" ")}`}}let u=[],h=[];for(let f of i){let S=ss(f);S===null?h.push(f):u.push(S)}let d=[...s.values.get("filter")?.words??[],...s.values.get("include")?.words??[]];if(d.length>0&&n)for(let f of h.length>0?h:[[p(".")]])for(let S of d)u.push(`find ${c(f)} -name ${c(S)} -delete`);else h.length>0&&u.push(`rm${r} ${h.map(f=>n&&!this.notShown(f)?Vt(f):c(f)).join(" ")}`);return{text:this.several(u),used:o}}listedItems(e){for(let t=e.length-1;t>=0;t--){let s=e[t];if(s.name==="get-childitem"){let n=x(b["get-childitem"],s.elem.args),r=this.paths(n),i=[...n.values.get("filter")?.words??[],...n.values.get("include")?.words??[]],o=[];for(let l of r.length>0?r:[[p(".")]])if(ut(l))o.push(c(l));else for(let u of i.length>0?i:[[p("*")]])o.push(`${c(l)}/${It(u)}`);return{items:o,recurse:F(n,"recurse")||n.values.has("depth")}}if(!At(s))return null}return null}several(e){return e.length===0?"true":e.length===1?e[0]:y(e.join("; "))}clearContent(e,t){let s=x(b["clear-content"],e.args);if(_(s))return this.whatIfStandIn(e);let{paths:n,used:r,xargs:i}=this.inputPaths(s,t);return i?{text:"xargs truncate -s 0"}:{text:this.several(n.map(o=>`: > ${c(o)}`)),used:r}}writeContent(e,t,s){let n=x(b[e==="add-content"?"set-content":e],t.args);if(_(n))return this.whatIfStandIn(t);let r=e==="add-content"||F(n,"append"),i=r?">>":">",o=this.paths(n,e==="out-file"||e==="tee-object"?["filepath","literalpath"]:["path","literalpath"]),l=F(n,"nonewline")?"'%s'":"'%s\\n'",u=n.values.get(e==="set-content"||e==="add-content"?"value":"inputobject"),h=o.length>0?o:e==="tee-object"?[]:[j];if(e==="tee-object"&&h.length===0)return{text:s.k==="none"?"true":"cat"};let d=f=>h.map(S=>f.words.length===0?r?`true >> ${c(S)}`:`: > ${c(S)}`:`printf ${l} ${f.words.map(c).join(" ")} ${i} ${c(S)}`);return u!==void 0?{text:this.several(d(u))}:s.k==="value"?{text:this.several(d(s.val)),used:!0}:s.k==="cmd"?{text:`tee${r?" -a":""} ${h.map(c).join(" ")}${e==="tee-object"?"":" > /dev/null"}`}:{text:this.several(h.map(f=>`: ${i} ${c(f)}`))}}newItem(e,t){let s=x(b["new-item"],e.args);if(_(s))return this.whatIfStandIn(e);let n=(s.values.get("itemtype")?.text??"").toLowerCase(),r=s.values.get("name"),i=this.inputPaths(s,t,["path"]),o=i.paths,l=i.used;if(r!==void 0){let d=k(r);o=o.length>0?o.map(f=>W(f,[p("\\")],d)):[this.fixPath(d)]}o.length===0&&(o=[j]);let u=s.values.get("value"),h=[];for(let d of o){let f=w(d.slice(0,1))?.toLowerCase()??"";if(/^env:/.test(f)){let m=u&&u.words.length>0?B(k(u)):"''";h.push(`export ${ee(w(d)?.replace(/^env:[\\/]?/i,"")??Q)}=${m}`);continue}if(/^(function|alias):/.test(f)){h.push(this.unread("a function or alias defined through a provider"));continue}if(/^variable:/.test(f)){h.push(`${fe(w(d)?.replace(/^variable:[\\/]?/i,"")??"v")}=${u&&u.words.length>0?B(k(u)):""}`);continue}let S=ze(d);if(S!==null){h.push(`reg add ${M(S)}`);continue}if("directory".startsWith(n)&&n!=="")h.push(`mkdir -p ${c(d)}`);else if(["symboliclink","junction","hardlink"].some(m=>m.startsWith(n))&&n!==""){let m=c(u?this.fixPath(k(u)):j);h.push(`ln${"hardlink".startsWith(n)?"":" -s"} ${m} ${c(d)}`)}else u!==void 0&&u.words.length>0?h.push(`printf '%s\\n' ${u.words.map(c).join(" ")} > ${c(d)}`):h.push(F(s,"force")?`: > ${c(d)}`:`touch ${c(d)}`)}return{text:this.several(h),used:l}}mkdir(e,t){let s=x(b.mkdir,e.args);if(_(s))return this.whatIfStandIn(e);let{paths:n,used:r,xargs:i}=this.inputPaths(s,t,["path"]),o=s.values.get("name"),l=o?[...n,...o.words]:n;return i?{text:"xargs mkdir -p"}:{text:l.length>0?`mkdir -p ${l.map(c).join(" ")}`:"true",used:r}}copyMove(e,t,s){let n=x(b[e],t.args);if(_(n))return this.whatIfStandIn(t);let r=n.values.get("destination"),i=r?this.fixPath(k(r)):[p(".")],o=e==="copy-item"?`cp${F(n,"recurse")?" -r":""}`:"mv",l=F(n,"force")?" -f":"",{paths:u,used:h,xargs:d}=this.inputPaths(n,s);return d?{text:`xargs ${o}${l} -t ${c(i)}`}:u.length===0?{text:"true"}:{text:`${o}${l} ${u.map(c).join(" ")} ${c(i)}`,used:h}}renameItem(e,t){let s=x(b["rename-item"],e.args);if(_(s))return this.whatIfStandIn(e);let{paths:n,used:r,xargs:i}=this.inputPaths(s,t),o=s.values.get("newname"),l=o?k(o):j;if(i)return{text:`xargs mv -t ${c(l)}`};let u=n.map(h=>{let d=w(l),f=d!==null&&/[\\/]/.test(d)?this.fixPath(l):W(Ie(h),l);return`mv ${c(h)} ${c(f)}`});return{text:this.several(u),used:r}}pathCommand(e,t,s){let{paths:n,used:r,xargs:i}=this.inputPaths(t,s);return i?{text:`xargs ${e}`}:{text:[e,...n.map(c)].join(" "),used:r}}selectString(e){let t=x(b["select-string"],e.args),s=(t.values.get("pattern")?.words??[]).flatMap(r=>["-e",c(r)]),n=this.paths(t);return{text:["grep",...F(t,"notmatch")?["-v"]:[],...s,...n.map(c)].join(" ")}}readOnlyPath(e,t,s){let n=x(b["read-only-path"],t.args),{paths:r,used:i,xargs:o}=this.inputPaths(n,s);if(o)return{text:"xargs ls"};if(r.length===0)return{text:"true",used:i};if(e==="test-path")return{text:this.several(r.map(u=>`test -e ${c(u)}`)),used:i};let l=`ls ${r.map(c).join(" ")}`;return r.length===1?{text:l,used:i,value:C(r[0],!0)}:{text:l,used:i}}joinPath(e){let t=x(b["join-path"],e.args),n=[t.values.get("path"),t.values.get("childpath"),t.values.get("additionalchildpath"),...t.extra].filter(o=>o!==void 0).flatMap(o=>o.words);if(n.length===0)return{text:"true"};let r=this.fixPath(n[0]);for(let o of n.slice(1)){let l=r[r.length-1],u=l?.t==="lit"&&/[\\/]$/.test(l.s),h=o[0],d=h?.t==="lit"&&/^[\\/]/.test(h.s);r=W(r,u||d?[]:[p("\\")],o)}let i=C(r,!0);return{text:`printf '%s\\n' ${c(r)}`,value:i}}splitPath(e){let t=x(b["split-path"],e.args),s=this.paths(t)[0];if(s===void 0)return{text:"true"};let n=w(s),r=T;if(F(t,"leaf")){let i=s[s.length-1];i?.t==="lit"&&/[\\/]/.test(i.s.replace(/[\\/]+$/,""))?r=Y(i.s.replace(/[\\/]+$/,"").split(/[\\/]/).pop()):n!==null&&(r=Y(n))}else if(!["qualifier","noqualifier","isabsolute","extension","leafbase"].some(i=>F(t,i))){let i=Ie(s);i.length>0&&!ts(i)&&(r=C(pt(i),!0))}return{text:r===T?"true":`printf '%s\\n' ${c(r.words[0])}`,value:r}}setLocation(e){let t=x(b["set-location"],e.args),s=this.paths(t)[0];if(s===void 0)return{text:"cd"};let n=w(s);if(n==="-"||n==="+")return this.sh.drive=null,{text:'cd "$OLDPWD"'};let r=n!==null?ke(n):s[0]?.t==="lit"?ke(s[0].s):null;return r!==null?this.sh.drive=this.sh.maybe>0&&r!==this.sh.drive?null:r:n===null&&s[0]?.t!=="lit"&&(this.sh.drive=null),{text:`cd ${c(s)}`}}write(e,t){let s=x(b[e],t.args),n=s.values.get(e==="write-host"?"object":"inputobject"),r=[...n?[n]:[],...s.extra],i=r.flatMap(l=>l.words),o=["echo",...i.map(c)].join(" ");return e==="write-output"&&i.length>0?{text:o,value:de(r)}:{text:o}}startProcess(e){let t=x(b["start-process"],e.args);if(_(t))return this.whatIfStandIn(e);let s=t.values.get("filepath");if(s===void 0)return{text:"true"};let n=k(s),r=w(n),i=t.values.get("argumentlist"),o=[];i!==void 0&&(o=i.words.length===1?ft(i.words[0]):[...i.words]),o.push(...t.extra.flatMap(m=>m.words));let l,u=r!==null?be(r):Ne(n),h=t.values.has("redirectstandardinput")?_e(this.sh,"commands from a file"):null;u===null?l=this.unknownProgram(n,!1,o.map(c)):u==="powershell"||u==="pwsh"?l=this.cli(o,h,u==="pwsh"):u==="cmd"?l=qe(o,this.sh,h):u==="taskkill"?l=Fe(o):u==="schtasks"?l=De(o,this.sh,m=>this.knownText(C(m))):u==="wmic"?l=Be(o,this.sh,m=>this.knownText(C(m))):r!==null&&/^[a-z][a-z0-9+.-]*:\/\//i.test(r)?l=["xdg-open",M(r)].join(" "):l=[r!==null&&We(r)?c(this.scriptWord(r)):B([p(u)]),...o.map(c)].join(" ");let d=t.values.get("verb")?.text?.toLowerCase();(d==="runas"||d==="runasuser")&&(l=`sudo ${l}`);let f=[["redirectstandardoutput",">"],["redirectstandarderror","2>"],["redirectstandardinput","<"]].map(([m,z])=>{let A=t.values.get(m);return A?` ${z} ${c(this.fixPath(k(A)))}`:""}).join(""),S=t.values.get("workingdirectory");return S!==void 0?{text:`( cd ${c(this.fixPath(k(S)))} && ${l}${f} )`}:{text:f?`${l.includes("; ")?y(l):l}${f}`:l}}processCreate(e){let t=`wmic process call create ${e!==void 0&&e.words.length>0?c(k(e)):"''"}`;return Ee(t,e===void 0?null:this.knownText(e),this.sh,"a process Win32_Process.Create starts")}hashValue(e,t){let s=e!==void 0&&e.words.length===1?e.words[0]:null,n=s?.length===1&&s[0].t==="var"?this.known(s[0].n)?.hash:void 0;return(e?.hash??n)?.find(([r])=>r.toLowerCase()===t)?.[1]}scheduledTask(e,t,s){let n=x(b["scheduled-task"],t.args);if(_(n))return this.whatIfStandIn(t);let r={"register-scheduledtask":"/create","set-scheduledtask":"/change","unregister-scheduledtask":"/delete","start-scheduledtask":"/run"}[e],i=n.values.get("taskname"),o=["schtasks",M(r),...i?["'/tn'",...i.words.map(c)]:[]];if(r!=="/create"&&r!=="/change")return{text:o.join(" ")};if(n.values.has("xml"))return{text:y(`${o.join(" ")}; ${this.unread("a scheduled task from XML")}`)};let l=n.values.get("action")??n.values.get("inputobject")??n.extra.find(d=>d.action!==void 0),u=!1;if(l===void 0&&s.k==="value"?(l=s.val,u=!0):l===void 0&&s.k==="cmd"&&(l=T),l===void 0)return{text:o.join(" ")};let h=l.action;return h!==void 0&&o.push("'/tr'",c(k(h))),{text:Ee(o.join(" "),h===void 0?null:this.knownText(h),this.sh,"a scheduled task"),used:u}}taskValue(e,t){let s=x(b[e],t.args),n=[...s.values.values(),...s.extra],r=O(n)||"true",i;if(e==="new-scheduledtask")i=s.values.get("action")?.action;else{let o=s.values.get("execute"),l=s.values.get("argument");if(o!==void 0){let u=k(o),h=w(u),d=h!==null&&/\s/.test(h)&&!h.startsWith('"')?[p(`"${h}"`)]:u;i={words:[W(d,...l!==void 0?[[p(" ")],k(l)]:[])]}}}return{text:r,value:i===void 0?P(n):{...P(n),action:i}}}invokeExpression(e,t){let n=x(b["invoke-expression"],e.args).values.get("command");return n!==void 0?{text:this.codeFrom(n,"Invoke-Expression")}:t.k==="value"?{text:this.codeFrom(t.val,"Invoke-Expression"),used:!0}:t.k==="cmd"?{text:this.pipedCode(t,"Invoke-Expression")}:{text:"true"}}codeFrom(e,t,s="ps",n=!1){if(e.unread)return re(O([e]));let r=this.knownText(e,n);return re(r===null?Se(this.unread(`${t}: text with a part the line does not show`),[e]):s==="ps"?this.nested(r,t):$e(r,this.sh,t))}knownText(e,t=!1){if(e.unread)return null;let s="";for(let[n,r]of(t?e.words:[k(e)]).entries()){n>0&&(s+=`
27
+ `);for(let i of r){let o=i.t==="var"?this.known(i.n):null;if(i.t==="lit")s+=i.s;else if(i.t==="home"||i.t==="var"&&ht.has(i.n))s+=ye(this.sh,i);else if(o?.text!==void 0)s+=o.text;else if(o&&!o.unread&&k(o).every(l=>l.t==="lit"||l.t==="home"))for(let l of k(o))s+=l.t==="lit"?l.s:ye(this.sh,l);else return null}}return s}pipedCode(e,t){return Nt(e.calls[e.calls.length-1])?"sh":this.unread(`${t}: code another command prints`)}invokeCommand(e){let t=x(b["invoke-command"],e.args),s=t.values.get("scriptblock"),n=t.values.get("computername")??t.values.get("hostname")??t.values.get("vmname")??t.values.get("containerid")??t.values.get("connectionuri"),r=n!==void 0||t.values.has("session"),i=t.values.get("filepath"),o;if(s?.block)s.block.used=!0,o=s.block.code||"true";else if(s!==void 0){let l=k(s),u=l.length===1&&l[0].t==="var"?this.known(l[0].n):null;if(!u?.block)return{text:this.unread("Invoke-Command running a script block held in a variable")};o=u.block.code||"true"}else if(i!==void 0)o=`source ${c(this.scriptWord(w(k(i))??""))}`;else return{text:"true"};return r?{text:`ssh ${c(n?k(n):j)} ${M(o)}`}:{text:y(o)}}webRequest(e){let t=e.values.get("uri"),s=(e.values.get("custommethod")?.text??e.values.get("method")?.text??"GET").toUpperCase(),n=["curl","-X",ct.test(s)?s:M(s),c(t?k(t):j)],r=e.values.get("headers");if(r?.hash)for(let[u,h]of r.hash)n.push("-H",c(W([p(`${u}: `)],k(h))));else r!==void 0&&n.push("-H",c(k(r)));let i=e.values.get("body")??e.values.get("form");i!==void 0&&n.push("-d",c(k(i)));let o=e.values.get("infile");o!==void 0&&n.push("-T",c(this.fixPath(k(o))));let l=e.values.get("outfile");return l!==void 0&&n.push("-o",c(this.fixPath(k(l)))),{text:n.join(" ")}}stopProcess(e,t,s){let n=x(b["stop-process"],e.args);if(_(n))return this.whatIfStandIn(e);let r=n.values.get("name")?.words??[],i=[...n.values.get("id")?.words??[],...n.values.get("inputobject")?.words??[],...n.extra.flatMap(l=>l.words)],o=[...r.map(l=>`pkill -x ${c(Pe(l))}`),...i.length>0?[`kill ${i.map(c).join(" ")}`]:[]];if(o.length>0)return{text:this.several(o)};if(t.k==="value")return{text:`kill ${t.val.words.map(c).join(" ")||"''"}`,used:!0};if(t.k==="cmd"){let l=[...s].reverse().find(u=>u.name==="get-process");if(l!==void 0){let u=x(b["get-process"],l.elem.args),h=s[s.length-1]===l,d=u.values.get("name")?.words??[],f=u.values.get("id")?.words??[];return d.length>0?{text:this.several(d.map(S=>`pkill -x ${c(Pe(S))}`)),used:h}:f.length>0?{text:`kill ${f.map(c).join(" ")}`,used:h}:h?{text:"kill -9 -1",used:!0}:{text:`pkill -x ${c(j)}`}}return{text:"xargs kill"}}return{text:"true"}}getProcess(e){let s=x(b["get-process"],e.args).values.get("name")?.words??[];return{text:s.length>0?this.several(s.map(n=>`pgrep -x ${c(Pe(n))}`)):"ps"}}archive(e,t){let s=x(b[e],t.args);if(_(s))return this.whatIfStandIn(t);let n=this.paths(s),r=s.values.get("destinationpath"),i=r?this.fixPath(k(r)):[p(".")];return e==="expand-archive"?{text:this.several(n.map(o=>`unzip ${c(o)} -d ${c(i)}`))}:{text:`zip ${c(i)} ${n.map(c).join(" ")}`.trim()}}blockStage(e,t,s){let n=x(b[e],t.args),r=[...n.values.entries()].filter(([l])=>["process","begin","end","remainingscripts","parallel","filterscript"].includes(l)).map(([,l])=>l);r.push(...n.extra);let i=[];for(let l of r)l.block?(l.block.used=!0,l.block.code&&i.push(l.block.code)):e==="foreach-object"&&l.text!==void 0&&nt.has(l.text.toLowerCase())&&i.push(this.unread(`ForEach-Object calling .${l.text}() on each item`));let o=n.values.get("membername")?.text;return o!==void 0&&nt.has(o.toLowerCase())&&i.push(this.unread(`ForEach-Object calling .${o}() on each item`)),i.length===0?{text:s.k==="none"?"true":"cat"}:i.length===1&&i[0]===ge?{text:ge}:{text:y(i.join("; "))}}runsBlock(e){let t=x(b["script-runner"],e.args),s=[];for(let r of[...t.values.values(),...t.extra])r.block&&(r.block.used=!0,r.block.code&&s.push(r.block.code));let n=t.values.get("filepath");return n!==void 0&&s.push(c(this.scriptWord(w(k(n))??""))),{text:s.length>0?y(s.join("; ")):"true"}}setVariable(e){let t=x(b["set-variable"],e.args),s=t.values.get("name")?.text,n=t.values.get("value")??je;if(s===void 0)return{text:O([n])||"true"};let r=fe(s);return this.setVar(r,pe(n)===null?n:null),{text:`${r}=${n.words.length===0?"":n.words.length===1?B(n.words[0]):c(k(n))}`}}newObject(e){let t=x(b["new-object"],e.args),s=[...t.values.values()];if(t.values.has("comobject"))return{text:this.unread("a COM object (New-Object -ComObject)")};let n=t.values.get("typename")?.text;if(n===void 0)return{text:this.unread("New-Object of a type chosen at run time")};let r=rt(n);return t.values.has("argumentlist")&&!(Oe.has(r)||Te(r))?{text:this.unread(`New-Object ${n} with arguments`)}:{text:O(s)||"true",value:P(s)}}tcpConnections(e){let t=x(b["get-nettcpconnection"],e.args),s=t.values.get("localport");if(s===void 0)return{text:"true"};let n=t.values.get("state")?.text?.toLowerCase()==="listen";return{text:["lsof","-ti",...s.words.map(r=>c(W([p("tcp:")],r))),...n?["-sTCP:LISTEN"]:[]].join(" ")}}};function Ie(a){for(let e=a.length-1;e>=0;e--){let t=a[e];if(t.t!=="lit")continue;let s=Math.max(t.s.lastIndexOf("\\"),t.s.lastIndexOf("/"));if(s>=0)return W(a.slice(0,e),[p(t.s.slice(0,s+1))])}return w(a)!==null?[]:[...j,p("\\")]}function ts(a){let e=a[0];return e?.t==="var"&&e.n===Q}function pt(a){let e=a[a.length-1];if(e?.t!=="lit")return a;let t=e.s.length>1&&!/^[A-Za-z]:[\\/]$/.test(e.s)?e.s.replace(/[\\/]+$/,""):e.s;return W(a.slice(0,-1),[p(t)])}function ss(a){let e=a[0];if(e?.t!=="lit")return null;let t=e.s,s=/^env:[\\/]?(.*)$/i.exec(t);if(s){let r=W([p(s[1])],a.slice(1)),i=w(r);return i!==null&&i!==""?`unset ${ee(i)}`:`unset "$${Q}"`}if(/^(function|alias|variable):/i.test(t))return"true";let n=ze(a);return n===null?null:`reg delete ${M(n)}`}function ze(a){let e=w(a);if(e===null){let n=a[0];return n?.t==="lit"&&/^(hkcu|hklm|hkcr|hku|hkcc):|^registry::/i.test(n.s)?"(a registry key the line does not show)":null}let t=/^(hkcu|hklm|hkcr|hku|hkcc):[\\/]?(.*)$/i.exec(e);if(t)return`${t[1].toUpperCase()}${t[2]?`\\${t[2]}`:""}`;let s=/^registry::(.*)$/i.exec(e);return s?s[1]:null}function Pe(a){let e=w(a);if(e===null)return a;let t=e.replace(/\.exe$/i,"");return/[*?]/.test(t)?[p(t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."))]:[p(t)]}function rt(a){return a.replace(/\s+/g,"").toLowerCase().replace(/^system\./,"")}function Te(a){return/^collections\.(generic\.)?(list|dictionary|hashset|queue|stack|sortedlist|sorteddictionary|arraylist|hashtable|ordereddictionary|specialized\.ordereddictionary)/.test(a)||/^(list|dictionary|hashset)\[/.test(a)}function Me(a,e){let t=e,s=r=>U(a[r]??"");if(a[t]==="0"&&(a[t+1]==="x"||a[t+1]==="X")&&/[0-9a-fA-F]/.test(a[t+2]??""))for(t+=2;/[0-9a-fA-F]/.test(a[t]??"");)t++;else if(a[t]==="0"&&(a[t+1]==="b"||a[t+1]==="B")&&/[01]/.test(a[t+2]??""))for(t+=2;/[01]/.test(a[t]??"");)t++;else{let r=t;for(;s(t);)t++;if(a[t]==="."&&s(t+1))for(t++;s(t);)t++;if(t===r)return e;if((a[t]==="e"||a[t]==="E")&&(s(t+1)||(a[t+1]==="+"||a[t+1]==="-")&&s(t+2)))for(t+=2;s(t);)t++}let n=a.slice(t,t+2).toLowerCase();return/^[kmgtp]b$/.test(n)||/^(ul|lu|uy|us|un)$/.test(n)?t+2:/^[ldunys]$/.test(n[0]??"")&&!R(a[t+1]??"")?t+1:t}function ns(a){return a===""||q(a)||a===`
28
+ `||";)}|,+-*/%.]=><&".includes(a)}function Ae(a){return ft([p(a)])}function ft(a){let e=[],t=[],s=!1,n=!1,r=()=>{s&&e.push(W(t)),t=[],s=!1};for(let i of a){if(i.t!=="lit"){t.push(i),s=!0;continue}let o=i.s;for(let l=0;l<o.length;l++){let u=o[l];if(u==="\\"){let h=0;for(;o[l+h]==="\\";)h++;o[l+h]==='"'?(t.push(p("\\".repeat(Math.floor(h/2)))),h%2===1?t.push(p('"')):n=!n,l+=h):(t.push(p("\\".repeat(h))),l+=h-1),s=!0;continue}if(u==='"'){n=!n,s=!0;continue}if(!n&&(u===" "||u===" "||u===`
29
+ `)){r();continue}t.push(p(u)),s=!0}}return r(),e}function Fe(a){let e=[];for(let t=0;t<a.length;t++){let s=w(a[t])?.toLowerCase(),n=a[t+1];(s==="/im"||s==="-im")&&n?(e.push(`pkill -x ${c(Pe(n))}`),t++):(s==="/pid"||s==="-pid")&&n?(e.push(`kill ${c(n)}`),t++):(s==="/fi"||s==="/s"||s==="/u"||s==="/p")&&n&&t++}return e.length===0?["taskkill",...a.map(c)].join(" "):e.length===1?e[0]:y(e.join("; "))}function qe(a,e,t){for(let s=0;s<a.length;s++){let n=a[s],r=n[0];if(r?.t!=="lit"||!r.s.startsWith("/"))continue;let i=/\/([ckr])/i.exec(r.s);if(i===null)continue;let l=[[p(r.s.slice(i.index+2)),...n.slice(1)],...a.slice(s+1)].map(h=>h.map(d=>d.t==="lit"?d.s:ye(e,d)).join("")).filter((h,d)=>d>0||h!=="").join(" "),u=re($e(rs(l),e,"cmd /c",t));return i[1].toLowerCase()==="k"&&t!==null?`${u}; ${t("cmd","cmd /k reading its input")}`:u}return t!==null?t("cmd","cmd reading its input"):"true"}function ye(a,e){return a.marks.push(e),`${X}${a.marks.length-1}${ie}`}function He(a,e,t){let s=a.indexOf(ie,e),n=s<0?void 0:t.marks[Number(a.slice(e+1,s))];return n===void 0&&g("a broken marker"),n}function rs(a){let e=a.trim();if(!e.startsWith('"'))return e;let t=e.lastIndexOf('"');return t>0?e.slice(1,t)+e.slice(t+1):e.slice(1)}function $e(a,e,t="cmd /c",s=null){Ze(e,a),++e.depth>we&&ae("nests too deeply");let n=e.unread.length;try{return gt(a,e,s)}catch(r){if(!(r instanceof ne)||r.fatal)throw r;return Ke(e,n,`${t}: ${r.why}`)}finally{e.depth--}}function ce(a,e){let t=a[0];if(t?.t!=="lit")return a;let s=t.s;return!(s.startsWith("\\")||s.startsWith("/"))||s.startsWith("\\\\")||s.startsWith("//")?a:e===null?j:W([p(e)],a)}var is={...Ve,homepath:[K],cd:[L("PWD")]};function mt(a,e,t){let s=t!==null?/^%%?([A-Za-z])/.exec(a.slice(e,e+3)):null;if(s&&s[1]===t)return{word:[L(t.toLowerCase())],end:e+s[0].length};let n=/^%(~[a-z]*)?[0-9*]/i.exec(a.slice(e,e+16));if(n)return{word:j,end:e+n[0].length};let r=a.indexOf("%",e+1);if(r<0)return null;let i=a.slice(e+1,r);return i.length>128||!/^[A-Za-z_][^%\s"]*$/.test(i)?null:i.includes(":")?{word:j,end:r+1}:{word:is[i.toLowerCase()]??[L(ee(i))],end:r+1}}function gt(a,e,t=null){let s=new Ue(a,e,t),n=s.list(!1);return s.end(),n}var Ue=class{constructor(e,t,s=null){this.src=e;this.sh=t;this.stdin=s}pos=0;loopVar=null;echoed=null;end(){this.blank(!0),this.pos<this.src.length&&g(`cmd: unexpected ${JSON.stringify(this.src[this.pos])}`)}peek(e=0){return this.src[this.pos+e]??""}blank(e=!1){for(;;){let t=this.peek();if(t===" "||t===" "||e&&(t===`
30
+ `||t==="@"))this.pos++;else if(t==="^"&&this.peek(1)===`
31
+ `)this.pos+=2;else return}}list(e){let t=[],s=[];for(;this.blank(!0),!(this.pos>=this.src.length||e&&this.peek()===")");){t.push(this.pipeline(e)||"true"),this.blank();let n=this.peek()+this.peek(1);if(n==="&&"||n==="||")this.pos+=2,s.push(` ${n} `);else if(this.peek()==="&"||this.peek()===`
32
+ `)this.pos++,s.push("; ");else break}return t.map((n,r)=>r===0?n:`${s[r-1]}${n}`).join("")}pipeline(e){let t=this.stdin,s=[this.command(e)];for(;this.blank(),!(this.peek()!=="|"||this.peek(1)==="|");)this.pos++,this.stdin=this.echoed!==null?Rt(this.echoed,this.sh):_e(this.sh,"code another command prints"),s.push(this.command(e));return this.stdin=t,s.length===1?s[0]:s.map(n=>n===""?"true":/; | && | \|\| /.test(n)&&!n.startsWith("{ ")?y(n):n).join(" | ")}command(e){this.blank(!0),++this.sh.depth>we&&ae("nests too deeply");try{return this.commandIn(e)}finally{this.sh.depth--}}commandIn(e){if(this.echoed=null,this.peek()==="("){this.pos++;let d=this.list(!0);this.peek()!==")"&&g("cmd: a missing )"),this.pos++;let f=[];for(;;){this.blank();let S=this.redirect(e);if(S===null)break;f.push(S)}return this.echoed=null,y(d||"true")+vt(f,this.sh)}let t=this.commandName(e),s=w(t.word)?.toLowerCase()??"";if(s==="rem"||s.startsWith("::")){for(;this.pos<this.src.length&&this.peek()!==`
33
+ `;)this.pos++;return""}if(s==="if"||s==="for"){let d=s==="if"?this.ifCommand(e):this.forCommand(e);return this.echoed=null,d}let n=this.pos,r=[],i=[],o=this.pos;for(;;){this.blank();let d=this.peek();if(d===""||d===`
34
+ `||d==="&"||d==="|"||e&&d===")")break;let f=this.redirect(e);if(f!==null){i.push(f);continue}r.push(this.word(e)),o=this.pos}let l=this.src.slice(n,o),u=i.some(d=>/^0?<$/.test(d.op))?_e(this.sh,"commands from a file"):this.stdin,h=Qe(t,r,i,this.sh,l,this.loopVar,u);return this.echoed=be(w(t.word)??"")==="echo"&&i.length===0?os(l,this.sh,this.loopVar):null,h}commandName(e){let t=/^(rd|rmdir|del|erase|cd|chdir|echo|md|mkdir|dir|copy|move|type|pushd)(?=[/\\.:;,=+(])/i.exec(this.src.slice(this.pos,this.pos+8));return t?(this.pos+=t[1].length,{word:[p(t[1])],quoted:!1}):this.word(e)}nextWord(e){this.blank();let t=this.peek();if(t===""||t===`
35
+ `||t==="&"||t==="|"||t==="("||t===")")return null;let s=this.word(e);return{...s,text:w(s.word)?.toLowerCase()??""}}ifCommand(e){let t=this.nextWord(e);t?.text==="/i"&&(t=this.nextWord(e));let s=t?.text==="not";s&&(t=this.nextWord(e)),t===null&&g("cmd: an if without a condition");let n=ve;if(t.text==="exist"){let o=this.nextWord(e);o!==null&&(n=`${s?"! ":""}test -e ${c(ce(o.word,this.sh.drive))}`)}else if(t.text==="defined"||t.text==="errorlevel"||t.text==="cmdextversion")this.nextWord(e);else if(!t.text.includes("==")||t.text.endsWith("==")){let o=t.text.endsWith("==")?null:this.nextWord(e);(o===null||o.text==="=="||/^(equ|neq|lss|leq|gtr|geq)$/.test(o.text))&&this.nextWord(e)}let r=`if ${n}; then ${this.command(e)||"true"}`,i=this.pos;return this.blank(),/^else(?=[\s(])/i.test(this.src.slice(this.pos,this.pos+5))?(this.pos+=4,r+=`; else ${this.command(e)||"true"}`):this.pos=i,`${r}; fi`}forCommand(e){let t=this.nextWord(e),s=!1;for(;t!==null&&t.text.startsWith("/");){let h=t.text;t=this.nextWord(e),h==="/f"&&(s=!0),(h==="/f"||h==="/r")&&t!==null&&!t.text.startsWith("%")&&(t=this.nextWord(e))}let n=(t===null?"":w(t.word)??"").replace(/^%+/,"");/^[A-Za-z]$/.test(n)||g("cmd: a for loop without a variable"),this.nextWord(e)?.text!=="in"&&g("cmd: a for loop without in"),this.blank(),this.peek()!=="("&&g("cmd: a for loop without its (set)");let r=this.src.indexOf(")",this.pos);r<0&&g("cmd: a missing )");let i=this.src.slice(this.pos+1,r).trim();this.pos=r+1,this.nextWord(e)?.text!=="do"&&g("cmd: a for loop without do"),this.loopVar=n;let o;try{o=this.command(e)||"true"}finally{this.loopVar=null}let l=/^(['`])([\s\S]*)\1$/.exec(i),u;return s&&l?u=c([{t:"sub",code:re($e(l[2],this.sh,"for /f"))}]):s?u=c([{t:"sub",code:`cat ${c(ce([p(i.replace(/^"|"$/g,""))],this.sh.drive))}`}]):u=Ae(i).map(h=>c(ce(h,this.sh.drive))).join(" ")||"''",`for ${n.toLowerCase()} in ${u}; do ${o}; done`}redirect(e){let t=this.pos,s="";U(this.src[t]??"")&&(this.src[t+1]===">"||this.src[t+1]==="<")&&(s=this.src[t],t++);let n=this.src[t];if(n!==">"&&n!=="<")return null;let r=n;t++,n===">"&&this.src[t]===">"&&(r=">>",t++);let i=s==="1"?"":s;if(this.src[t]==="&"&&U(this.src[t+1]??""))return this.pos=t+2,{op:`${i}${r}&${this.src[t+1]}`,target:null};this.pos=t,this.blank();let o=this.word(e).word;o.length===0&&g("cmd: a redirection without a file");let l=w(o)?.toLowerCase();return{op:`${i}${r}`,target:l==="nul"||l==="nul:"?[p("/dev/null")]:o}}word(e){let t=this.peek()==='"',s=new se,n=!1;for(;;){let r=this.peek();if(r===""||r===`
36
+ `||!n&&(r===" "||r===" "||r==="&"||r==="|"||r==="<"||r===">"||e&&r===")"))break;if(r==="^"&&!n){let i=this.peek(1);this.pos+=2,i!==`
37
+ `&&s.text(i);continue}if(r==='"'){n=!n,this.pos++;continue}if(r==="%"){let i=mt(this.src,this.pos,this.loopVar);if(i!==null){s.add(i.word),this.pos=i.end;continue}}if(r===X){s.add([He(this.src,this.pos,this.sh)]),this.pos=this.src.indexOf(ie,this.pos)+1;continue}s.text(r),this.pos++}return{word:s.word(),quoted:t}}};function vt(a,e){return a.map(t=>t.target===null?` ${t.op}`:` ${t.op} ${w(t.target)==="/dev/null"?"/dev/null":c(ce(t.target,e.drive))}`).join("")}function as(a){let e=new Set,t=[];for(let s of a){let n=w(s.word);if(n!==null&&!s.quoted&&/^(\/[A-Za-z0-9:+-]+)+$/.test(n))for(let r of n.split("/"))r!==""&&e.add(r.toLowerCase());else t.push(s.word)}return{opts:e,args:t}}function os(a,e,t){let s=a.replace(/^[\s.:;,=(]/,"").replace(/\s+$/,"");return/^(on|off)$/i.test(s)?"":Xe(s,e,t).map(n=>n.t==="lit"?n.s:ye(e,n)).join("")}function Qe(a,e,t,s,n,r,i=null){let o=vt(t,s),l=w(a.word),u=l!==null?be(l):Ne(a.word);if(u===null)return y(`${[c(j),...e.map(v=>c(v.word))].join(" ")}${o}; ${oe(s,"a command named by a value the line does not show")}`);let h=l??u,d=u,{opts:f,args:S}=as(e),m=S.map(v=>ce(v,s.drive)),z=v=>v.map(c).join(" "),A=e.map(v=>v.word);switch(d){case"rd":case"rmdir":return m.length===0?`true${o}`:`${f.has("s")?`rm -r${f.has("q")?" -f":""}`:"rmdir"} ${z(m)}${o}`;case"del":case"erase":{if(m.length===0)return`true${o}`;let v=f.has("f")||f.has("q")?" -f":"";if(!f.has("s"))return`rm${v} ${z(m)}${o}`;let $=m.map(N=>{let ue=N[N.length-1],he=ue?.t==="lit"?ue.s.split(/[\\/]/).pop()??"":"";if(/[*?]/.test(he)||/\.[A-Za-z0-9]+$/.test(he)){let Je=pt(Ie(N));return`find ${c(Je.length>0?Je:[p(".")])} -name ${M(he)} -delete`}return`rm -r${v} ${c(N)}`});return($.length===1?$[0]:y($.join("; ")))+o}case"copy":case"xcopy":{if(m.length===0)return`true${o}`;let v=d==="xcopy"&&(f.has("s")||f.has("e"))?" -r":"",$=m.length>1?m[m.length-1]:[p(".")];return`cp${v} ${z(m.length>1?m.slice(0,-1):m)} ${c($)}${o}`}case"robocopy":{let[v,$]=[m[0],m[1]];return v===void 0||$===void 0?`true${o}`:f.has("mir")||f.has("purge")?`robocopy ${c(v)} ${c($)} ${f.has("mir")?"/MIR":"/PURGE"}${o}`:f.has("move")?`mv ${c(v)} ${c($)}${o}`:`cp${f.has("e")||f.has("s")?" -r":""} ${c(v)} ${c($)}${o}`}case"move":{if(m.length===0)return`true${o}`;let v=m.length>1?m[m.length-1]:[p(".")];return`mv ${z(m.length>1?m.slice(0,-1):m)} ${c(v)}${o}`}case"ren":case"rename":{let[v,$]=[m[0],S[1]];return v===void 0||$===void 0?`true${o}`:`mv ${c(v)} ${c(W(Ie(v),$))}${o}`}case"mklink":{let[v,$]=[m[0],m[1]];return v===void 0||$===void 0?`true${o}`:`ln${f.has("h")?"":" -s"} ${c($)} ${c(v)}${o}`}case"type":return`cat ${z(m)}${o}`;case"md":case"mkdir":return m.length>0?`mkdir -p ${z(m)}${o}`:`true${o}`;case"dir":return`ls${m.length>0?` ${z(m)}`:""}${o}`;case"echo":{let v=n.replace(/^[\s.:;,=(]/,"").replace(/\s+$/,"");if(/^(on|off)$/i.test(v)&&o==="")return"true";let $=Xe(v,s,r);return`echo${$.length>0?` ${c($)}`:""}${o}`}case"cd":case"chdir":case"pushd":{if(m.length===0)return d==="pushd"?"true":`pwd${o}`;let v=m.length===1?m[0]:W(...m.flatMap((ue,he)=>he>0?[[p(" ")],ue]:[ue])),$=w(v),N=$!==null?ke($):null;return N!==null?s.drive=N:$===null&&(s.drive=null),`cd ${c(v)}`}case"popd":return s.drive=null,'cd "$OLDPWD"';case"set":return ls(n,s,r)+o;case"start":{let v=e[0]?.quoted?1:0;for(;v<e.length;){let N=w(e[v].word)?.toLowerCase();if(N===void 0||!N.startsWith("/"))break;v+=["/d","/affinity","/node","/machine"].includes(N)?2:1}let $=e[v];return $===void 0?`true${o}`:Qe($,e.slice(v+1),t,s,"",r,i)}case"call":{let v=e[0],$=v?w(v.word):null;return v===void 0||$?.startsWith(":")?"true":$!==null&&/\.(bat|cmd)$/i.test($)?[M(/[\\/]/.test($)?$.replace(/\\/g,"/"):`./${$}`),...e.slice(1).map(N=>c(N.word))].join(" ")+o:Qe(v,e.slice(1),t,s,"",r,i)}case"exit":return"exit";case"cls":case"title":case"ver":case"vol":case"pause":case"color":case"prompt":case"setlocal":case"endlocal":case"verify":case"goto":case"shift":case"break":return"true";case"cmd":return qe(A,s,i)+o;case"powershell":case"pwsh":return new xe("",s).cli(A,i,d==="pwsh")+o;case"taskkill":return Fe(A)+o;case"schtasks":return De(A,s,v=>Ge(v,s))+o;case"wmic":return Be(A,s,v=>Ge(v,s))+o;default:return/\.(bat|cmd)$/i.test(h)?[M(/[\\/]/.test(h)?h.replace(/\\/g,"/"):`./${h}`),...A.map(c)].join(" ")+o:[We(h)?M(h.replace(/\\/g,"/")):B([p(d)]),...A.map(c)].join(" ")+o}}function ls(a,e,t){let s=a.trim(),n=!1,r=/^\/([ap])\s+/i.exec(s);r&&(s=s.slice(r[0].length),n=!0),s.startsWith('"')&&(s=s.slice(1).replace(/"[^"]*$/,""));let i=s.indexOf("=");if(i<=0)return"env";let o=ee(s.slice(0,i).trim()),l=s.slice(i+1);return n?`export ${o}="$${Q}"`:l===""?`unset ${o}`:`export ${o}=${B(Xe(l,e,t))}`}function Xe(a,e,t){let s=new se;for(let n=0;n<a.length;){let r=a[n];if(r==="^"){s.text(a[n+1]??""),n+=2;continue}if(r==="%"){let i=mt(a,n,t);if(i!==null){s.add(i.word),n=i.end;continue}}if(r===X){s.add([He(a,n,e)]),n=a.indexOf(ie,n)+1;continue}s.text(r),n++}return s.word()}0&&(module.exports={readCmd,readPowerShell});
@@ -0,0 +1,28 @@
1
+ import{existsSync as _i,linkSync as xi,readFileSync as Si,renameSync as Ai,statSync as Ut,unlinkSync as Ht,writeFileSync as Ci}from"fs";import{homedir as $e,hostname as to}from"os";import{basename as Ke,dirname as Y,join as P}from"path";import{fileURLToPath as Ri,pathToFileURL as Ni}from"url";import{createHmac as Bo,randomBytes as gt,timingSafeEqual as zo}from"crypto";import{closeSync as Tn,existsSync as mt,fsyncSync as Ln,linkSync as Ko,mkdirSync as Dn,openSync as Mn,readdirSync as Jo,readFileSync as se,unlinkSync as Fn,writeSync as Hn}from"fs";import{basename as qo,dirname as je,join as O}from"path";var v={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"},oo="Anvil. Claude Code",z=80,so=11;function U(e){if(!e){let l=c=>c;return{on:!1,bold:l,dim:l,blue:l,grey:l,amber:l,mark:l,field:l}}let t=e==="truecolor",n=l=>c=>`\x1B[${l}m${c}\x1B[0m`,r=n(t?"38;2;76;139;255":"38;5;69"),o=n(t?"38;2;130;134;150":"90"),s=n(t?"38;2;245;165;36":"38;5;214"),a=n(t?"38;2;34;197;94":"32"),i={[v.on]:r,[v.blocked]:r,[v.held]:r,[v.next]:r,[v.watching]:o,[v.problem]:s,[v.ok]:a};return{on:!0,bold:n("1"),dim:n("2"),blue:r,grey:o,amber:s,mark:l=>(i[l]??(c=>c))(l),field:l=>`\x1B[${t?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${Ye(l)}\x1B[0m`}}var K=U(!1),io=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function Ye(e){return e.replace(io,"")}function Gt(e){return Ye(e).length}function Yt(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}\u2026`}function Zt(e,t){let n=[],r="";for(let o of e.split(/\s+/).filter(Boolean))r&&r.length+1+o.length>t?(n.push(r),r=o):r=r?`${r} ${o}`:o;return r&&n.push(r),n.length>0?n:[""]}function ao(e,t){let n=[],r="";for(let o of e){if(r&&r.length+3+o.length<=t){r=`${r} \xB7 ${o}`;continue}r&&n.push(r);let s=o.length>t?Zt(o,t):[o];n.push(...s.slice(0,-1)),r=s[s.length-1]}return r&&n.push(r),n.length>0?n:[""]}function Se(e,t,n=K){return` ${n.mark(e)} ${t}`}function D(e,t,n=K){return` ${n.dim(e.padEnd(so))}${t}`}function Ze(e,t,n=K,r=z){let o=` ${oo} \xB7 ${e}`,s=r-o.length-3,a=s>=8&&t?`${t.length>s?`\u2026${t.slice(t.length-s+1)}`:t} `:"",i=`${o}${" ".repeat(Math.max(2,r-o.length-a.length))}${a}`.slice(0,r);return n.on?n.field(i):i.trimEnd()}function Xe(e=z){return e-7}function Xt(e,t,n=K,r=z,o={}){let s=r-3,a=s-4,i=o.tone??n.grey,l=o.mark?`${n.mark(o.mark)} `:"",c=(o.mark?2:0)+e.length,f=o.note?` ${o.note}`:"",u=Math.max(1,s-4-c-1-f.length-(f?2:1)),d=` ${i("\u256D\u2500 ")}${l}${n.bold(e)} ${i("\u2500".repeat(u))}${f?`${n.dim(f)}${i(" \u2500\u256E")}`:i("\u2500\u256E")}`,g=t.map(h=>{let _e=Gt(h)>a?Yt(Ye(h),a):h;return` ${i("\u2502")} ${_e}${" ".repeat(Math.max(0,a-Gt(_e)))} ${i("\u2502")}`});return[d,...g,` ${i(`\u2570${"\u2500".repeat(s-2)}\u256F`)}`]}function Z(e,t,n,r=K,o=z-7,s=9,a=i=>i){let i=e===null?0:2,l=Math.max(10,o-i-s);return(typeof n=="string"?Zt(n,l):ao(n,l)).map((f,u)=>u===0?`${e===null?"":`${r.mark(e)} `}${r.bold(t.padEnd(s))}${a(f)}`:`${" ".repeat(i+s)}${a(f)}`)}function lo(e,t,n,r=K,o="blue",s=z){let i=` ${(o==="blue"?r.blue:o==="amber"?r.amber:r.grey)("\u258C")} ${r.dim(e.padEnd(9))}`,l=t?`${r.blue(r.bold(t))}${n?" ":""}`:"",c=s-3-9-(t?t.length+(n?3:0):0);return`${i}${l}${n?r.dim(Yt(n,Math.max(0,c))):""}`}function Qe(e,t,n=K,r=0,o="Next"){return lo(o,e.padEnd(t?r:0),t??"",n,"blue")}var R="claude";function J(e){return e==="ghost"||e==="enforce"?e:null}function X(e,t){if(!e||typeof e!="object"||e.kill_switch===!0)return"ghost";let n=J(e.services?.[R]?.actions?.[t]?.mode);return n||(J(e.default_mode)??"ghost")}function et(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[R]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function Q(e){return e==null?!0:typeof e!="object"||e.kill_switch===!0?!1:e.day_one===!0}function en(e,t,n,r=new Date){let o=e&&typeof e=="object"?e:et(r);if(n==="all")return{version:1,kill_switch:!1,default_mode:t,services:{[R]:{actions:{}}},updated_at:r.toISOString()};let s={...o.services?.[R]?.actions??{}};for(let a of n)s[a]={mode:t};return{version:1,kill_switch:o.kill_switch===!0,default_mode:J(o.default_mode)??"ghost",services:{...o.services??{},[R]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{}}}function co(e){return!e||typeof e!="object"||e.kill_switch===!0?!1:J(e.default_mode)==="enforce"?!0:Object.values(e.services?.[R]?.actions??{}).some(t=>J(t?.mode)==="enforce")}var tt="claude.agent.controls";function ee(e,t){return t===tt&&co(e)?"enforce":X(e,t)}var Qt={off:0,ghost:1,enforce:2};function de(e,t){return e===null?t:t===null?e:Qt[t]>Qt[e]?t:e}function tn(e,t){return!e||typeof e!="object"?null:J(e.services?.[R]?.actions?.[t]?.mode)??(J(e.default_mode)==="enforce"?"enforce":null)}function nt(e,t,n,r=!1){let s=de(tn(e,t),n)??(r&&Q(e)?"enforce":ee(e,t));return e?.kill_switch===!0&&s==="enforce"?"ghost":s}function nn(e,t,n){return de(tn(e,t),n)===null&&Q(e)&&ee(e,t)!=="enforce"}var Ae=[{id:"protect",name:"Protect what can't come back",verdict:"block",short:"wiping your home folder or the project, and force-pushing main",context:"blocks deleting the user's home folder, the disk, a system folder, the project or its .git, force-pushing main or deleting it on the remote, and killing every process",slugs:{protected:"deleting your home folder, the disk, a system folder, the project or its .git; force-pushing main or deleting it on the remote; killing every process"}},{id:"keep-anvil-on",name:"Keep Anvil on",verdict:"hold",short:"changes to Anvil",context:"holds any change to Anvil or to Claude Code's permissions, hooks and settings",slugs:{"agent-controls":"any change to Anvil, or to Claude Code's permissions, hooks and settings"}},{id:"stop-loops",name:"Stop runaway loops",verdict:"hold",short:"delete bursts and repeats",context:"holds more than 20 recursive deletes in a minute and the same app change twice in 10 minutes",slugs:{"delete-burst":"more than 20 recursive deletes in a minute",repeat:"the same app (MCP) change twice in 10 minutes"}},{id:"stop-helper-bursts",name:"Stop runaway helpers",verdict:"hold",short:"helper bursts",context:"holds more than 20 helper agent launches in 10 minutes in one session",slugs:{"helper-burst":"more than 20 helper launches in 10 minutes"}},{id:"keep-keys-in",name:"Keep keys in",verdict:"hold",short:"use of your account keys",context:"holds reading or writing the user's account key files (such as ~/.ssh/id_* and ~/.aws/credentials) and committing or sending a secrets file",slugs:{credentials:"reading or writing your account key files (~/.ssh/id_*, ~/.aws/credentials, ~/.npmrc \u2026)","secrets-expose":"committing or sending a secrets file"}},{id:"hold-unchecked",name:"Hold what it can't check",verdict:"hold",short:"actions it can't check",context:"holds a call it could not read in full or check in time",slugs:{"could-not-check":"a command too long or nested too deep to read, or one its classifier failed on","too-long-to-check":"a call it could not check in time (1 second a pass, 3 in all)"}}],uo="home and project wipes and force-pushes to main",fo=`always blocking ${uo}`,Gi=new Map(Ae.map(e=>[e.id,e]));var rn=new Set(Ae.flatMap(e=>Object.keys(e.slugs)));var on={"block-protected-targets":["protect"],"hold-delete-bursts":["stop-loops"],"hold-repeated-side-effect":["stop-loops"],"hold-helper-bursts":["stop-helper-bursts"],"hold-risky-actions":["keep-anvil-on","keep-keys-in"]};function sn(e){let t=new Set(po(e));return Ae.filter(n=>!Object.entries(on).some(([r,o])=>o.includes(n.id)&&t.has(r)))}var fe=new Set([tt,"claude.bash.secrets.expose"]);function po(e){let t=new Set(e.policies.filter(n=>n.origin==="baseline").flatMap(n=>n.rules.map(r=>r.id)));return Object.keys(on).filter(n=>!t.has(n))}var M={"claude.bash.fs.delete_recursive":{slug:"delete",text:"recursive delete"},"claude.bash.fs.delete_disposable":{slug:"delete-temp",text:"delete of temp or build files"},"claude.bash.git.force_push":{slug:"force-push",text:"force-push"},"claude.bash.git.push_main":{slug:"push-main",text:"push or merge to main"},"claude.bash.git.discard":{slug:"discard",text:"discard uncommitted work"},"claude.bash.db.destructive":{slug:"db-destroy",text:"destroy database data"},"claude.bash.deploy":{slug:"deploy",text:"deploy"},"claude.bash.publish":{slug:"publish",text:"publish a package or release"},"claude.bash.secrets.print":{slug:"secrets-print",text:"print secrets"},"claude.bash.privilege":{slug:"sudo",text:"run as root, or run code it cannot read"},"claude.bash.process.kill_by_name":{slug:"kill",text:"kill processes by name or port"},"claude.bash.external_write":{slug:"external-write",text:"write to an external API"},"claude.bash.spend":{slug:"spend",text:"start paid compute"},"claude.bash.secrets.expose":{slug:"secrets-expose",text:"commit or send a secrets file"},"claude.bash.net.expose":{slug:"net-expose",text:"open this machine to the internet"},"claude.bash.data.export":{slug:"data-export",text:"copy a remote database here"},"claude.bash.crypto.transaction":{slug:"crypto",text:"send a transaction on a real chain"},"claude.bash.persistence":{slug:"persistence",text:"install background jobs or global git hooks"},"claude.agent.controls":{slug:"agent-controls",text:"change its own permissions, hooks or rules"},"claude.agent.helper":{slug:"helper-agent",text:"launch a helper agent"},"claude.file.write_secret":{slug:"secret-file-write",text:"write a secrets file"},"claude.file.read_secret":{slug:"secret-file-read",text:"read a secrets file"},"claude.mcp.side_effect":{slug:"mcp-write",text:"MCP tool that changes something"},"claude.mcp.call":{slug:"mcp-read",text:"MCP tool call"},"claude.bash.unclassified":{slug:"other",text:"command"},"claude.tool.other":{slug:"tool",text:"tool call"}},an={slug:"catastrophic",text:"cluster, cloud and database destroys, and cloud-credential prints"};function ln(e){if(!Q(e))return null;let t="cluster, cloud and database destroys";return{what:t,context:`It also holds ${t} and cloud-credential prints, until the user sets a mode for their kinds.`}}var Ce={"block-protected-targets":{slug:"protected",text:"never: home, root, project root, .git, main, every process"},"hold-repeated-side-effect":{slug:"repeat",text:"the same MCP action again within 10 minutes"},"hold-delete-bursts":{slug:"delete-burst",text:"more than 20 deletes in a minute"},"hold-helper-bursts":{slug:"helper-burst",text:"more than 20 helper launches in 10 minutes"},"too-long-to-check":{slug:"too-long-to-check",text:"too long to check in time"},"could-not-check":{slug:"could-not-check",text:"could not be checked"}};function Re(e,t){return e&&Ce[e]?Ce[e].slug:!e||e==="hold-risky-actions"?M[t]?.slug??t:e.replace(/@.*$/,"")}function Ne(e){return M[e]?.text??e}function cn(e){let t=new Set(rn);for(let n of e.policies)for(let r of n.rules)if(r.primitive!=="durable_key_dedup")if(r.id==="hold-risky-actions")for(let o of r.applies_to??[])t.add(Re(null,o));else t.add(Re(r.id,""));return t.size}function rt(e){let t=new Set;for(let n of e.policies)for(let r of n.rules)if(r.primitive!=="durable_key_dedup")for(let o of r.applies_to??n.allowed_actions)t.add(o);return[...t]}function un(e,t){let n=rt(e).filter(o=>M[o]),r=n.filter(o=>ee(t,o)==="enforce");return{enforced:r,text:r.length===0?"ghost":r.length===n.length?"enforce":`${r.length} enforced, rest ghost`}}var ot="anvil-claude";function N(e){let t=e.trim();return t===ot||t.endsWith(` ${ot}`)||t.endsWith(`/${ot}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}var dn="\u{1F539}",st=e=>`${dn} ${e} ${dn}`;var fn="anvil";function it(e){fn=typeof e=="string"&&/^[\w@./ -]{1,60}$/.test(e)?e:"anvil"}var $=e=>`${N(fn)} ${e}`;import{spawnSync as ql}from"child_process";import{createHash as Gl}from"crypto";import{chmodSync as Zl,existsSync as Xl,lstatSync as No,mkdirSync as Ql,readdirSync as ec,readFileSync as Oo,readlinkSync as Eo,realpathSync as An,rmdirSync as tc,statSync as ft,unlinkSync as nc,writeFileSync as rc}from"fs";import{dirname as Po,join as sc,resolve as Io}from"path";import{createHash as jl}from"crypto";import{appendFileSync as $o,closeSync as bn,constants as wn,fstatSync as kn,mkdirSync as _o,openSync as vn,readdirSync as Ll,readFileSync as xo,readSync as $n,renameSync as So,statSync as _n,unlinkSync as Dl,writeFileSync as Ao}from"fs";import{homedir as Co}from"os";import{dirname as Hl,join as I}from"path";var pn;var go="its file (claude-conditions.js) is missing or won't load";function gn(e,t){return pn?pn.capMoved(e,t):`Anvil can't read amounts: ${go}`}import{existsSync as wa,readdirSync as ba,statSync as ka}from"fs";import{dirname as $a,isAbsolute as _a,join as xa,posix as Sa,resolve as Aa}from"path";import{posix as yn}from"path";var mo=null;function Oe(){return mo??process.platform==="win32"}var hn=/^([A-Za-z]):(.*)$/s,ho=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function at(e,t){let n=yn.normalize(`/${t}`);return n==="/"?e:`${e}${n.replace(/\/$/,"")}`}function te(e,t){return e.split("/").map(n=>{if(n===""||n==="."||n===".."||/[\u0000\u0001]/.test(n))return n;let r=n.indexOf(":"),o=r>=0?n.slice(0,r):n,s=t?o:o.replace(/[. ]+$/,"");return s===""?".":s}).join("/")}function lt(e){if(!Oe())return e;let t=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),n=!1,r=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(t);if(r){let l=r[2];if(r[1]===".")return`/dev/${l.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(l))t=`\\\\${l.slice(4)}`;else if(hn.test(l))t=l;else return`/dev/${l.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;n=!0}t=t.replace(/\\/g,"/");let o=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(t);if(o){let l=`/unc/${te(o[1],n).toLowerCase()}${o[2]?`/${te(o[2],n).toLowerCase()}`:""}`;return at(l,te(o[3]??"",n).toLowerCase())}let s=hn.exec(t);if(s){let l=s[2];return l===""?`/${s[1].toLowerCase()}`:l.startsWith("/")?at(`/${s[1].toLowerCase()}`,te(l,n).toLowerCase()):null}let a=ho.exec(t);if(a)return at(`/${a[1].toLowerCase()}`,te(a[2]??"",n).toLowerCase());let i=te(t,n).toLowerCase();if(i.startsWith("/")){let l=yn.normalize(i);return l.length>1&&l.endsWith("/")?l.slice(0,-1):l}return i}function yo(e){return lt(e)??e}function ct(e){return!Oe()||typeof e!="string"||e===""?e:yo(e)}import{domainToASCII as ja}from"url";var Wa="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as sl,readdirSync as il,realpathSync as al}from"fs";import{basename as cl,dirname as ul,join as dl}from"path";var dt="anvil-claude-compiled/1";function ko(e,t){return!e.applies_to||e.applies_to.length===0||e.applies_to.includes(t)}function pe(e,t){return e.origin!=="project"||!!(t&&e.project_dir&&vo(t,e.project_dir))}function Ee(e,t,n){let r=null;for(let o of e.policies)if(!(o.origin==="baseline"||!pe(o,n))){for(let s of o.rules)s.mode&&ko(s,t)&&(r=de(r,s.mode));o.off?.includes(t)&&(r=de(r,"off"))}return r}function vo(e,t){let n=ct(e),r=ct(t),o=r.endsWith("/")?r.slice(0,-1):r;return n===o||n.startsWith(o+"/")}function xn(e=Co()){return Pe(I(e,".anvil","claude"))}function Pe(e){return{dir:e,bin:I(e,"bin"),compiled:I(e,"compiled.json"),modes:I(e,"modes.json"),decisions:I(e,"decisions.jsonl"),install:I(e,"install.json"),state:I(e,"state"),approvals:I(e,"approvals"),counts:I(e,"counts"),backups:I(e,"backups")}}var Ro=3500;function y(e,t=8*1024*1024){try{let n=_n(e);return n.isFile()&&n.size<=t}catch(n){return n.code==="ENOENT"?null:!1}}function ut(e,t=8*1024*1024){let n;try{n=vn(e,wn.O_RDONLY|wn.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=kn(n);if(!r.isFile())throw new Error(`${e} is not a regular file`);if(r.size>t)throw new Error(`${e} is over ${t} bytes`);let o=Buffer.alloc(r.size),s=0;for(;s<r.size;){let a=$n(n,o,s,r.size-s,s);if(a===0)break;s+=a}return o.subarray(0,s)}finally{bn(n)}}function ge(e){try{let t=_n(e);return t.isFile()?t.size:0}catch{return 0}}function Sn(e,t){let n=t.endsWith(`
2
+ `)?t:`${t}
3
+ `;if(Buffer.byteLength(n)>Ro)throw new Error(`refusing to append a ${Buffer.byteLength(n)}-byte line`);if(y(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);$o(e,n,{mode:384})}function x(e){_o(e,{recursive:!0,mode:448})}function j(e,t){if(y(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let n;try{n=vn(e,"r")}catch{return""}try{let r=kn(n).size,o=Math.max(0,r-t),s=r-o;if(s<=0)return"";let a=Buffer.alloc(s);$n(n,a,0,s,o);let i=a.toString("utf8");if(o>0){let l=i.indexOf(`
4
+ `);i=l<0?"":i.slice(l+1)}return i}finally{bn(n)}}function S(e,t,n=384){let r=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;Ao(r,t,{mode:n}),me(r,e)}function me(e,t){for(let n=0;;n++)try{So(e,t);return}catch(r){let o=r.code;if(process.platform!=="win32"||n>=12||o!=="EPERM"&&o!=="EACCES"&&o!=="EBUSY")throw r;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20+n*10)}}function b(e){if(y(e)!==!0)return null;try{return JSON.parse(xo(e,"utf8"))}catch{return null}}var Ul=256*1024,Bl=1024*1024;var jo="/.anvil/claude/bin/claude-hook.js",To=/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js/i;var ne=class extends Error{constructor(t){super(t),this.name="SettingsRefused"}};function Cn(e,t){let n=e.startsWith("\uFEFF")?e.slice(1):e;if(n.trim()==="")return{};let r;try{r=JSON.parse(n)}catch(o){throw new ne(`${t} is not valid JSON (${o instanceof Error?o.message:String(o)}). Anvil changed nothing; fix the file and run this again.`)}if(!r||typeof r!="object"||Array.isArray(r))throw new ne(`${t} is not a JSON object. Anvil changed nothing.`);return r}function Lo(e){if(!e||typeof e!="object")return null;let{command:t,args:n}=e;return typeof t!="string"?null:Array.isArray(n)?[t,...n.filter(r=>typeof r=="string")].join(" "):t}var Do=e=>{let t=Lo(e);return t!==null&&(t.includes(jo)||To.test(t))};function Mo(e,t){if(!e||typeof e!="object")return!1;let n=e;return typeof t=="string"?n.command===t:n.command===t.command&&Array.isArray(n.args)&&n.args.length===t.args.length&&n.args.every((r,o)=>r===t.args[o])}function Rn(e){return Array.isArray(e.args)?{command:e.command,args:e.args}:e.command}function Fo(e){return ut(e,64*1024*1024)}function Nn(e){try{if(!No(e).isSymbolicLink())return e}catch{return e}try{return An(e)}catch(t){let n=t.code;throw n==="ENOENT"?new ne(`${e} is a link to ${Ho(e)}, which does not exist. Anvil changed nothing; create that file or remove the link, and run this again.`):new ne(`${e} is a link Anvil cannot follow (${n??String(t)}). Anvil changed nothing.`)}}function Ho(e){let t=Po(e);try{t=An(t)}catch{}return Io(t,Eo(e))}function On(e){try{let t=Fo(Nn(e));if(t===null)return null;let n=Cn(t.toString("utf8"),e).hooks?.PreToolUse;if(!Array.isArray(n))return null;let r=n.flatMap(o=>{let s=o&&typeof o=="object"?o.hooks:void 0;return Array.isArray(s)?s.filter(Do):[]});return r.length===0?null:r.every(o=>o.onFailure==="block")}catch{return null}}function En(e,t){let n;try{n=Nn(e)}catch{return"unreadable"}let r;try{r=ft(n)}catch{return"no-file"}if(!r.isFile()||r.size>4*1024*1024)return"unreadable";let o;try{o=Cn(Oo(n,"utf8"),e)}catch{return"unreadable"}if(o.disableAllHooks===!0)return"disabled";let s=o.hooks?.PreToolUse;return Array.isArray(s)&&s.some(i=>{let l=i&&typeof i=="object"?i:null,c=l?.matcher;return(c===void 0||c===""||c==="*")&&Array.isArray(l?.hooks)&&l.hooks.some(f=>Mo(f,t))})?"present":"missing"}function Wo(e){let t=e.trim().match(/'(?:[^']|'\\'')*'|[^\s']+/g),n=s=>s.startsWith("'")?s.slice(1,-1).replace(/'\\''/g,"'"):s,r=t?t.findIndex(s=>s==="/bin/sh"||s==="sh"):-1,o=t&&r>=0&&(t[r+3]==="PreToolUse"||t[r+3]==="SessionStart")?1:0;if(t&&r>=0&&t[r+3+o]==="||"){let s=r>0&&r%5===0;for(let a=0;s&&a<r;a+=5)s=t[a]==="["&&(t[a+1]==="-s"||t[a+1]==="-f")&&t[a+3]==="]"&&t[a+4]==="&&"&&n(t[a+2])===n(t[r+1]);if(r===0||s)return[n(t[r+1]),n(t[r+2])]}return!t||t.length!==2?null:[n(t[0]),n(t[1])]}function Uo(e){if(!e||typeof e!="object")return null;let{command:t,args:n}=e;if(typeof t!="string")return null;if(Array.isArray(n)){let r=n.find(o=>typeof o=="string"&&/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js$/i.test(o));return r?[t,r]:null}return Wo(t)}function pt(e){let t=Uo(e);if(!t)return!1;try{return ft(t[0]).isFile()&&ft(t[1]).isFile()}catch{return!1}}var F="_seal";function De(e){return O(e.dir,"seal.key")}function oe(e,t){return O(e.state,"lkg",t)}function C(e){let t=De(e);if(y(t,1024)!==!0)return null;try{let n=se(t,"utf8").trim();return/^[0-9a-f]{64}$/.test(n)?Buffer.from(n,"hex"):null}catch{return null}}function wt(e){return C(e)?"ok":y(De(e),1024)===null?"missing":"damaged"}var Te=class extends Error{};function Me(e,t){return`Anvil's seal key (${De(e)}) is ${t==="damaged"?"damaged":"missing"}`}function Vo(e){let t=C(e);if(t)return t;let n=wt(e);if(n==="damaged"||bt(e))throw new Te(`${Me(e,n)}; run ${$("on")} to restore it`);let{key:r,created:o}=Go(e,!1);return o&&Yo(e,r),r}function Pn(e,t,n){let r=Mn(e,n,384);try{Hn(r,t),Ln(r)}finally{Tn(r)}}function Go(e,t){Dn(e.dir,{recursive:!0,mode:448});let n=De(e),r=O(e.dir,`.seal.key.${process.pid}.${gt(4).toString("hex")}.tmp`);Pn(r,`${gt(32).toString("hex")}
5
+ `,"wx");let o=!1;try{t?me(r,n):Ko(r,n),o=!0}catch(a){let i=a.code??"";if(i!=="EEXIST"){if(t||!["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS","EXDEV"].includes(i))throw a;try{Pn(n,se(r,"utf8"),"wx"),o=!0}catch(l){if(l.code!=="EEXIST")throw l}}}finally{try{Fn(r)}catch{}}let s=C(e);if(!s)throw new Te(`${Me(e,"damaged")}; run ${$("on")} to restore it`);return{key:s,created:o}}function Yo(e,t){let n=[[e.modes,he],[e.compiled,Bn],[e.install,void 0]];for(let[r,o]of n)if(y(r,8*1024*1024)===!0)try{let s=se(r,"utf8");if(s.includes(`"${F}"`))continue;let a=JSON.parse(s);if(!a||typeof a!="object"||Array.isArray(a))continue;let i=`${JSON.stringify(yt(t,a),null,2)}
6
+ `;re(r,i),o&&re(oe(e,o),i)}catch{}if(y(e.modes)===null&&y(oe(e,he))===null){let r=`${JSON.stringify(yt(t,et()),null,2)}
7
+ `;re(e.modes,r),re(oe(e,he),r)}}function ht(e,t=0){if(t>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(n=>ht(n===void 0?null:n,t+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(r=>!(t===0&&r===F)&&e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${ht(e[r],t+1)}`).join(",")}}`:JSON.stringify(e??null)}function Wn(e,t){return Bo("sha256",e).update(ht(t)).digest("hex")}function Ie(e){if(!(F in e))return e;let t={...e};return delete t[F],t}function yt(e,t){let n=Ie(t);return{...n,[F]:Wn(e,n)}}function Zo(e,t){let n=t[F];if(typeof n!="string"||!/^[0-9a-f]{64}$/.test(n))return!1;let r;try{r=Wn(e,t)}catch{return!1}return zo(Buffer.from(n,"hex"),Buffer.from(r,"hex"))}function re(e,t,n=384){Dn(je(e),{recursive:!0,mode:448});let r=O(je(e),`.${qo(e)}.${process.pid}.${Date.now().toString(36)}.${gt(3).toString("hex")}.tmp`);try{let o=Mn(r,"w",n);try{Hn(o,t),Ln(o)}finally{Tn(o)}me(r,e)}catch(o){try{Fn(r)}catch{}throw o}}function A(e,t,n=8*1024*1024){let r=y(e,n);if(r===null)return{status:"missing"};if(r===!1)return{status:"unreadable"};let o;try{o=JSON.parse(se(e,"utf8"))}catch{return{status:"unreadable"}}return!o||typeof o!="object"||Array.isArray(o)?{status:"unreadable"}:t?F in o?Zo(t,o)?{status:"ok",value:Ie(o)}:{status:"changed",value:Ie(o)}:{status:"unsealed",value:o}:{status:"unkeyed",value:Ie(o)}}function Un(e,t,n,r){let o=Vo(e),s=`${JSON.stringify(yt(o,n),null,2)}
8
+ `;re(t,s),r&&re(oe(e,r),s)}var he="modes.json",Bn="compiled.json";function zn(e,t){Un(e,e.modes,t,he)}function bt(e){return mt(O(e.bin,"claude-hook.sh"))||Xo(e)}function Xo(e){let t=n=>{try{return Jo(n).slice(0,200).some(r=>r.endsWith(".json")&&y(O(n,r),65536)===!0&&se(O(n,r),"utf8").includes(`"${F}"`))}catch{return!1}};if(t(O(e.state,"lkg"))||t(O(e.state,"pending"))||t(e.approvals))return!0;for(let n of[e.modes,e.compiled,e.install])if(y(n,8*1024*1024)===!0)try{if(se(n,"utf8").includes(`"${F}"`))return!0}catch{}return!1}var Le={missing:"is missing",unreadable:"cannot be read",unsealed:"was changed outside Anvil",changed:"was changed outside Anvil"};function In(e=new Date){return en(null,"enforce","all",e)}function q(e,t=C(e),n={}){if(!t){let a=wt(e);if(n.installed===!0||a==="damaged"||bt(e))return{value:In(),source:"strict",problem:`${Me(e,a)}, so every rule is enforced until \`${$("on")}\` restores it`};let i=A(e.modes,null);return{value:i.status==="unkeyed"?i.value:null,source:"unkeyed",problem:null}}let r=A(e.modes,t);if(r.status==="ok")return{value:r.value,source:"file",problem:null};let o=`modes.json ${Le[r.status]??"cannot be used"}`,s=A(oe(e,he),t);return s.status==="ok"?{value:s.value,source:"last-good",problem:`${o}; Anvil keeps the modes it last set`}:{value:In(),source:"strict",problem:`${o}, and so is Anvil's own copy, so every rule is enforced until \`${$("on")}\` resets it`}}function V(e,t,n=C(e),r={}){let o=c=>!!c&&typeof c=="object"&&c.format===dt&&Array.isArray(c.policies),s=()=>{if(!t)return null;let c=A(t,null);return c.status==="unkeyed"&&o(c.value)?c.value:null};if(!n){let c=wt(e),f=r.installed===!0||c==="damaged"||bt(e),u=A(e.compiled,null),d=u.status==="unkeyed"&&o(u.value)?u.value:null;return f?{value:null,source:"strict",problem:`${Me(e,c)}: \`${$("on")}\` restores it`}:{value:d??s(),source:"unkeyed",problem:null}}let a=A(e.compiled,n);if(a.status==="ok"&&o(a.value))return{value:a.value,source:"file",problem:null};let i=`compiled.json ${a.status==="ok"?"is not a rules table":Le[a.status]??"cannot be used"}`,l=A(oe(e,Bn),n);return l.status==="ok"&&o(l.value)?{value:l.value,source:"last-good",problem:`${i}; Anvil keeps the rules it last compiled`}:a.status==="missing"&&l.status==="missing"&&y(e.install)===null&&r.installed!==!0?{value:s(),source:"file",problem:null}:{value:null,source:"strict",problem:`${i}, and so is Anvil's own copy: \`${$("on")}\` recompiles them`}}function jn(e,t){return t&&(e===t||e.startsWith(`${t}/`))?`~${e.slice(t.length)}`:e}function Fe(e,t,n,r=!0){let o=A(e.install,t,4194304);if(o.status==="missing")return[];if(o.status==="unreadable")return[`install.json ${Le.unreadable}`];if(t&&o.status!=="ok")return[`install.json ${Le[o.status]??"cannot be used"}`];let s=(o.status==="ok"||o.status==="unkeyed")&&o.value.installs&&typeof o.value.installs=="object"?Object.values(o.value.installs):[],a=[];for(let u of s.slice(0,64)){if(!u||typeof u.real_path!="string"||typeof u.command!="string")continue;let d=En(u.settings_path??u.real_path,Rn(u)),g=jn(u.settings_path??u.real_path,n);d!=="present"&&(d==="no-file"&&u.scope==="project"&&!mt(je(je(u.real_path)))||(d==="disabled"?r&&a.push(`${g} turns off every Claude Code hook ("disableAllHooks"), so new sessions are not checked`):d==="missing"||d==="no-file"?a.push(`Anvil's hook was taken out of ${g} outside \`${$("off")}\`, so new sessions are not checked`):a.push(`${g} cannot be read, so Anvil cannot tell whether new sessions are checked`)))}let i=o.status==="ok"||o.status==="unkeyed"?o.value:null,l=[...Array.isArray(i?.package_dirs)?i.package_dirs:[],...typeof i?.package_dir=="string"?[i.package_dir]:[]].filter(u=>typeof u=="string"&&u.startsWith("/")).slice(0,16),c=l[l.length-1]??"",f=/[\\/]@useanvil[\\/]claude-code[\\/]?$/.test(c)?"npx @useanvil/claude-code":"npx @useanvil/sdk";return s.length>0&&l.length>0&&l.every(u=>!mt(O(u,"package.json")))&&a.push(`the Anvil package that installed this hook is gone (${jn(c,n)}): keep Anvil with ${N(f)} on, or remove it with ${N(f)} off --purge`),a}function Qo(e){return O(e.state,"health.json")}function He(e){let t=A(Qo(e),null,65536);return t.status==="unkeyed"&&t.value.v===1&&Array.isArray(t.value.problems)?t.value:null}import{accessSync as Gn,constants as Yn,existsSync as vt,statfsSync as es}from"fs";import{createHash as vc,randomBytes as $c}from"crypto";import{readdirSync as Jn,renameSync as xc,unlinkSync as Sc}from"fs";import{join as kt}from"path";var Nc=600*1e3,Oc=1440*60*1e3;function Kn(e){return kt(e.state,"pending")}function qn(e,t,n){let r=[];try{r=Jn(Kn(e)).filter(s=>s.endsWith(".json")).slice(0,2e3)}catch{return[]}let o=[];for(let s of r){let a=kt(Kn(e),s),i=A(a,t,64*1024);i.status!=="ok"||i.value.v!==2||!Array.isArray(i.value.stops)||!(Date.parse(i.value.expires_at)>=n)||o.push({hold:i.value,file:a})}return o.sort((s,a)=>Date.parse(a.hold.created_at)-Date.parse(s.hold.created_at))}function Vn(e,t){let n=[];try{n=Jn(e.approvals).filter(o=>o.endsWith(".json")&&!o.includes(".used-")).slice(0,2e3)}catch{return 0}let r=0;for(let o of n){let s=A(kt(e.approvals,o),t,65536);s.status!=="missing"&&(s.status!=="ok"||s.value.v!==2||!Array.isArray(s.value.stops))&&r++}return r}var $t=(e,t)=>e===t?"~":e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e;function Zn(e,t,n){let r=[],o=b(e.install),s=o&&o.installs&&typeof o.installs=="object"?Object.values(o.installs):[];for(let i of s)!i||typeof i.settings_path!="string"||On(i.settings_path)===!1&&r.push(`the hook in ${$t(i.settings_path,t)} was installed without onFailure, so Claude Code runs a call when Anvil's check fails or stalls: run ${$("on")} to add it`);try{vt(e.decisions)?Gn(e.decisions,Yn.W_OK):vt(e.dir)&&Gn(e.dir,Yn.W_OK)}catch{r.push(`${$t(e.decisions,t)} cannot be written, so stops are not recorded and the counts here read low`)}try{let i=es(vt(e.dir)?e.dir:t);Number(i.bavail)*Number(i.bsize)<1024*1024&&r.push(`the disk holding ${$t(e.dir,t)} is full, so stops are not recorded and a held call cannot be allowed once`)}catch{}let a=n?Vn(e,n):0;return a>0&&r.push(`${a===1?"an approval was":`${a} approvals were`} written outside \`${$("allow")}\`; ${a===1?"it releases":"they release"} nothing (${$("on")} removes ${a===1?"it":"them"})`),r}import{spawn as Fc}from"child_process";import{readFileSync as Wc,statSync as Uc}from"fs";import{join as ts}from"path";var Xn="sync-next",Qn="sync-pulled";var Kc=5*6e4;function er(e,t){return e.ANVIL_WORKSPACE_KEYS_PATH?.trim()||ts(t,".anvil","workspace-keys.json")}var Jc=10*6e4;import{join as jt}from"path";import{closeSync as ns,constants as tr,fstatSync as rs,openSync as os,readdirSync as ss,readSync as is,unlinkSync as as}from"fs";import{join as nr}from"path";var ls=9,rr=4*1024*1024;function cs(e){let t;try{t=os(e,tr.O_RDONLY|tr.O_NONBLOCK)}catch(n){if(n.code==="ENOENT")return"";throw n}try{let n=rs(t);if(!n.isFile())throw new Error("the day's cap count is not a regular file");if(n.size>rr)throw new Error(`the day's cap count is over ${rr/1024/1024} MB`);let r=Buffer.alloc(n.size),o=0;for(;o<n.size;){let s=is(t,r,o,n.size-o,o);if(s===0)break;o+=s}return r.subarray(0,o).toString("utf8")}finally{ns(t)}}function ye(e,t){if(e.window==="minute")return t-6e4;if(e.window==="hour")return t-36e5;let n=new Date(t);return n.setHours(0,0,0,0),e.window==="week"&&n.setDate(n.getDate()-(n.getDay()+6)%7),n.getTime()}function sr(e,t){if(e.window==="minute"||e.window==="hour")return t;let n=new Date(ye(e,t));return n.setDate(n.getDate()+(e.window==="week"?7:1)),n.getTime()}var or=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`};var We=class extends Error{};function _t(e,t){return e.unit==="money"&&e.money?us(t,e.money):`${e.unit==="usd"?"$":""}${Math.round(t*100)/100}`}function us(e,t){let n=String(Math.max(0,Math.round(e))).padStart(t.digits+1,"0"),r=t.digits>0?n.slice(-t.digits):"";return`${t.sign}${n.slice(0,n.length-t.digits).replace(/\B(?=(\d{3})+(?!\d))/g,",")}${r&&!/^0+$/.test(r)?`.${r}`:""}`}function ir(e,t,n=null){if(e.unit==="money"){let s=gn(e,n);if(typeof s=="string")throw new We(s);return s}if(e.unit==="calls")return 1;let r=t?.machines??1,o=(t?.hours??1)*r;return e.unit==="machines"?r:e.unit==="hours"?o:(e.price?.per==="hour"?o:r)*(e.price?.usd??0)}function ds(e,t,n){try{return ir(e,t,n)}catch(r){if(r instanceof We)return e.limit;throw r}}var Ue=class{constructor(t){this.dir=t}file(t){return nr(this.dir,`${or(t)}.log`)}write(t){x(this.dir),Sn(this.file(t.t),JSON.stringify(t))}read(t,n){let r=[],o=new Date(t);for(o.setHours(0,0,0,0);o.getTime()<=n;o.setDate(o.getDate()+1))for(let s of cs(this.file(o.getTime())).split(`
9
+ `))if(s)try{let a=JSON.parse(s);typeof a.t=="number"&&typeof a.cap=="string"&&typeof a.key=="string"&&r.push(a)}catch{}return r}usedIn(t,n,r,o=t.length,s=!1){let a=ye(n,r),i=new Map;for(let c=0;c<o;c++){let f=t[c];f.cap===n.id&&i.set(f.key,f.op==="x"||!i.has(f.key)||i.get(f.key).op==="x"?f:{...i.get(f.key),op:f.op})}let l=0;for(let c of i.values())c.op!=="x"&&c.t>=a&&(s||c.t<=r)&&(l+=c.n);return l}admit(t,n,r,o,s,a=null){if(t.length===0)return null;let i=t.map(u=>ir(u,r,a));this.resolve(t,o),t.forEach((u,d)=>this.write({t:o,op:"ran",cap:u.id,key:n,n:i[d]})),s?.();let l=Math.min(...t.map(u=>ye(u,o))),c=this.read(l,o+6e4),f=null;for(let u of t){let d=c.findIndex(h=>h.cap===u.id&&h.key===n&&h.op==="ran"&&h.t===o);if(d<0){f={cap:u,used:u.limit};break}let g=this.usedIn(c,u,o,d+1,!0);if(g>u.limit){f={cap:u,used:g-c[d].n};break}}if(f)for(let u of t)this.write({t:o,op:"x",cap:u.id,key:n,n:0});return this.prune(o),f}count(t,n,r,o,s="ran",a,i=null){for(let l of t)this.write({t:o,op:s,cap:l.id,key:n,n:ds(l,r,i),...s==="ask"&&a?.tr&&a.call?{tr:a.tr,call:a.call}:{}})}used(t,n){return this.resolve([t],n),this.usedIn(this.read(ye(t,n),n),t,n)}resolve(t,n){let r=new Set(t.map(i=>i.id)),o=Math.min(...t.map(i=>ye(i,n))),s=new Map;for(let i of this.read(o,n)){if(!r.has(i.cap))continue;let l=`${i.cap}\0${i.key}`;i.op==="ask"?s.set(l,i):s.delete(l)}let a=0;for(let i of s.values()){if(a>=4||n-i.t<1e3)continue;a++;let l=xt(i.tr,i.call);l==="no"?this.write({t:i.t,op:"x",cap:i.cap,key:i.key,n:0}):l==="yes"&&this.write({t:i.t,op:"ran",cap:i.cap,key:i.key,n:i.n})}}prune(t){try{let n=or(t-ls*864e5);for(let r of ss(this.dir))/^\d{4}-\d{2}-\d{2}\.log$/.test(r)&&r.slice(0,10)<n&&as(nr(this.dir,r))}catch{}}};function xt(e,t){return!e||!t?null:fs(j(e,4*1024*1024),t)}function fs(e,t){let n=e.indexOf(`"tool_use_id":"${t}"`);if(n<0)return null;let r=e.slice(e.lastIndexOf(`
10
+ `,n)+1,e.indexOf(`
11
+ `,n)<0?void 0:e.indexOf(`
12
+ `,n));try{let o=JSON.parse(r),a=(Array.isArray(o.message?.content)?o.message.content:[]).find(l=>l.type==="tool_result"&&l.tool_use_id===t);if(!a)return null;let i=typeof a.content=="string"?a.content:JSON.stringify(a.content??"");return a.is_error===!0&&/doesn't want to proceed with this tool use|The tool use was rejected/.test(i)?"no":"yes"}catch{return null}}import{createHash as le}from"crypto";import{closeSync as we,constants as pr,fstatSync as Ns,mkdirSync as Os,openSync as _r,readdirSync as Es,readSync as Nt,statSync as Ps,unlinkSync as gr}from"fs";import{join as T}from"path";var ps="https://api.anvilcontrol.ai";function St(e=process.env){let t=e.ANVIL_HOSTED_API_URL?.trim();return(t&&t.length>0?t:ps).replace(/\/+$/,"")}import{chmodSync as ru,mkdirSync as ou,readFileSync as gs,writeFileSync as su}from"fs";import{homedir as ms}from"os";import{dirname as lu,join as hs}from"path";function ys(){return process.env.ANVIL_WORKSPACE_KEYS_PATH?.trim()||hs(ms(),".anvil","workspace-keys.json")}function ws(e=ys()){let t;try{t=JSON.parse(gs(e,"utf8"))}catch{return{}}if(!t||typeof t!="object")return{};let n={};for(let[r,o]of Object.entries(t))typeof o=="string"?o&&(n[r]={apiKey:o}):o&&typeof o=="object"&&typeof o.apiKey=="string"&&o.apiKey&&(n[r]=o);return n}var bs=new Set(["gmail","googlemail","outlook","hotmail","live","msn","yahoo","ymail","rocketmail","icloud","me","mac","proton","protonmail","pm","aol","gmx","mail","zoho","fastmail","hey","qq","foxmail","163","126","yandex"]);function At(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ks(e){let t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return At(e)||"workspace";let n=e.slice(0,t),o=e.slice(t+1).split(".")[0]??"",s=bs.has(o.toLowerCase())?n:o;return At(s)||At(n)||"workspace"}function vs(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,Math.floor((Date.now()-t)/864e5))}function ar(e){let n=Object.entries(ws(e)).find(([,s])=>s.active===!0);if(!n)return null;let[r,o]=n;return{email:r,workspace:ks(r),apiKey:o.apiKey,...o.apiBaseUrl?{apiBaseUrl:o.apiBaseUrl}:{},keyAgeDays:vs(o.rememberedAt),...o.rememberedAt?{rememberedAt:o.rememberedAt}:{},...o.keyPrefix?{keyPrefix:o.keyPrefix}:{},...o.label?{label:o.label}:{},...o.workspaceId?{workspaceId:o.workspaceId}:{}}}import{accessSync as $s,constants as _s}from"fs";import{join as lr}from"path";var xs=["hook-removed","hooks-disabled","settings-unreadable","no-node","classifier-missing","rules-missing","modes-changed","rules-changed","install-record-changed","key-missing","node-fallback","spool-unwritable","other"],Ss=/^claude\.[a-z0-9_]+(?:\.[a-z0-9_]+)*$/,As=new Set(["hook-removed","hooks-disabled","settings-unreadable","no-node","classifier-missing","rules-missing"]),Cs=[[/^Anvil's seal key \(.*\) is missing/,"key-missing"],[/^modes\.json /,"modes-changed"],[/^compiled\.json /,"rules-changed"],[/^install\.json /,"install-record-changed"],[/\("disableAllHooks"\)/,"hooks-disabled"],[/^Anvil's hook was taken out of /,"hook-removed"],[/cannot be read, so Anvil cannot tell whether new sessions are checked/,"settings-unreadable"],[/^the Node Anvil was set up with is gone/,"node-fallback"],[/no Node 20 or later was found/,"no-node"],[/classifier (file is missing|did not load|answered a known call wrongly)/,"classifier-missing"],[/^no rules (are )?compiled/,"rules-missing"],[/cannot be written, so stops are not recorded/,"spool-unwritable"]];function cr(e){for(let[t,n]of Cs)if(t.test(e))return n;return"other"}var Rs=1440*60*1e3;function ur(e){let t=Date.parse(e.trim());return Number.isFinite(t)?t:null}function dr(e){let{paths:t,now:n}=e,r=new Set,o=d=>{d&&r.add(cr(d))},s=null;try{s=C(t)}catch{s=null}let a={};try{let d=q(t,s);o(d.problem);for(let g of e.kinds.slice(0,64))g.length<=200&&Ss.test(g)&&(a[g]=fe.has(g)?"enforce":ee(d.value,g))}catch{}try{let d=V(t,e.fallbackTable,s);o(d.problem),d.value||r.add("rules-missing")}catch{r.add("rules-missing")}let i=y(t.install,4*1024*1024)===!0;if(i)try{for(let d of Fe(t,s,e.home))o(d)}catch{}let l=e.hookBin??(i?t.bin:void 0);l&&y(lr(l,"claude-hook-core.js"),64*1024*1024)!==!0&&r.add("classifier-missing");try{$s(y(t.decisions,Number.MAX_SAFE_INTEGER)===null?t.dir:t.decisions,_s.W_OK)}catch{(y(t.dir,Number.MAX_SAFE_INTEGER)!==null||i)&&r.add("spool-unwritable")}let c=null;try{let d=He(t),g=d?ur(d.at):null;if(d&&g!==null&&(c=g,n-g<Rs))for(let h of d.problems)cr(h)==="node-fallback"&&r.add("node-fallback")}catch{}let f=ur(j(lr(t.state,"no-node"),64));f!==null&&(c===null||f>c)&&(r.add("no-node"),c=f);let u=xs.filter(d=>r.has(d));return{modes:a,ok:!u.some(d=>As.has(d)),problems:u,hook_checked_at:c===null?null:new Date(c).toISOString()}}function fr(){try{return/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]{1,20})?$/.test("0.8.0")?"0.8.0":null}catch{return null}}var Is=50,js=50,Ts=1e4,be=512*1024,Rt=30*6e4,Ls="/v1/claude-code/machine",xr=360*6e4,Ds={confirmation_required:"confirmation_required",service_in_blocklist:"service_in_blocklist",resource_mutation_rate_exceeded:"resource_mutation_rate_exceeded",allowlist:"allowlist",spend_per_user:"spend_per_user",time_limit:"anvil_unavailable"};function ze(e,t){let n=null;try{let s=er(e,t);y(s,1024*1024)===!0&&(n=ar(s))}catch{n=null}if(n?.apiKey){let s=n.workspaceId?`ws:${le("sha256").update(n.workspaceId).digest("hex").slice(0,12)}`:hr(n.apiKey);return{apiKey:n.apiKey,baseUrl:mr(n.apiBaseUrl||St(e)),id:s,linkedAt:n.rememberedAt??null,source:"login"}}let r=e.ANVIL_API_KEY?.trim(),o=e.ANVIL_API_BASE_URL?.trim();return r?{apiKey:r,baseUrl:mr(o||St(e)),id:hr(r),linkedAt:null,source:"env"}:null}function mr(e){return e.replace(/\/+$/,"")}function hr(e){return`sha256:${le("sha256").update(e).digest("hex").slice(0,12)}`}function yr(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\.(local|lan|home|localdomain)$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,"")||"machine"}function Ms(e){return T(e.dir,"machine.json")}function Ot(e,t){let n=b(Ms(e))?.label;return yr(typeof n=="string"&&n?n:t)}var ie=e=>typeof e=="string"&&e.length>0?e:null;function Fs(e,t){return e===null||e==="hold-risky-actions"||Ce[e]?Re(e,t):"your-rule"}function Hs(e){if(!e)return"none";let t=e.replace(/-/g,"").toLowerCase();return/^[a-f0-9]{8,}$/.test(t)?t.slice(0,8):le("sha256").update(e).digest("hex").slice(0,8)}function Sr(e,t){let n;try{n=JSON.parse(e)}catch{return null}if(!n||typeof n!="object"||n.v!==1)return null;let r=ie(n.action),o=n.verdict,s=n.mode,a=ie(n.ts);if(!r||!r.startsWith("claude.")||r.length>200||o!=="hold"&&o!=="block"||s!=="ghost"&&s!=="enforce"||n.delivered==="approved"||!a||!Number.isFinite(Date.parse(a)))return null;let i=Ds[ie(n.blocked_by)??""];if(!i)return null;let l=s==="ghost"?"would_block":o==="hold"?"held":"blocked",f=ie(n.blocked_by)==="time_limit"?s==="ghost"?"Not checked in time":"Held: could not be checked in time":l==="held"?"Held for your OK":l==="blocked"?"Blocked":o==="hold"?"Would have held":"Would have blocked",u=typeof n.ms=="number"&&Number.isFinite(n.ms)&&n.ms>=0?Math.round(n.ms):0;return{key:`cc/${t}/${Hs(ie(n.session))}/${le("sha256").update(e).digest("hex").slice(0,12)}`,action:r,decided_by:"claude_code_hook",outcome:l,mode:s,blocked_by:i,reason:`${f} \xB7 ${Ne(r)}`,rule_id:Fs(ie(n.rule),r),decided_at:new Date(Date.parse(a)).toISOString(),duration_ms:Math.min(u,6e5)}}function wr(e,t=null){return{v:2,identity:e,since:t,offset:0,ino:0,last_hash:null,registered:!1,registered_kinds:[],sent:0,rejected:0,last_push_ok:null,last_pull_ok:null,last_error:null,last_note:null,failures:0,next_try_at:0,report_next_at:0,last_report_ok:null,window_start:0,window_sent:0,skip:[],source:null,linked_at:null,last_pass_at:null}}function Ar(e,t){return T(e.state,"sync",`${le("sha256").update(t).digest("hex").slice(0,16)}.json`)}function Cr(e){return T(e.state,"signed-out.json")}function Be(e){let t=b(Cr(e)),n=o=>typeof o=="string"&&Number.isFinite(Date.parse(o))?o:null,r=Array.isArray(t?.windows)?t.windows.filter(o=>Array.isArray(o)&&o.length===2&&n(o[0])!==null&&n(o[1])!==null):[];return{open:n(t?.open)??n(t?.at),windows:r}}function Rr(e,t,n,r){x(e.state);let o=n.filter(s=>r-Date.parse(s[1])<400*864e5).slice(-500);S(Cr(e),`${JSON.stringify(t!==null?{open:t,windows:o}:{windows:o})}
13
+ `)}function Nr(e,t){try{let n=Be(e);n.open===null&&Rr(e,new Date(t).toISOString(),n.windows,t)}catch{}}function Ws(e,t){try{let n=Be(e);n.open!==null&&Date.parse(n.open)<=t&&Rr(e,null,[...n.windows,[n.open,new Date(t).toISOString()]],t)}catch{}}function Or(e){let t=[];try{t=Es(T(e.state,"sync")).filter(n=>n.endsWith(".json"))}catch{return null}for(let n of t){let r=b(T(e.state,"sync",n)),o=typeof r?.last_pull_ok=="string"?Date.parse(r.last_pull_ok):NaN;if(typeof r?.identity=="string"&&r.source==="env"&&Number.isFinite(o))return r.identity}return null}function ve(e,t,n=Date.now()){let r=b(Ar(e,t));if(!r||r.v!==2||r.identity!==t)return wr(t);let o={...wr(t),...r,v:2,identity:t},s=Number.isFinite(o.next_try_at)?Math.min(o.next_try_at,n+Rt):0,a=typeof o.report_next_at=="number"&&Number.isFinite(o.report_next_at)?Math.min(o.report_next_at,n+xr):0,i=Number.isFinite(o.window_start)&&o.window_start<=n?o.window_start:0,l=Array.isArray(o.skip)?o.skip.filter(u=>Array.isArray(u)&&u.length===2&&u.every(d=>typeof d=="string"&&Number.isFinite(Date.parse(d)))).slice(-500):[],c=u=>typeof u=="string"&&Number.isFinite(Date.parse(u))?u:null,f=Array.isArray(o.registered_kinds)?o.registered_kinds.filter(u=>typeof u=="string").slice(0,256):[];return{...o,next_try_at:s,report_next_at:a,last_report_ok:c(o.last_report_ok),window_start:i,window_sent:i===0?0:o.window_sent,skip:l,linked_at:c(o.linked_at),last_pass_at:c(o.last_pass_at),registered_kinds:f}}function Us(e,t){let n=Ar(e,t.identity);Os(T(e.state,"sync"),{recursive:!0,mode:448}),S(n,`${JSON.stringify(t,null,2)}
14
+ `)}function Et(e){return T(e.state,"mode-pending.json")}function Bs(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.action=="string"&&t.action.startsWith("claude.")&&(t.mode==="ghost"||t.mode==="enforce")&&typeof t.at=="string"&&typeof t.identity=="string"&&(t.from===null||t.from==="ghost"||t.from==="enforce")&&(t.origin===void 0||t.origin==="link")}function ae(e){let t=b(Et(e));return{v:2,changes:Array.isArray(t?.changes)?t.changes.filter(Bs):[]}}var G=e=>`${e.identity}|${e.action}|${e.at}`;function Er(e,t){x(e.state);let n=T(e.state,"mode-pending.lock"),r=!1;for(let o=0;o<40&&!r;o++)try{we(_r(n,"wx",384)),r=!0}catch{try{Date.now()-Ps(n).mtimeMs>1e4&&gr(n)}catch{}let s=Date.now()+25;for(;Date.now()<s;);}try{return t()}finally{if(r)try{gr(n)}catch{}}}function zs(e,t){t.length!==0&&Er(e,()=>{let n=ae(e).changes,r=(a,i)=>a.identity===i.identity&&a.action===i.action,o=t.map(a=>{let i=n.find(l=>r(l,a));return i?{...a,from:i.from}:a}),s=n.filter(a=>!t.some(i=>r(a,i)));S(Et(e),`${JSON.stringify({v:2,changes:[...s,...o]},null,2)}
15
+ `)})}function Ks(e,t){t.size!==0&&Er(e,()=>{let n=ae(e).changes.filter(r=>!t.has(G(r)));S(Et(e),`${JSON.stringify({v:2,changes:n},null,2)}
16
+ `)})}async function ke(e,t,n,r,o){try{let s=await e.fetch(`${t.baseUrl}${r}`,{method:n,headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json","User-Agent":"anvil-claude-sync",...o===void 0?{}:{"Content-Type":"application/json"}},...o===void 0?{}:{body:JSON.stringify(o)},signal:AbortSignal.timeout(e.timeoutMs??Ts)}),a=await s.text().catch(()=>""),i=null;try{i=a?JSON.parse(a):null}catch{i=null}let l=Number(s.headers.get("retry-after"));return{status:s.status,body:i,retryAfterMs:Number.isFinite(l)&&l>0?l*1e3:null,error:null}}catch(s){return{status:0,body:null,retryAfterMs:null,error:s instanceof Error?s.name==="TimeoutError"?"timed out":s.message:String(s)}}}function H(e,t,n="anvil"){if(e.status===0)return`could not reach the workspace (${e.error})`;if(e.status===401||e.status===403)return t.source==="env"?`the workspace refused ANVIL_API_KEY (HTTP ${e.status}): set a valid key, or unset it and run ${n} login`:`the workspace refused this machine's key (HTTP ${e.status}): run ${n} login again`;if(e.status===429)return"rate limited by the workspace (HTTP 429)";let r=e.body&&typeof e.body=="object"?e.body.code:null;return`HTTP ${e.status}${typeof r=="string"&&/^[a-z][a-z0-9_]{0,39}$/.test(r)?` (${r})`:""}`}function Js(e){return e?rt(e).filter(t=>t.startsWith("claude.")).sort().slice(0,js):[]}async function br(e,t,n,r,o=!1){return ke(e,t,"POST","/v1/modes",o?{action:n,mode:"ghost",if_not_stronger:!0}:{action:n,mode:r,reason:`anvil claude ${r} (Claude Code on ${e.machine})`})}async function qs(e,t,n){for(let r=0;r<e.length;r+=t)if((await Promise.all(e.slice(r,r+t).map(n))).includes(!1))return!1;return!0}function kr(e){if(e.status!==200||!e.body||typeof e.body!="object"||!Array.isArray(e.body.modes))return null;let t=new Map;for(let n of e.body.modes){if(!n||typeof n!="object")continue;let r=n;typeof r.action=="string"&&t.set(r.action,{explicit:r.explicit===!0,effective:r.explicit===!0&&r.mode==="enforce"?"enforce":"ghost"})}return t}function Vs(e){return e.status===0||e.status===401||e.status===403||e.status===429||e.status>=500}var vr={linked:!1,sent:0,rejected:0,waiting:0,modesPulled:!1,modesChanged:!1,error:null};async function Pt(e){if(!e.identity)return vr;try{return await Gs(e,e.identity)}catch(t){return{...vr,linked:!0,error:`the sync failed: ${t instanceof Error?t.message:String(t)}`}}}async function Gs(e,t){let{paths:n}=e,r=e.now(),o=ve(n,t.id,r),s=o.since!==null;if(!s){let p=t.linkedAt&&Number.isFinite(Date.parse(t.linkedAt))?t.linkedAt:new Date(r).toISOString();o={...o,since:p}}let a=T(n.state,"sync-active.json"),i=b(a),l=typeof i?.at=="string"&&Number.isFinite(Date.parse(i.at))?i.at:null,c=t.linkedAt!==null&&Number.isFinite(Date.parse(t.linkedAt))?t.linkedAt:null;if(s&&typeof i?.id=="string"&&i.id!==t.id&&l!==null&&Date.parse(l)<r){let p=c!==null&&Date.parse(c)>Date.parse(l)&&Date.parse(c)<r?c:new Date(r).toISOString();o={...o,skip:[...o.skip,[l,p]].slice(-500)}}let f=!(e.force===!0&&t.source==="env"&&typeof i?.id=="string"&&i.id!==t.id);if(i?.id!==t.id&&f){x(n.state);let p=c!==null&&l!==null&&Date.parse(c)>Date.parse(l)&&Date.parse(c)<=r?c:s?new Date(r).toISOString():o.since;S(a,`${JSON.stringify({id:t.id,at:p})}
17
+ `)}o={...o,source:t.source};let u=Be(n);c!==null&&u.open!==null&&Date.parse(u.open)<=Date.parse(c)&&Ws(n,Date.parse(c));for(let p of Be(n).windows)o.skip.some(_=>_[0]===p[0]&&_[1]===p[1])||(o={...o,skip:[...o.skip,p].slice(-500)});o={...o,linked_at:c??o.linked_at,last_pass_at:new Date(r).toISOString()};let d=!e.force&&r<o.next_try_at,g=Js(V(n,e.fallbackTable).value),h=[],m=null,_e=ae(n).changes,xe=o.registered?g.filter(p=>!o.registered_kinds.includes(p)):g,B=null;if(g.length>0&&(xe.length>0||_e.length>0)){let p=await ke(e,t,"GET",`/v1/modes?actions=${g.map(encodeURIComponent).join(",")}`);B=kr(p),B||(m=p)}if(!m&&B&&xe.length>0){let p=q(n).value,_=!o.registered&&p!==null&&p.source!=="workspace"?g.filter(k=>X(p,k)==="enforce"&&B.get(k)?.effective!=="enforce"):[];zs(n,_.map(k=>({action:k,mode:"enforce",at:new Date(r).toISOString(),identity:t.id,from:B.get(k)?.effective??null,origin:"link"})));let w=null;await qs(xe.filter(k=>!_.includes(k)&&!B.get(k)?.explicit),4,async k=>{let ue=await br(e,t,k,"ghost",!0);return ue.status>=200&&ue.status<300?!0:(w??=ue,!1)})?o={...o,registered:!0,registered_kinds:[...new Set([...o.registered_kinds,...xe])]}:w&&Vs(w)?m=w:w&&h.push(`could not register the kinds of action yet (${H(w,t,e.cli)})`)}let Bt=ae(n).changes;if(!m&&Bt.length>0){let p=new Set,_=[];for(let w of Bt){if(w.identity!==t.id){p.add(G(w)),h.push("a mode change made under another account was not sent to this one");continue}if(m)break;if(!ae(n).changes.some(ue=>G(ue)===G(w)))continue;let Ge=B?.get(w.action);if(w.from!==null&&Ge&&Ge.effective!==w.from){p.add(G(w)),h.push(`your workspace changed ${w.action} after you set it offline, so its mode stands`);continue}let k=await br(e,t,w.action,w.mode);k.status>=200&&k.status<300?(p.add(G(w)),w.origin==="link"&&_.push(w.action)):k.status===400||k.status===422?(p.add(G(w)),h.push(`the workspace refused a mode change for ${w.action} (${H(k,t,e.cli)})`)):m=k}Ks(n,p),_.length>0&&h.push(`at sign-in, this machine's enforce for ${_.length===1?Ne(_[0]):`${_.length} kinds of action`} went to your workspace`)}let qe=!1,zt=!1,Kt=()=>ae(n).changes.some(p=>p.identity===t.id);if(!m&&g.length>0&&!Kt()){let p=await ke(e,t,"GET",`/v1/modes?actions=${g.map(encodeURIComponent).join(",")}`);kr(p)?Kt()||(qe=!0,zt=ei(n,p.body.modes,new Date(r)),o={...o,last_pull_ok:new Date(r).toISOString()},Ys(n,r)):m=p}let Ve=m!==null&&(m.status===0||m.status===401||m.status===403);!Ve&&r>=o.report_next_at&&(o=await Zs(e,t,o,g,qe,r,h));let Jt=0,qt=0,Vt=null;if(!d&&!Ve){let p=await Qs(e,t,o,r);o=p.state,Jt=p.sent,qt=p.rejected,Vt=p.failed}let W=Vt??(Ve&&!d?m:null);if(W){let p=o.failures+1,_=W.status===429&&W.retryAfterMs?Math.min(W.retryAfterMs,Rt):W.status===0?6e4:Math.min(6e4*2**(p-1),Rt);o={...o,failures:p,last_error:H(W,t,e.cli),next_try_at:r+_}}else d?m&&(o={...o,last_error:H(m,t,e.cli)}):o={...o,failures:0,last_error:m?H(m,t,e.cli):null,next_try_at:0};let ro=W?H(W,t,e.cli):m?H(m,t,e.cli):d?o.last_error:null;return h.length>0&&(o={...o,last_note:h[h.length-1]}),Us(n,o),{linked:!0,sent:Jt,rejected:qt,waiting:It(n,o,e.machine),modesPulled:qe,modesChanged:zt,error:ro}}function Ys(e,t){try{x(e.state),S(T(e.state,Qn),String(t))}catch{}}async function Zs(e,t,n,r,o,s,a){let i;try{i=dr({paths:e.paths,kinds:r,now:s,...e.home?{home:e.home}:{},...e.fallbackTable?{fallbackTable:e.fallbackTable}:{},...e.hookBin?{hookBin:e.hookBin}:{}})}catch{return n}let l=await ke(e,t,"POST",Ls,{machine:e.machine,version:fr(),modes:i.modes,ok:i.ok,problems:i.problems,hook_checked_at:i.hook_checked_at,modes_pulled:o});return l.status>=200&&l.status<300?{...n,last_report_ok:new Date(s).toISOString()}:l.status===404||l.status===405?{...n,report_next_at:s+xr}:((l.status===400||l.status===422)&&a.push(`the workspace refused this machine's health report (${H(l,t,e.cli)})`),n)}function Ct(e){let t;try{t=_r(e,pr.O_RDONLY|pr.O_NONBLOCK)}catch{return null}try{let n=Ns(t);if(n.isFile())return{fd:t,ino:n.ino,size:n.size}}catch{}return we(t),null}function Pr(e,t){let n=Ct(e.decisions);if(t.ino!==0){if(n&&n.ino===t.ino&&n.size>=t.offset)return[{...n,start:t.offset}];let a=Ct(`${e.decisions}.1`);if(a&&a.ino===t.ino&&a.size>=t.offset)return n?[{...a,start:t.offset},{...n,start:0}]:[{...a,start:t.offset}];a&&we(a.fd)}let r=Ct(`${e.decisions}.1`),o=r&&t.last_hash?$r(r.fd,r.size,t.last_hash):null;if(r&&o!==null)return n?[{...r,start:o},{...n,start:0}]:[{...r,start:o}];let s=n&&t.last_hash?$r(n.fd,n.size,t.last_hash):null;return s!==null&&n?(r&&we(r.fd),[{...n,start:s}]):[...r?[{...r,start:0}]:[],...n?[{...n,start:0}]:[]]}function Ir(e){for(let t of e)try{we(t.fd)}catch{}}function $r(e,t,n){let r=0,o=Buffer.alloc(0);for(;r<t;){let s=Math.min(be,t-r),a=Buffer.alloc(s);Nt(e,a,0,s,r);let i=o.length>0?Buffer.concat([o,a]):a,l=r-o.length,c=0;for(let f=0;f<i.length;f++)if(i[f]===10){if(jr(i.toString("utf8",c,f))===n)return l+f+1;c=f+1}o=i.subarray(c),o.length>4*be&&(o=Buffer.alloc(0)),r+=s}return null}function jr(e){return le("sha256").update(e).digest("hex").slice(0,16)}function Xs(e,t,n){for(let r=t;r<n;){let o=Math.min(be,n-r),s=Buffer.alloc(o);Nt(e,s,0,o,r);let a=s.indexOf(10);if(a>=0)return r+a+1;r+=o}return null}function Tr(e,t,n){let r=Math.min(be,n-t);if(r<=0)return{lines:[],skipTo:null};let o=Buffer.alloc(r);Nt(e,o,0,r,t);let s=[],a=0;for(let i=0;i<r;i++)o[i]===10&&(s.push({text:o.toString("utf8",a,i),end:t+i+1}),a=i+1);return{lines:s,skipTo:s.length===0&&r===be?Xs(e,t+r,n):null}}function Lr(e,t){try{let n=JSON.parse(e).ts;if(typeof n!="string")return!1;let r=Date.parse(n);return t.since&&!(r>=Date.parse(t.since))?!1:!t.skip.some(([o,s])=>r>=Date.parse(o)&&r<Date.parse(s))}catch{return!1}}async function Qs(e,t,n,r){let o=n;r-o.window_start>=6e4&&(o={...o,window_start:r,window_sent:0});let s=Pr(e.paths,o),a=0,i=0,l=null;try{e:for(let c of s){o={...o,ino:c.ino,offset:c.start};let f=c.start;for(;f<c.size;){let{lines:u,skipTo:d}=Tr(c.fd,f,c.size);if(u.length===0){if(d===null)break;i++,o={...o,rejected:o.rejected+1,offset:d,last_note:"an unreadable stretch of the spool was skipped"},f=d;continue}for(let g of u){let h=Lr(g.text,o)?Sr(g.text,e.machine):null;if(h){if(o.window_sent>=Is)break e;let m=await ke(e,t,"POST","/v1/decision",h);if(m.status>=200&&m.status<300)a++,o={...o,sent:o.sent+1,window_sent:o.window_sent+1,last_push_ok:new Date(r).toISOString()};else if(m.status===400||m.status===422)i++,o={...o,rejected:o.rejected+1,last_note:`a stop was refused: ${H(m,t,e.cli)}`};else{l=m;break e}}o={...o,offset:g.end,last_hash:jr(g.text)}}f=u[u.length-1].end}}}finally{Ir(s)}return{state:o,sent:a,rejected:i,failed:l}}function It(e,t,n){let r=Pr(e,t);try{let o=0;for(let s of r)o+=Tr(s.fd,s.start,s.size).lines.filter(a=>Lr(a.text,t)&&Sr(a.text,n)!==null).length;return o}finally{Ir(r)}}function ei(e,t,n){let r={};for(let f of t){if(!f||typeof f!="object")continue;let u=f;typeof u.action!="string"||!u.action.startsWith("claude.")||u.explicit===!0&&(u.mode==="enforce"||u.mode==="ghost")&&(r[u.action]={mode:u.mode})}let o=q(e),s=o.value,a=new Set([...Object.keys(r),...Object.keys(s?.services?.[R]?.actions??{}),...Object.keys(M)]),i=o.source==="strict"||Q(s)||s?.day_one===!0,l={version:1,kill_switch:!1,default_mode:"ghost",services:{[R]:{actions:r}},updated_at:n.toISOString(),source:"workspace",...i?{day_one:!0}:{}},c=[...a].some(f=>X(s,f)!==X(l,f))||s?.source!=="workspace"||s?.day_one===!0!==i;return(c||o.source!=="file")&&zn(e,l),c}var E=e=>e.toLocaleString("en-US");function Tt(e,t){let n=[],r=`${j(`${e.decisions}.1`,2097152)}
18
+ ${j(e.decisions,4194304)}`;for(let o of r.split(`
19
+ `))if(o.trim())try{let s=JSON.parse(o);s.ts&&Date.parse(s.ts)>=t&&n.push(s)}catch{}return n}function ti(e,t){let n=e?Date.parse(e):NaN;if(!Number.isFinite(n))return null;let r=Math.max(0,Math.round((t.getTime()-n)/1e3));return r<90?`${r}s ago`:r<5400?`${Math.round(r/60)} min ago`:r<129600?`${Math.round(r/3600)} h ago`:`${Math.round(r/86400)} d ago`}function ni(e,t,n,r,o,s=U(!1),a=i=>`${o} ${i}`){if(!t)return Or(e)!==null?D("Dashboard",`synced by a key this terminal does not have (ANVIL_API_KEY where Claude Code runs) \xB7 ${a("login")} here to change modes from this terminal`,s):D("Dashboard",`${a("login")} ${s.dim("see every session in one place (optional)")}`,s);let i=ve(e,t.id,r.getTime()),l=i.since===null?0:It(e,i,n),c=ti(i.last_pull_ok,r),f=[a("open"),`this machine shows as ${n}`];return t.source==="env"&&f.push("using ANVIL_API_KEY"),f.push("sends stops, not commands"),c&&f.push(`synced ${c}`),l>0&&f.push(`${E(l)} ${l===1?"stop":"stops"} waiting to send`),i.last_error?f.push(i.last_error):i.last_note&&f.push(i.last_note),D("Dashboard",f.join(" \xB7 "),s)}var ri="what every Claude Code session spends",Dr=e=>e.split(/, and |; /).map(t=>t.trim()).filter(Boolean);function oi(e,t=U(!1),n=Xe()){let r=i=>M[i]?.text??i,o=[...e.floor.filter(i=>i.verdict==="block").flatMap(i=>Dr(i.short)),...e.held.filter(i=>e.blocking.has(i)).map(r)],s=[...e.held.filter(i=>!e.blocking.has(i)).map(r),...e.dayOne?Dr(an.text):[],...e.floor.filter(i=>i.verdict==="hold").map(i=>i.short)],a=e.all>0&&e.held.length>=e.all;return[...o.length>0?Z(v.blocked,"Blocks",o,t,n):[],...s.length>0?Z(v.held,"Holds",s,t,n):[],...Z(v.watching,"Watches",a?"nothing else: every risky kind is held":"every other risky action \xB7 it runs, with a note",t,n,9,t.dim),...e.off.length>0?Z(" ","Off",e.off.map(i=>M[i]?.slug??i),t,n,9,t.dim):[],...e.spend!==void 0?Z(v.watching,"Counts",`${ri}${e.spend?` \xB7 ${e.spend}`:""}`,t,n,9,t.dim):[]]}function si(e,t=U(!1),n=z,r=[],o="What it does now"){return Xt(o,[...oi(e,t,Xe(n)),...r],t,n)}function ii(e,t){let n=new Set;for(let r of e?.policies??[])if(!(r.origin==="baseline"||!pe(r,t))){for(let o of r.rules)if(o.intent==="block")for(let s of o.applies_to??[])n.add(s)}return n}var Mr=Object.keys(M).filter(e=>!["claude.bash.unclassified","claude.tool.other","claude.mcp.call","claude.agent.helper"].includes(e)&&!fe.has(e));function ai(e,t,n){return Mr.filter(r=>nt(t,r,e?Ee(e,r,n):null)==="enforce")}function li(e,t,n){return Mr.filter(r=>nt(t,r,e?Ee(e,r,n):null)==="off")}var ci=["claude.bash.deploy","claude.bash.db.destructive","claude.bash.secrets.print","claude.bash.fs.delete_recursive"];function ui(e,t){return t&&!ci.some(n=>nn(e,n,Ee(t,n,null)))?null:ln(e)}function di(e,t,n){let r=e.filter(o=>o.floor).length;return`stopped ${E(e.length)}${r?` (${E(r)} always on)`:""}${t?` \xB7 allowed once ${E(t)}`:""}${n?` \xB7 declined ${E(n)}`:""} \xB7 ${Fr(e)}`}function Fr(e){let t=new Map;for(let n of e)t.set(n.slug??"other",(t.get(n.slug??"other")??0)+1);return[...t.entries()].sort((n,r)=>r[1]-n[1]).slice(0,5).map(([n,r])=>`${n} ${E(r)}`).join(" \xB7 ")}function fi(e,t){return e.window==="minute"||e.window==="hour"?"rolling":e.window==="day"?"resets at midnight":`resets ${new Date(sr(e,t.getTime())).toLocaleDateString("en-US",{weekday:"long"})}`}function pi(e,t,n,r=U(!1),o=null){let s=(e?.policies??[]).filter(i=>pe(i,o)).flatMap(i=>i.caps??[]);if(s.length===0)return[];let a=new Ue(jt(t.dir,"caps"));return s.map((i,l)=>{let c;try{c=a.used(i,n.getTime())}catch{c=null}let f=i.window==="minute"||i.window==="hour"?"":` \xB7 ${fi(i,n)}`;return D(l===0?"Caps":"",`${i.text} \xB7 ${c===null?"can't be counted now: its calls are held":`${_t(i,c)} of ${_t(i,i.limit)} used`}${f}${i.unit!=="calls"&&i.unit!=="money"?" \xB7 an estimate":""}`,r)})}function Hr(e,t,n,r="anvil",o=null){if(n)return`${st("Anvil isn't working")} run in a terminal: ${N(r)} on`;let s=t.toISOString().slice(0,10),a=ge(jt(e.counts,s)),i=`${j(`${e.decisions}.1`,2*1024*1024)}
20
+ ${j(e.decisions,4*1024*1024)}`,l=0;for(let d of i.split(`
21
+ `))if(d.includes(`"ts":"${s}`))try{let g=JSON.parse(d);g.mode==="enforce"&&(g.delivered==="deny"||g.delivered==="ask")&&(l+=1)}catch{}let c=0;try{c=qn(e,C(e),t.getTime()).length}catch{c=0}let f=[...a>0?[`${E(a)} checked`]:[],...l>0?[`${E(l)} stopped`]:[],...o?.today?[o.text]:[]],u=[...f.length>0?[`${f.join(" \xB7 ")} today`]:[],...o&&!o.today?[o.text]:[],...c>0?[`${E(c)} waiting for your OK \xB7 in a terminal: ${N(r)} allow`]:[]];return[st("Anvil on"),...u.length>0?[u.join(" \xB7 ")]:[]].join(" ")}function gi(e,t,n=U(!1)){let r=t.toISOString().slice(0,10),o=ge(jt(e.counts,r)),s=Tt(e,Date.parse(`${r}T00:00:00.000Z`)),a=s.filter(d=>d.mode==="ghost"&&(d.verdict==="hold"||d.verdict==="block")),i=s.filter(d=>d.mode==="enforce"&&(d.delivered==="deny"||d.delivered==="ask")),l=i.filter(d=>d.delivered==="ask").map(d=>xt(d.transcript,d.call)),c=s.filter(d=>d.delivered==="approved").length+l.filter(d=>d==="yes").length,f=l.filter(d=>d==="no").length,u=[`${E(o)} ${o===1?"action":"actions"} checked`];return i.length>0&&u.push(di(i,c,f)),a.length>0&&u.push(`would have stopped ${E(a.length)} \xB7 ${Fr(a)}`),i.length===0&&a.length===0&&u.push("nothing it would stop"),D("Today",u.join(" \xB7 "),n)}function Wr(e){let t=U(!1);if(!e.table)return[Ze("Report","not checking",t),"",Se(v.problem,e.installed?"Not working \xB7 Claude's calls are held until it's fixed":"No rules compiled, so nothing is checked"),"",...(e.problems??[]).map(s=>D("Problem",s)),...(e.problems??[]).length>0?[""]:[],Qe(`${N(e.cli)} on`,e.installed?"fix it, in your own terminal":"turn it on")];let{text:n}=un(e.table,e.modes),r=ai(e.table,e.modes,null),o=e.problems??[];return[Ze("Report",o.length>0?"on, with a problem":"on",t),"",o.length>0?Se(v.problem,"On, with a problem"):Se(v.on,"On. Every action Claude Code takes is checked before it runs."),"",...o.map(s=>D("Problem",s)),...o.length>0?[""]:[],...si({floor:sn(e.table),held:r,blocking:ii(e.table,null),off:li(e.table,e.modes,null),dayOne:ui(e.modes,e.table)!==null,all:n==="enforce"?r.length:Number.POSITIVE_INFINITY,spend:null},t),"",D("Rules",String(cn(e.table))),...pi(e.table,e.paths,e.now),gi(e.paths,e.now),ni(e.paths,e.identity,e.machine,e.now,e.cli),"",Qe(`${N(e.cli)} rules edit`,"change rules, in your terminal")]}import{randomUUID as hi}from"crypto";import{existsSync as Kr,mkdirSync as Jr,readFileSync as qr,writeFileSync as yi}from"fs";import{join as ce}from"path";import{existsSync as Yu,mkdirSync as Zu,readFileSync as Xu,writeFileSync as Qu}from"fs";import{homedir as td}from"os";import{join as rd}from"path";import{randomUUID as sd}from"crypto";var mi="https://app.anvilcontrol.ai";function Lt(e=process.env){let t=e.ANVIL_HOSTED_DASHBOARD_URL?.trim();return(t&&t.length>0?t:mi).replace(/\/+$/,"")}import{lookup as Ju}from"dns/promises";function Dt(){return/^(1|true|on|yes)$/i.test((process.env.ANVIL_FUNNEL_DISABLED||"").trim())||/^(1|true|on|yes)$/i.test((process.env.DO_NOT_TRACK||"").trim())}function Ur(e,t,n,r){try{if(Dt()||!t||!/^https?:\/\//i.test(t)||!n)return Promise.resolve();let o=new AbortController,s=setTimeout(()=>o.abort(),1200);typeof s.unref=="function"&&s.unref();let a=r!=null&&Object.keys(r).length>0;return fetch(t.replace(/\/+$/,"")+"/api/funnel",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a?{fid:n,event:e,props:r}:{fid:n,event:e}),signal:o.signal}).then(()=>{clearTimeout(s)},()=>{clearTimeout(s)})}catch{return Promise.resolve()}}var Br={claude_on:["mode","scope","linked","plugin"],replay_run:["window","sessions","actions","would_stop","active_days"],decisions_daily:["day","calls","held","blocked","would","approved","errors"]};var wi=["CI","GITHUB_ACTIONS","GITLAB_CI","BUILDKITE","CIRCLECI","TF_BUILD","JENKINS_URL","TEAMCITY_VERSION"],Mt=e=>e!==void 0&&e.trim()!==""&&!/^(0|false|no|off)$/i.test(e.trim());function Vr(e){return Mt(e.DO_NOT_TRACK)||Mt(e.ANVIL_FUNNEL_DISABLED)?!1:!wi.some(t=>Mt(e[t]))}function Gr(e){return ce(e,".anvil","telemetry-notice")}function Yr(e){return Kr(Gr(e))}function bi(e){return!Number.isFinite(e)||e<=0?"0":e<10?"1-9":e<100?"10-99":e<1e3?"100-999":e<1e4?"1k-9k":"10k+"}function ki(e){let t=ce(e,".anvil","claude","telemetry-id");try{let r=qr(t,"utf8").trim();if(/^c_[a-f0-9]{32}$/.test(r))return r}catch{}let n=`c_${hi().replace(/-/g,"")}`;try{Jr(ce(e,".anvil","claude"),{recursive:!0,mode:448}),yi(t,`${n}
22
+ `,{mode:384})}catch{}return n}async function vi(e,t,n,r){try{if(!Vr(n)||Dt()||!Yr(r)||!Br[e].every(o=>o in t)||Object.keys(t).some(o=>!Br[e].includes(o)))return;await Ur(e,Lt(n),ki(r),t)}catch{}}function zr(e){return ce(e.state,"telemetry.json")}function $i(e,t){let n=ge(ce(e.counts,t)),r=Date.parse(`${t}T00:00:00.000Z`),o=r+864e5,s=Tt(e,r).filter(i=>i.ts&&Date.parse(i.ts)<o),a=i=>s.filter(i).length;return{day:t,calls:bi(n),held:a(i=>i.mode==="enforce"&&i.verdict==="hold"&&(i.delivered==="deny"||i.delivered==="ask")),blocked:a(i=>i.mode==="enforce"&&i.verdict==="block"),would:a(i=>i.mode==="ghost"&&(i.verdict==="hold"||i.verdict==="block")),approved:a(i=>i.delivered==="approved"),errors:a(i=>i.verdict==="error")}}async function Zr(e,t,n,r){if(!Vr(t)||!Yr(n))return 0;let o=r.toISOString().slice(0,10),s=b(zr(e))?.last_daily??null,a="";try{a=new Date(Date.parse(qr(Gr(n),"utf8").trim())).toISOString().slice(0,10)}catch{return 0}let i=[];for(let l=7;l>=1;l--){let c=new Date(Date.parse(`${o}T00:00:00.000Z`)-l*864e5).toISOString().slice(0,10);c<a||s!==null&&c<=s||Kr(ce(e.counts,c))&&i.push(c)}if(i.length===0)return 0;try{Jr(e.state,{recursive:!0}),S(zr(e),`${JSON.stringify({last_daily:i[i.length-1]})}
23
+ `)}catch{return 0}return await Promise.all(i.map(l=>vi("decisions_daily",$i(e,l),t,n))),i.length}var L=Y(Ri(import.meta.url)),Wt=Ke(L)==="bin"&&Ke(Y(L))==="claude"&&Ke(Y(Y(L)))===".anvil"?Y(L):void 0,Je=!Wt&&Ke(L)==="bin"&&_i(P(Y(L),".claude-plugin","plugin.json"))?P(L,"baseline.json"):void 0,Ft=6e4,Xr=5e3,Oi=30*6e4,Ei=720*6e4,Pi=780*6e4;function Ii(e){try{return process.kill(e,0),!0}catch{return!1}}function ji(e,t){let n=b(e),r=typeof n?.pid=="number"?n.pid:0,o=typeof n?.started=="number"?n.started:0;if(r>0&&o>0)return r===process.pid||!Ii(r)||t-o>=Pi;try{return t-Ut(e).mtimeMs>1e4}catch{return!0}}function Ti(e,t){x(e.state);let n=P(e.state,"sync.lock"),r=P(e.state,`sync.lock.${process.pid}.${t}.tmp`);try{Ci(r,JSON.stringify({pid:process.pid,started:t}),{mode:384})}catch{return!1}try{for(let o=0;o<2;o++)try{return xi(r,n),!0}catch(s){if(s.code!=="EEXIST"||!ji(n,t))return!1;try{Ai(n,`${n}.stale.${process.pid}`),Ht(`${n}.stale.${process.pid}`)}catch{return!1}}return!1}finally{try{Ht(r)}catch{}}}function no(e){let t=P(e.state,"sync.lock");try{b(t)?.pid===process.pid&&Ht(t)}catch{}}function Li(e,t){let n=0,r=o=>new Date(t-o).toISOString().slice(0,10);for(let o of[P(e.counts,r(0)),P(e.counts,r(864e5)),e.decisions])try{n=Math.max(n,Ut(o).mtimeMs)}catch{}return n}function Di(e){try{return Ut(e.decisions).size}catch{return 0}}function Mi(e,t){if(t)return!0;if(y(e.install,1024*1024)!==!0)return!1;try{let n=JSON.parse(Si(e.install,"utf8"));return Object.keys(n.installs??{}).length>0}catch{return!1}}function Qr(e,t){try{x(e.state),S(P(e.state,Xn),String(Math.round(t)))}catch{}}function eo(e,t){return{paths:e.paths,identity:t,machine:Ot(e.paths,e.hostname),fetch:e.fetch,now:e.now,home:e.home,...e.pluginBaseline?{fallbackTable:e.pluginBaseline,hookBin:Y(e.pluginBaseline)}:{}}}async function Fi(e){let{paths:t}=e,n=e.now();if(!Ti(t,n))return"locked";let r="idle",o=e.now()+6e4;try{let s=0,a=-1;for(;;){let l=e.now(),c=ze(e.env,e.home);if(!c)return Nr(t,l),r="unlinked",o=l+10*6e4,r;let f=Di(t),u=ve(t,c.id,l).next_try_at;if((l-s>=Ft||f!==a||u>0&&l>=u)&&(a=f,await Pt(eo(e,c)),l-s>=Ft&&(s=l,await(e.sendDaily??Zr)(t,e.env,e.home,new Date(l)))),Qr(t,e.now()+3*Xr+Ft),!Mi(t,e.pluginBaseline!==void 0)){r="off";break}if(e.now()-Li(t,e.now())>Oi){r="idle";break}if(e.now()-n>Ei){r="lifetime";break}await e.sleep(Xr)}let i=ze(e.env,e.home);return i&&await Pt(eo(e,i)),o=r==="off"?e.now()+10*6e4:0,r}finally{Qr(t,o),no(t)}}function Hi(e){let t=d=>typeof d=="string"&&/^[\w@./ -]{1,60}$/.test(d),n=b(e.install),r=n?.cli;it(t(r)?r:"anvil");let o=V(e,Je??P(L,"baseline.json")),s=q(e),a=o.value,i=[a?.cli,r].find(t)??"anvil";it(i);let l=Object.values(n?.installs??{}).filter(d=>d&&typeof d.command=="string"&&!pt(d)).map(d=>`Anvil's hook in ${d.settings_path} can't start (its files are gone), so new sessions are not checked: run ${$("on")}`),c=C(e),f=[...new Set([...l,o.problem,s.problem,...Fe(e,c,$e()),...Zn(e,$e(),c),...He(e)?.problems??[]].filter(d=>!!d))],u=Wr({paths:e,table:a,modes:s.value,identity:ze(process.env,$e()),machine:Ot(e,to()),now:new Date,cli:i,problems:f,installed:Object.keys(n?.installs??{}).length>0});process.stdout.write(`${u.join(`
24
+ `)}
25
+ `)}async function Wi(e){let t=Date.now(),n=null;try{n=(await import(Ni(P(L,"claude-meter.js")).href)).statusSpend?.(e,t)??null}catch{}let r=c=>typeof c=="string"&&/^[\w@./ -]{1,60}$/.test(c),o=b(e.install),s=o?.cli,a=r(s)?s:"anvil",i=V(e,Je??P(L,"baseline.json")),l=Object.values(o?.installs??{}).some(c=>c&&typeof c.command=="string"&&!pt(c));return Hr(e,new Date(t),!i.value||l?"not working":null,a,n)}async function Ui(){let e=Wt?Pe(Wt):xn($e());for(let t of["SIGTERM","SIGINT","SIGHUP"])process.on(t,()=>{no(e),process.exit(0)});if(process.argv.includes("--statusline")){try{process.stdout.write(`${await Wi(e)}
26
+ `)}catch{process.stdout.write(`\u{1F539} Anvil isn't working \u{1F539} run in a terminal: ${$("on")}
27
+ `)}process.exit(0)}if(process.argv.includes("--status")){try{Hi(e)}catch(t){process.stdout.write(`Anvil could not read its status: ${t instanceof Error?t.message:String(t)}
28
+ `)}process.exit(0)}try{await Fi({paths:e,env:process.env,home:$e(),hostname:to(),fetch:globalThis.fetch,now:()=>Date.now(),sleep:t=>new Promise(n=>setTimeout(n,t)),...Je?{pluginBaseline:Je}:{}})}catch{}process.exit(0)}process.argv[1]&&/claude-sync\.js$/.test(process.argv[1])&&Ui();export{Oi as IDLE_EXIT_MS,Ei as MAX_LIFE_MS,Ft as PULL_EVERY_MS,Xr as TICK_MS,Qr as holdSpawns,Li as lastActivity,no as releaseLock,Fi as runSyncLoop,Ti as takeLock};