@useanvil/claude-code 0.0.0-stage → 0.8.1

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 Le=Object.defineProperty;var wt=Object.getOwnPropertyDescriptor;var bt=Object.getOwnPropertyNames;var xt=Object.prototype.hasOwnProperty;var yt=(a,e)=>{for(var t in e)Le(a,t,{get:e[t],enumerable:!0})},$t=(a,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of bt(e))!xt.call(a,n)&&n!==t&&Le(a,n,{get:()=>e[n],enumerable:!(s=wt(e,n))||s.enumerable});return a};var St=a=>$t(Le({},"__esModule",{value:!0}),a);var us={};yt(us,{readCmd:()=>jt,readPowerShell:()=>Ct});module.exports=St(us);var at=require("buffer");function O(a){return Object.assign(Object.create(null),a)}function Ct(a,e){return lt(a,e,(t,s)=>new ye(s,t).program())}function jt(a,e){return lt(a,e,(t,s)=>vt(s,t))}var ot=64*1024,be=32,Wt=128*1024,Pt=4*ot,Et=64*1024,K="Unknown",ke=`[ -n "$${K}" ]`,J="\uFDD0",ae="\uFDD1",ve='eval "$PowerShellUnread"',re=class extends Error{constructor(t,s=!1){super(t);this.why=t;this.fatal=s}};function g(a){throw new re(a)}function oe(a){throw new re(a,!0)}function le(a,e){return a.unread.push(e),ve}function Ze(a,e,t){return a.unread.length=e,a.drive=null,le(a,t)}function lt(a,e,t){if(a.length>ot)return{kind:"unreadable",why:"longer than 64 KB"};if(a.includes(J)||a.includes(ae)||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:we(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>Wt?{kind:"unreadable",why:"too long once translated"}:{kind:"shell",text:r===""?"true":r,unread:[...n.unread]}}catch(r){if(r instanceof re)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}),Z={t:"home"},j=[L(K)];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 ne=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 N(a){return(a.includes("\0")||a.includes(""))&&g("a NUL character"),a.split(/([\v\f\r])/).map(e=>/^[\v\f\r]$/.test(e)?ct[e]:e===""?"":`'${e.replace(/'/g,"'\\''")}'`).join("")||"''"}var ct=O({"\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+N(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=>`"${ct[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 ut=/^[A-Za-z0-9_.,:/@%+=-]+$/;function z(a){let e=w(a);return e!==null&&ut.test(e)?e:c(a)}var We={words:[]},M={words:[j]};function G(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 H(a){return a===""?We:{words:[[{t:"sub",code:a}]]}}function pe(a){return a.reduce((e,t)=>e+t.words.length,0)>Et&&oe("too long once translated"),{words:a.flatMap(e=>e.words)}}function He(a,e){a.work+=e.length,a.work>Pt&&oe("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?M:a.some(t=>t.unread)?{words:[e],computed:!0,unread:!0}:{words:[e],computed:!0}}function Vt(a,e,t=[]){return{words:[[...t.flatMap(n=>n.words.flatMap(r=>r.filter(i=>i.t==="sub"))),{t:"sub",code:le(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 T(a){let e=a.flatMap(t=>t.words.flatMap(s=>s.filter(n=>n.t==="sub")));return e.length>0?`true ${c(e)}`:""}function Ce(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 fe(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 _e(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:xe(s)}function It(a){let e=c(a),t=a[a.length-1];return ht(a)||e.endsWith("/")||t?.t==="lit"&&/[\\/]$/.test(t.s)?e:`${e}/`}function ht(a){let e=a[a.length-1];return e?.t!=="lit"?!1:/[*?[]/.test(e.s.split(/[\\/]/).pop()??"")}function At(a){let e=w(a);return e!==null&&/^[A-Za-z0-9_.*?-]+$/.test(e)?e:c(a)}function Rt(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 Ge(a){let e=a[a.length-1];return e?.t==="lit"&&/(^|[:\\/])win32_process$/i.test(e.s)}function Lt(a,e){return(t,s)=>t==="cmd"?Se(a,e,s):Ot(a,e,s)}function De(a,e){return(t,s)=>le(a,`${s}: ${e}`)}function et(a,e){let t="";for(let s of a)if(s.t==="lit")t+=s.s;else if(s.t==="home"||s.t==="var"&&dt.has(s.n))t+=$e(e,s);else return null;return t}function Ve(a,e,t,s){return y(e===null?`${a}; ${le(t,`${s}: a command line the line does not show`)}`:`${a}; ${ie(Se(e,t,s))}`)}function Be(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}; ${le(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 Ve(s,i===void 0?null:t(i),e,"a scheduled task")}function ze(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 Ve(s,i===void 0?null:t(i),e,"a process wmic starts")}function Ot(a,e,t){He(e,a),++e.depth>be&&oe("nests too deeply");let s=e.unread.length;try{return new ye(a.replace(/\r\n?/g,`
3
+ `),e).program()}catch(n){if(!(n instanceof re)||n.fatal)throw n;return Ze(e,s,`${t}: ${n.why}`)}finally{e.depth--}}var Tt=[["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]],Mt=O({ep:"executionpolicy",ec:"encodedcommand",ea:"encodedarguments",wd:"workingdirectory",of:"outputformat",if:"inputformat"});function Nt(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 Tt)if(t.startsWith(e)&&e.length>=s.length)return{name:Mt[t]??t,value:n};return"unknown"}var Oe=O({currentusercurrenthost:[Z,p("/Documents/PowerShell/Microsoft.PowerShell_profile.ps1")],currentuserallhosts:[Z,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")]}),dt=new Set(["PWD","TMPDIR","CLAUDE_PROJECT_DIR"]);function _t(a){return a!==void 0&&["invoke-webrequest","invoke-restmethod","curl","wget"].includes(a.name)}var Dt="'\u2018\u2019\u201A\u201B",Bt='"\u201C\u201D\u201E',zt="-\u2013\u2014\u2015",ee=a=>a!==""&&Dt.includes(a),X=a=>a!==""&&Bt.includes(a),se=a=>ee(a)||X(a),I=a=>a!==""&&zt.includes(a),Q=a=>a>="0"&&a<="9"&&a.length===1;function U(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 B(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=>B(a)||Q(a)||a==="_";function ce(a){return a===""||U(a)||a===`
4
+ `||a===";"||a==="|"||a==="&"||a==="("||a===")"||a==="{"||a==="}"||a===","||a===">"||a==="<"}var Ft=O({0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
5
+ `,r:"\r",t:" ",v:"\v"});function we(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 qt=O({"%":"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"}),Ut=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"]),Qt=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"]),pt=O({verbose:"s",debug:"s",erroraction:"v",warningaction:"v",informationaction:"v",progressaction:"v",errorvariable:"v",warningvariable:"v",informationvariable:"v",outvariable:"v",outbuffer:"v",pipelinevariable:"v"}),Kt=O({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=O({path:"v",literalpath:"v"}),E=O({pspath:"literalpath",lp:"literalpath"}),Y=O({filter:"v",include:"v",exclude:"v",credential:"v"}),b=O({"remove-item":{params:{...V,...Y,recurse:"s",force:"s",stream:"v"},positions:["path"],aliases:E,prefer:["force","recurse","path","literalpath"],sp:!0},"clear-content":{params:{...V,...Y,force:"s",stream:"v"},positions:["path"],aliases:E,prefer:["force","path"],sp:!0},"set-content":{params:{...V,...Y,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,...Y,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,...Y,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,...Y,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,...Y,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,...Y,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,...Y,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,...Y,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 Zt(a,e){let t=e.toLowerCase(),s={...pt,...a.sp?{whatif:"s",confirm:"s"}:{},...a.params},n={...Kt,...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 Ht(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={...pt,...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(...Re(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(G(d.text));continue}let f=Zt(a,d.name);if(f!==null){if(t[f]==="s"){n.set(f,Ht(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,M)}}}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 q(a,e){return a.switches.get(e)===!0||a.splat&&!a.switches.has(e)}function D(a){return a.switches.get("whatif")===!0}var je=a=>`if ${ke}; then ${a||"true"}; fi`,y=a=>`{ ${a}; }`,ie=a=>a===""?"true":/; | && | \|\| | \| /.test(a)?y(a):a,Xt=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"]),tt=new Set(["script","global","local","private","using","workflow","variable"]),st=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 Jt(a){let e=a.toLowerCase();return st.has(e)?!0:(e.startsWith("c")||e.startsWith("i"))&&st.has(e.slice(1))&&!["f","and","or","xor","is","isnot","as","band","bor","bxor","shl","shr"].includes(e.slice(1))}var Ie=O({userprofile:[Z],home:[Z],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:[Z,p("/AppData/Roaming")],localappdata:[Z,p("/AppData/Local")],claude_project_dir:[L("CLAUDE_PROJECT_DIR")],public:[p("C:\\Users\\Public")],comspec:[p("C:\\Windows\\System32\\cmd.exe")]});function te(a){let e=a.toUpperCase().replace(/[^A-Z0-9_]/g,"_");return/^[A-Z_]/.test(e)?e:`_${e}`}function nt(a){return Ie[a.toLowerCase()]??[L(te(a))]}function me(a){let e=a.toLowerCase().replace(/[^a-z0-9_]/g,"_");return/^[a-z_]/.test(e)&&e!=="_"?e:`v_${e}`}function ge(a){return`fn_${a.toLowerCase().replace(/[^a-z0-9_]/g,"_")}`}function xe(a){return(a.split(/[\\/]/).pop()??a).toLowerCase().replace(/\.(exe|cmd|bat|com)$/,"")}function Pe(a){return/[\\/]/.test(a)&&!/\.(exe|cmd|bat|com)$/i.test(a)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(a)}var rt=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"]),Yt=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"]),Gt=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"]),Te=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"]),es=new Set(["diagnostics.process.start","console.setout","console.seterror","console.setin"]),ts=new Set(["net.servicepointmanager.securityprotocol","console.outputencoding","console.inputencoding"]),ye=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>be&&oe("nests too deeply")}leave(){this.sh.depth--}exprIn(){++this.exprDepth>4*be&&oe("nests too deeply")}unread(e){return le(this.sh,e)}unreadVal(e,t=[]){return Vt(this.sh,e,t)}skip(e=!1){for(;;){let t=this.peek();if(U(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(;B(this.src[e]??"");)e++;return this.src.slice(this.pos,e).toLowerCase()}keyword(){let e=this.wordAhead();if(!Xt.has(e))return null;let t=this.src[this.pos+e.length]??"";return t===""||U(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}="$${K}"`);return(t.length>0||s.length>0)&&(this.lastPure=null),[e,...s,...t.map(n=>je(n.code))].filter(n=>n!=="").join("; ")}statementBody(){if(this.peek()===":"&&B(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 ["),ee(n)?this.singleQuoted():X(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),je(this.body(!0));case"return":case"exit":case"throw":return this.flowStatement(e);case"break":case"continue":if(this.skip(!1),B(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()&&!U(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 }"),ee(s)?this.singleQuoted():X(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:ke}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===ke?"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||ke}; do ${r}${n?`; ${n}`:""}; done`].filter(Boolean).join("; ")}foreachStatement(){if(this.skip(!1),I(this.peek()))for(this.pos++;B(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=T([s]);this.skip(!0);let r=this.body(!0);t.push(je([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(je(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?T([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?T([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()&&!U(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&&tt.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`${ge(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=T([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==="{"||se(e)||e==="!"||e===","||I(e))return!0;if(e==="@")return t==="("||t==="{"||se(t);if(e==="+")return Q(t)||t==="+";if(e===".")return Q(t);if(Q(e)){let s=Ne(this.src,this.pos);return s>this.pos&&rs(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:H(n),code:n}}this.pos=e;let s=this.chain("out");return s.val!==null?{val:s.val,code:""}:{val:H(s.text),code:s.text}}assign(e,t,s,n){let r=()=>n||T([s]);switch(e.k){case"var":{let i=e.name;if(t==="=")return this.setVar(i,fe(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?"":z(s.words[0])}`;if(t==="+="&&s.words.length<=1){let o=this.known(i);return this.setVar(i,o!==null&&o.words.length>1?pe([o,s]):null),`${i}=${c(W([L(i)],s.words[0]??[]))}`}return this.setVar(i,null),[r(),`${i}="$${K}"`].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!=="="?[T([s]),`export ${e.name}="$${K}"`].filter(Boolean).join("; "):i===null||w(i)===""?`unset ${e.name}`:`export ${e.name}=${z(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}="$${K}"`:"")].filter(Boolean).join("; ");case"static":return ts.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),`${ge(e.name)}() { ${s.block.code||"true"}; }`):(this.sh.functions.add(e.name),[r(),`${ge(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===K),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 F=m.text+this.redirectText(f.redirects);m.value!==void 0&&f.redirects.length===0?(r=F,i={k:"value",val:m.value}):(n.push(F),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=fe(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=fe(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===ve){let l=`true ${c(r.slice(0,-1))}; ${ve}`;return s===""?l:`${y(l)}${s}`}return e.words.filter(l=>!(l.length===1&&l[0].t==="var"&&l[0].n===K)).length===0?s===""?T([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),ce(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==="."&&(U(this.peek(1))||this.peek(1)==="{"||this.peek(1)==="$"||se(this.peek(1)))?(this.pos++,this.skip(!1),e="dot",t=this.argValue()):((ce(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)&&(U(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(!(B(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=ce(this.peek())?null:this.argList();return{t:"param",name:n,text:`-${n}`,val:i,colon:!0}}return ce(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]:pe(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==="@"&&se(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==="."&&(B(i)||i==="_"||se(i)||i==="$"||i==="(")||r==="["||r===":"&&i===":"?this.postfix(n).val:ce(r)||r==="`"&&this.peek(1)===`
21
+ `?n.val:this.genericToken(k(n.val))}this.pos=s}return this.genericToken()}genericToken(e=[]){let t=new ne;for(t.add(e);;){let r=this.peek();if(ce(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 ee(r)?t.add(this.singleQuoted()):X(r)?t.add(this.doubleQuoted()):r===J?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=[Z,...n.s.length>1?[p(n.s.slice(1))]:[],...s.slice(1)]),s.length===0?G(""):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!==J&&e!==ae?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(Ft[e]??e)}mark(){let e=Xe(this.src,this.pos,this.sh);return this.pos=this.src.indexOf(ae,this.pos)+1,e}singleQuoted(){this.pos++;let e=new ne;for(;;){this.eof()&&g("an unclosed string");let t=this.peek();if(ee(t)){if(ee(this.peek(1))){e.text("'"),this.pos+=2;continue}return this.pos++,e.word()}t===J?e.add([this.mark()]):(e.text(t),this.pos++)}}doubleQuoted(){return this.pos++,this.expandable(e=>!(!X(e)||X(this.peek(1))))}expandable(e,t=-1){let s=new ne;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&&X(n)&&X(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===J?s.add([this.mark()]):(s.text(n),this.pos++)}return s.word()}hereAhead(){let e=this.pos+2;for(;U(this.src[e]??"");)e++;return this.src[e]===`
23
+ `}hereString(){let e=this.peek(1),t=ee(e);for(this.pos+=2;U(this.peek());)this.pos++;this.pos++;let s=this.pos,n=-1;for(let o=s;;){if((t?ee(this.src[o]??""):X(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 ne;for(this.pos=s;this.pos<r;)this.peek()===J?o.add([this.mark()]):o.text(this.src[this.pos++]);let l=o.word();i=l.length===0?G(""):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:M,target:{k:"other"}};if(!R(t))return e?null:(this.pos++,{val:G("$"),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(nt(t),["userprofile","home","temp","tmp"].includes(t.toLowerCase())),target:{k:"env",name:te(t)}};if(s===null||tt.has(s)){let n=t.toLowerCase();switch(n){case"null":return{val:We,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([Z],!0),target:{k:"other"}};case"pwd":return{val:C([L("PWD")],!0),target:{k:"other"}};case"profile":return{val:{...C(Oe.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=me(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:M,target:{k:"function",name:t.toLowerCase()}};if(s.length===1&&B(s)){let n=`${s.toUpperCase()}:${t}`;return{val:H(`cat ${N(n)}`),target:{k:"file",path:n}}}return{val:M,target:{k:"other"}}}subValue(){this.enter();try{let e=this.statements(")"),t=this.parsed===1?this.lastPure:null;return this.pos++,t??H(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++,We;let e=this.pos;if(this.keyword()!==null){this.pos=e;let r=this.statements(")").join("; ");return this.pos++,H(r)}let s=this.chain("out");if(this.skip(!0),this.peek()===")")return this.pos++,s.val??H(s.text);let n=this.statements(")");return this.pos++,H([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(se(n)||n==="$"||n==="("){let l=this.unary();t.push(l.val),s=l.val.text??""}else{let l=this.pos;for(;!this.eof()&&!U(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=H(this.keywordStatement(i)??"");else{this.pos=r;let l=this.chain("out");o=l.val??H(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:pe(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)&&B(s)){let n=this.pos+1;for(;B(this.src[n]??"");)n++;let r=this.src.slice(this.pos+1,n);return!Jt(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==="?"&&U(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:pe([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:M,target:null}}if(I(e)){if(B(t)){let s=this.pos+1;for(;B(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(Q(t)||t==="."&&Q(this.peek(2))){let s=Ne(this.src,this.pos+1),n=this.src.slice(this.pos,s);return this.pos=s,{val:G(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=it(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")&&Ge(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:M,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==="@"||se(e)||Q(e)||e==="{"||e===J||(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==="@"&&se(t)&&this.hereAhead())return{val:this.hereString(),target:null};if(e==="{")return{val:this.scriptBlock(),target:null};if(ee(e)){let s=this.singleQuoted();return{val:s.length===0?G(""):C(s),target:null}}if(X(e))return{val:C(this.doubleQuoted()),target:null};if(e===J)return{val:C([this.mark()]),target:null};if(Q(e)||e==="."&&Q(t)){let s=Ne(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:G(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!=="."&&(B(n)||n==="_"||se(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&&Oe[r.name]!==void 0)t={val:C(Oe[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:M,target:null};continue}break}return t}memberName(){let e=this.peek();if(ee(e)){let s=this.singleQuoted();return{name:w(s)?.toLowerCase()??null,val:w(s)===null?C(s):null}}if(X(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"?H(Ce(this.processCreate(s[0]),s.slice(1))):t===null?this.unreadVal("a method chosen at run time",[e.val,...s]):Yt.has(t)?P([e.val,...s]):Gt.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:G(t.name),target:{k:"static",type:e,member:t.name}}:{val:M,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=>H(Ce(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 ${te(l)}`):o(`export ${te(l)}=${z(k(u))}`)}case"environment.getenvironmentvariable":{let l=s[0]?.text;return l===void 0||T(s)!==""?P(s):C(nt(l))}case"environment.getfolderpath":return T(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):M;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"&&(Te.has(e)||Me(e))||Te.has(e)&&t!=="new"&&!es.has(n)&&!(e==="diagnostics.process"&&t==="start")||Me(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([Z]);case"applicationdata":return s(Ie.appdata);case"localapplicationdata":return s(Ie.localappdata);case"desktop":case"desktopdirectory":return s([Z,p("/Desktop")]);case"mydocuments":case"personal":return s([Z,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 M}}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=we(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 ue(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=qt[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(ge(t))],elem:s}:/^[a-z]+-[a-z0-9]+$/i.test(t)||t==="mkdir"?{name:t,kind:"cmdlet",prog:[p(t)],elem:s}:{name:Pe(e)?e:xe(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:[ge(e.name),...this.nativeArgs(n.args)].join(" ")}:l=e.kind==="program"?this.programStage(e,t):this.cmdlet(e,t,s);let u=Ce(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),fe(t.name)!==null,this.nativeArgs(t.args))}}unknownProgram(e,t,s){let n=_e(e);return n!==null?[z([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(N(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(...Re(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(...Re(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:Ue(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:qe(r)};case"schtasks":return{text:Be(r,this.sh,o=>this.knownText(C(o)))};case"wmic":return{text:ze(r,this.sh,o=>this.knownText(C(o)))};default:break}return Pe(n)?{text:[c(this.scriptWord(n)),...this.nativeArgs(s.args)].join(" ")}:{text:[z([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:Nt(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=at.Buffer.from(u,"base64").toString("utf16le");return/[\u0000\u0001\uFDD0\uFDD1]/.test(h)?r(this.unread("an encoded command holding control characters")):r(ie(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){He(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 re)||n.fatal)throw n;return Ze(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 ${me(l)}`:`${me(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(D(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||!Ge(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 Ut.has(r)?this.standIn(n,t,!0):Qt.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(D(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 ${te(l[1])}=${z(k(o))}`:`unset ${te(l[1])}`};let u=r?Fe(r):null;if(u!==null){let h=n.values.get("name");return{text:["reg","add",N(u),...h?["'/v'",c(k(h))]:[],...o?["'/d'",c(k(o))]:[],"'/f'"].join(" ")}}return this.passThrough(t)}passThrough(e){return{text:[z([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=T(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(D(s))return this.whatIfStandIn(e);let n=q(s,"recurse"),r=`${n?" -r":""}${q(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":""}${q(s,"force")?" -f":""} ${f.items.join(" ")}`}}let u=[],h=[];for(let f of i){let S=ns(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)?It(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(ht(l))o.push(c(l));else for(let u of i.length>0?i:[[p("*")]])o.push(`${c(l)}/${At(u)}`);return{items:o,recurse:q(n,"recurse")||n.values.has("depth")}}if(!Rt(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(D(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(D(n))return this.whatIfStandIn(t);let r=e==="add-content"||q(n,"append"),i=r?">>":">",o=this.paths(n,e==="out-file"||e==="tee-object"?["filepath","literalpath"]:["path","literalpath"]),l=q(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(D(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?z(k(u)):"''";h.push(`export ${te(w(d)?.replace(/^env:[\\/]?/i,"")??K)}=${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(`${me(w(d)?.replace(/^variable:[\\/]?/i,"")??"v")}=${u&&u.words.length>0?z(k(u)):""}`);continue}let S=Fe(d);if(S!==null){h.push(`reg add ${N(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(q(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(D(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(D(n))return this.whatIfStandIn(t);let r=n.values.get("destination"),i=r?this.fixPath(k(r)):[p(".")],o=e==="copy-item"?`cp${q(n,"recurse")?" -r":""}`:"mv",l=q(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(D(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(Ae(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",...q(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=M;if(q(t,"leaf")){let i=s[s.length-1];i?.t==="lit"&&/[\\/]/.test(i.s.replace(/[\\/]+$/,""))?r=G(i.s.replace(/[\\/]+$/,"").split(/[\\/]/).pop()):n!==null&&(r=G(n))}else if(!["qualifier","noqualifier","isabsolute","extension","leafbase"].some(i=>q(t,i))){let i=Ae(s);i.length>0&&!ss(i)&&(r=C(ft(i),!0))}return{text:r===M?"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?we(n):s[0]?.t==="lit"?we(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:pe(r)}:{text:o}}startProcess(e){let t=x(b["start-process"],e.args);if(D(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?mt(i.words[0]):[...i.words]),o.push(...t.extra.flatMap(m=>m.words));let l,u=r!==null?xe(r):_e(n),h=t.values.has("redirectstandardinput")?De(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=Ue(o,this.sh,h):u==="taskkill"?l=qe(o):u==="schtasks"?l=Be(o,this.sh,m=>this.knownText(C(m))):u==="wmic"?l=ze(o,this.sh,m=>this.knownText(C(m))):r!==null&&/^[a-z][a-z0-9+.-]*:\/\//i.test(r)?l=["xdg-open",N(r)].join(" "):l=[r!==null&&Pe(r)?c(this.scriptWord(r)):z([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,F])=>{let A=t.values.get(m);return A?` ${F} ${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 Ve(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(D(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",N(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=M),l===void 0)return{text:o.join(" ")};let h=l.action;return h!==void 0&&o.push("'/tr'",c(k(h))),{text:Ve(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=T(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 ie(T([e]));let r=this.knownText(e,n);return ie(r===null?Ce(this.unread(`${t}: text with a part the line does not show`),[e]):s==="ps"?this.nested(r,t):Se(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"&&dt.has(i.n))s+=$e(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:$e(this.sh,l);else return null}}return s}pipedCode(e,t){return _t(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)} ${N(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",ut.test(s)?s:N(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(D(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(Ee(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(Ee(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(Ee(n))}`)):"ps"}}archive(e,t){let s=x(b[e],t.args);if(D(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&&rt.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&&rt.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]===ve?{text:ve}:{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")??We;if(s===void 0)return{text:T([n])||"true"};let r=me(s);return this.setVar(r,fe(n)===null?n:null),{text:`${r}=${n.words.length===0?"":n.words.length===1?z(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=it(n);return t.values.has("argumentlist")&&!(Te.has(r)||Me(r))?{text:this.unread(`New-Object ${n} with arguments`)}:{text:T(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 Ae(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 ss(a){let e=a[0];return e?.t==="var"&&e.n===K}function ft(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 ns(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 ${te(i)}`:`unset "$${K}"`}if(/^(function|alias|variable):/i.test(t))return"true";let n=Fe(a);return n===null?null:`reg delete ${N(n)}`}function Fe(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 Ee(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 it(a){return a.replace(/\s+/g,"").toLowerCase().replace(/^system\./,"")}function Me(a){return/^collections\.(generic\.)?(list|dictionary|hashset|queue|stack|sortedlist|sorteddictionary|arraylist|hashtable|ordereddictionary|specialized\.ordereddictionary)/.test(a)||/^(list|dictionary|hashset)\[/.test(a)}function Ne(a,e){let t=e,s=r=>Q(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 rs(a){return a===""||U(a)||a===`
28
+ `||";)}|,+-*/%.]=><&".includes(a)}function Re(a){return mt([p(a)])}function mt(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 qe(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(Ee(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 Ue(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:$e(e,d)).join("")).filter((h,d)=>d>0||h!=="").join(" "),u=ie(Se(is(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 $e(a,e){return a.marks.push(e),`${J}${a.marks.length-1}${ae}`}function Xe(a,e,t){let s=a.indexOf(ae,e),n=s<0?void 0:t.marks[Number(a.slice(e+1,s))];return n===void 0&&g("a broken marker"),n}function is(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 Se(a,e,t="cmd /c",s=null){He(e,a),++e.depth>be&&oe("nests too deeply");let n=e.unread.length;try{return vt(a,e,s)}catch(r){if(!(r instanceof re)||r.fatal)throw r;return Ze(e,n,`${t}: ${r.why}`)}finally{e.depth--}}function ue(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 as=O({...Ie,homepath:[Z],cd:[L("PWD")]});function gt(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:as[i.toLowerCase()]??[L(te(i))],end:r+1}}function vt(a,e,t=null){let s=new Qe(a,e,t),n=s.list(!1);return s.end(),n}var Qe=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?Lt(this.echoed,this.sh):De(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>be&&oe("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")+kt(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))?De(this.sh,"commands from a file"):this.stdin,h=Ke(t,r,i,this.sh,l,this.loopVar,u);return this.echoed=xe(w(t.word)??"")==="echo"&&i.length===0?ls(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=ke;if(t.text==="exist"){let o=this.nextWord(e);o!==null&&(n=`${s?"! ":""}test -e ${c(ue(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:ie(Se(l[2],this.sh,"for /f"))}]):s?u=c([{t:"sub",code:`cat ${c(ue([p(i.replace(/^"|"$/g,""))],this.sh.drive))}`}]):u=Re(i).map(h=>c(ue(h,this.sh.drive))).join(" ")||"''",`for ${n.toLowerCase()} in ${u}; do ${o}; done`}redirect(e){let t=this.pos,s="";Q(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]==="&"&&Q(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 ne,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=gt(this.src,this.pos,this.loopVar);if(i!==null){s.add(i.word),this.pos=i.end;continue}}if(r===J){s.add([Xe(this.src,this.pos,this.sh)]),this.pos=this.src.indexOf(ae,this.pos)+1;continue}s.text(r),this.pos++}return{word:s.word(),quoted:t}}};function kt(a,e){return a.map(t=>t.target===null?` ${t.op}`:` ${t.op} ${w(t.target)==="/dev/null"?"/dev/null":c(ue(t.target,e.drive))}`).join("")}function os(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 ls(a,e,t){let s=a.replace(/^[\s.:;,=(]/,"").replace(/\s+$/,"");return/^(on|off)$/i.test(s)?"":Je(s,e,t).map(n=>n.t==="lit"?n.s:$e(e,n)).join("")}function Ke(a,e,t,s,n,r,i=null){let o=kt(t,s),l=w(a.word),u=l!==null?xe(l):_e(a.word);if(u===null)return y(`${[c(j),...e.map(v=>c(v.word))].join(" ")}${o}; ${le(s,"a command named by a value the line does not show")}`);let h=l??u,d=u,{opts:f,args:S}=os(e),m=S.map(v=>ue(v,s.drive)),F=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"} ${F(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} ${F(m)}${o}`;let $=m.map(_=>{let he=_[_.length-1],de=he?.t==="lit"?he.s.split(/[\\/]/).pop()??"":"";if(/[*?]/.test(de)||/\.[A-Za-z0-9]+$/.test(de)){let Ye=ft(Ae(_));return`find ${c(Ye.length>0?Ye:[p(".")])} -name ${N(de)} -delete`}return`rm -r${v} ${c(_)}`});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} ${F(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 ${F(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(Ae(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 ${F(m)}${o}`;case"md":case"mkdir":return m.length>0?`mkdir -p ${F(m)}${o}`:`true${o}`;case"dir":return`ls${m.length>0?` ${F(m)}`:""}${o}`;case"echo":{let v=n.replace(/^[\s.:;,=(]/,"").replace(/\s+$/,"");if(/^(on|off)$/i.test(v)&&o==="")return"true";let $=Je(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((he,de)=>de>0?[[p(" ")],he]:[he])),$=w(v),_=$!==null?we($):null;return _!==null?s.drive=_:$===null&&(s.drive=null),`cd ${c(v)}`}case"popd":return s.drive=null,'cd "$OLDPWD"';case"set":return cs(n,s,r)+o;case"start":{let v=e[0]?.quoted?1:0;for(;v<e.length;){let _=w(e[v].word)?.toLowerCase();if(_===void 0||!_.startsWith("/"))break;v+=["/d","/affinity","/node","/machine"].includes(_)?2:1}let $=e[v];return $===void 0?`true${o}`:Ke($,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($)?[N(/[\\/]/.test($)?$.replace(/\\/g,"/"):`./${$}`),...e.slice(1).map(_=>c(_.word))].join(" ")+o:Ke(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 Ue(A,s,i)+o;case"powershell":case"pwsh":return new ye("",s).cli(A,i,d==="pwsh")+o;case"taskkill":return qe(A)+o;case"schtasks":return Be(A,s,v=>et(v,s))+o;case"wmic":return ze(A,s,v=>et(v,s))+o;default:return/\.(bat|cmd)$/i.test(h)?[N(/[\\/]/.test(h)?h.replace(/\\/g,"/"):`./${h}`),...A.map(c)].join(" ")+o:[Pe(h)?N(h.replace(/\\/g,"/")):z([p(d)]),...A.map(c)].join(" ")+o}}function cs(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=te(s.slice(0,i).trim()),l=s.slice(i+1);return n?`export ${o}="$${K}"`:l===""?`unset ${o}`:`export ${o}=${z(Je(l,e,t))}`}function Je(a,e,t){let s=new ne;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=gt(a,n,t);if(i!==null){s.add(i.word),n=i.end;continue}}if(r===J){s.add([Xe(a,n,e)]),n=a.indexOf(ae,n)+1;continue}s.text(r),n++}return s.word()}0&&(module.exports={readCmd,readPowerShell});
@@ -0,0 +1,28 @@
1
+ import{existsSync as Ai,linkSync as Ci,readFileSync as Ri,renameSync as Ni,statSync as Bt,unlinkSync as Wt,writeFileSync as Oi}from"fs";import{homedir as _e,hostname as no}from"os";import{basename as Je,dirname as Z,join as I}from"path";import{fileURLToPath as Ei,pathToFileURL as Pi}from"url";import{createHmac as zo,randomBytes as mt,timingSafeEqual as Ko}from"crypto";import{closeSync as Ln,existsSync as ht,fsyncSync as Dn,linkSync as Jo,mkdirSync as Mn,openSync as Fn,readdirSync as qo,readFileSync as ie,unlinkSync as Hn,writeSync as Wn}from"fs";import{basename as Vo,dirname as Te,join as E}from"path";var v={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"},so="Anvil. Claude Code",K=80,io=11;function B(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${Ze(l)}\x1B[0m`}}var J=B(!1),ao=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function Ze(e){return e.replace(ao,"")}function Yt(e){return Ze(e).length}function Zt(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}\u2026`}function Xt(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 lo(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?Xt(o,t):[o];n.push(...s.slice(0,-1)),r=s[s.length-1]}return r&&n.push(r),n.length>0?n:[""]}function Ae(e,t,n=J){return` ${n.mark(e)} ${t}`}function M(e,t,n=J){return` ${n.dim(e.padEnd(io))}${t}`}function Xe(e,t,n=J,r=K){let o=` ${so} \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 Qe(e=K){return e-7}function Qt(e,t,n=J,r=K,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 xe=Yt(h)>a?Zt(Ze(h),a):h;return` ${i("\u2502")} ${xe}${" ".repeat(Math.max(0,a-Yt(xe)))} ${i("\u2502")}`});return[d,...g,` ${i(`\u2570${"\u2500".repeat(s-2)}\u256F`)}`]}function X(e,t,n,r=J,o=K-7,s=9,a=i=>i){let i=e===null?0:2,l=Math.max(10,o-i-s);return(typeof n=="string"?Xt(n,l):lo(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 co(e,t,n,r=J,o="blue",s=K){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(Zt(n,Math.max(0,c))):""}`}function et(e,t,n=J,r=0,o="Next"){return co(o,e.padEnd(t?r:0),t??"",n,"blue")}var N="claude";function q(e){return e==="ghost"||e==="enforce"?e:null}function Q(e,t){if(!e||typeof e!="object"||e.kill_switch===!0)return"ghost";let n=q(e.services?.[N]?.actions?.[t]?.mode);return n||(q(e.default_mode)??"ghost")}function tt(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[N]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function ee(e){return e==null?!0:typeof e!="object"||e.kill_switch===!0?!1:e.day_one===!0}function tn(e,t,n,r=new Date){let o=e&&typeof e=="object"?e:tt(r);if(n==="all")return{version:1,kill_switch:!1,default_mode:t,services:{[N]:{actions:{}}},updated_at:r.toISOString()};let s={...o.services?.[N]?.actions??{}};for(let a of n)s[a]={mode:t};return{version:1,kill_switch:o.kill_switch===!0,default_mode:q(o.default_mode)??"ghost",services:{...o.services??{},[N]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{}}}function uo(e){return!e||typeof e!="object"||e.kill_switch===!0?!1:q(e.default_mode)==="enforce"?!0:Object.values(e.services?.[N]?.actions??{}).some(t=>q(t?.mode)==="enforce")}var nt="claude.agent.controls";function te(e,t){return t===nt&&uo(e)?"enforce":Q(e,t)}var en={off:0,ghost:1,enforce:2};function fe(e,t){return e===null?t:t===null?e:en[t]>en[e]?t:e}function nn(e,t){return!e||typeof e!="object"?null:q(e.services?.[N]?.actions?.[t]?.mode)??(q(e.default_mode)==="enforce"?"enforce":null)}function rt(e,t,n,r=!1){let s=fe(nn(e,t),n)??(r&&ee(e)?"enforce":te(e,t));return e?.kill_switch===!0&&s==="enforce"?"ghost":s}function rn(e,t,n){return fe(nn(e,t),n)===null&&ee(e)&&te(e,t)!=="enforce"}function _(e){return Object.assign(Object.create(null),e)}var Ce=[{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)"}}],fo="home and project wipes and force-pushes to main",po=`always blocking ${fo}`,ea=new Map(Ce.map(e=>[e.id,e]));var on=new Set(Ce.flatMap(e=>Object.keys(e.slugs)));var sn=_({"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 an(e){let t=new Set(go(e));return Ce.filter(n=>!Object.entries(sn).some(([r,o])=>o.includes(n.id)&&t.has(r)))}var pe=new Set([nt,"claude.bash.secrets.expose"]);function go(e){let t=new Set(e.policies.filter(n=>n.origin==="baseline").flatMap(n=>n.rules.map(r=>r.id)));return Object.keys(sn).filter(n=>!t.has(n))}var F=_({"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"}}),ln={slug:"catastrophic",text:"cluster, cloud and database destroys, and cloud-credential prints"};function cn(e){if(!ee(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 Re=_({"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 Ne(e,t){return e&&Re[e]?Re[e].slug:!e||e==="hold-risky-actions"?F[t]?.slug??t:e.replace(/@.*$/,"")}function Oe(e){return F[e]?.text??e}function un(e){let t=new Set(on);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(Ne(null,o));else t.add(Ne(r.id,""));return t.size}function ot(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 dn(e,t){let n=ot(e).filter(o=>F[o]),r=n.filter(o=>te(t,o)==="enforce");return{enforced:r,text:r.length===0?"ghost":r.length===n.length?"enforce":`${r.length} enforced, rest ghost`}}var st="anvil-claude";function O(e){let t=e.trim();return t===st||t.endsWith(` ${st}`)||t.endsWith(`/${st}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}var fn="\u{1F539}",it=e=>`${fn} ${e} ${fn}`;var pn="anvil";function at(e){pn=typeof e=="string"&&/^[\w@./ -]{1,60}$/.test(e)?e:"anvil"}var $=e=>`${O(pn)} ${e}`;import{spawnSync as oc}from"child_process";import{createHash as ic}from"crypto";import{chmodSync as lc,existsSync as cc,lstatSync as Oo,mkdirSync as uc,readdirSync as dc,readFileSync as Eo,readlinkSync as Po,realpathSync as Cn,rmdirSync as fc,statSync as pt,unlinkSync as pc,writeFileSync as gc}from"fs";import{dirname as Io,join as hc,resolve as jo}from"path";import{createHash as Kl}from"crypto";import{appendFileSync as _o,closeSync as kn,constants as bn,fstatSync as vn,mkdirSync as xo,openSync as $n,readdirSync as ql,readFileSync as So,readSync as _n,renameSync as Ao,statSync as xn,unlinkSync as Vl,writeFileSync as Co}from"fs";import{homedir as Ro}from"os";import{dirname as Zl,join as j}from"path";var gn;var mo="its file (claude-conditions.js) is missing or won't load";function mn(e,t){return gn?gn.capMoved(e,t):`Anvil can't read amounts: ${mo}`}import{existsSync as Aa,readdirSync as Ca,statSync as Ra}from"fs";import{dirname as Oa,isAbsolute as Ea,join as Pa,posix as Ia,resolve as ja}from"path";import{posix as wn}from"path";var ho=null;function Ee(){return ho??process.platform==="win32"}var yn=/^([A-Za-z]):(.*)$/s,yo=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function lt(e,t){let n=wn.normalize(`/${t}`);return n==="/"?e:`${e}${n.replace(/\/$/,"")}`}function ne(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 ct(e){if(!Ee())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(yn.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/${ne(o[1],n).toLowerCase()}${o[2]?`/${ne(o[2],n).toLowerCase()}`:""}`;return lt(l,ne(o[3]??"",n).toLowerCase())}let s=yn.exec(t);if(s){let l=s[2];return l===""?`/${s[1].toLowerCase()}`:l.startsWith("/")?lt(`/${s[1].toLowerCase()}`,ne(l,n).toLowerCase()):null}let a=yo.exec(t);if(a)return lt(`/${a[1].toLowerCase()}`,ne(a[2]??"",n).toLowerCase());let i=ne(t,n).toLowerCase();if(i.startsWith("/")){let l=wn.normalize(i);return l.length>1&&l.endsWith("/")?l.slice(0,-1):l}return i}function wo(e){return ct(e)??e}function ut(e){return!Ee()||typeof e!="string"||e===""?e:wo(e)}import{domainToASCII as Ba}from"url";var Za="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as ml,readdirSync as hl,realpathSync as yl}from"fs";import{basename as bl,dirname as kl,join as vl}from"path";var ft="anvil-claude-compiled/1";function vo(e,t){return!e.applies_to||e.applies_to.length===0||e.applies_to.includes(t)}function ge(e,t){return e.origin!=="project"||!!(t&&e.project_dir&&$o(t,e.project_dir))}function Pe(e,t,n){let r=null;for(let o of e.policies)if(!(o.origin==="baseline"||!ge(o,n))){for(let s of o.rules)s.mode&&vo(s,t)&&(r=fe(r,s.mode));o.off?.includes(t)&&(r=fe(r,"off"))}return r}function $o(e,t){let n=ut(e),r=ut(t),o=r.endsWith("/")?r.slice(0,-1):r;return n===o||n.startsWith(o+"/")}function Sn(e=Ro()){return Ie(j(e,".anvil","claude"))}function Ie(e){return{dir:e,bin:j(e,"bin"),compiled:j(e,"compiled.json"),modes:j(e,"modes.json"),decisions:j(e,"decisions.jsonl"),install:j(e,"install.json"),state:j(e,"state"),approvals:j(e,"approvals"),counts:j(e,"counts"),backups:j(e,"backups")}}var No=3500;function y(e,t=8*1024*1024){try{let n=xn(e);return n.isFile()&&n.size<=t}catch(n){return n.code==="ENOENT"?null:!1}}function dt(e,t=8*1024*1024){let n;try{n=$n(e,bn.O_RDONLY|bn.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=vn(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{kn(n)}}function me(e){try{let t=xn(e);return t.isFile()?t.size:0}catch{return 0}}function An(e,t){let n=t.endsWith(`
2
+ `)?t:`${t}
3
+ `;if(Buffer.byteLength(n)>No)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 S(e){xo(e,{recursive:!0,mode:448})}function T(e,t){if(y(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let n;try{n=$n(e,"r")}catch{return""}try{let r=vn(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{kn(n)}}function A(e,t,n=384){let r=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;Co(r,t,{mode:n}),he(r,e)}function he(e,t){for(let n=0;;n++)try{Ao(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(So(e,"utf8"))}catch{return null}}var Ql=256*1024,ec=1024*1024;var To="/.anvil/claude/bin/claude-hook.js",Lo=/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js/i;var re=class extends Error{constructor(t){super(t),this.name="SettingsRefused"}};function Rn(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 re(`${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 re(`${t} is not a JSON object. Anvil changed nothing.`);return r}function Do(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 Mo=e=>{let t=Do(e);return t!==null&&(t.includes(To)||Lo.test(t))};function Fo(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 Nn(e){return Array.isArray(e.args)?{command:e.command,args:e.args}:e.command}function Ho(e){return dt(e,64*1024*1024)}function On(e){try{if(!Oo(e).isSymbolicLink())return e}catch{return e}try{return Cn(e)}catch(t){let n=t.code;throw n==="ENOENT"?new re(`${e} is a link to ${Wo(e)}, which does not exist. Anvil changed nothing; create that file or remove the link, and run this again.`):new re(`${e} is a link Anvil cannot follow (${n??String(t)}). Anvil changed nothing.`)}}function Wo(e){let t=Io(e);try{t=Cn(t)}catch{}return jo(t,Po(e))}function En(e){try{let t=Ho(On(e));if(t===null)return null;let n=Rn(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(Mo):[]});return r.length===0?null:r.every(o=>o.onFailure==="block")}catch{return null}}function Pn(e,t){let n;try{n=On(e)}catch{return"unreadable"}let r;try{r=pt(n)}catch{return"no-file"}if(!r.isFile()||r.size>4*1024*1024)return"unreadable";let o;try{o=Rn(Eo(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=>Fo(f,t))})?"present":"missing"}function Uo(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 Bo(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 Uo(t)}function gt(e){let t=Bo(e);if(!t)return!1;try{return pt(t[0]).isFile()&&pt(t[1]).isFile()}catch{return!1}}var H="_seal";function Me(e){return E(e.dir,"seal.key")}function se(e,t){return E(e.state,"lkg",t)}function R(e){let t=Me(e);if(y(t,1024)!==!0)return null;try{let n=ie(t,"utf8").trim();return/^[0-9a-f]{64}$/.test(n)?Buffer.from(n,"hex"):null}catch{return null}}function bt(e){return R(e)?"ok":y(Me(e),1024)===null?"missing":"damaged"}var Le=class extends Error{};function Fe(e,t){return`Anvil's seal key (${Me(e)}) is ${t==="damaged"?"damaged":"missing"}`}function Go(e){let t=R(e);if(t)return t;let n=bt(e);if(n==="damaged"||kt(e))throw new Le(`${Fe(e,n)}; run ${$("on")} to restore it`);let{key:r,created:o}=Yo(e,!1);return o&&Zo(e,r),r}function In(e,t,n){let r=Fn(e,n,384);try{Wn(r,t),Dn(r)}finally{Ln(r)}}function Yo(e,t){Mn(e.dir,{recursive:!0,mode:448});let n=Me(e),r=E(e.dir,`.seal.key.${process.pid}.${mt(4).toString("hex")}.tmp`);In(r,`${mt(32).toString("hex")}
5
+ `,"wx");let o=!1;try{t?he(r,n):Jo(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{In(n,ie(r,"utf8"),"wx"),o=!0}catch(l){if(l.code!=="EEXIST")throw l}}}finally{try{Hn(r)}catch{}}let s=R(e);if(!s)throw new Le(`${Fe(e,"damaged")}; run ${$("on")} to restore it`);return{key:s,created:o}}function Zo(e,t){let n=[[e.modes,ye],[e.compiled,zn],[e.install,void 0]];for(let[r,o]of n)if(y(r,8*1024*1024)===!0)try{let s=ie(r,"utf8");if(s.includes(`"${H}"`))continue;let a=JSON.parse(s);if(!a||typeof a!="object"||Array.isArray(a))continue;let i=`${JSON.stringify(wt(t,a),null,2)}
6
+ `;oe(r,i),o&&oe(se(e,o),i)}catch{}if(y(e.modes)===null&&y(se(e,ye))===null){let r=`${JSON.stringify(wt(t,tt()),null,2)}
7
+ `;oe(e.modes,r),oe(se(e,ye),r)}}function yt(e,t=0){if(t>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(n=>yt(n===void 0?null:n,t+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(r=>!(t===0&&r===H)&&e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${yt(e[r],t+1)}`).join(",")}}`:JSON.stringify(e??null)}function Un(e,t){return zo("sha256",e).update(yt(t)).digest("hex")}function je(e){if(!(H in e))return e;let t={...e};return delete t[H],t}function wt(e,t){let n=je(t);return{...n,[H]:Un(e,n)}}function Xo(e,t){let n=t[H];if(typeof n!="string"||!/^[0-9a-f]{64}$/.test(n))return!1;let r;try{r=Un(e,t)}catch{return!1}return Ko(Buffer.from(n,"hex"),Buffer.from(r,"hex"))}function oe(e,t,n=384){Mn(Te(e),{recursive:!0,mode:448});let r=E(Te(e),`.${Vo(e)}.${process.pid}.${Date.now().toString(36)}.${mt(3).toString("hex")}.tmp`);try{let o=Fn(r,"w",n);try{Wn(o,t),Dn(o)}finally{Ln(o)}he(r,e)}catch(o){try{Hn(r)}catch{}throw o}}function C(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(ie(e,"utf8"))}catch{return{status:"unreadable"}}return!o||typeof o!="object"||Array.isArray(o)?{status:"unreadable"}:t?H in o?Xo(t,o)?{status:"ok",value:je(o)}:{status:"changed",value:je(o)}:{status:"unsealed",value:o}:{status:"unkeyed",value:je(o)}}function Bn(e,t,n,r){let o=Go(e),s=`${JSON.stringify(wt(o,n),null,2)}
8
+ `;oe(t,s),r&&oe(se(e,r),s)}var ye="modes.json",zn="compiled.json";function Kn(e,t){Bn(e,e.modes,t,ye)}function kt(e){return ht(E(e.bin,"claude-hook.sh"))||Qo(e)}function Qo(e){let t=n=>{try{return qo(n).slice(0,200).some(r=>r.endsWith(".json")&&y(E(n,r),65536)===!0&&ie(E(n,r),"utf8").includes(`"${H}"`))}catch{return!1}};if(t(E(e.state,"lkg"))||t(E(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(ie(n,"utf8").includes(`"${H}"`))return!0}catch{}return!1}var De=_({missing:"is missing",unreadable:"cannot be read",unsealed:"was changed outside Anvil",changed:"was changed outside Anvil"});function jn(e=new Date){return tn(null,"enforce","all",e)}function V(e,t=R(e),n={}){if(!t){let a=bt(e);if(n.installed===!0||a==="damaged"||kt(e))return{value:jn(),source:"strict",problem:`${Fe(e,a)}, so every rule is enforced until \`${$("on")}\` restores it`};let i=C(e.modes,null);return{value:i.status==="unkeyed"?i.value:null,source:"unkeyed",problem:null}}let r=C(e.modes,t);if(r.status==="ok")return{value:r.value,source:"file",problem:null};let o=`modes.json ${De[r.status]??"cannot be used"}`,s=C(se(e,ye),t);return s.status==="ok"?{value:s.value,source:"last-good",problem:`${o}; Anvil keeps the modes it last set`}:{value:jn(),source:"strict",problem:`${o}, and so is Anvil's own copy, so every rule is enforced until \`${$("on")}\` resets it`}}function G(e,t,n=R(e),r={}){let o=c=>!!c&&typeof c=="object"&&c.format===ft&&Array.isArray(c.policies),s=()=>{if(!t)return null;let c=C(t,null);return c.status==="unkeyed"&&o(c.value)?c.value:null};if(!n){let c=bt(e),f=r.installed===!0||c==="damaged"||kt(e),u=C(e.compiled,null),d=u.status==="unkeyed"&&o(u.value)?u.value:null;return f?{value:null,source:"strict",problem:`${Fe(e,c)}: \`${$("on")}\` restores it`}:{value:d??s(),source:"unkeyed",problem:null}}let a=C(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":De[a.status]??"cannot be used"}`,l=C(se(e,zn),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 Tn(e,t){return t&&(e===t||e.startsWith(`${t}/`))?`~${e.slice(t.length)}`:e}function He(e,t,n,r=!0){let o=C(e.install,t,4194304);if(o.status==="missing")return[];if(o.status==="unreadable")return[`install.json ${De.unreadable}`];if(t&&o.status!=="ok")return[`install.json ${De[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=Pn(u.settings_path??u.real_path,Nn(u)),g=Tn(u.settings_path??u.real_path,n);d!=="present"&&(d==="no-file"&&u.scope==="project"&&!ht(Te(Te(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=>!ht(E(u,"package.json")))&&a.push(`the Anvil package that installed this hook is gone (${Tn(c,n)}): keep Anvil with ${O(f)} on, or remove it with ${O(f)} off --purge`),a}function es(e){return E(e.state,"health.json")}function We(e){let t=C(es(e),null,65536);return t.status==="unkeyed"&&t.value.v===1&&Array.isArray(t.value.problems)?t.value:null}import{accessSync as Yn,constants as Zn,existsSync as $t,statfsSync as ts}from"fs";import{createHash as Ic,randomBytes as jc}from"crypto";import{readdirSync as qn,renameSync as Lc,unlinkSync as Dc}from"fs";import{join as vt}from"path";var Wc=600*1e3,Uc=1440*60*1e3;function Jn(e){return vt(e.state,"pending")}function Vn(e,t,n){let r=[];try{r=qn(Jn(e)).filter(s=>s.endsWith(".json")).slice(0,2e3)}catch{return[]}let o=[];for(let s of r){let a=vt(Jn(e),s),i=C(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 Gn(e,t){let n=[];try{n=qn(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=C(vt(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 Xn(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"||En(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{$t(e.decisions)?Yn(e.decisions,Zn.W_OK):$t(e.dir)&&Yn(e.dir,Zn.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=ts($t(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?Gn(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 Zc}from"child_process";import{readFileSync as Qc,statSync as eu}from"fs";import{join as ns}from"path";var Qn="sync-next",er="sync-pulled";var ru=5*6e4;function tr(e,t){return e.ANVIL_WORKSPACE_KEYS_PATH?.trim()||ns(t,".anvil","workspace-keys.json")}var ou=10*6e4;import{join as Tt}from"path";import{closeSync as rs,constants as nr,fstatSync as os,openSync as ss,readdirSync as is,readSync as as,unlinkSync as ls}from"fs";import{join as rr}from"path";var cs=9,or=4*1024*1024;function us(e){let t;try{t=ss(e,nr.O_RDONLY|nr.O_NONBLOCK)}catch(n){if(n.code==="ENOENT")return"";throw n}try{let n=os(t);if(!n.isFile())throw new Error("the day's cap count is not a regular file");if(n.size>or)throw new Error(`the day's cap count is over ${or/1024/1024} MB`);let r=Buffer.alloc(n.size),o=0;for(;o<n.size;){let s=as(t,r,o,n.size-o,o);if(s===0)break;o+=s}return r.subarray(0,o).toString("utf8")}finally{rs(t)}}function we(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 ir(e,t){if(e.window==="minute"||e.window==="hour")return t;let n=new Date(we(e,t));return n.setDate(n.getDate()+(e.window==="week"?7:1)),n.getTime()}var sr=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`};var Ue=class extends Error{};function xt(e,t){return e.unit==="money"&&e.money?ds(t,e.money):`${e.unit==="usd"?"$":""}${Math.round(t*100)/100}`}function ds(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 ar(e,t,n=null){if(e.unit==="money"){let s=mn(e,n);if(typeof s=="string")throw new Ue(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 fs(e,t,n){try{return ar(e,t,n)}catch(r){if(r instanceof Ue)return e.limit;throw r}}var Be=class{constructor(t){this.dir=t}file(t){return rr(this.dir,`${sr(t)}.log`)}write(t){S(this.dir),An(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 us(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=we(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=>ar(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=>we(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:fs(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(we(t,n),n),t,n)}resolve(t,n){let r=new Set(t.map(i=>i.id)),o=Math.min(...t.map(i=>we(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=St(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=sr(t-cs*864e5);for(let r of is(this.dir))/^\d{4}-\d{2}-\d{2}\.log$/.test(r)&&r.slice(0,10)<n&&ls(rr(this.dir,r))}catch{}}};function St(e,t){return!e||!t?null:ps(T(e,4*1024*1024),t)}function ps(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 ce}from"crypto";import{closeSync as be,constants as gr,fstatSync as Os,mkdirSync as Es,openSync as xr,readdirSync as Ps,readSync as Ot,statSync as Is,unlinkSync as mr}from"fs";import{join as L}from"path";var gs="https://api.anvilcontrol.ai";function At(e=process.env){let t=e.ANVIL_HOSTED_API_URL?.trim();return(t&&t.length>0?t:gs).replace(/\/+$/,"")}import{chmodSync as mu,mkdirSync as hu,readFileSync as ms,writeFileSync as yu}from"fs";import{homedir as hs}from"os";import{dirname as ku,join as ys}from"path";function ws(){return process.env.ANVIL_WORKSPACE_KEYS_PATH?.trim()||ys(hs(),".anvil","workspace-keys.json")}function bs(e=ws()){let t;try{t=JSON.parse(ms(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 ks=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 Ct(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function vs(e){let t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return Ct(e)||"workspace";let n=e.slice(0,t),o=e.slice(t+1).split(".")[0]??"",s=ks.has(o.toLowerCase())?n:o;return Ct(s)||Ct(n)||"workspace"}function $s(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 lr(e){let n=Object.entries(bs(e)).find(([,s])=>s.active===!0);if(!n)return null;let[r,o]=n;return{email:r,workspace:vs(r),apiKey:o.apiKey,...o.apiBaseUrl?{apiBaseUrl:o.apiBaseUrl}:{},keyAgeDays:$s(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 xs}from"fs";import{join as cr}from"path";var Ss=["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"],As=/^claude\.[a-z0-9_]+(?:\.[a-z0-9_]+)*$/,Cs=new Set(["hook-removed","hooks-disabled","settings-unreadable","no-node","classifier-missing","rules-missing"]),Rs=[[/^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 ur(e){for(let[t,n]of Rs)if(t.test(e))return n;return"other"}var Ns=1440*60*1e3;function dr(e){let t=Date.parse(e.trim());return Number.isFinite(t)?t:null}function fr(e){let{paths:t,now:n}=e,r=new Set,o=d=>{d&&r.add(ur(d))},s=null;try{s=R(t)}catch{s=null}let a={};try{let d=V(t,s);o(d.problem);for(let g of e.kinds.slice(0,64))g.length<=200&&As.test(g)&&(a[g]=pe.has(g)?"enforce":te(d.value,g))}catch{}try{let d=G(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 He(t,s,e.home))o(d)}catch{}let l=e.hookBin??(i?t.bin:void 0);l&&y(cr(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,xs.W_OK)}catch{(y(t.dir,Number.MAX_SAFE_INTEGER)!==null||i)&&r.add("spool-unwritable")}let c=null;try{let d=We(t),g=d?dr(d.at):null;if(d&&g!==null&&(c=g,n-g<Ns))for(let h of d.problems)ur(h)==="node-fallback"&&r.add("node-fallback")}catch{}let f=dr(T(cr(t.state,"no-node"),64));f!==null&&(c===null||f>c)&&(r.add("no-node"),c=f);let u=Ss.filter(d=>r.has(d));return{modes:a,ok:!u.some(d=>Cs.has(d)),problems:u,hook_checked_at:c===null?null:new Date(c).toISOString()}}function pr(){try{return/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]{1,20})?$/.test("0.8.1")?"0.8.1":null}catch{return null}}var js=50,Ts=50,Ls=1e4,ke=512*1024,Nt=30*6e4,Ds="/v1/claude-code/machine",Sr=360*6e4,Ms=_({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 Ke(e,t){let n=null;try{let s=tr(e,t);y(s,1024*1024)===!0&&(n=lr(s))}catch{n=null}if(n?.apiKey){let s=n.workspaceId?`ws:${ce("sha256").update(n.workspaceId).digest("hex").slice(0,12)}`:yr(n.apiKey);return{apiKey:n.apiKey,baseUrl:hr(n.apiBaseUrl||At(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:hr(o||At(e)),id:yr(r),linkedAt:null,source:"env"}:null}function hr(e){return e.replace(/\/+$/,"")}function yr(e){return`sha256:${ce("sha256").update(e).digest("hex").slice(0,12)}`}function wr(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 Fs(e){return L(e.dir,"machine.json")}function Et(e,t){let n=b(Fs(e))?.label;return wr(typeof n=="string"&&n?n:t)}var ae=e=>typeof e=="string"&&e.length>0?e:null;function Hs(e,t){return e===null||e==="hold-risky-actions"||Re[e]?Ne(e,t):"your-rule"}function Ws(e){if(!e)return"none";let t=e.replace(/-/g,"").toLowerCase();return/^[a-f0-9]{8,}$/.test(t)?t.slice(0,8):ce("sha256").update(e).digest("hex").slice(0,8)}function Ar(e,t){let n;try{n=JSON.parse(e)}catch{return null}if(!n||typeof n!="object"||n.v!==1)return null;let r=ae(n.action),o=n.verdict,s=n.mode,a=ae(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=Ms[ae(n.blocked_by)??""];if(!i)return null;let l=s==="ghost"?"would_block":o==="hold"?"held":"blocked",f=ae(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}/${Ws(ae(n.session))}/${ce("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 ${Oe(r)}`,rule_id:Hs(ae(n.rule),r),decided_at:new Date(Date.parse(a)).toISOString(),duration_ms:Math.min(u,6e5)}}function br(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 Cr(e,t){return L(e.state,"sync",`${ce("sha256").update(t).digest("hex").slice(0,16)}.json`)}function Rr(e){return L(e.state,"signed-out.json")}function ze(e){let t=b(Rr(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 Nr(e,t,n,r){S(e.state);let o=n.filter(s=>r-Date.parse(s[1])<400*864e5).slice(-500);A(Rr(e),`${JSON.stringify(t!==null?{open:t,windows:o}:{windows:o})}
13
+ `)}function Or(e,t){try{let n=ze(e);n.open===null&&Nr(e,new Date(t).toISOString(),n.windows,t)}catch{}}function Us(e,t){try{let n=ze(e);n.open!==null&&Date.parse(n.open)<=t&&Nr(e,null,[...n.windows,[n.open,new Date(t).toISOString()]],t)}catch{}}function Er(e){let t=[];try{t=Ps(L(e.state,"sync")).filter(n=>n.endsWith(".json"))}catch{return null}for(let n of t){let r=b(L(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 $e(e,t,n=Date.now()){let r=b(Cr(e,t));if(!r||r.v!==2||r.identity!==t)return br(t);let o={...br(t),...r,v:2,identity:t},s=Number.isFinite(o.next_try_at)?Math.min(o.next_try_at,n+Nt):0,a=typeof o.report_next_at=="number"&&Number.isFinite(o.report_next_at)?Math.min(o.report_next_at,n+Sr):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 Bs(e,t){let n=Cr(e,t.identity);Es(L(e.state,"sync"),{recursive:!0,mode:448}),A(n,`${JSON.stringify(t,null,2)}
14
+ `)}function Pt(e){return L(e.state,"mode-pending.json")}function zs(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 le(e){let t=b(Pt(e));return{v:2,changes:Array.isArray(t?.changes)?t.changes.filter(zs):[]}}var Y=e=>`${e.identity}|${e.action}|${e.at}`;function Pr(e,t){S(e.state);let n=L(e.state,"mode-pending.lock"),r=!1;for(let o=0;o<40&&!r;o++)try{be(xr(n,"wx",384)),r=!0}catch{try{Date.now()-Is(n).mtimeMs>1e4&&mr(n)}catch{}let s=Date.now()+25;for(;Date.now()<s;);}try{return t()}finally{if(r)try{mr(n)}catch{}}}function Ks(e,t){t.length!==0&&Pr(e,()=>{let n=le(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)));A(Pt(e),`${JSON.stringify({v:2,changes:[...s,...o]},null,2)}
15
+ `)})}function Js(e,t){t.size!==0&&Pr(e,()=>{let n=le(e).changes.filter(r=>!t.has(Y(r)));A(Pt(e),`${JSON.stringify({v:2,changes:n},null,2)}
16
+ `)})}function qs(e){if(!/^[\x21-\x7e]+$/.test(e.apiKey))return"the key has characters no key has";let t;try{t=new URL(e.baseUrl)}catch{return"the workspace address isn't a URL"}if(t.username||t.password)return"the workspace address carries a password";let n=["localhost","127.0.0.1","[::1]"].includes(t.hostname)||t.hostname.endsWith(".localhost")||t.hostname.endsWith(".test");return t.protocol!=="https:"&&!(t.protocol==="http:"&&n)?"the workspace address isn't https":null}function Vs(e){if(e instanceof Error&&e.name==="TimeoutError")return"timed out";let t=e?.cause?.code;return typeof t=="string"&&/^[A-Z][A-Z0-9_]{1,40}$/.test(t)?t:"no answer"}async function ve(e,t,n,r,o){let s=qs(t);if(s)return{status:0,body:null,retryAfterMs:null,error:s};try{let a=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??Ls)}),i=await a.text().catch(()=>""),l=null;try{l=i?JSON.parse(i):null}catch{l=null}let c=Number(a.headers.get("retry-after"));return{status:a.status,body:l,retryAfterMs:Number.isFinite(c)&&c>0?c*1e3:null,error:null}}catch(a){return{status:0,body:null,retryAfterMs:null,error:Vs(a)}}}function W(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 Gs(e){return e?ot(e).filter(t=>t.startsWith("claude.")).sort().slice(0,Ts):[]}async function kr(e,t,n,r,o=!1){return ve(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 Ys(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 vr(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 Zs(e){return e.status===0||e.status===401||e.status===403||e.status===429||e.status>=500}var $r={linked:!1,sent:0,rejected:0,waiting:0,modesPulled:!1,modesChanged:!1,error:null};async function It(e){if(!e.identity)return $r;try{return await Xs(e,e.identity)}catch(t){return{...$r,linked:!0,error:`the sync failed: ${t instanceof Error?t.message:String(t)}`}}}async function Xs(e,t){let{paths:n}=e,r=e.now(),o=$e(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=L(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){S(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;A(a,`${JSON.stringify({id:t.id,at:p})}
17
+ `)}o={...o,source:t.source};let u=ze(n);c!==null&&u.open!==null&&Date.parse(u.open)<=Date.parse(c)&&Us(n,Date.parse(c));for(let p of ze(n).windows)o.skip.some(x=>x[0]===p[0]&&x[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=Gs(G(n,e.fallbackTable).value),h=[],m=null,xe=le(n).changes,Se=o.registered?g.filter(p=>!o.registered_kinds.includes(p)):g,z=null;if(g.length>0&&(Se.length>0||xe.length>0)){let p=await ve(e,t,"GET",`/v1/modes?actions=${g.map(encodeURIComponent).join(",")}`);z=vr(p),z||(m=p)}if(!m&&z&&Se.length>0){let p=V(n).value,x=!o.registered&&p!==null&&p.source!=="workspace"?g.filter(k=>Q(p,k)==="enforce"&&z.get(k)?.effective!=="enforce"):[];Ks(n,x.map(k=>({action:k,mode:"enforce",at:new Date(r).toISOString(),identity:t.id,from:z.get(k)?.effective??null,origin:"link"})));let w=null;await Ys(Se.filter(k=>!x.includes(k)&&!z.get(k)?.explicit),4,async k=>{let de=await kr(e,t,k,"ghost",!0);return de.status>=200&&de.status<300?!0:(w??=de,!1)})?o={...o,registered:!0,registered_kinds:[...new Set([...o.registered_kinds,...Se])]}:w&&Zs(w)?m=w:w&&h.push(`could not register the kinds of action yet (${W(w,t,e.cli)})`)}let zt=le(n).changes;if(!m&&zt.length>0){let p=new Set,x=[];for(let w of zt){if(w.identity!==t.id){p.add(Y(w)),h.push("a mode change made under another account was not sent to this one");continue}if(m)break;if(!le(n).changes.some(de=>Y(de)===Y(w)))continue;let Ye=z?.get(w.action);if(w.from!==null&&Ye&&Ye.effective!==w.from){p.add(Y(w)),h.push(`your workspace changed ${w.action} after you set it offline, so its mode stands`);continue}let k=await kr(e,t,w.action,w.mode);k.status>=200&&k.status<300?(p.add(Y(w)),w.origin==="link"&&x.push(w.action)):k.status===400||k.status===422?(p.add(Y(w)),h.push(`the workspace refused a mode change for ${w.action} (${W(k,t,e.cli)})`)):m=k}Js(n,p),x.length>0&&h.push(`at sign-in, this machine's enforce for ${x.length===1?Oe(x[0]):`${x.length} kinds of action`} went to your workspace`)}let Ve=!1,Kt=!1,Jt=()=>le(n).changes.some(p=>p.identity===t.id);if(!m&&g.length>0&&!Jt()){let p=await ve(e,t,"GET",`/v1/modes?actions=${g.map(encodeURIComponent).join(",")}`);vr(p)?Jt()||(Ve=!0,Kt=ri(n,p.body.modes,new Date(r)),o={...o,last_pull_ok:new Date(r).toISOString()},Qs(n,r)):m=p}let Ge=m!==null&&(m.status===0||m.status===401||m.status===403);!Ge&&r>=o.report_next_at&&(o=await ei(e,t,o,g,Ve,r,h));let qt=0,Vt=0,Gt=null;if(!d&&!Ge){let p=await ni(e,t,o,r);o=p.state,qt=p.sent,Vt=p.rejected,Gt=p.failed}let U=Gt??(Ge&&!d?m:null);if(U){let p=o.failures+1,x=U.status===429&&U.retryAfterMs?Math.min(U.retryAfterMs,Nt):U.status===0?6e4:Math.min(6e4*2**(p-1),Nt);o={...o,failures:p,last_error:W(U,t,e.cli),next_try_at:r+x}}else d?m&&(o={...o,last_error:W(m,t,e.cli)}):o={...o,failures:0,last_error:m?W(m,t,e.cli):null,next_try_at:0};let oo=U?W(U,t,e.cli):m?W(m,t,e.cli):d?o.last_error:null;return h.length>0&&(o={...o,last_note:h[h.length-1]}),Bs(n,o),{linked:!0,sent:qt,rejected:Vt,waiting:jt(n,o,e.machine),modesPulled:Ve,modesChanged:Kt,error:oo}}function Qs(e,t){try{S(e.state),A(L(e.state,er),String(t))}catch{}}async function ei(e,t,n,r,o,s,a){let i;try{i=fr({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 ve(e,t,"POST",Ds,{machine:e.machine,version:pr(),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+Sr}:((l.status===400||l.status===422)&&a.push(`the workspace refused this machine's health report (${W(l,t,e.cli)})`),n)}function Rt(e){let t;try{t=xr(e,gr.O_RDONLY|gr.O_NONBLOCK)}catch{return null}try{let n=Os(t);if(n.isFile())return{fd:t,ino:n.ino,size:n.size}}catch{}return be(t),null}function Ir(e,t){let n=Rt(e.decisions);if(t.ino!==0){if(n&&n.ino===t.ino&&n.size>=t.offset)return[{...n,start:t.offset}];let a=Rt(`${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&&be(a.fd)}let r=Rt(`${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&&be(r.fd),[{...n,start:s}]):[...r?[{...r,start:0}]:[],...n?[{...n,start:0}]:[]]}function jr(e){for(let t of e)try{be(t.fd)}catch{}}function _r(e,t,n){let r=0,o=Buffer.alloc(0);for(;r<t;){let s=Math.min(ke,t-r),a=Buffer.alloc(s);Ot(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(Tr(i.toString("utf8",c,f))===n)return l+f+1;c=f+1}o=i.subarray(c),o.length>4*ke&&(o=Buffer.alloc(0)),r+=s}return null}function Tr(e){return ce("sha256").update(e).digest("hex").slice(0,16)}function ti(e,t,n){for(let r=t;r<n;){let o=Math.min(ke,n-r),s=Buffer.alloc(o);Ot(e,s,0,o,r);let a=s.indexOf(10);if(a>=0)return r+a+1;r+=o}return null}function Lr(e,t,n){let r=Math.min(ke,n-t);if(r<=0)return{lines:[],skipTo:null};let o=Buffer.alloc(r);Ot(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===ke?ti(e,t+r,n):null}}function Dr(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 ni(e,t,n,r){let o=n;r-o.window_start>=6e4&&(o={...o,window_start:r,window_sent:0});let s=Ir(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}=Lr(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=Dr(g.text,o)?Ar(g.text,e.machine):null;if(h){if(o.window_sent>=js)break e;let m=await ve(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: ${W(m,t,e.cli)}`};else{l=m;break e}}o={...o,offset:g.end,last_hash:Tr(g.text)}}f=u[u.length-1].end}}}finally{jr(s)}return{state:o,sent:a,rejected:i,failed:l}}function jt(e,t,n){let r=Ir(e,t);try{let o=0;for(let s of r)o+=Lr(s.fd,s.start,s.size).lines.filter(a=>Dr(a.text,t)&&Ar(a.text,n)!==null).length;return o}finally{jr(r)}}function ri(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=V(e),s=o.value,a=new Set([...Object.keys(r),...Object.keys(s?.services?.[N]?.actions??{}),...Object.keys(F)]),i=o.source==="strict"||ee(s)||s?.day_one===!0,l={version:1,kill_switch:!1,default_mode:"ghost",services:{[N]:{actions:r}},updated_at:n.toISOString(),source:"workspace",...i?{day_one:!0}:{}},c=[...a].some(f=>Q(s,f)!==Q(l,f))||s?.source!=="workspace"||s?.day_one===!0!==i;return(c||o.source!=="file")&&Kn(e,l),c}var P=e=>e.toLocaleString("en-US");function Lt(e,t){let n=[],r=`${T(`${e.decisions}.1`,2097152)}
18
+ ${T(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 oi(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 si(e,t,n,r,o,s=B(!1),a=i=>`${o} ${i}`){if(!t)return Er(e)!==null?M("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):M("Dashboard",`${a("login")} ${s.dim("see every session in one place (optional)")}`,s);let i=$e(e,t.id,r.getTime()),l=i.since===null?0:jt(e,i,n),c=oi(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(`${P(l)} ${l===1?"stop":"stops"} waiting to send`),i.last_error?f.push(i.last_error):i.last_note&&f.push(i.last_note),M("Dashboard",f.join(" \xB7 "),s)}var ii="what every Claude Code session spends",Mr=e=>e.split(/, and |; /).map(t=>t.trim()).filter(Boolean);function ai(e,t=B(!1),n=Qe()){let r=i=>F[i]?.text??i,o=[...e.floor.filter(i=>i.verdict==="block").flatMap(i=>Mr(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?Mr(ln.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?X(v.blocked,"Blocks",o,t,n):[],...s.length>0?X(v.held,"Holds",s,t,n):[],...X(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?X(" ","Off",e.off.map(i=>F[i]?.slug??i),t,n,9,t.dim):[],...e.spend!==void 0?X(v.watching,"Counts",`${ii}${e.spend?` \xB7 ${e.spend}`:""}`,t,n,9,t.dim):[]]}function li(e,t=B(!1),n=K,r=[],o="What it does now"){return Qt(o,[...ai(e,t,Qe(n)),...r],t,n)}function ci(e,t){let n=new Set;for(let r of e?.policies??[])if(!(r.origin==="baseline"||!ge(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 Fr=Object.keys(F).filter(e=>!["claude.bash.unclassified","claude.tool.other","claude.mcp.call","claude.agent.helper"].includes(e)&&!pe.has(e));function ui(e,t,n){return Fr.filter(r=>rt(t,r,e?Pe(e,r,n):null)==="enforce")}function di(e,t,n){return Fr.filter(r=>rt(t,r,e?Pe(e,r,n):null)==="off")}var fi=["claude.bash.deploy","claude.bash.db.destructive","claude.bash.secrets.print","claude.bash.fs.delete_recursive"];function pi(e,t){return t&&!fi.some(n=>rn(e,n,Pe(t,n,null)))?null:cn(e)}function gi(e,t,n){let r=e.filter(o=>o.floor).length;return`stopped ${P(e.length)}${r?` (${P(r)} always on)`:""}${t?` \xB7 allowed once ${P(t)}`:""}${n?` \xB7 declined ${P(n)}`:""} \xB7 ${Hr(e)}`}function Hr(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} ${P(r)}`).join(" \xB7 ")}function mi(e,t){return e.window==="minute"||e.window==="hour"?"rolling":e.window==="day"?"resets at midnight":`resets ${new Date(ir(e,t.getTime())).toLocaleDateString("en-US",{weekday:"long"})}`}function hi(e,t,n,r=B(!1),o=null){let s=(e?.policies??[]).filter(i=>ge(i,o)).flatMap(i=>i.caps??[]);if(s.length===0)return[];let a=new Be(Tt(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 ${mi(i,n)}`;return M(l===0?"Caps":"",`${i.text} \xB7 ${c===null?"can't be counted now: its calls are held":`${xt(i,c)} of ${xt(i,i.limit)} used`}${f}${i.unit!=="calls"&&i.unit!=="money"?" \xB7 an estimate":""}`,r)})}function Wr(e,t,n,r="anvil",o=null){if(n)return`${it("Anvil isn't working")} run in a terminal: ${O(r)} on`;let s=t.toISOString().slice(0,10),a=me(Tt(e.counts,s)),i=`${T(`${e.decisions}.1`,2*1024*1024)}
20
+ ${T(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=Vn(e,R(e),t.getTime()).length}catch{c=0}let f=[...a>0?[`${P(a)} checked`]:[],...l>0?[`${P(l)} stopped`]:[],...o?.today?[o.text]:[]],u=[...f.length>0?[`${f.join(" \xB7 ")} today`]:[],...o&&!o.today?[o.text]:[],...c>0?[`${P(c)} waiting for your OK \xB7 in a terminal: ${O(r)} allow`]:[]];return[it("Anvil on"),...u.length>0?[u.join(" \xB7 ")]:[]].join(" ")}function yi(e,t,n=B(!1)){let r=t.toISOString().slice(0,10),o=me(Tt(e.counts,r)),s=Lt(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=>St(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=[`${P(o)} ${o===1?"action":"actions"} checked`];return i.length>0&&u.push(gi(i,c,f)),a.length>0&&u.push(`would have stopped ${P(a.length)} \xB7 ${Hr(a)}`),i.length===0&&a.length===0&&u.push("nothing it would stop"),M("Today",u.join(" \xB7 "),n)}function Ur(e){let t=B(!1);if(!e.table)return[Xe("Report","not checking",t),"",Ae(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=>M("Problem",s)),...(e.problems??[]).length>0?[""]:[],et(`${O(e.cli)} on`,e.installed?"fix it, in your own terminal":"turn it on")];let{text:n}=dn(e.table,e.modes),r=ui(e.table,e.modes,null),o=e.problems??[];return[Xe("Report",o.length>0?"on, with a problem":"on",t),"",o.length>0?Ae(v.problem,"On, with a problem"):Ae(v.on,"On. Every action Claude Code takes is checked before it runs."),"",...o.map(s=>M("Problem",s)),...o.length>0?[""]:[],...li({floor:an(e.table),held:r,blocking:ci(e.table,null),off:di(e.table,e.modes,null),dayOne:pi(e.modes,e.table)!==null,all:n==="enforce"?r.length:Number.POSITIVE_INFINITY,spend:null},t),"",M("Rules",String(un(e.table))),...hi(e.table,e.paths,e.now),yi(e.paths,e.now),si(e.paths,e.identity,e.machine,e.now,e.cli),"",et(`${O(e.cli)} rules edit`,"change rules, in your terminal")]}import{randomUUID as bi}from"crypto";import{existsSync as Jr,mkdirSync as qr,readFileSync as Vr,writeFileSync as ki}from"fs";import{join as ue}from"path";import{existsSync as cd,mkdirSync as ud,readFileSync as dd,writeFileSync as fd}from"fs";import{homedir as gd}from"os";import{join as hd}from"path";import{randomUUID as wd}from"crypto";var wi="https://app.anvilcontrol.ai";function Dt(e=process.env){let t=e.ANVIL_HOSTED_DASHBOARD_URL?.trim();return(t&&t.length>0?t:wi).replace(/\/+$/,"")}import{lookup as sd}from"dns/promises";function Mt(){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 Br(e,t,n,r){try{if(Mt()||!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 zr={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 vi=["CI","GITHUB_ACTIONS","GITLAB_CI","BUILDKITE","CIRCLECI","TF_BUILD","JENKINS_URL","TEAMCITY_VERSION"],Ft=e=>e!==void 0&&e.trim()!==""&&!/^(0|false|no|off)$/i.test(e.trim());function Gr(e){return Ft(e.DO_NOT_TRACK)||Ft(e.ANVIL_FUNNEL_DISABLED)?!1:!vi.some(t=>Ft(e[t]))}function Yr(e){return ue(e,".anvil","telemetry-notice")}function Zr(e){return Jr(Yr(e))}function $i(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 _i(e){let t=ue(e,".anvil","claude","telemetry-id");try{let r=Vr(t,"utf8").trim();if(/^c_[a-f0-9]{32}$/.test(r))return r}catch{}let n=`c_${bi().replace(/-/g,"")}`;try{qr(ue(e,".anvil","claude"),{recursive:!0,mode:448}),ki(t,`${n}
22
+ `,{mode:384})}catch{}return n}async function xi(e,t,n,r){try{if(!Gr(n)||Mt()||!Zr(r)||!zr[e].every(o=>o in t)||Object.keys(t).some(o=>!zr[e].includes(o)))return;await Br(e,Dt(n),_i(r),t)}catch{}}function Kr(e){return ue(e.state,"telemetry.json")}function Si(e,t){let n=me(ue(e.counts,t)),r=Date.parse(`${t}T00:00:00.000Z`),o=r+864e5,s=Lt(e,r).filter(i=>i.ts&&Date.parse(i.ts)<o),a=i=>s.filter(i).length;return{day:t,calls:$i(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 Xr(e,t,n,r){if(!Gr(t)||!Zr(n))return 0;let o=r.toISOString().slice(0,10),s=b(Kr(e))?.last_daily??null,a="";try{a=new Date(Date.parse(Vr(Yr(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||Jr(ue(e.counts,c))&&i.push(c)}if(i.length===0)return 0;try{qr(e.state,{recursive:!0}),A(Kr(e),`${JSON.stringify({last_daily:i[i.length-1]})}
23
+ `)}catch{return 0}return await Promise.all(i.map(l=>xi("decisions_daily",Si(e,l),t,n))),i.length}var D=Z(Ei(import.meta.url)),Ut=Je(D)==="bin"&&Je(Z(D))==="claude"&&Je(Z(Z(D)))===".anvil"?Z(D):void 0,qe=!Ut&&Je(D)==="bin"&&Ai(I(Z(D),".claude-plugin","plugin.json"))?I(D,"baseline.json"):void 0,Ht=6e4,Qr=5e3,Ii=30*6e4,ji=720*6e4,Ti=780*6e4;function Li(e){try{return process.kill(e,0),!0}catch{return!1}}function Di(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||!Li(r)||t-o>=Ti;try{return t-Bt(e).mtimeMs>1e4}catch{return!0}}function Mi(e,t){S(e.state);let n=I(e.state,"sync.lock"),r=I(e.state,`sync.lock.${process.pid}.${t}.tmp`);try{Oi(r,JSON.stringify({pid:process.pid,started:t}),{mode:384})}catch{return!1}try{for(let o=0;o<2;o++)try{return Ci(r,n),!0}catch(s){if(s.code!=="EEXIST"||!Di(n,t))return!1;try{Ni(n,`${n}.stale.${process.pid}`),Wt(`${n}.stale.${process.pid}`)}catch{return!1}}return!1}finally{try{Wt(r)}catch{}}}function ro(e){let t=I(e.state,"sync.lock");try{b(t)?.pid===process.pid&&Wt(t)}catch{}}function Fi(e,t){let n=0,r=o=>new Date(t-o).toISOString().slice(0,10);for(let o of[I(e.counts,r(0)),I(e.counts,r(864e5)),e.decisions])try{n=Math.max(n,Bt(o).mtimeMs)}catch{}return n}function Hi(e){try{return Bt(e.decisions).size}catch{return 0}}function Wi(e,t){if(t)return!0;if(y(e.install,1024*1024)!==!0)return!1;try{let n=JSON.parse(Ri(e.install,"utf8"));return Object.keys(n.installs??{}).length>0}catch{return!1}}function eo(e,t){try{S(e.state),A(I(e.state,Qn),String(Math.round(t)))}catch{}}function to(e,t){return{paths:e.paths,identity:t,machine:Et(e.paths,e.hostname),fetch:e.fetch,now:e.now,home:e.home,...e.pluginBaseline?{fallbackTable:e.pluginBaseline,hookBin:Z(e.pluginBaseline)}:{}}}async function Ui(e){let{paths:t}=e,n=e.now();if(!Mi(t,n))return"locked";let r="idle",o=e.now()+6e4;try{let s=0,a=-1;for(;;){let l=e.now(),c=Ke(e.env,e.home);if(!c)return Or(t,l),r="unlinked",o=l+10*6e4,r;let f=Hi(t),u=$e(t,c.id,l).next_try_at;if((l-s>=Ht||f!==a||u>0&&l>=u)&&(a=f,await It(to(e,c)),l-s>=Ht&&(s=l,await(e.sendDaily??Xr)(t,e.env,e.home,new Date(l)))),eo(t,e.now()+3*Qr+Ht),!Wi(t,e.pluginBaseline!==void 0)){r="off";break}if(e.now()-Fi(t,e.now())>Ii){r="idle";break}if(e.now()-n>ji){r="lifetime";break}await e.sleep(Qr)}let i=Ke(e.env,e.home);return i&&await It(to(e,i)),o=r==="off"?e.now()+10*6e4:0,r}finally{eo(t,o),ro(t)}}function Bi(e){let t=d=>typeof d=="string"&&/^[\w@./ -]{1,60}$/.test(d),n=b(e.install),r=n?.cli;at(t(r)?r:"anvil");let o=G(e,qe??I(D,"baseline.json")),s=V(e),a=o.value,i=[a?.cli,r].find(t)??"anvil";at(i);let l=Object.values(n?.installs??{}).filter(d=>d&&typeof d.command=="string"&&!gt(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=R(e),f=[...new Set([...l,o.problem,s.problem,...He(e,c,_e()),...Xn(e,_e(),c),...We(e)?.problems??[]].filter(d=>!!d))],u=Ur({paths:e,table:a,modes:s.value,identity:Ke(process.env,_e()),machine:Et(e,no()),now:new Date,cli:i,problems:f,installed:Object.keys(n?.installs??{}).length>0});process.stdout.write(`${u.join(`
24
+ `)}
25
+ `)}async function zi(e){let t=Date.now(),n=null;try{n=(await import(Pi(I(D,"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=G(e,qe??I(D,"baseline.json")),l=Object.values(o?.installs??{}).some(c=>c&&typeof c.command=="string"&&!gt(c));return Wr(e,new Date(t),!i.value||l?"not working":null,a,n)}async function Ki(){let e=Ut?Ie(Ut):Sn(_e());for(let t of["SIGTERM","SIGINT","SIGHUP"])process.on(t,()=>{ro(e),process.exit(0)});if(process.argv.includes("--statusline")){try{process.stdout.write(`${await zi(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{Bi(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 Ui({paths:e,env:process.env,home:_e(),hostname:no(),fetch:globalThis.fetch,now:()=>Date.now(),sleep:t=>new Promise(n=>setTimeout(n,t)),...qe?{pluginBaseline:qe}:{}})}catch{}process.exit(0)}process.argv[1]&&/claude-sync\.js$/.test(process.argv[1])&&Ki();export{Ii as IDLE_EXIT_MS,ji as MAX_LIFE_MS,Ht as PULL_EVERY_MS,Qr as TICK_MS,eo as holdSpawns,Fi as lastActivity,ro as releaseLock,Ui as runSyncLoop,Mi as takeLock};