@r5n/hydra 0.13.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,106 +1,103 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
- var Sa=Object.create;var{getPrototypeOf:xa,defineProperty:co,getOwnPropertyNames:Ea}=Object;var lo=Object.prototype.hasOwnProperty;function ka(e){return this[e]}var _a,Ta,po=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var o=t?_a??=new WeakMap:Ta??=new WeakMap,i=o.get(e);if(i)return i}n=e!=null?Sa(xa(e)):{};let s=t||!e||!e.__esModule||!lo.call(e,"default")?co(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let c of Ea(e))if(!lo.call(s,c))co(s,c,{get:ka.bind(e,c),enumerable:!0})}if(r)o.set(e,s);return s};var Pa=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Jn=Pa(function(If,ko){var Vn={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let n="";if(e<0)n+=`\x1B[${-e}D`;else if(e>0)n+=`\x1B[${e}C`;if(t<0)n+=`\x1B[${-t}A`;else if(t>0)n+=`\x1B[${t}B`;return n},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Ka={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},Va={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?Vn.up():"");if(e)t+=Vn.left;return t}};ko.exports={cursor:Vn,scroll:Ka,erase:Va,beep:"\x07"}});class de extends Error{constructor(e="Operation cancelled"){super(e)}}class y extends Error{hint;exitCode;constructor(e,t,n=1){super(e);this.hint=t;this.exitCode=n}}import{styleText as Ja}from"util";import{stdout as qn,stdin as To}from"process";import*as Ee from"readline";import Wa from"readline";var fo=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let n=0;e.lastIndex=0;while(e.test(t))n+=1;return t.length-n}})(),mo=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ho=(e)=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var Aa=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Ia=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,go=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Ha=/\t{1,1000}/y,yo=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Oa=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,La=/\p{M}+/gu,Na={limit:1/0,ellipsis:""},bo=(e,t={},n={})=>{let r=t.limit??1/0,o=t.ellipsis??"",i=t?.ellipsisWidth??(o?bo(o,Na,n).width:0),s=0,c=n.controlWidth??0,a=n.tabWidth??8,u=n.emojiWidth??2,d=2,p=n.regularWidth??1,m=n.wideWidth??2,h=[[Oa,p],[Aa,0],[Ia,c],[Ha,a],[yo,u],[go,m]],f=0,w=0,v=e.length,C=0,R=!1,P=v,H=Math.max(0,r-i),k=0,D=0,N=0,S=0;e:while(!0){if(D>k||w>=v&&w>f){let A=e.slice(k,D)||e.slice(f,w);C=0;for(let J of A.replaceAll(La,"")){let z=J.codePointAt(0)||0;if(mo(z))S=2;else if(ho(z))S=m;else S=p;if(N+S>H)P=Math.min(P,Math.max(k,f)+C);if(N+S>r){R=!0;break e}C+=J.length,N+=S}k=D=0}if(w>=v)break e;for(let A=0,J=h.length;A<J;A++){let[z,kt]=h[A];if(z.lastIndex=w,z.test(e)){if(C=z===go?fo(e.slice(w,z.lastIndex)):z===yo?1:z.lastIndex-w,S=C*kt,N+S>H)P=Math.min(P,w+Math.floor((H-N)/kt));if(N+S>r){R=!0;break e}N+=S,k=f,D=w,w=f=z.lastIndex;continue e}}w+=1}return{width:R?H:N,index:R?P:v,truncated:R,ellipsed:R&&r>=i}},wo=bo;var Da={limit:1/0,ellipsis:"",ellipsisWidth:0},Ga=(e,t={})=>wo(e,Da,t).width,Y=Ga;var Tt="\x1B",So="\x9B",Ma=39,Bn="\x07",xo="[",Fa="]",Eo="m",Kn=`${Fa}8;;`,$o=new RegExp(`(?:\\${xo}(?<code>\\d+)m|\\${Kn}(?<uri>.*)${Bn})`,"y"),vo=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},Ro=(e)=>`${Tt}${xo}${e}${Eo}`,Co=(e)=>`${Tt}${Kn}${e}${Bn}`,jn=(e,t,n)=>{let r=t[Symbol.iterator](),o=!1,i=!1,s=e.at(-1),c=s===void 0?0:Y(s),a=r.next(),u=r.next(),d=0;while(!a.done){let p=a.value,m=Y(p);if(c+m<=n)e[e.length-1]+=p;else e.push(p),c=0;if(p===Tt||p===So)o=!0,i=t.startsWith(Kn,d+1);if(o){if(i){if(p===Bn)o=!1,i=!1}else if(p===Eo)o=!1}else if(c+=m,c===n&&!u.done)e.push(""),c=0;a=u,u=r.next(),d+=p.length}if(s=e.at(-1),!c&&s!==void 0&&s.length&&e.length>1)e[e.length-2]+=e.pop()},Ua=(e)=>{let t=e.split(" "),n=t.length;while(n){if(Y(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},ja=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",o,i,s=e.split(" "),c=[""],a=0;for(let p=0;p<s.length;p++){let m=s[p];if(n.trim!==!1){let f=c.at(-1)??"",w=f.trimStart();if(f.length!==w.length)c[c.length-1]=w,a=Y(w)}if(p!==0){if(a>=t&&(n.wordWrap===!1||n.trim===!1))c.push(""),a=0;if(a||n.trim===!1)c[c.length-1]+=" ",a++}let h=Y(m);if(n.hard&&h>t){let f=t-a,w=1+Math.floor((h-f-1)/t);if(Math.floor((h-1)/t)<w)c.push("");jn(c,m,t),a=Y(c.at(-1)??"");continue}if(a+h>t&&a&&h){if(n.wordWrap===!1&&a<t){jn(c,m,t),a=Y(c.at(-1)??"");continue}c.push(""),a=0}if(a+h>t&&n.wordWrap===!1){jn(c,m,t),a=Y(c.at(-1)??"");continue}c[c.length-1]+=m,a+=h}if(n.trim!==!1)c=c.map((p)=>Ua(p));let u=c.join(`
4
- `),d=!1;for(let p=0;p<u.length;p++){let m=u[p];if(r+=m,!d){if(d=m>="\uD800"&&m<="\uDBFF",d)continue}else d=!1;if(m===Tt||m===So){$o.lastIndex=p+1;let f=$o.exec(u)?.groups;if(f?.code!==void 0){let w=Number.parseFloat(f.code);o=w===Ma?void 0:w}else if(f?.uri!==void 0)i=f.uri.length===0?void 0:f.uri}if(u[p+1]===`
5
- `){if(i)r+=Co("");let h=o?vo(o):void 0;if(o&&h)r+=Ro(h)}else if(m===`
6
- `){if(o&&vo(o))r+=Ro(o);if(i)r+=Co(i)}}return r},Ba=/\r?\n/;function he(e,t,n){return String(e).normalize().split(Ba).map((r)=>ja(r,t,n)).join(`
7
- `)}var W=po(Jn(),1);import{ReadStream as _o}from"tty";function Ne(e,t,n){if(!n.some((s)=>!s.disabled))return e;let r=e+t,o=Math.max(n.length-1,0),i=r<0?o:r>o?0:r;return n[i]?.disabled?Ne(i,t<0?-1:1,n):i}var qa=["up","down","left","right","space","enter","cancel"],za=["January","February","March","April","May","June","July","August","September","October","November","December"],K={actions:new Set(qa),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...za],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:(e)=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:(e)=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function zn(e,t){if(typeof e=="string")return K.aliases.get(e)===t;for(let n of e)if(n!==void 0&&zn(n,t))return!0;return!1}function Ya(e,t){if(e===t)return;let n=e.split(`
3
+ class rt extends Error{_tag="Cancel";constructor(e="Operation cancelled"){super(e)}}function K(e){return e}function Xc(e){return e==null?[]:Array.isArray(e)?e:[e]}function ak(e,t,n,r){var o,s=e[t],i=~r.string.indexOf(t)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~r.boolean.indexOf(t)?n==="false"?!1:n==="true"||(e._.push((o=+n,o*0===0)?o:n),!!n):(o=+n,o*0===0)?o:n;e[t]=s==null?i:Array.isArray(s)?s.concat(i):[s,i]}function zc(e,t){e=e||[],t=t||{};var n,r,o,s,i,a={_:[]},c=0,u=0,l=0,d=e.length;let f=t.alias!==void 0,m=t.unknown!==void 0,g=t.default!==void 0;if(t.alias=t.alias||{},t.string=Xc(t.string),t.boolean=Xc(t.boolean),f)for(n in t.alias){r=t.alias[n]=Xc(t.alias[n]);for(c=0;c<r.length;c++)(t.alias[r[c]]=r.concat(n)).splice(c,1)}for(c=t.boolean.length;c-- >0;){r=t.alias[t.boolean[c]]||[];for(u=r.length;u-- >0;)t.boolean.push(r[u])}for(c=t.string.length;c-- >0;){r=t.alias[t.string[c]]||[];for(u=r.length;u-- >0;)t.string.push(r[u])}if(g){for(n in t.default)if(s=typeof t.default[n],r=t.alias[n]=t.alias[n]||[],t[s]!==void 0){t[s].push(n);for(c=0;c<r.length;c++)t[s].push(r[c])}}let h=m?Object.keys(t.alias):[];for(c=0;c<d;c++){if(o=e[c],o==="--"){a._=a._.concat(e.slice(++c));break}for(u=0;u<o.length;u++)if(o.charCodeAt(u)!==45)break;if(u===0)a._.push(o);else if(o.substring(u,u+3)==="no-"){if(s=o.substring(u+3),m&&!~h.indexOf(s))return t.unknown(o);a[s]=!1}else{for(l=u+1;l<o.length;l++)if(o.charCodeAt(l)===61)break;s=o.substring(u,l),i=o.substring(++l)||(c+1===d||(""+e[c+1]).charCodeAt(0)===45||e[++c]),r=u===2?[s]:s;for(l=0;l<r.length;l++){if(s=r[l],m&&!~h.indexOf(s))return t.unknown("-".repeat(u)+s);ak(a,s,l+1<r.length||i,t)}}}if(g){for(n in t.default)if(a[n]===void 0)a[n]=t.default[n]}if(f)for(n in a){r=t.alias[n]||[];while(r.length>0)a[r.shift()]=a[n]}return a}var Qe=0,$o=1,Kp=2,Wp=255;function Ts(e){return Number.isInteger(e)&&e>=0&&e<=255}class b extends Error{hint;exitCode;_tag;constructor(e,t,n=1,r={}){super(e,"cause"in r?{cause:r.cause}:void 0);this.hint=t;this.exitCode=n;this._tag=r.tag??"Exit"}}class W extends b{constructor(e,t,n={}){super(e,t,2,{...n,tag:n.tag??"UsageError"})}}var Yp=1,ck=2,Cs="--",Xp="-",mn="no-",uk=new Set(["false","true"]),ko=/^--([^=]+)(?:=(.*))?$/s,xo=/^-([^-=][^=]*)(?:=(.*))?$/s,eu=/^(?:---|-no-|-_|-[^-=][^=]*_)/,lk="_",Eo="\x00";function St(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function br(e){let t={alias:{},boolean:[],default:{},string:[]};for(let[n,r]of Object.entries(e)){if(r.type==="boolean")t.boolean.push(n);else t.string.push(n);if(r.alias)t.alias[r.alias]=n;let o=St(n);if(o!==n)t.alias[o]=n;if(r.default!==void 0)t.default[n]=r.default}return t}function As(e,t){let n={};for(let[i,a]of Object.entries(t.alias))n[a]=[...n[a]??[],i];let{_:r,...o}=zc(Ns(e,dk),{alias:n,boolean:[...t.boolean],default:{...t.default},string:[...t.string]}),s=Object.entries(o).map(([i,a])=>[Qc(i),Qc(a)]);return{...Object.fromEntries(s),_:r.map(Qc)}}function dk(e){if(e===Xp)return`${Eo}${e}`;let t=ko.exec(e);if(eu.test(e)||pk(t?.[1]))return`--${Eo}${e}`;return(t?t[2]:xo.exec(e)?.[2])===""?`${e}${Eo}`:e}function pk(e){if(e===void 0)return!1;let t=e.startsWith(mn)?e.slice(mn.length):e;return t===lk||t in Object.prototype}function Qc(e){return typeof e==="string"&&e.startsWith(Eo)?e.slice(Eo.length):e}function vo(e,t){return Object.hasOwn(t.alias,e)?t.alias[e]??e:e}function yr(e,t){if(Object.hasOwn(t,e))return`--${St(e)}`;let n=Object.entries(t).find(([,r])=>r.alias===e)?.[0];if(n)return`--${St(n)}`;return e.length===Yp?`-${e}`:`--${e}`}function Os(e,t,n,r){let{alias:o}=br(t),s=Object.keys(e).find((i)=>!Object.hasOwn(t,i)&&!Object.hasOwn(o,i));if(s!==void 0)throw new W(`Unknown option: ${fk(s,r)}`,n)}function fk(e,t){if(e.startsWith("-"))return e;let n=t.indexOf(Cs);for(let r of n<0?t:t.slice(0,n)){let o=ko.exec(r)?.[1];if(o===e||r===`--${mn}${e}`)return`--${o}`;if(o===void 0&&xo.exec(r)?.[1]?.includes(e))return`-${e}`}return yr(e,{})}function zp(e,t){for(let[r,o]of Object.entries(e))if(Array.isArray(o))throw new W(`${yr(r,t)} can only be provided once`);let n={...e};for(let[r,o]of Object.entries(t)){let s=e[r];if(s===void 0)continue;if(o.type==="string"&&typeof s==="boolean")throw Qp(yr(r,t));if(o.type!=="number")continue;let i=Number(s);if(typeof s==="boolean"||typeof s==="string"&&s.trim().length===0||!Number.isFinite(i)){let a=yr(r,t);throw new W(`Invalid number for ${a}: "${s}"`,`Use ${a}=<number> with a finite numeric value`)}n[r]=i}return n}function Qp(e){return new W(`${e} needs a value`,`Use ${e}=<value>`)}function Ps(e,t){let n=br(t),r=tu([...e],n),o=As(r,n)._[0],s=o===void 0?-1:r.indexOf(o);return{before:s>=0?e.slice(0,s):[...e],command:o,restArgs:s>=0?e.slice(s+1):[]}}function Zp(e,t){let n=br(t);for(let r=0;r<e.length;r+=1){let o=e[r]??"";if(o===Cs)return-1;if(o===Xp||!o.startsWith("-"))return r;if(mk(o,n,t))r+=1}return-1}function mk(e,t,n){if(e.startsWith(`--${mn}`))return!1;let r=ko.exec(e),o=r??xo.exec(e);if(!o||o[2]!==void 0)return!1;let s=r?o[1]??"":o[1]?.at(-1)??"",i=n[vo(s,t)]?.type;return i==="string"||i==="number"}function _o(e,t,n=t){let r=br(t),{before:o,command:s,restArgs:i}=Ps(e,t),a=br(n);Zc(o,r,t,!0),Zc(e,a,n,!0);let{_:c,...u}=As(ef(o,r,t),r);Os(u,t,"Place command options after the command name",o);let{_:l,...d}=As(tu(i,a),a),f=zp({...Jp(u,t,r),...Jp(d,n,a)},t);return{command:s,flags:f,restArgs:i}}function Jp(e,t,n){return Object.fromEntries(Object.entries(e).filter(([r])=>Object.hasOwn(t,r)||Object.hasOwn(n.alias,r)))}function Is(e,t){return Object.fromEntries(Object.keys(t).flatMap((n)=>{let r=e[n];return r===void 0?[]:[[n,r]]}))}function To(e,t={}){let n=br(t),r=gk(e,n);Zc(r,n,t);let o=As(ef(r,n,t),n),{_:s,...i}=o;return{args:zp(i,t),rawPositionals:s.map(String)}}function Zc(e,t,n,r=!1){let o=new Set;for(let s of e){if(s===Cs)break;let i=s.match(/^-+/)?.[0];if(!i||eu.test(s))continue;let a=s.slice(i.length),c=a.split("=",Yp)[0]??"",u=a.startsWith(mn)?[a.slice(mn.length)]:i.length===ck?[c]:[...c];for(let l of u){let d=vo(l,t);if(r&&!Object.hasOwn(n,d))continue;if(o.has(d))throw new W(`${yr(d,n)} can only be provided once`);o.add(d)}}}function Ns(e,t){let n=e.indexOf(Cs);return e.map((r,o)=>n>=0&&o>=n?r:t(r,e[o+1]))}function tu(e,t){return Ns(e,(n)=>{let r=ko.exec(n)??xo.exec(n);if(!r||r[2]!==void 0||n.startsWith(`--${mn}`))return n;let o=n.startsWith("--")?r[1]??"":r[1]?.at(-1)??"";return t.boolean.includes(vo(o,t))?`${n}=true`:n})}function ef(e,t,n){let r=(i)=>n[vo(i,t)]?.type,o=(i)=>i!==void 0&&!i.startsWith("-"),s=Ns(e,(i,a)=>{let c=ko.exec(i),u=c?null:xo.exec(i);if(i.startsWith(`--${mn}`)||eu.test(i))return i;let l=c?[c[1]??""]:[...u?.[1]??""],d=c?c[2]:u?.[2];for(let[f,m]of l.entries()){let g=r(m),h=f===l.length-1,E=yr(vo(m,t),n),v=!h||d===void 0&&!o(a);if(g==="string"&&(v||d===""))throw Qp(E);if(g==="number"&&v)throw new W(`${E} needs a value`,`Use ${E}=<number>`);if(g==="boolean"&&h&&d!==void 0&&!uk.has(d))throw new W(`Invalid value for ${E}: "${d}"`,`Use ${E}=true or ${E}=false`)}return i});return tu(s,t)}function gk(e,t){return Ns(e,(n)=>n.replace(/^--(no-[^=]+)(=.*)?$/,(r,o,s)=>{let i=t.alias[o];return i&&t.boolean.includes(i)?`--${i}${s??""}`:r}))}function Ds(e,t){let n={},r=Object.entries(t);for(let[o,[s,i]]of r.entries())n[s]=i.variadic?e.slice(o):e[o];return n}function Ls(e,t){for(let[n,r]of Object.entries(t)){if(!r.required)continue;let o=e[n];if(Array.isArray(o)?o.length===0:!o)return`Missing required argument: <${n}${r.variadic?"...":""}>`}return null}function tf(e,t){let n=Object.values(t);if(n.some((r)=>r.variadic))return;return e[n.length]}var hk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,yk=new Set(["help","json"]),bk=/^[a-zA-Z0-9]$/,wk=new Set(["h","j"]);function Ms(){return(e)=>{let t={args:e.args??{},description:e.description,examples:e.examples??[],json:e.json??!1,name:e.name,passthrough:e.passthrough??!1,positionals:e.positionals??{},prompts:e.prompts??!1,run:e.run,strict:e.strict??!0,subcommands:e.subcommands??[]};return Sk(t),Object.freeze(t)}}function Hs(e,t){let n=nu(t.map((r)=>r.name));if(n!==void 0)throw Error(`${e} has more than one command named "${n}"`)}function Sk(e){let t=`Command "${e.name}"`;if(!hk.test(e.name))throw Error(`${t} must be named with a lower-case word such as "list" or "dry-run"`);if(!e.run&&e.subcommands.length===0)throw Error(`${t} needs run or subcommands`);for(let[l,d]of Object.entries(e.args)){if(yk.has(St(l)))throw Error(`${t} cannot define the option "${l}": --${St(l)} is a global flag`);if(d.alias!==void 0&&wk.has(d.alias))throw Error(`${t} cannot give "${l}" the alias -${d.alias}: it belongs to a global flag`)}let n=Object.keys(e.args).map(St),r=nu(n);if(r!==void 0)throw Error(`${t} has more than one option named --${r}`);let o=Object.values(e.args).flatMap((l)=>l.alias??[]),s=o.find((l)=>!bk.test(l));if(s!==void 0)throw Error(`${t} uses the alias "${s}": an alias is one letter or digit`);let i=o.find((l)=>n.includes(l));if(i!==void 0)throw Error(`${t} uses the alias -${i}, which is also an option's name`);let a=nu(o);if(a!==void 0)throw Error(`${t} uses the alias -${a} more than once`);let c=Object.keys(e.positionals),u=c.find((l)=>e.positionals[l]?.variadic);if(u!==void 0&&u!==c.at(-1))throw Error(`${t} declares the variadic positional "${u}" before other positionals`);if(e.passthrough&&(!e.run||u===void 0))throw Error(`${t} uses passthrough, which needs run and a variadic last positional`);Hs(t,e.subcommands)}function nu(e){return e.find((t,n)=>e.indexOf(t)!==n)}function ae(e){return e}import{Console as Ck}from"console";import{Writable as Ok}from"stream";import{format as Pk,stripVTControlCharacters as Ik}from"util";var gn={active:!1};var Rk=new Set(["0","false"]);function Ao(e){if(process.env.NO_COLOR)return!1;let t=process.env.FORCE_COLOR;if(t!==void 0)return!Rk.has(t);return e?.isTTY===!0}var $k=Ao(process.stdout),of=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Ek=["bold","dim","italic","underline","reset"],sf={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},vk={black:"\x1B[30m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",green:"\x1B[32m",magenta:"\x1B[35m",red:"\x1B[31m",white:"\x1B[37m",yellow:"\x1B[33m"},kk={black:"\x1B[40m",blue:"\x1B[44m",cyan:"\x1B[46m",gray:"\x1B[100m",green:"\x1B[42m",magenta:"\x1B[45m",red:"\x1B[41m",white:"\x1B[47m",yellow:"\x1B[43m"},nf={"\x1B[30m":"\x1B[90m","\x1B[31m":"\x1B[91m","\x1B[32m":"\x1B[92m","\x1B[33m":"\x1B[93m","\x1B[34m":"\x1B[94m","\x1B[35m":"\x1B[95m","\x1B[36m":"\x1B[96m","\x1B[37m":"\x1B[97m"};function Gs(e){return(t)=>$k&&!gn.active?`${e}${t}${sf.reset}`:t}function xk(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32&&n!==27)return!1}return!0}function rf({bright:e=!1,color:t}){let n=Bun.color(t,"ansi"),r=typeof n==="string"&&n.length>0&&xk(n)?n:vk[t];if(!r)return"";return e&&r in nf?nf[r]:r}var _k=of.reduce((e,t)=>{let n=rf({color:t});if(n)e[t]=Gs(n);let r=rf({bright:!0,color:t});if(r)e[`${t}Bright`]=Gs(r);return e},{}),Tk=Ek.reduce((e,t)=>(e[t]=Gs(sf[t]),e),{}),Ak=of.reduce((e,t)=>{let n=kk[t];if(n){let r=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;e[r]=Gs(n)}return e},{}),p={..._k,...Tk,...Ak};var Nk=2,uf=["clear","count","countReset","debug","dir","dirxml","group","groupCollapsed","groupEnd","info","log","table"],Dk=[...uf,"trace","write"],Lk=1,Mk="EPIPE",Hk="EIO",he={closedStreams:new Set,documentWritten:!1,jsonRuns:0,outputGuarded:!1,restoreStdout:void 0,sealed:!1,stdoutClosed:!1,stdoutWrite:void 0};function Co(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function ru(e){return Co()&&!gn.active&&e?.json!==!0}function lf(){return gn.active}function hn(e){let t=JSON.stringify(e??null,null,Nk);if(t===void 0)throw TypeError("JSON cannot represent the value");return`${t}
4
+ `}function df(){return he.documentWritten}function pf(){he.sealed=!0}function Zt(e){if(he.documentWritten=!0,he.sealed||he.stdoutClosed)return;let t=he.stdoutWrite??process.stdout.write;try{t.call(process.stdout,e)}catch(n){if(!Fs(n,process.stdout))throw n;he.stdoutClosed=!0}}function ff(){if(he.outputGuarded)return;he.outputGuarded=!0,process.stdout.write=af(process.stdout.write,!0),console.write=af(console.write,0),process.stdout.on("error",(e)=>{if(!Fs(e,process.stdout))throw e;he.stdoutClosed=!0}),process.stderr.on("error",(e)=>{if(!Fs(e,process.stderr))throw e});for(let e of[process.stdout,process.stderr])e.once("close",()=>he.closedStreams.add(e))}function af(e,t){let n=(r)=>{let o=r.at(-1);if(typeof o==="function")queueMicrotask(()=>o());return t};return function(...o){if(he.stdoutClosed)return n(o);try{return e.apply(this,o)}catch(s){if(!Fs(s,process.stdout))throw s;return he.stdoutClosed=!0,n(o)}}}function Fs(e,t){if(!(e instanceof Error))return!1;let n=Reflect.get(e,"code");return n===Mk||n===Hk&&t.isTTY===!0}function Us(){let e=Ao(process.stderr);return new Ok({decodeStrings:!1,write(t,n,r){process.stderr.write(e?t:Ik(t)),r()}})}async function mf(e,t){if(!e)return t();he.jsonRuns+=1,he.restoreStdout??=Gk(),gn.active=!0;try{return await t()}finally{if(he.jsonRuns-=1,gn.active=he.jsonRuns>0,!gn.active&&!he.outputGuarded)he.restoreStdout?.(),he.restoreStdout=void 0}}async function gf(e){let t=Promise.all([he.stdoutClosed?void 0:cf(process.stdout),cf(process.stderr)]);await(e===void 0?t:Promise.race([t,Bun.sleep(e)]))}function cf(e){if(e.writableFinished||he.closedStreams.has(e))return Promise.resolve();return new Promise((t)=>{e.once("close",t),e.once("finish",t),e.once("error",()=>t()),e.end(()=>t())})}function Gk(){let e=process.stdout.write,t=new Ck({stderr:process.stderr,stdout:process.stderr}),n=Object.fromEntries(Dk.map((o)=>[o,console[o]])),r=Object.fromEntries(uf.map((o)=>[o,t[o].bind(t)]));return he.stdoutWrite=e,process.stdout.write=process.stderr.write.bind(process.stderr),Object.assign(console,r,{trace:Fk(t),write:Uk}),()=>{process.stdout.write=e,Object.assign(console,n),he.stdoutWrite=void 0}}function Fk(e){let t=(...n)=>{let r={};Error.captureStackTrace(r,t);let o=r.stack?.split(`
5
+ `).slice(Lk)??[];e.error([`Trace: ${Pk(...n)}`,...o].join(`
6
+ `))};return t}function Uk(...e){let t=Buffer.concat(e.map(jk));return process.stderr.write(t),t.byteLength}function jk(e){if(typeof e==="string")return Buffer.from(e);return ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}var He={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"},json:{alias:"j",description:"Write one JSON document to stdout",type:"boolean"}},wr={help:He.help,json:He.json},Hn="help",js={[Qe]:"success",[$o]:"failure",[Kp]:"usage error"};import{stripVTControlCharacters as $u}from"util";import{styleText as nx}from"util";import{stdout as Cf,stdin as rx}from"process";import ox from"readline";var hf=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let n=0;e.lastIndex=0;while(e.test(t))n+=1;return t.length-n}})(),yf=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,bf=(e)=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var Bk=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Vk=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,wf=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,qk=/\t{1,1000}/y,Sf=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Kk=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Wk=/\p{M}+/gu,Jk={limit:1/0,ellipsis:""},Rf=(e,t={},n={})=>{let r=t.limit??1/0,o=t.ellipsis??"",s=t?.ellipsisWidth??(o?Rf(o,Jk,n).width:0),i=0,a=n.controlWidth??0,c=n.tabWidth??8,u=n.emojiWidth??2,l=2,d=n.regularWidth??1,f=n.wideWidth??2,m=[[Kk,d],[Bk,0],[Vk,a],[qk,c],[Sf,u],[wf,f]],g=0,h=0,E=e.length,v=0,S=!1,_=E,C=Math.max(0,r-s),w=0,x=0,y=0,R=0;e:while(!0){if(x>w||h>=E&&h>g){let A=e.slice(w,x)||e.slice(g,h);v=0;for(let k of A.replaceAll(Wk,"")){let D=k.codePointAt(0)||0;if(yf(D))R=2;else if(bf(D))R=f;else R=d;if(y+R>C)_=Math.min(_,Math.max(w,g)+v);if(y+R>r){S=!0;break e}v+=k.length,y+=R}w=x=0}if(h>=E)break e;for(let A=0,k=m.length;A<k;A++){let[D,B]=m[A];if(D.lastIndex=h,D.test(e)){if(v=D===wf?hf(e.slice(h,D.lastIndex)):D===Sf?1:D.lastIndex-h,R=v*B,y+R>C)_=Math.min(_,h+Math.floor((C-y)/B));if(y+R>r){S=!0;break e}y+=R,w=g,x=h,h=g=D.lastIndex;continue e}}h+=1}return{width:S?C:y,index:S?_:E,truncated:S,ellipsed:S&&r>=s}},$f=Rf;var Yk={limit:1/0,ellipsis:"",ellipsisWidth:0},Xk=(e,t={})=>$f(e,Yk,t).width,Ne=Xk;var Bs="\x1B",_f="\x9B",zk=39,su="\x07",Tf="[",Qk="]",Af="m",iu=`${Qk}8;;`,Ef=new RegExp(`(?:\\${Tf}(?<code>\\d+)m|\\${iu}(?<uri>.*)${su})`,"y"),vf=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},kf=(e)=>`${Bs}${Tf}${e}${Af}`,xf=(e)=>`${Bs}${iu}${e}${su}`,ou=(e,t,n)=>{let r=t[Symbol.iterator](),o=!1,s=!1,i=e.at(-1),a=i===void 0?0:Ne(i),c=r.next(),u=r.next(),l=0;while(!c.done){let d=c.value,f=Ne(d);if(a+f<=n)e[e.length-1]+=d;else e.push(d),a=0;if(d===Bs||d===_f)o=!0,s=t.startsWith(iu,l+1);if(o){if(s){if(d===su)o=!1,s=!1}else if(d===Af)o=!1}else if(a+=f,a===n&&!u.done)e.push(""),a=0;c=u,u=r.next(),l+=d.length}if(i=e.at(-1),!a&&i!==void 0&&i.length&&e.length>1)e[e.length-2]+=e.pop()},Zk=(e)=>{let t=e.split(" "),n=t.length;while(n){if(Ne(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},ex=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",o,s,i=e.split(" "),a=[""],c=0;for(let d=0;d<i.length;d++){let f=i[d];if(n.trim!==!1){let g=a.at(-1)??"",h=g.trimStart();if(g.length!==h.length)a[a.length-1]=h,c=Ne(h)}if(d!==0){if(c>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),c=0;if(c||n.trim===!1)a[a.length-1]+=" ",c++}let m=Ne(f);if(n.hard&&m>t){let g=t-c,h=1+Math.floor((m-g-1)/t);if(Math.floor((m-1)/t)<h)a.push("");ou(a,f,t),c=Ne(a.at(-1)??"");continue}if(c+m>t&&c&&m){if(n.wordWrap===!1&&c<t){ou(a,f,t),c=Ne(a.at(-1)??"");continue}a.push(""),c=0}if(c+m>t&&n.wordWrap===!1){ou(a,f,t),c=Ne(a.at(-1)??"");continue}a[a.length-1]+=f,c+=m}if(n.trim!==!1)a=a.map((d)=>Zk(d));let u=a.join(`
7
+ `),l=!1;for(let d=0;d<u.length;d++){let f=u[d];if(r+=f,!l){if(l=f>="\uD800"&&f<="\uDBFF",l)continue}else l=!1;if(f===Bs||f===_f){Ef.lastIndex=d+1;let g=Ef.exec(u)?.groups;if(g?.code!==void 0){let h=Number.parseFloat(g.code);o=h===zk?void 0:h}else if(g?.uri!==void 0)s=g.uri.length===0?void 0:g.uri}if(u[d+1]===`
8
+ `){if(s)r+=xf("");let m=o?vf(o):void 0;if(o&&m)r+=kf(m)}else if(f===`
9
+ `){if(o&&vf(o))r+=kf(o);if(s)r+=xf(s)}}return r},tx=/\r?\n/;function yn(e,t,n){return String(e).normalize().split(tx).map((r)=>ex(r,t,n)).join(`
10
+ `)}var lt={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let n="";if(e<0)n+=`\x1B[${-e}D`;else if(e>0)n+=`\x1B[${e}C`;if(t<0)n+=`\x1B[${-t}A`;else if(t>0)n+=`\x1B[${t}B`;return n},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"};var Oo={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?lt.up():"");if(e)t+=lt.left;return t}};function qs(e,t,n){if(!n.some((i)=>!i.disabled))return e;let r=e+t,o=Math.max(n.length-1,0),s=r<0?o:r>o?0:r;return n[s]?.disabled?qs(s,t<0?-1:1,n):s}var sx=["up","down","left","right","space","enter","cancel"],ix=["January","February","March","April","May","June","July","August","September","October","November","December"],je={actions:new Set(sx),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,accessible:void 0,date:{monthNames:[...ix],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:(e)=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:(e)=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function Of(e){if(e!==void 0)return e;if(je.accessible!==void 0)return je.accessible;let t=process.env.ACCESSIBLE;return t!==void 0&&t!==""&&t!=="0"&&t!=="false"}function Pf(e,t){if(typeof e=="string")return je.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Pf(n,t))return!0;return!1}function ax(e,t){if(e===t)return;let n=e.split(`
8
11
  `),r=t.split(`
9
- `),o=Math.max(n.length,r.length),i=[];for(let s=0;s<o;s++)n[s]!==r[s]&&i.push(s);return{lines:i,numLinesBefore:n.length,numLinesAfter:r.length,numLines:o}}var Xa=globalThis.process.platform.startsWith("win"),Wn=Symbol("clack:cancel");function lt(e){return e===Wn}function Pt(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Po({input:e=To,output:t=qn,overwrite:n=!0,hideCursor:r=!0}={}){let o=Ee.createInterface({input:e,output:t,prompt:"",tabSize:1});Ee.emitKeypressEvents(e,o),e instanceof _o&&e.isTTY&&e.setRawMode(!0);let i=(s,{name:c,sequence:a})=>{let u=String(s);if(zn([u,c,a],"cancel")){r&&t.write(W.cursor.show),process.exit(0);return}if(!n)return;Ee.moveCursor(t,c==="return"?0:-1,c==="return"?-1:0,()=>{Ee.clearLine(t,1,()=>{e.once("keypress",i)})})};return r&&t.write(W.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),r&&t.write(W.cursor.show),e instanceof _o&&e.isTTY&&!Xa&&e.setRawMode(!1),o.terminal=!1,o.close()}}var dt=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Yn=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function ke(e,t,n,r=n,o=n,i){let s=dt(e??qn);return he(t,s-n.length,{hard:!0,trim:!1}).split(`
10
- `).map((c,a,u)=>{let d=i?i(c,a):c;return a===0?`${r}${d}`:a===u.length-1?`${o}${d}`:`${n}${d}`}).join(`
11
- `)}function Ao(e,t){if("~standard"in e){let n=e["~standard"].validate(t);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return e(t)}class pt{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:n=To,output:r=qn,render:o,signal:i,...s}=e;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=o.bind(this),this._track=t,this._abortSignal=i,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let o of n)o.cb(...t),o.once&&r.push(()=>n.splice(n.indexOf(o),1));for(let o of r)o()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Wn);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Wa.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Pt(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(W.cursor.show),this.output.off("resize",this.render),Pt(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(W.cursor.show),this.output.off("resize",this.render),Pt(this.input,!1),e(Wn)})})}_isActionKey(e,t){return e==="\t"}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),t?.name&&(!this._track&&K.aliases.has(t.name)&&this.emit("cursor",K.aliases.get(t.name)),K.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,t),t?.name==="return"&&this._shouldSubmit(e,t)){if(this.opts.validate){let n=Ao(this.opts.validate,this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}zn([e,t?.name,t?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
12
- `),Pt(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=he(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
- `).length-1;this.output.write(W.cursor.move(-999,e*-1))}render(){let e=he(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(W.cursor.hide);else{let t=Ya(this._prevFrame,e),n=Yn(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),o=Math.max(0,t.numLinesBefore-n),i=t.lines.find((s)=>s>=r);if(i===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(W.cursor.move(0,i-o)),this.output.write(W.erase.lines(1));let s=e.split(`
14
- `);this.output.write(s[i]),this._prevFrame=e,this.output.write(W.cursor.move(0,s.length-i-1));return}else if(t.lines.length>1){if(r<o)i=r;else{let c=i-o;c>0&&this.output.write(W.cursor.move(0,c))}this.output.write(W.erase.down());let s=e.split(`
15
- `).slice(i);this.output.write(s.join(`
16
- `)),this._prevFrame=e;return}}this.output.write(W.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}class Xn extends pt{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(W.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class Zn extends pt{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((n)=>n.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((n)=>!e.includes(n.value));this.value=t.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),0);this.cursor=this.options[t]?.disabled?Ne(t,1,this.options):t,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=Ne(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Ne(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Io=class extends pt{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let t=this._selectedValue;this.value=t===void 0?void 0:t.value}constructor(t){super(t,!1),this.options=t.options;let n=this.options.findIndex(({value:o})=>o===t.initialValue),r=n===-1?0:n;this.cursor=this.options[r]?.disabled?Ne(r,1,this.options):r,this.changeValue(),this.on("cursor",(o)=>{switch(o){case"left":case"up":this.cursor=Ne(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Ne(this.cursor,1,this.options);break}this.changeValue()})}};class Qn extends pt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${Ja("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as g,stripVTControlCharacters as qf}from"util";import ie from"process";var mt=po(Jn(),1);function Za(){if(ie.platform!=="win32")return ie.env.TERM!=="linux";return Boolean(ie.env.CI)||Boolean(ie.env.WT_SESSION)||Boolean(ie.env.TERMINUS_SUBLIME)||ie.env.ConEmuTask==="{cmd::Cmder}"||ie.env.TERM_PROGRAM==="Terminus-Sublime"||ie.env.TERM_PROGRAM==="vscode"||ie.env.TERM==="xterm-256color"||ie.env.TERM==="alacritty"||ie.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var er=Za(),Qa=()=>process.env.CI==="true";var O=(e,t)=>er?e:t,eu=O("\u25C6","*"),Do=O("\u25A0","x"),Go=O("\u25B2","x"),Ht=O("\u25C7","o"),tu=O("\u250C","T"),_=O("\u2502","|"),_e=O("\u2514","\u2014"),Zf=O("\u2510","T"),Qf=O("\u2518","\u2014"),tr=O("\u25CF",">"),It=O("\u25CB"," "),nu=O("\u25FB","[\u2022]"),Ho=O("\u25FC","[+]"),Oo=O("\u25FB","[ ]"),em=O("\u25AA","\u2022"),Lo=O("\u2500","-"),ru=O("\u256E","+"),ou=O("\u251C","+"),iu=O("\u256F","+"),su=O("\u2570","+"),tm=O("\u256D","+"),au=O("\u25CF","\u2022"),uu=O("\u25C6","*"),cu=O("\u25B2","!"),lu=O("\u25A0","x"),Ot=(e)=>{switch(e){case"initial":case"active":return g("cyan",eu);case"cancel":return g("red",Do);case"error":return g("yellow",Go);case"submit":return g("green",Ht)}},Mo=(e)=>{switch(e){case"initial":case"active":return g("cyan",_);case"cancel":return g("red",_);case"error":return g("yellow",_);case"submit":return g("green",_)}};function Fo(e,t){let n=[`${t?`${g("cyan",_)} `:""}${e.join(" \u2022 ")}`];return t&&n.push(g("cyan",_e)),n}var No=(e,t,n,r,o,i=!1)=>{let s=t,c=0;if(i)for(let a=r-1;a>=n;a--){let u=e[a];if(u&&(s-=u.length),c++,s<=o)break}else for(let a=n;a<r;a++){let u=e[a];if(u&&(s-=u.length),c++,s<=o)break}return{lineCount:s,removals:c}},nr=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:o=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:s=4})=>{let c=dt(r)-i,a=Yn(r),u=g("dim","..."),d=Math.max(a-s,0),p=Math.max(Math.min(o,d),5),m=0;e>=p-3&&(m=Math.max(Math.min(e-p+3,t.length-p),0));let h=p<t.length&&m>0,f=p<t.length&&m+p<t.length,w=Math.min(m+p,t.length),v=[],C=0;h&&C++,f&&C++;let R=m+(h?1:0),P=w-(f?1:0);for(let k=R;k<P;k++){let D=t[k],N=D?n(D,k===e):"",S=he(N,c,{hard:!0,trim:!1}).split(`
17
- `);v.push(S),C+=S.length}if(C>d){let k=0,D=0,N=C,S=e-R,A=d,J=()=>No(v,N,0,S,A),z=()=>No(v,N,S+1,v.length,A,!0);h?({lineCount:N,removals:k}=J(),N>A&&(f||(A-=1),{lineCount:N,removals:D}=z())):(f||(A-=1),{lineCount:N,removals:D}=z(),N>A&&(A-=1,{lineCount:N,removals:k}=J())),k>0&&(h=!0,v.splice(0,k)),D>0&&(f=!0,v.splice(v.length-D,D))}let H=[];h&&H.push(u);for(let k of v)for(let D of k)H.push(D);return f&&H.push(u),H};var Uo=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new Xn({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??K.withGuide,o=`${Ot(this.state)} `,i=r?`${g("gray",_)} `:"",s=ke(e.output,e.message,i,o),c=`${r?`${g("gray",_)}
18
- `:""}${s}
19
- `,a=this.value?t:n;switch(this.state){case"submit":{let u=r?`${g("gray",_)} `:"";return`${c}${u}${g("dim",a)}`}case"cancel":{let u=r?`${g("gray",_)} `:"";return`${c}${u}${g(["strikethrough","dim"],a)}${r?`
20
- ${g("gray",_)}`:""}`}default:{let u=r?`${g("cyan",_)} `:"",d=r?g("cyan",_e):"";return`${c}${u}${this.value?`${g("green",tr)} ${t}`:`${g("dim",It)} ${g("dim",t)}`}${e.vertical?r?`
21
- ${g("cyan",_)} `:`
22
- `:` ${g("dim","/")} `}${this.value?`${g("dim",It)} ${g("dim",n)}`:`${g("green",tr)} ${n}`}
23
- ${d}
24
- `}}}}).prompt()};var Lt=async(e,t)=>{let n={},r=Object.keys(e);for(let o of r){let i=e[o],s=await i({results:n})?.catch((c)=>{throw c});if(typeof t?.onCancel=="function"&&lt(s)){n[o]="canceled",t.onCancel({results:n});continue}n[o]=s}return n},du=[`${g("dim","\u2191/\u2193")} to navigate`,`${g("dim","Space:")} select`,`${g("dim","Enter:")} confirm`],ft=(e,t)=>e.split(`
25
- `).map((n)=>t(n)).join(`
26
- `),jo=(e)=>{let t=(o,i)=>{let s=o.label??String(o.value);return i==="disabled"?`${g("gray",Oo)} ${ft(s,(c)=>g(["strikethrough","gray"],c))}${o.hint?` ${g("dim",`(${o.hint??"disabled"})`)}`:""}`:i==="active"?`${g("cyan",nu)} ${s}${o.hint?` ${g("dim",`(${o.hint})`)}`:""}`:i==="selected"?`${g("green",Ho)} ${ft(s,(c)=>g("dim",c))}${o.hint?` ${g("dim",`(${o.hint})`)}`:""}`:i==="cancelled"?`${ft(s,(c)=>g(["strikethrough","dim"],c))}`:i==="active-selected"?`${g("green",Ho)} ${s}${o.hint?` ${g("dim",`(${o.hint})`)}`:""}`:i==="submitted"?`${ft(s,(c)=>g("dim",c))}`:`${g("dim",Oo)} ${ft(s,(c)=>g("dim",c))}`},n=e.required??!0,r=e.showInstructions??!0;return new Zn({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(o){if(n&&(o===void 0||o.length===0))return`Please select at least one option.
27
- ${g("reset",g("dim",`Press ${g(["gray","bgWhite","inverse"]," space ")} to select, ${g("gray",g("bgWhite",g("inverse"," enter ")))} to submit`))}`},render(){let o=e.withGuide??K.withGuide,i=ke(e.output,e.message,o?`${Mo(this.state)} `:"",`${Ot(this.state)} `),s=`${o?`${g("gray",_)}
12
+ `),o=Math.max(n.length,r.length),s=[];for(let i=0;i<o;i++)n[i]!==r[i]&&s.push(i);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:o}}var GW=globalThis.process.platform.startsWith("win"),Ks=Symbol("clack:cancel");function Po(e){return e===Ks}function Vs(e,t){let n=e;n.isTTY&&n.setRawMode(t)}var Sr=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,au=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function Rr(e,t,n,r=n,o=n,s){let i=Sr(e??Cf),a=Ne(n);return yn(t,i-a,{hard:!0,trim:!1}).split(`
13
+ `).map((c,u,l)=>{let d=s?s(c,u):c;return u===0?`${r}${d}`:u===l.length-1?`${o}${d}`:`${n}${d}`}).join(`
14
+ `)}function If(e,t){if("~standard"in e){let n=e["~standard"].validate(t);return n instanceof Promise?n.then((r)=>r.issues?.at(0)?.message):n.issues?.at(0)?.message}return e(t)}var cu=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return Of(this.opts.accessible)}constructor(t,n=!0){let{input:r=rx,output:o=Cf,render:s,signal:i,...a}=t;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=s.bind(this),this._track=n,this._abortSignal=i,this.input=r,this.output=o}unsubscribe(){this._subscribers.clear()}setSubscriber(t,n){let r=this._subscribers.get(t)??[];r.push(n),this._subscribers.set(t,r)}on(t,n){this.setSubscriber(t,{cb:n})}once(t,n){this.setSubscriber(t,{cb:n,once:!0})}emit(t,...n){let r=this._subscribers.get(t)??[],o=[];for(let s of r)s.cb(...n),s.once&&o.push(()=>r.splice(r.indexOf(s),1));for(let s of o)s()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Ks);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=ox.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Vs(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(lt.show),this.output.off("resize",this.render),Vs(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(lt.show),this.output.off("resize",this.render),Vs(this.input,!1),t(Ks)})})}_isActionKey(t,n){return t==="\t"}_shouldSubmit(t,n){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,n){this.userInput=t??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}async onKeypress(t,n){if(this.state!=="validating"){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(t,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&je.aliases.has(n.name)&&this.emit("cursor",je.aliases.get(n.name)),je.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,n),n?.name==="return"&&this._shouldSubmit(t,n)){if(this.opts.validate){let r=If(this.opts.validate,this.value),o;r instanceof Promise?(this.state="validating",this.render(),o=await r):o=r,o&&(this.error=o instanceof Error?o.message:o,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Pf([t,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
15
+ `),Vs(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=yn(this._prevFrame,Sr(this.output),{hard:!0,trim:!1}).split(`
16
+ `).length-1;this.output.write(lt.move(-999,t*-1))}render(){let t=yn(this._render(this)??"",Sr(this.output),{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(lt.hide);else{let n=ax(this._prevFrame,t),r=au(this.output);if(this.restoreCursor(),n){let o=Math.max(0,n.numLinesAfter-r),s=Math.max(0,n.numLinesBefore-r),i=n.lines.find((a)=>a>=o);if(i===void 0){this._prevFrame=t;return}if(n.lines.length===1){this.output.write(lt.move(0,i-s)),this.output.write(Oo.lines(1));let a=t.split(`
17
+ `);this.output.write(a[i]),this._prevFrame=t,this.output.write(lt.move(0,a.length-i-1));return}else if(n.lines.length>1){if(o<s)i=o;else{let c=i-s;c>0&&this.output.write(lt.move(0,c))}this.output.write(Oo.down());let a=t.split(`
18
+ `).slice(i);this.output.write(a.join(`
19
+ `)),this._prevFrame=t;return}}this.output.write(Oo.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};class uu extends cu{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(lt.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var Nf=class extends cu{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let t=this._selectedValue;this.value=t===void 0?void 0:t.value}constructor(t){super(t,!1),this.options=t.options;let n=this.options.findIndex(({value:o})=>o===t.initialValue),r=n===-1?0:n;this.cursor=this.options[r]?.disabled?qs(r,1,this.options):r,this.changeValue(),this.on("cursor",(o)=>{switch(o){case"left":case"up":this.cursor=qs(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=qs(this.cursor,1,this.options);break}this.changeValue()})}};class lu extends cu{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${nx("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as M,stripVTControlCharacters as QW}from"util";import dt from"process";function cx(){if(dt.platform!=="win32")return dt.env.TERM!=="linux";return Boolean(dt.env.CI)||Boolean(dt.env.WT_SESSION)||Boolean(dt.env.TERMINUS_SUBLIME)||dt.env.ConEmuTask==="{cmd::Cmder}"||dt.env.TERM_PROGRAM==="Terminus-Sublime"||dt.env.TERM_PROGRAM==="vscode"||dt.env.TERM==="xterm-256color"||dt.env.TERM==="alacritty"||dt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var pu=cx(),Hf=()=>process.env.CI==="true";var le=(e,t)=>pu?e:t,Df=le("\u25C6","*"),fu=le("\u25A0","x"),mu=le("\u25B2","x"),Io=le("\u25C7","o"),ux=le("\u250C","T"),ce=le("\u2502","|"),Gn=le("\u2514","\u2014"),r6=le("\u2510","T"),o6=le("\u2518","\u2014"),du=le("\u25CF",">"),Js=le("\u25CB"," "),s6=le("\u25FB","[\u2022]"),i6=le("\u25FC","[+]"),a6=le("\u25FB","[ ]"),c6=le("\u25AA","\u2022"),Lf=le("\u2500","-"),lx=le("\u256E","+"),dx=le("\u251C","+"),px=le("\u256F","+"),fx=le("\u2570","+"),u6=le("\u256D","+"),mx=le("\u25CF","\u2022"),gx=le("\u25C6","*"),hx=le("\u25B2","!"),yx=le("\u25A0","x"),gu=(e)=>{switch(e){case"initial":case"active":return M("cyan",Df);case"cancel":return M("red",fu);case"error":return M("yellow",mu);case"submit":return M("green",Io);case"validating":return M("dim",Df)}},bx=(e)=>{switch(e){case"initial":case"active":return M("cyan",ce);case"cancel":return M("red",ce);case"error":return M("yellow",ce);case"submit":return M("green",ce)}};function wx(e,t,n){let r=n?`${M("cyan",ce)} `:"",o=Rr(e,t.join(" \u2022 "),r).split(`
20
+ `);return n&&o.push(M("cyan",Gn)),o}var Mf=(e,t,n,r,o,s=!1)=>{let i=t,a=0;if(s)for(let c=r-1;c>=n;c--){let u=e[c];if(u&&(i-=u.length),a++,i<=o)break}else for(let c=n;c<r;c++){let u=e[c];if(u&&(i-=u.length),a++,i<=o)break}return{lineCount:i,removals:a}},Sx=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:o=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:i=4})=>{let a=Sr(r)-s,c=au(r),u=M("dim","..."),l=Math.max(c-i,0),d=Math.max(Math.min(o,l),5),f=0;e>=d-3&&(f=Math.max(Math.min(e-d+3,t.length-d),0));let m=d<t.length&&f>0,g=d<t.length&&f+d<t.length,h=Math.min(f+d,t.length),E=[],v=0;m&&v++,g&&v++;let S=f+(m?1:0),_=h-(g?1:0);for(let w=S;w<_;w++){let x=t[w],y=x!==void 0?n(x,w===e):"",R=yn(y,a,{hard:!0,trim:!1}).split(`
21
+ `);E.push(R),v+=R.length}if(v>l){let w=0,x=0,y=v,R=e-S,A=l,k=()=>Mf(E,y,0,R,A),D=()=>Mf(E,y,R+1,E.length,A,!0);m?({lineCount:y,removals:w}=k(),y>A&&(g||(A-=1),{lineCount:y,removals:x}=D())):(g||(A-=1),{lineCount:y,removals:x}=D(),y>A&&(A-=1,{lineCount:y,removals:w}=k())),w>0&&(m=!0,E.splice(0,w)),x>0&&(g=!0,E.splice(E.length-x,x))}let C=[];m&&C.push(u);for(let w of E)for(let x of w)C.push(x);return g&&C.push(u),C};var Gf=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new uu({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??je.withGuide,o=`${gu(this.state)} `,s=r?`${M("gray",ce)} `:"",i=Rr(e.output,e.message,s,o),a=`${r?`${M("gray",ce)}
28
22
  `:""}${i}
29
- `,c=this.value??[],a=(u,d)=>{if(u.disabled)return t(u,"disabled");let p=c.includes(u.value);return d&&p?t(u,"active-selected"):p?t(u,"selected"):t(u,d?"active":"inactive")};switch(this.state){case"submit":{let u=this.options.filter(({value:p})=>c.includes(p)).map((p)=>t(p,"submitted")).join(g("dim",", "))||g("dim","none"),d=ke(e.output,u,o?`${g("gray",_)} `:"");return`${s}${d}`}case"cancel":{let u=this.options.filter(({value:p})=>c.includes(p)).map((p)=>t(p,"cancelled")).join(g("dim",", "));if(u.trim()==="")return`${s}${g("gray",_)}`;let d=ke(e.output,u,o?`${g("gray",_)} `:"");return`${s}${d}${o?`
30
- ${g("gray",_)}`:""}`}case"error":{let u=o?`${g("yellow",_)} `:"",d=this.error.split(`
31
- `).map((h,f)=>f===0?`${o?`${g("yellow",_e)} `:""}${g("yellow",h)}`:` ${h}`).join(`
32
- `),p=s.split(`
33
- `).length,m=d.split(`
34
- `).length+1;return`${s}${u}${nr({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:u.length,rowPadding:p+m,style:a}).join(`
35
- ${u}`)}
36
- ${d}
37
- `}default:{let u=o?`${g("cyan",_)} `:"",d=s.split(`
38
- `).length,p=r?Fo(du,o):o?[g("cyan",_e)]:[],m=p.join(`
39
- `),h=p.length+1;return`${s}${u}${nr({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:u.length,rowPadding:d+h,style:a}).join(`
40
- ${u}`)}
41
- ${m}
42
- `}}}}).prompt()};var b={message:(e=[],{symbol:t=g("gray",_),secondarySymbol:n=g("gray",_),output:r=process.stdout,spacing:o=1,withGuide:i}={})=>{let s=[],c=i??K.withGuide,a=c?n:"",u=c?`${t} `:"",d=c?`${n} `:"";for(let m=0;m<o;m++)s.push(a);let p=Array.isArray(e)?e:e.split(`
43
- `);if(p.length>0){let[m,...h]=p;m.length>0?s.push(`${u}${m}`):s.push(c?t:"");for(let f of h)f.length>0?s.push(`${d}${f}`):s.push(c?n:"")}r.write(`${s.join(`
23
+ `,c=this.value?t:n;switch(this.state){case"submit":{let u=r?`${M("gray",ce)} `:"";return`${a}${u}${M("dim",c)}`}case"cancel":{let u=r?`${M("gray",ce)} `:"";return`${a}${u}${M(["strikethrough","dim"],c)}${r?`
24
+ ${M("gray",ce)}`:""}`}default:{let u=r?`${M("cyan",ce)} `:"",l=r?M("cyan",Gn):"";return`${a}${u}${this.value?`${M("green",du)} ${t}`:`${M("dim",Js)} ${M("dim",t)}`}${e.vertical?r?`
25
+ ${M("cyan",ce)} `:`
26
+ `:` ${M("dim","/")} `}${this.value?`${M("dim",Js)} ${M("dim",n)}`:`${M("green",du)} ${n}`}
27
+ ${l}
28
+ `}}}}).prompt()};var Ys=async(e,t)=>{let n={},r=Object.keys(e);for(let o of r){let s=e[o],i=await s({results:n})?.catch((a)=>{throw a});if(typeof t?.onCancel=="function"&&Po(i)){n[o]="canceled",t.onCancel({results:n});continue}n[o]=i}return n},l6=[`${M("dim","\u2191/\u2193")} to navigate`,`${M("dim","Space:")} select`,`${M("dim","Enter:")} confirm`];var Be={message:(e=[],{symbol:t=M("gray",ce),secondarySymbol:n=M("gray",ce),output:r=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??je.withGuide,c=a?n:"",u=a?`${t} `:"",l=a?`${n} `:"";for(let f=0;f<o;f++)i.push(c);let d=Array.isArray(e)?e:e.split(`
29
+ `);if(d.length>0){let[f,...m]=d;f.length>0?i.push(`${u}${f}`):i.push(a?t:"");for(let g of m)g.length>0?i.push(`${l}${g}`):i.push(a?n:"")}r.write(`${i.join(`
44
30
  `)}
45
- `)},info:(e,t)=>{b.message(e,{...t,symbol:g("blue",au)})},success:(e,t)=>{b.message(e,{...t,symbol:g("green",uu)})},step:(e,t)=>{b.message(e,{...t,symbol:g("green",Ht)})},warn:(e,t)=>{b.message(e,{...t,symbol:g("yellow",cu)})},warning:(e,t)=>{b.warn(e,t)},error:(e,t)=>{b.message(e,{...t,symbol:g("red",lu)})}};var Nt=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??K.withGuide?`${g("gray",tu)} `:"";n.write(`${r}${e}
46
- `)},Dt=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??K.withGuide?`${g("gray",_)}
47
- ${g("gray",_e)} `:"";n.write(`${r}${e}
48
-
49
- `)};var pu=(e)=>e,fu=(e,t,n)=>{let r={hard:!0,trim:!1},o=he(e,t,r).split(`
50
- `),i=o.reduce((a,u)=>Math.max(Y(u),a),0),s=o.map(n).reduce((a,u)=>Math.max(Y(u),a),0),c=t-(s-i);return he(e,c,r)},We=(e="",t="",n)=>{let r=n?.output??ie.stdout,o=n?.withGuide??K.withGuide,i=n?.format??pu,s=["",...fu(e,dt(r)-6,i).split(`
51
- `).map(i),""],c=Y(t),a=Math.max(s.reduce((m,h)=>{let f=Y(h);return f>m?f:m},0),c)+2,u=s.map((m)=>`${g("gray",_)} ${m}${" ".repeat(a-Y(m))}${g("gray",_)}`).join(`
52
- `),d=o?`${g("gray",_)}
53
- `:"",p=o?ou:su;r.write(`${d}${g("green",Ht)} ${g("reset",t)} ${g("gray",Lo.repeat(Math.max(a-c-1,1))+ru)}
31
+ `)},info:(e,t)=>{Be.message(e,{...t,symbol:M("blue",mx)})},success:(e,t)=>{Be.message(e,{...t,symbol:M("green",gx)})},step:(e,t)=>{Be.message(e,{...t,symbol:M("green",Io)})},warn:(e,t)=>{Be.message(e,{...t,symbol:M("yellow",hx)})},warning:(e,t)=>{Be.warn(e,t)},error:(e,t)=>{Be.message(e,{...t,symbol:M("red",yx)})}};var Ff=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??je.withGuide?`${M("gray",ux)} `:"";n.write(`${r}${e}
32
+ `)},Uf=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??je.withGuide?`${M("gray",ce)}
33
+ ${M("gray",Gn)} `:"";n.write(`${r}${e}
34
+
35
+ `)};var Rx=(e)=>e,$x=(e,t,n)=>{let r={hard:!0,trim:!1},o=yn(e,t,r).split(`
36
+ `),s=o.reduce((c,u)=>Math.max(Ne(u),c),0),i=o.map(n).reduce((c,u)=>Math.max(Ne(u),c),0),a=t-(i-s);return yn(e,a,r)},jf=(e="",t="",n)=>{let r=n?.output??dt.stdout,o=n?.withGuide??je.withGuide,s=n?.format??Rx,i=["",...$x(e,Sr(r)-6,s).split(`
37
+ `).map(s),""],a=Ne(t),c=Math.max(i.reduce((f,m)=>{let g=Ne(m);return g>f?g:f},0),a)+2,u=i.map((f)=>`${M("gray",ce)} ${f}${" ".repeat(c-Ne(f))}${M("gray",ce)}`).join(`
38
+ `),l=o?`${M("gray",ce)}
39
+ `:"",d=o?dx:fx;r.write(`${l}${M("green",Io)} ${M("reset",t)} ${M("gray",Lf.repeat(Math.max(c-a-1,1))+lx)}
54
40
  ${u}
55
- ${g("gray",p+Lo.repeat(a+2)+iu)}
56
- `)};var mu=(e)=>g("magenta",e),Z=({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:o,frames:i=er?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:s=er?80:120,signal:c,...a}={})=>{let u=Qa(),d,p,m=!1,h=!1,f="",w,v=performance.now(),C=dt(n),R=a?.styleFrame??mu,P=(G)=>{let oe=G>1?o??K.messages.error:r??K.messages.cancel;h=G===1,m&&(ct(oe,G),h&&typeof t=="function"&&t())},H=()=>P(2),k=()=>P(1),D=()=>{process.on("uncaughtExceptionMonitor",H),process.on("unhandledRejection",H),process.on("SIGINT",k),process.on("SIGTERM",k),process.on("exit",P),c&&c.addEventListener("abort",k)},N=()=>{process.removeListener("uncaughtExceptionMonitor",H),process.removeListener("unhandledRejection",H),process.removeListener("SIGINT",k),process.removeListener("SIGTERM",k),process.removeListener("exit",P),c&&c.removeEventListener("abort",k)},S=()=>{if(w===void 0)return;u&&n.write(`
57
- `);let G=he(w,C,{hard:!0,trim:!1}).split(`
58
- `);G.length>1&&n.write(mt.cursor.up(G.length-1)),n.write(mt.cursor.to(0)),n.write(mt.erase.down())},A=(G)=>G.replace(/\.+$/,""),J=(G)=>{let oe=(performance.now()-G)/1000,we=Math.floor(oe/60),$e=Math.floor(oe%60);return we>0?`[${we}m ${$e}s]`:`[${$e}s]`},z=a.withGuide??K.withGuide,kt=(G="")=>{m=!0,d=Po({output:n}),f=A(G),v=performance.now(),z&&n.write(`${g("gray",_)}
59
- `);let oe=0,we=0;D(),p=setInterval(()=>{if(u&&f===w)return;S(),w=f;let $e=R(i[oe]),_t;if(u)_t=`${$e} ${f}...`;else if(e==="timer")_t=`${$e} ${f} ${J(v)}`;else{let Ca=".".repeat(Math.floor(we)).slice(0,3);_t=`${$e} ${f}${Ca}`}let Ra=he(_t,C,{hard:!0,trim:!1});n.write(Ra),oe=oe+1<i.length?oe+1:0,we=we<4?we+0.125:0},s)},ct=(G="",oe=0,we=!1)=>{if(!m)return;m=!1,clearInterval(p),S();let $e=oe===0?g("green",Ht):oe===1?g("red",Do):g("red",Go);f=G??f,we||(e==="timer"?n.write(`${$e} ${f} ${J(v)}
60
- `):n.write(`${$e} ${f}
61
- `)),N(),d()};return{start:kt,stop:(G="")=>ct(G,0),message:(G="")=>{f=A(G??f)},cancel:(G="")=>ct(G,1),error:(G="")=>ct(G,2),clear:()=>ct("",0,!0),get isCancelled(){return h}}},nm={light:O("\u2500","-"),heavy:O("\u2501","="),block:O("\u2588","#")};var hu=[`${g("dim","\u2191/\u2193")} to navigate`,`${g("dim","Enter:")} confirm`],At=(e,t)=>e.includes(`
41
+ ${M("gray",d+Lf.repeat(c+2)+px)}
42
+ `)};var d6={light:le("\u2500","-"),heavy:le("\u2501","="),block:le("\u2588","#")};var Ex=[`${M("dim","\u2191/\u2193")} to navigate`,`${M("dim","Enter:")} confirm`],Ws=(e,t)=>e.includes(`
62
43
  `)?e.split(`
63
44
  `).map((n)=>t(n)).join(`
64
- `):t(e),Bo=(e)=>{let t=(r,o)=>{if(r===void 0)return"";let i=r.label??String(r.value);switch(o){case"disabled":return`${g("gray",It)} ${At(i,(s)=>g("gray",s))}${r.hint?` ${g("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${At(i,(s)=>g("dim",s))}`;case"active":return`${g("green",tr)} ${i}${r.hint?` ${g("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${At(i,(s)=>g(["strikethrough","dim"],s))}`;default:return`${g("dim",It)} ${At(i,(s)=>g("dim",s))}`}},n=e.showInstructions??!0;return new Io({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??K.withGuide,o=`${Ot(this.state)} `,i=`${Mo(this.state)} `,s=ke(e.output,e.message,i,o),c=`${r?`${g("gray",_)}
65
- `:""}${s}
66
- `;switch(this.state){case"submit":{let a=r?`${g("gray",_)} `:"",u=ke(e.output,t(this.options[this.cursor],"selected"),a);return`${c}${u}`}case"cancel":{let a=r?`${g("gray",_)} `:"",u=ke(e.output,t(this.options[this.cursor],"cancelled"),a);return`${c}${u}${r?`
67
- ${g("gray",_)}`:""}`}default:{let a=r?`${g("cyan",_)} `:"",u=c.split(`
68
- `).length,d=n?Fo(hu,r):r?[g("cyan",_e)]:[],p=d.join(`
69
- `),m=d.length+1;return`${c}${a}${nr({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:u+m,style:(h,f)=>t(h,h.disabled?"disabled":f?"active":"inactive")}).join(`
70
- ${a}`)}
71
- ${p}
72
- `}}}}).prompt()};var rm=`${g("gray",_)} `;var Ko=(e)=>new Qn({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??K.withGuide,n=`${`${t?`${g("gray",_)}
73
- `:""}${Ot(this.state)} `}${e.message}
74
- `,r=e.placeholder&&e.placeholder.length>0?g("inverse",e.placeholder[0])+g("dim",e.placeholder.slice(1)):g(["inverse","hidden"],"_"),o=this.userInput?this.userInputWithCursor:r,i=this.value??"";switch(this.state){case"error":{let s=this.error?` ${g("yellow",this.error)}`:"",c=t?`${g("yellow",_)} `:"",a=t?g("yellow",_e):"";return`${n.trim()}
75
- ${c}${o}
76
- ${a}${s}
77
- `}case"submit":{let s=i?` ${g("dim",i)}`:"",c=t?g("gray",_):"";return`${n}${c}${s}`}case"cancel":{let s=i?` ${g(["strikethrough","dim"],i)}`:"",c=t?g("gray",_):"";return`${n}${c}${s}${i.trim()?`
78
- ${c}`:""}`}default:{let s=t?`${g("cyan",_)} `:"",c=t?g("cyan",_e):"";return`${n}${s}${o}
79
- ${c}
80
- `}}}}).prompt();var yu=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),Wo=["black","blue","cyan","gray","green","magenta","red","white","yellow"],bu=["bold","dim","italic","underline","reset"],qo={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},wu={black:"\x1B[30m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",green:"\x1B[32m",magenta:"\x1B[35m",red:"\x1B[31m",white:"\x1B[37m",yellow:"\x1B[33m"},$u={black:"\x1B[40m",blue:"\x1B[44m",cyan:"\x1B[46m",gray:"\x1B[100m",green:"\x1B[42m",magenta:"\x1B[45m",red:"\x1B[41m",white:"\x1B[47m",yellow:"\x1B[43m"},Vo={"\x1B[30m":"\x1B[90m","\x1B[31m":"\x1B[91m","\x1B[32m":"\x1B[92m","\x1B[33m":"\x1B[93m","\x1B[34m":"\x1B[94m","\x1B[35m":"\x1B[95m","\x1B[36m":"\x1B[96m","\x1B[37m":"\x1B[97m"};function Gt(e){return(t)=>yu?`${e}${t}${qo.reset}`:t}function vu(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32&&n!==27)return!1}return!0}function Jo({bright:e=!1,color:t}){let n=Bun.color(t,"ansi"),r=typeof n==="string"&&n.length>0&&vu(n)?n:wu[t];if(!r)return"";return e&&r in Vo?Vo[r]:r}var Ru=Wo.reduce((e,t)=>{let n=Jo({color:t});if(n)e[t]=Gt(n);let r=Jo({bright:!0,color:t});if(r)e[`${t}Bright`]=Gt(r);return e},{}),Cu=bu.reduce((e,t)=>(e[t]=Gt(qo[t]),e),{}),Su=Wo.reduce((e,t)=>{let n=$u[t];if(n){let r=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;e[r]=Gt(n)}return e},{}),l={...Ru,...Cu,...Su};function Mt(e){if(lt(e))throw new de;return e}function Eu(e){return e.map((t)=>t.key?`${l.bold(t.key)} ${l.dim(t.text)}`:l.dim(t.text)).join(l.dim(" \xB7 "))}function Ft(e){b.info(Eu(e))}var Ut={confirm:[{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],multiselect:[{key:"\u2191\u2193",text:"navigate"},{key:"Space",text:"toggle"},{key:"a",text:"all"},{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],select:[{key:"\u2191\u2193",text:"navigate"},{key:"Enter",text:"select"},{key:"Esc",text:"cancel"}],text:[{key:"Enter",text:"submit"},{key:"Esc",text:"cancel"}]};async function pe(e){return Ft(Ut.confirm),Mt(await Uo(e))}async function ve(e){return Ft(Ut.text),Mt(await Ko(e))}async function De(e){return Ft(Ut.select),Mt(await Bo({showInstructions:!1,...e}))}async function Ge(e){return Ft(Ut.multiselect),Mt(await jo({showInstructions:!1,...e}))}var ku=4;function qe(e,t=0){if(t>=ku)return;let n=[...e instanceof AggregateError?e.errors:[],...e.cause!==void 0?[e.cause]:[]];for(let r of n){if(b.info(l.dim(`caused by: ${r instanceof Error?r.message:String(r)}`)),r instanceof y&&r.hint)b.info(l.dim(` ${r.hint}`));if(r instanceof Error)qe(r,t+1)}}function rr(e){return e==null?[]:Array.isArray(e)?e:[e]}function _u(e,t,n,r){var o,i=e[t],s=~r.string.indexOf(t)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~r.boolean.indexOf(t)?n==="false"?!1:n==="true"||(e._.push((o=+n,o*0===0)?o:n),!!n):(o=+n,o*0===0)?o:n;e[t]=i==null?s:Array.isArray(i)?i.concat(s):[i,s]}function ht(e,t){e=e||[],t=t||{};var n,r,o,i,s,c={_:[]},a=0,u=0,d=0,p=e.length;let m=t.alias!==void 0,h=t.unknown!==void 0,f=t.default!==void 0;if(t.alias=t.alias||{},t.string=rr(t.string),t.boolean=rr(t.boolean),m)for(n in t.alias){r=t.alias[n]=rr(t.alias[n]);for(a=0;a<r.length;a++)(t.alias[r[a]]=r.concat(n)).splice(a,1)}for(a=t.boolean.length;a-- >0;){r=t.alias[t.boolean[a]]||[];for(u=r.length;u-- >0;)t.boolean.push(r[u])}for(a=t.string.length;a-- >0;){r=t.alias[t.string[a]]||[];for(u=r.length;u-- >0;)t.string.push(r[u])}if(f){for(n in t.default)if(i=typeof t.default[n],r=t.alias[n]=t.alias[n]||[],t[i]!==void 0){t[i].push(n);for(a=0;a<r.length;a++)t[i].push(r[a])}}let w=h?Object.keys(t.alias):[];for(a=0;a<p;a++){if(o=e[a],o==="--"){c._=c._.concat(e.slice(++a));break}for(u=0;u<o.length;u++)if(o.charCodeAt(u)!==45)break;if(u===0)c._.push(o);else if(o.substring(u,u+3)==="no-"){if(i=o.substring(u+3),h&&!~w.indexOf(i))return t.unknown(o);c[i]=!1}else{for(d=u+1;d<o.length;d++)if(o.charCodeAt(d)===61)break;i=o.substring(u,d),s=o.substring(++d)||(a+1===p||(""+e[a+1]).charCodeAt(0)===45||e[++a]),r=u===2?[i]:i;for(d=0;d<r.length;d++){if(i=r[d],h&&!~w.indexOf(i))return t.unknown("-".repeat(u)+i);_u(c,i,d+1<r.length||s,t)}}}if(f){for(n in t.default)if(c[n]===void 0)c[n]=t.default[n]}if(m)for(n in c){r=t.alias[n]||[];while(r.length>0)c[r.shift()]=c[n]}return c}var zo=1,Tu=2;function ze(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function or(e){let t={alias:{},boolean:[],default:{},string:[]};for(let[n,r]of Object.entries(e)){if(r.type==="boolean")t.boolean.push(n);else t.string.push(n);if(r.alias)t.alias[r.alias]=n;let o=ze(n);if(o!==n)t.alias[o]=n;if(r.default!==void 0)t.default[n]=r.default}return t}function jt(e,t){if(e in t)return`--${ze(e)}`;let n=Object.entries(t).find(([,r])=>r.alias===e)?.[0];if(n)return`--${ze(n)}`;return e.length===zo?`-${e}`:`--${ze(e)}`}function T(e,t,n){let{alias:r}=or(t),o=Object.keys(e).find((i)=>!Object.hasOwn(t,i)&&!Object.hasOwn(r,i));if(o!==void 0)throw new y(`Unknown option: ${jt(o,t)}`,n)}function Yo(e,t){for(let[r,o]of Object.entries(e))if(Array.isArray(o))throw new y(`${jt(r,t)} can only be provided once`);let n={...e};for(let[r,o]of Object.entries(t)){if(o.type!=="number")continue;let i=e[r];if(i===void 0)continue;let s=Number(i);if(typeof i==="boolean"||typeof i==="string"&&i.trim().length===0||!Number.isFinite(s)){let c=jt(r,t);throw new y(`Invalid number for ${c}: "${i}"`,`Use ${c}=<number> with a finite numeric value`)}n[r]=s}return n}function gt(e,t){let n=or(t);Xo(e,n,t,!0);let r=ht(e,n),o=r._[0],i=o?e.indexOf(o):-1,s=ht(i>=0?e.slice(0,i):e,n),{_:c,...a}=s;T(a,t,"Place command options after the command name");let{_:u,...d}=r,p=Object.fromEntries(Object.entries(d).filter(([h])=>(h in t)||(h in n.alias))),m=Yo(p,t);return{command:o,flags:m,restArgs:i>=0?e.slice(i+1):[]}}function ir(e,t={}){let n=or(t),r=Pu(e,n);Xo(r,n,t);let o=ht(r,n),{_:i,...s}=o;return{args:Yo(s,t),rawPositionals:i}}function Xo(e,t,n,r=!1){let o=new Set;for(let i of e){if(i==="--")break;let s=i.match(/^-+/)?.[0];if(!s)continue;let c=i.slice(s.length),a=c.split("=",zo)[0]??"",u=c.startsWith("no-")?[c.slice(3)]:s.length===Tu?[a]:[...a];for(let d of u){let p=Object.hasOwn(t.alias,d)?t.alias[d]??d:d;if(r&&!Object.hasOwn(n,p))continue;if(o.has(p))throw new y(`${jt(p,n)} can only be provided once`);o.add(p)}}}function Pu(e,t){let n=!0;return e.map((r)=>{if(r==="--")n=!1;if(!n)return r;return r.replace(/^--(no-[^=]+)(=.*)?$/,(o,i,s)=>{let c=t.alias[i];return c&&t.boolean.includes(c)?`--${c}${s??""}`:o})})}function sr(e,t){let n={},r=Object.entries(t);for(let[o,[i,s]]of r.entries())n[i]=s.variadic?e.slice(o):e[o];return n}function Zo(e,t){for(let[n,r]of Object.entries(t)){if(!r.required)continue;let o=e[n];if(Array.isArray(o)?o.length===0:!o)return`Missing required argument: <${n}${r.variadic?"...":""}>`}return null}var Au=(e)=>e,E={arg:l.magenta,cmd:l.cyan,default:l.bold,desc:Au,flag:l.green,header:(e)=>l.bold(l.yellow(e)),hint:l.dim,name:(e)=>l.bold(l.cyan(e)),placeholder:l.magenta};class ar{metadata;commands;globalArgs;constructor(e,t,n){this.metadata=e;this.commands=t;this.globalArgs=n}version(){return`${E.name(this.metadata.name)} ${E.hint(this.metadata.version??"0.0.0")}`}global(){let e=[],{name:t,bin:n,version:r,description:o}=this.metadata;if(e.push(`${E.name(t)}${r?` ${E.hint(`v${r}`)}`:""}`),o)e.push(E.desc(o));e.push(""),e.push(E.header("Usage:")),e.push(` ${E.cmd(n)} ${E.placeholder("[command]")} ${E.placeholder("[options]")}`),e.push(""),e.push(E.header("Commands:"));let i=Array.from(this.commands.values()).map((s)=>[` ${E.cmd(s.name)}`,E.desc(s.description)]);return e.push(...this.formatColumns(i)),e.push(""),e.push(E.header("Options:")),e.push(...this.formatArgDefs(this.globalArgs)),e.push(""),e.push(`${E.hint("Run")} ${E.cmd(`${n} <command> --help`)} ${E.hint("for command details.")}`),e.join(`
81
- `).trimEnd()}command(e,t){let n=[],r=t??this.metadata.bin,o=`${r} ${e.name}`,i=`${E.cmd(r)} ${E.cmd(e.name)}`;n.push(E.name(o)),n.push(E.desc(e.description)),n.push(""),n.push(E.header("Usage:"));let s=this.formatPositionalUsage(e.positionals);if(e.hasSubcommands())n.push(` ${i} ${E.placeholder("<subcommand>")} ${E.placeholder("[options]")}`);else{let u=[i];if(s)u.push(s);u.push(E.placeholder("[options]")),n.push(` ${u.join(" ")}`)}if(e.prompts&&Object.keys(e.positionals).length>0)n.push(` ${E.hint("Omit positional arguments to run interactively.")}`);if(n.push(""),e.hasSubcommands()){n.push(E.header("Subcommands:"));let u=e.getSubcommands().map((d)=>[` ${E.cmd(d.name)}`,E.desc(d.description)]);n.push(...this.formatColumns(u)),n.push("")}if(Object.entries(e.positionals).length>0)n.push(E.header("Arguments:")),n.push(...this.formatPositionalDefs(e.positionals)),n.push("");if(Object.entries(e.args).length>0)n.push(E.header("Options:")),n.push(...this.formatArgDefs(e.args));return n.join(`
82
- `).trimEnd()}formatPositionalUsage(e){return Object.entries(e).map(([t,n])=>{let r=n.variadic?`${t}...`:t;return n.required?E.arg(`<${r}>`):E.arg(`[${r}]`)}).join(" ")}formatPositionalDefs(e){let t=Object.entries(e).map(([n,r])=>{let o=r.variadic?`${n}...`:n,i=E.desc(r.description??""),s=r.required?"":E.hint(" (optional)");return[` ${E.arg(o)}`,`${i}${s}`]});return this.formatColumns(t)}formatArgDefs(e){let t=[];for(let[n,r]of Object.entries(e)){let o=r.alias?`${E.flag(`-${r.alias}`)}, `:" ",i=r.type==="boolean"?"":` ${E.placeholder(`<${r.type==="number"?"number":"value"}>`)}`,s=`${o}${E.flag(`--${ze(n)}`)}${i}`,c=E.desc(r.description??""),a=this.formatDefault(r),u=a===void 0?"":` (default: ${E.default(a)})`;t.push([` ${s}`,`${c}${u}`])}return this.formatColumns(t)}formatDefault(e){if(typeof e.displayDefault==="string")return e.displayDefault;if(e.default===void 0)return;if(e.type==="boolean"&&e.default===!1)return;if(e.type==="string")return`"${e.default}"`;return String(e.default)}formatColumns(e){if(e.length===0)return[];let t=Math.max(...e.map(([r])=>this.stripAnsi(r).length)),n=2;return e.map(([r,o])=>{let i=t-this.stripAnsi(r).length+n;return`${r}${" ".repeat(i)}${o}`})}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}}var Re=new Uint32Array(65536),Iu=(e,t)=>{let n=e.length,r=t.length,o=1<<n-1,i=-1,s=0,c=n,a=n;while(a--)Re[e.charCodeAt(a)]|=1<<a;for(a=0;a<r;a++){let u=Re[t.charCodeAt(a)],d=u|s;if(u|=(u&i)+i^i,s|=~(u|i),i&=u,s&o)c++;if(i&o)c--;s=s<<1|1,i=i<<1|~(d|s),s&=d}a=n;while(a--)Re[e.charCodeAt(a)]=0;return c},Hu=(e,t)=>{let n=t.length,r=e.length,o=[],i=[],s=Math.ceil(n/32),c=Math.ceil(r/32);for(let f=0;f<s;f++)i[f]=-1,o[f]=0;let a=0;for(;a<c-1;a++){let f=0,w=-1,v=a*32,C=Math.min(32,r)+v;for(let R=v;R<C;R++)Re[e.charCodeAt(R)]|=1<<R;for(let R=0;R<n;R++){let P=Re[t.charCodeAt(R)],H=i[R/32|0]>>>R&1,k=o[R/32|0]>>>R&1,D=P|f,N=((P|k)&w)+w^w|P|k,S=f|~(N|w),A=w&N;if(S>>>31^H)i[R/32|0]^=1<<R;if(A>>>31^k)o[R/32|0]^=1<<R;S=S<<1|H,A=A<<1|k,w=A|~(D|S),f=S&D}for(let R=v;R<C;R++)Re[e.charCodeAt(R)]=0}let u=0,d=-1,p=a*32,m=Math.min(32,r-p)+p;for(let f=p;f<m;f++)Re[e.charCodeAt(f)]|=1<<f;let h=r;for(let f=0;f<n;f++){let w=Re[t.charCodeAt(f)],v=i[f/32|0]>>>f&1,C=o[f/32|0]>>>f&1,R=w|u,P=((w|C)&d)+d^d|w|C,H=u|~(P|d),k=d&P;if(h+=H>>>r-1&1,h-=k>>>r-1&1,H>>>31^v)i[f/32|0]^=1<<f;if(k>>>31^C)o[f/32|0]^=1<<f;H=H<<1|v,k=k<<1|C,d=k|~(R|H),u=H&R}for(let f=p;f<m;f++)Re[e.charCodeAt(f)]=0;return h},Ou=(e,t)=>{if(e.length<t.length){let n=t;t=e,e=n}if(t.length===0)return e.length;if(e.length<=32)return Iu(e,t);return Hu(e,t)},Qo=(e,t)=>{let n=1/0,r=0;for(let o=0;o<t.length;o++){let i=Ou(e,t[o]);if(i<n)n=i,r=o}return t[r]};function Bt(e,t,n,r){let o=Qo(t,n);if(console.error(l.red(`Unknown ${e}: ${t}`)),o)console.error(l.yellow(`Did you mean "${o}"?`));console.error(`
83
- Run "${r} --help" for usage.`),process.exit(1)}function Kt(e,t){if(Array.isArray(t))return[...t];if(!ei(e)||!ei(t))return t;return Object.fromEntries([...Object.entries(e),...Object.entries(t).map(([n,r])=>[n,Kt(Object.hasOwn(e,n)?e[n]:void 0,r)])])}function ei(e){if(e===null||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var ur="__exit__";class Ye{command;env;prefix;options;selections;constructor(e,t,n,r={}){this.command=e;this.env=t;this.prefix=n;this.options=r;this.selections=r.selections??new Map}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(e,t){if(t&&process.stdout.isTTY!==!0)throw new y("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(t)await this.routeInteractive();else await this.routeDirect(e)}async routeDirect(e){let[t,...n]=e;if(t&&this.command.hasSubcommands()){let r=this.command.getSubcommand(t);if(r){await this.handleSubcommandRoute(r,n);return}if(!t.startsWith("-")){this.handleUnknownSubcommand(t);return}}await this.executeCommand(e)}handleUnknownSubcommand(e){let t=this.command.getSubcommands().map((n)=>n.name);Bt("subcommand",e,t,this.commandPath)}async handleSubcommandRoute(e,t){await new Ye(e,this.env,this.commandPath).route(t,!1)}async executeCommand(e){if(this.isHelpRequest(e)){this.printHelp(this.command);return}if(this.command.hasSubcommands()&&!this.command.execute){this.printHelp(this.command);return}if(!this.command.execute)return;let{args:n,rawPositionals:r}=ir(e,this.command.args),o=sr(r,this.command.positionals),i=Zo(o,this.command.positionals);if(i)b.error(i),console.error(`
84
- Run "${this.commandPath} --help" for usage.`),process.exit(1);let s=this.command.prompts&&r.length===0&&process.stdout.isTTY===!0,c=this.buildContext(o,n,s);await this.command.execute(c)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:e}=ir([],this.command.args),t=sr([],this.command.positionals),n=this.buildContext(t,e,!0);await this.command.execute?.(n)}async runSubcommandMenu(){while(!0){let e=await this.promptSubcommandSelectionOrBack();if(e===null)return;if(e===ur){this.options.onExit?.();return}let t=this.command.getSubcommand(e);if(t)this.selections.set(this.commandPath,e),await this.executeSubcommand(t)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(e){if(e instanceof de){if(this.options.isRoot)this.options.onExit?.();return null}throw e}}async executeSubcommand(e){try{await new Ye(e,this.env,this.commandPath,{selections:this.selections}).route([],!0)}catch(t){if(t instanceof de)return;if(t instanceof y){if(b.warn(l.yellow(t.message)),t.hint)b.info(l.dim(t.hint));qe(t);return}throw t}}promptSubcommandSelection(){let{isRoot:e}=this.options,t=e?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:ur}:{hint:"Return to previous menu",label:"Back",value:ur};return De({message:e?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,initialValue:this.selections.get(this.commandPath),options:[...this.command.getSubcommands().map((n)=>({hint:n.description,label:n.name,value:n.name})),t]})}buildContext(e,t,n){return{...this.env,args:t,interactive:n,positionals:e}}isHelpRequest(e){let t=e.indexOf("--"),n=t<0?e:e.slice(0,t);return n.includes("--help")||n.includes("-h")}printHelp(e){let t=e===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(e,t))}}var Lu={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"},cr={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};class lr{commands=new Map;metadata;configManager;help;bin;globalArgs={...cr};constructor(e,t){this.configManager=e,this.metadata={...Lu,...t},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new ar({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(e){for(let t of e)t.init?.(),this.commands.set(t.name,t)}async run(e=process.argv.slice(2)){try{let{command:t,flags:n,restArgs:r}=gt(e,this.globalArgs);if(n.version&&!t)return console.log(this.help.version());if(n.interactive&&!t)return await this.runInteractive();if(!t)return console.log(this.help.global());if(t==="help")return this.printHelpFor(r[0]);await this.runDirect(t,r,!!n.help)}catch(t){this.handleError(t)}}printHelpFor(e){if(!e)return console.log(this.help.global());let t=this.commands.get(e);if(!t)return this.handleUnknownCommand(e);console.log(this.help.command(t))}async runInteractive(){this.showIntro();let e=this.createVirtualRootCommand(),t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},n=new Ye(e,t,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await n.route([],!0)}catch(r){this.handleError(r)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(e)=>this.commands.get(e),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){Dt(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(e,t,n){let r=this.commands.get(e);if(!r)return this.handleUnknownCommand(e);let o=t.length>0&&!t[0]?.startsWith("-");if(n&&!o)return console.log(this.help.command(r));try{let i={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new Ye(r,i,this.bin).route(t,!1)}catch(i){this.handleError(i)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let e=this.metadata.version?` v${this.metadata.version}`:"";Nt(`${l.bgCyan(l.black(` ${this.metadata.name}${e} `))}`)}handleUnknownCommand(e){let t=Array.from(this.commands.keys());Bt("command",e,t,this.bin)}handleError(e){if(this.metadata.onError?.(e))return;if(e instanceof de)process.exit(0);if(e instanceof y){if(b.warn(l.yellow(e.message)),e.hint)b.info(l.dim(e.hint));qe(e),process.exit(e.exitCode)}if(e instanceof Error)b.error(l.red(e.message)),qe(e),process.exit(1);console.error(l.red("Error:"),e),process.exit(1)}}class yt{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(e){for(let t of e)t.init?.(),this.subcommands.set(t.name,t)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(e){return this.subcommands.get(e)}getSubcommands(){return Array.from(this.subcommands.values())}}function L(e){return e}function B(e){return e}import se from"fs";import ni from"path";var bt=(e)=>(e.map=(t)=>bt((n)=>t(e(n))),e.or=(t)=>bt((n)=>{try{return e(n)}catch(r){return t(n)}}),e),F=()=>"bad banditype"();var wt=(e)=>bt((t)=>e.includes(t)?t:F()),Vt=(e)=>bt((t)=>typeof t===typeof e?t:F()),U=()=>Vt(""),Q=()=>Vt(0),te=()=>Vt(!0);var ti=()=>Vt();var Jt=(e)=>bt((t)=>t instanceof e?t:F());var ge=(e)=>Jt(Object).map((t)=>{let n={};for(let r in e){let o=e[r](t[r]);o!==void 0&&(n[r]=o)}return n});var Wt=(e)=>Jt(Array).map((t)=>t.map(e));function pr(e,t){JSON.parse(e);let n=JSON.parse(JSON.stringify(t)),r=Nu(e),o=e.match(/^[\t ]+(?=\S)/m)?.[0]??" ",i=e.includes(`\r
45
+ `):t(e),Bf=(e)=>{let t=(r,o)=>{if(r===void 0)return"";let s=r.label??String(r.value);switch(o){case"disabled":return`${M("gray",Js)} ${Ws(s,(i)=>M("gray",i))}${r.hint?` ${M("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${Ws(s,(i)=>M("dim",i))}`;case"active":return`${M("green",du)} ${s}${r.hint?` ${M("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${Ws(s,(i)=>M(["strikethrough","dim"],i))}`;default:return`${M("dim",Js)} ${Ws(s,(i)=>M("dim",i))}`}},n=e.showInstructions??!0;return new Nf({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??je.withGuide,o=`${gu(this.state)} `,s=`${bx(this.state)} `,i=Rr(e.output,e.message,s,o),a=`${r?`${M("gray",ce)}
46
+ `:""}${i}
47
+ `;switch(this.state){case"submit":{let c=r?`${M("gray",ce)} `:"",u=Rr(e.output,t(this.options[this.cursor],"selected"),c);return`${a}${u}`}case"cancel":{let c=r?`${M("gray",ce)} `:"",u=Rr(e.output,t(this.options[this.cursor],"cancelled"),c);return`${a}${u}${r?`
48
+ ${M("gray",ce)}`:""}`}default:{let c=r?`${M("cyan",ce)} `:"",u=a.split(`
49
+ `).length,l=n?wx(e.output,Ex,r):r?[M("cyan",Gn)]:[],d=l.join(`
50
+ `),f=l.length+1;return`${a}${c}${Sx({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:c.length,rowPadding:u+f,style:(m,g)=>t(m,m.disabled?"disabled":g?"active":"inactive")}).join(`
51
+ ${c}`)}
52
+ ${d}
53
+ `}}}}).prompt()};var p6=`${M("gray",ce)} `;var Vf=(e)=>new lu({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??je.withGuide,n=`${`${t?`${M("gray",ce)}
54
+ `:""}${gu(this.state)} `}${e.message}
55
+ `,r=e.placeholder&&e.placeholder.length>0?M("inverse",e.placeholder[0])+M("dim",e.placeholder.slice(1)):M(["inverse","hidden"],"_"),o=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"validating":{let i=t?`${M("cyan",ce)} `:"",a=t?M("cyan",Gn):"",c=M("dim",o),u=M("dim","Validating...");return`${n}${i}${c}
56
+ ${a} ${u}
57
+ `}case"error":{let i=this.error?` ${M("yellow",this.error)}`:"",a=t?`${M("yellow",ce)} `:"",c=t?M("yellow",Gn):"";return`${n.trim()}
58
+ ${a}${o}
59
+ ${c}${i}
60
+ `}case"submit":{let i=s?`${t?" ":""}${M("dim",s)}`:"",a=t?M("gray",ce):"";return`${n}${a}${i}`}case"cancel":{let i=s?` ${M(["strikethrough","dim"],s)}`:"",a=t?M("gray",ce):"";return`${n}${a}${i}${s.trim()?`
61
+ ${a}`:""}`}default:{let i=t?`${M("cyan",ce)} `:"",a=t?M("cyan",Gn):"";return`${n}${i}${o}
62
+ ${a}
63
+ `}}}}).prompt();function qf(e=process.stdin){return e.readableEnded||e.destroyed}async function Kf({edits:e,input:t=process.stdin,signal:n},r){let o=new AbortController,s=()=>o.abort(),i=(c,u)=>{if(u.sequence==="\x04"&&(!e||t.isPaused()))s()},a=r(n?AbortSignal.any([o.signal,n]):o.signal);t.on("keypress",i),t.once("end",s),t.once("close",s);try{return await a}finally{t.off("keypress",i),t.off("end",s),t.off("close",s)}}import{stripVTControlCharacters as kx}from"util";var hu=pu?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],xx=80,_x=8,Tx=3,Ax="...",yu="\r\x1B[K",Cx=80,Ox=/\s*\n\s*/g,No=new Set;function Jf(){for(let e of[...No])e.error()}function Yf({output:e=process.stdout}={}){let t=e.isTTY===!0&&!Hf(),n=Ao(e),r="",o=0,s=!1,i,a=(m)=>{e.write(t||n?m:kx(m))},c=()=>{let m=p.magenta(hu[o%hu.length]??""),g=".".repeat(Math.floor(o/_x)%(Tx+1)),h=`${m} ${r.replace(Ox," ")}${g}`;a(`${yu}${Bun.sliceAnsi(h,0,(e.columns||Cx)-1)}`),o+=1},u=()=>t?c():a(`${p.magenta(hu[0]??"")} ${r}${Ax}
64
+ `),l=()=>(clearInterval(i),No.delete(f)),d=(m,g)=>{if(l())a(`${t?yu:""}${m} ${g}
65
+ `)},f={cancel(m=r){s=No.has(f)||s,d(p.red(fu),m)},clear(){if(l()&&t)a(yu)},error(m=r){d(p.red(mu),m)},get isCancelled(){return s},message(m=r){let g=Wf(m);if(g===r)return;if(r=g,No.has(f)&&!t)u()},start(m=""){if(f.clear(),s=!1,r=Wf(m),o=0,No.add(f),a(`${p.gray(ce)}
66
+ `),u(),!t)return;i=setInterval(c,xx),i.unref()},stop(m=r){d(p.green(Io),m)}};return f}function Wf(e){return e.replace(/\.+$/,"")}var Px="Pass the value as an argument or option instead";function Ix(e){if(Po(e))throw new rt;return e}function Nx(e){if(ru())return;throw new W(`Cannot prompt for ${e} without a terminal`,Px)}async function bu(e,t,{edits:n=!1,hint:r}){if(Nx(t.message),qf(t.input))throw new rt;return Lx(r),Ix(await Kf({...t,edits:n},(o)=>e({...t,signal:o})))}function Dx(e){return e.map((t)=>t.key?`${p.bold(t.key)} ${p.dim(t.text)}`:p.dim(t.text)).join(p.dim(" \xB7 "))}function Lx(e){Be.info(Dx(e))}var wu={confirm:[{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],multiselect:[{key:"\u2191\u2193",text:"navigate"},{key:"Space",text:"toggle"},{key:"a",text:"all"},{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],select:[{key:"\u2191\u2193",text:"navigate"},{key:"Enter",text:"select"},{key:"Esc",text:"cancel"}],text:[{key:"Enter",text:"submit"},{key:"Esc",text:"cancel"}]};async function Rt(e){return bu(Gf,e,{hint:wu.confirm})}async function Fn(e){return bu(Vf,e,{edits:!0,hint:wu.text})}async function Xs(e){return bu(Bf,{showInstructions:!1,...e},{hint:wu.select})}function Er(e){return lf()&&e.output===void 0?{...e,output:process.stderr}:e}function $r(e){return(t,n={})=>e(t,Er(n))}var T={error:$r(Be.error),info:$r(Be.info),message:(e,t={})=>Be.message(e,Er(t)),step:$r(Be.step),success:$r(Be.success),warn:$r(Be.warn),warning:$r(Be.warning)};function Su(e,t={}){Ff(e,Er(t))}function Ru(e,t={}){Uf(e,Er(t))}function Do(e,t,n={}){jf(e,t,Er(n))}function ot(e={}){return Yf(Er(e))}import{inspect as Mx}from"util";var Hx=4;function zs(e,t=[]){if(t.length>=Hx)return[];let n=e instanceof AggregateError?e.errors:[],r=[...t,e];return[...n,...e.cause!==void 0?[e.cause]:[]].filter((s)=>!r.includes(s)).flatMap((s)=>[{hint:Zs(s),message:Qs(s)},...s instanceof Error?zs(s,r):[]])}function Qs(e){return ei(e instanceof Error?e.message||e.name:e)}function Zs(e){return e instanceof b&&e.hint!==void 0?ei(e.hint):void 0}function ei(e){return typeof e==="string"?e:Mx(e,{breakLength:Number.POSITIVE_INFINITY})}var Gx="Error",Fx=27,Ux=new RegExp(`${String.fromCharCode(Fx)}\\[[\\d;]*m`,"g"),jx=9,Bx=10,Vx=31,qx=127,Kx=159,Wx=16,Jx=4;function It(e,{json:t}){if(Jf(),zx(e),t)Zt(hn({error:Yx(e)}));return Xf(e)}function Yx(e){let t=Xf(e),n=$u(Qs(e));if(!(e instanceof Error))return{_tag:Gx,message:n,exitCode:t,causes:[]};let r=Zs(e);return{_tag:Xx(e),message:n,hint:r===void 0?void 0:$u(r),exitCode:t,causes:zs(e).map((o)=>$u(o.message))}}function Xf(e){if(e instanceof rt)return Qe;if(e instanceof b)return Ts(e.exitCode)?e.exitCode:$o;return $o}function Xx(e){let t=Reflect.get(e,"_tag");return typeof t==="string"?t:ei(e.name)}function zx(e){if(e instanceof rt)return;let t=Us(),n=ti(Qs(e));if(e instanceof b){let r=Zs(e);if(T.warn(p.yellow(n),{output:t}),r)T.info(p.dim(ti(r)),{output:t})}else T.error(p.red(n),{output:t});if(!(e instanceof Error))return;for(let r of zs(e))if(T.info(p.dim(`caused by: ${ti(r.message)}`),{output:t}),r.hint)T.info(p.dim(` ${ti(r.hint)}`),{output:t})}function ti(e){return Array.from(e.replace(Ux,""),(t)=>{let n=t.charCodeAt(0);return n<=Vx&&n!==jx&&n!==Bx||n>=qx&&n<=Kx?`\\u${n.toString(Wx).padStart(Jx,"0")}`:t}).join("")}var Qx=500,Zx="The command stopped before it finished because nothing was left for it to wait for";function zf({json:e}){let t={ending:void 0,failed:!1,settled:!1},n=(o,s)=>(t.ending??=e_(o,s),t.ending),r=(o)=>{if(t.failed||t.ending)return;t.failed=!0;let s=It(o,{json:e&&!df()});pf(),n(s,t.settled?void 0:Qx)};return process.on("uncaughtException",r),process.on("unhandledRejection",r),process.on("beforeExit",()=>{if(!t.settled)r(Error(Zx))}),{exit:(o)=>n(o),settle(){t.settled=!0}}}async function e_(e,t){process.exitCode=e,await gf(t),process.exit(e)}var en=new Uint32Array(65536),t_=(e,t)=>{let n=e.length,r=t.length,o=1<<n-1,s=-1,i=0,a=n,c=n;while(c--)en[e.charCodeAt(c)]|=1<<c;for(c=0;c<r;c++){let u=en[t.charCodeAt(c)],l=u|i;if(u|=(u&s)+s^s,i|=~(u|s),s&=u,i&o)a++;if(s&o)a--;i=i<<1|1,s=s<<1|~(l|i),i&=l}c=n;while(c--)en[e.charCodeAt(c)]=0;return a},n_=(e,t)=>{let n=t.length,r=e.length,o=[],s=[],i=Math.ceil(n/32),a=Math.ceil(r/32);for(let g=0;g<i;g++)s[g]=-1,o[g]=0;let c=0;for(;c<a-1;c++){let g=0,h=-1,E=c*32,v=Math.min(32,r)+E;for(let S=E;S<v;S++)en[e.charCodeAt(S)]|=1<<S;for(let S=0;S<n;S++){let _=en[t.charCodeAt(S)],C=s[S/32|0]>>>S&1,w=o[S/32|0]>>>S&1,x=_|g,y=((_|w)&h)+h^h|_|w,R=g|~(y|h),A=h&y;if(R>>>31^C)s[S/32|0]^=1<<S;if(A>>>31^w)o[S/32|0]^=1<<S;R=R<<1|C,A=A<<1|w,h=A|~(x|R),g=R&x}for(let S=E;S<v;S++)en[e.charCodeAt(S)]=0}let u=0,l=-1,d=c*32,f=Math.min(32,r-d)+d;for(let g=d;g<f;g++)en[e.charCodeAt(g)]|=1<<g;let m=r;for(let g=0;g<n;g++){let h=en[t.charCodeAt(g)],E=s[g/32|0]>>>g&1,v=o[g/32|0]>>>g&1,S=h|u,_=((h|v)&l)+l^l|h|v,C=u|~(_|l),w=l&_;if(m+=C>>>r-1&1,m-=w>>>r-1&1,C>>>31^E)s[g/32|0]^=1<<g;if(w>>>31^v)o[g/32|0]^=1<<g;C=C<<1|E,w=w<<1|v,l=w|~(S|C),u=C&S}for(let g=d;g<f;g++)en[e.charCodeAt(g)]=0;return m},r_=(e,t)=>{if(e.length<t.length){let n=t;t=e,e=n}if(t.length===0)return e.length;if(e.length<=32)return t_(e,t);return n_(e,t)},Qf=(e,t)=>{let n=1/0,r=0;for(let o=0;o<t.length;o++){let s=r_(e,t[o]);if(s<n)n=s,r=o}return t[r]};function ni(e,t,n){let r=t.length>0?Qf(e,[...t]):void 0,o=`Run "${n} --help" for usage.`;return new W(`Unknown command: ${e}`,r?`Did you mean "${r}"? ${o}`:o)}function Lo(e,t){if(Array.isArray(t))return[...t];if(!Zf(e)||!Zf(t))return t;return Object.fromEntries([...Object.entries(e),...Object.entries(t).map(([n,r])=>[n,Lo(Object.hasOwn(e,n)?e[n]:void 0,r)])])}function Zf(e){if(e===null||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function em(e,t){return{name:e.name,bin:e.bin,version:e.version,description:e.description,exitCodes:{...js},options:tm(He),commands:t.map((n)=>ri(n,`${e.bin} ${n.name}`))}}function ri(e,t){return{name:e.name,path:t,description:e.description,json:e.json,prompts:e.prompts,passthrough:e.passthrough,positionals:Object.entries(e.positionals).map(([n,r])=>({name:n,required:r.required??!1,variadic:r.variadic??!1,description:r.description??""})),options:tm(e.args),examples:[...e.examples],commands:e.subcommands.map((n)=>ri(n,`${t} ${n.name}`))}}function tm(e){return Object.entries(e).map(([t,n])=>({name:t,flag:`--${St(t)}`,...n.alias?{alias:`-${n.alias}`}:{},type:n.type,...n.default===void 0?{}:{default:n.default},...n.displayDefault===void 0?{}:{displayDefault:n.displayDefault},description:n.description??""}))}import{stripVTControlCharacters as nm}from"util";var o_=2,s_="0.0.0",i_=(e)=>e,te={arg:p.magenta,cmd:p.cyan,default:p.bold,desc:i_,flag:p.green,header:(e)=>p.bold(p.yellow(e)),hint:p.dim,name:(e)=>p.bold(p.cyan(e)),placeholder:p.magenta};function rm(e){return`${te.name(e.name)} ${te.hint(e.version??s_)}`}function om(e,t){let n=`${te.name(e.name)}${e.version?` ${te.hint(`v${e.version}`)}`:""}`;return im([[n,...e.description?[te.desc(e.description)]:[]],Nt("Usage:",[` ${te.cmd(e.bin)} ${te.placeholder("[command]")} ${te.placeholder("[options]")}`]),Nt("Commands:",am(t)),Nt("Options:",um(He)),Nt("Exit codes:",cm()),[`${te.hint("Run")} ${te.cmd(`${e.bin} <command> --help`)} ${te.hint("for command details.")}`]])}function sm(e,t){let n=e.json?{...e.args,json:He.json}:e.args,r=[...e.subcommands.length>0?[` ${te.cmd(t)} ${te.placeholder("<command>")} ${te.placeholder("[options]")}`]:[],...e.run?[` ${a_(e,t).join(" ")}`]:[],...e.prompts&&Object.keys(e.positionals).length>0?[` ${te.hint("Omit positional arguments to run interactively.")}`]:[],...e.passthrough?[` ${te.hint("Options end at the first argument; it and everything after it are passed on unchanged.")}`]:[]];return im([[te.name(t),te.desc(e.description)],Nt("Usage:",r),Nt("Commands:",am(e.subcommands)),Nt("Arguments:",u_(e.positionals)),Nt("Options:",um(n)),Nt("Examples:",e.examples.map((o)=>` ${te.cmd(o)}`)),Nt("Exit codes:",cm())])}function a_(e,t){let n=c_(e.positionals);return e.passthrough?[te.cmd(t),te.placeholder("[options]"),te.placeholder("[--]"),...n]:[te.cmd(t),...n,te.placeholder("[options]")]}function Nt(e,t){return t.length>0?[te.header(e),...t]:[]}function im(e){return e.filter((t)=>t.length>0).map((t)=>t.join(`
67
+ `)).join(`
68
+
69
+ `)}function am(e){return oi(e.map((t)=>[` ${te.cmd(t.name)}`,te.desc(t.description)]))}function cm(){return oi(Object.entries(js).map(([e,t])=>[` ${e}`,t]))}function Eu(e,t){return t.variadic?`${e}...`:e}function c_(e){return Object.entries(e).map(([t,n])=>n.required?te.arg(`<${Eu(t,n)}>`):te.arg(`[${Eu(t,n)}]`))}function u_(e){return oi(Object.entries(e).map(([t,n])=>[` ${te.arg(Eu(t,n))}`,`${te.desc(n.description??"")}${n.required?"":te.hint(" (optional)")}`]))}function um(e){return oi(Object.entries(e).map(([t,n])=>{let r=n.alias?`${te.flag(`-${n.alias}`)}, `:" ",o=n.type==="boolean"?"":` ${te.placeholder(`<${n.type==="number"?"number":"value"}>`)}`,s=l_(n),i=s===void 0?"":` (default: ${te.default(s)})`;return[` ${r}${te.flag(`--${St(t)}`)}${o}`,`${te.desc(n.description??"")}${i}`]}))}function l_(e){if(typeof e.displayDefault==="string")return e.displayDefault;if(e.default===void 0)return;if(e.type==="boolean"&&e.default===!1)return;if(e.type==="string")return`"${e.default}"`;return String(e.default)}function oi(e){let t=Math.max(0,...e.map(([n])=>nm(n).length));return e.map(([n,r])=>`${n}${" ".repeat(t-nm(n).length+o_)}${r}`)}function si(e){let t=!1;return{emitted:()=>t,json:e,result(n,r){if(t)throw Error("ctx.output.result was called more than once; a command emits one result");let o=d_(e,n,r);if(t=!0,o!==void 0)Zt(o)}}}function d_(e,t,n){if(e)return hn(t);return n?`${n(t)}
70
+ `:void 0}function ii(e,t,n){return{args:t.args,cli:e.info,config:e.config,interactive:t.interactive,json:t.json,output:n,positionals:t.positionals}}async function ai(e,t,n,r){let o=await mf(n.json,async()=>{let s=await e.run?.(n);return typeof s==="number"?p_(t,s):Qe});if(n.json&&!r.emitted())throw Error(`${t} finished in JSON mode without calling ctx.output.result`);return o}function p_(e,t){if(Ts(t))return t;throw Error(`${e} returned ${t}, which is not an exit code from ${Qe} to ${Wp}`)}var vu="__exit__",lm="__run__",f_="Back",m_="Return to previous menu";async function dm(e,t){if(t)throw new W("Interactive mode cannot be combined with --json","Pass a command and its arguments instead");if(!Co())throw new W("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(e.interactive.clearOnStart)console.clear();let n=e.info.version?` v${e.info.version}`:"";Su(p.bgCyan(p.black(` ${e.info.name}${n} `)));let r={commands:e.commands,message:e.interactive.promptMessage,path:e.info.bin,root:!0};return await pm(e,new Map,r),Ru(e.interactive.goodbyeMessage),Qe}async function pm(e,t,n){while(!0){let r=await g_(e,t,n);if(r===void 0)return;if(t.set(n.path,r),r===lm&&n.owner){await fm(e,n.owner,n.path);continue}let o=n.commands.find((s)=>s.name===r);if(o)await h_(e,t,o,`${n.path} ${r}`)}}async function g_(e,t,n){let r=n.root?{hint:e.interactive.exitHint,label:e.interactive.exitLabel,value:vu}:{hint:m_,label:f_,value:vu};try{let o=await Xs({initialValue:t.get(n.path),message:n.message,options:[...n.owner?[{hint:n.owner.description,label:n.owner.name,value:lm}]:[],...n.commands.map((s)=>({hint:s.description,label:s.name,value:s.name})),r]});return o===vu?void 0:o}catch(o){if(o instanceof rt)return;throw o}}async function h_(e,t,n,r){if(n.subcommands.length===0)return fm(e,n,r);return pm(e,t,{commands:n.subcommands,message:`${n.name}:`,path:r,root:!1,...n.run?{owner:n}:{}})}async function fm(e,t,n){try{await y_(e,t,n)}catch(r){if(r instanceof rt)return;if(!(r instanceof b))throw r;It(r,{json:!1})}}async function y_(e,t,n){let{args:r}=To([],t.args),o=Ds([],t.positionals),s=t.prompts?null:Ls(o,t.positionals);if(s)throw new W(s,`Run "${n} --help" for usage.`);let i=si(!1),a={args:Is(r,t.args),interactive:t.prompts,json:!1,positionals:o};await ai(t,n,ii(e,a,i),i)}var b_="--",w_=/^(?:--json(?:=true)?|-[^-=]*j[^-=]*(?:=true)?)$/,S_=/^(?:--no-(?:help|json)|(?:--(?:help|json)|-[hj]+)(?:=(?:true|false))?)$/;async function ku(e,t){try{return await R_(e,t)}catch(n){return{code:It(n,{json:_u(t)}),menu:!1}}}function xu(e,t){let{command:n,restArgs:r}=Ps(t,He),o=n===void 0||n===Hn?void 0:hm(e,n,r);if(!o||o instanceof W||!o.command.passthrough)return{operands:[],options:[...t]};let s=Zp(o.tokens,{...o.command.args,...wr}),i=s<0?[]:o.tokens.slice(s);return{operands:i,options:t.slice(0,t.length-i.length)}}async function R_(e,{options:t,operands:n}){let{command:r,flags:o,restArgs:s}=_o(t,He,wr),i=o.json===!0,a={code:Qe,menu:!1};if(r===void 0){if(o.interactive&&!o.help&&!o.version)return{code:await dm(e,i),menu:!0};return Zt(o.version&&!o.help?E_(e,i):mm(e,i)),a}let c=o.interactive?"--interactive":o.version?"--version":void 0;if(c)throw new W(`${c} cannot be combined with a command`,`Run "${e.info.bin} ${c}" on its own.`);if(r===Hn)return Zt(v_(e,s,i)),a;let u=k_(e,r,s);if(o.help)return Zt(Tu(u.command,u.path,i)),a;return{code:await x_(e,u,n,i),menu:!1}}function _u({options:e}){let{before:t,restArgs:n}=Ps(e,He);return[t,n].some((r)=>$_(r).some((o)=>w_.test(o)))}function $_(e){let t=e.indexOf(b_);return t<0?e:e.slice(0,t)}function E_({info:e},t){return t?hn({name:e.name,bin:e.bin,version:e.version}):`${rm(e)}
71
+ `}function mm(e,t){return t?hn(em(e.info,e.commands)):`${om(e.info,e.commands)}
72
+ `}function Tu(e,t,n){return n?hn(ri(e,t)):`${sm(e,t)}
73
+ `}function v_(e,t,n){let{args:r,rawPositionals:o}=To(t,wr);if(Os(r,wr,`Run "${e.info.bin} ${Hn} [command]" for usage.`,t),o.length===0)return mm(e,n);let{command:s,path:i}=gm(e.commands,o,e.info.bin);return Tu(s,i,n)}function gm(e,t,n){let[r="",...o]=t,s=e.find((a)=>a.name===r);if(!s)throw ni(r,Au(e),n);let i=`${n} ${r}`;return o.length===0?{command:s,path:i}:gm(s.subcommands,o,i)}function Au(e){return e.map((t)=>t.name)}function k_(e,t,n){let r=hm(e,t,n);if(r instanceof W)throw r;return r}function hm(e,t,n){let r=e.commands.find((o)=>o.name===t);if(!r)return ni(t,Au(e.commands),e.info.bin);return ym({command:r,path:`${e.info.bin} ${t}`,tokens:n})}function ym(e){let{command:t,path:n,tokens:r}=e;if(t.subcommands.length===0)return e;let o=r.findIndex((a)=>!S_.test(a)),s=r[o];if(s===void 0||s.startsWith("-"))return e;let i=t.subcommands.find((a)=>a.name===s);if(i)return ym({command:i,path:`${n} ${s}`,tokens:r.toSpliced(o,1)});if(t.run&&Object.keys(t.positionals).length>0)return e;return ni(s,Au(t.subcommands),n)}async function x_(e,{command:t,path:n,tokens:r},o,s){let i=`Run "${n} --help" for usage.`,a={...t.args,...wr},c=To(r,a),{args:u}=c,l=[...c.rawPositionals,...o];if(t.strict)Os(u,a,i,r);if(s&&!t.json)throw new W(`${n} does not support --json`,i);let d=t.strict?tf(l,t.positionals):void 0;if(d!==void 0)throw new W(`Unexpected argument: ${d}`,i);if(!t.run)return Zt(Tu(t,n,s)),Qe;let f=Ds(l,t.positionals),m=Ls(f,t.positionals);if(m)throw new W(m,i);let g=t.prompts&&l.length===0&&Co()&&!s,h={args:Is(u,t.args),interactive:g,json:s,positionals:f},E=si(s);try{return await ai(t,n,ii(e,h,E),E)}catch(v){return It(v,{json:s&&!E.emitted()})}}var __={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",promptMessage:"What would you like to do?"};function Cu(e){let t=`CLI "${e.name}"`;if(Hs(t,e.commands),e.commands.some((r)=>r.name===Hn))throw Error(`${t} cannot define a command named "${Hn}": the framework provides it`);let n={commands:e.commands,config:e.config,info:{bin:e.bin??e.name,description:e.description,name:e.name,version:e.version},interactive:{...__,...e.interactive}};return{async main(r=process.argv.slice(2)){ff();let o=xu(n,r),s=zf({json:_u(o)}),i=await ku(n,o);if(s.settle(),i.code===Qe&&!i.menu)return;await s.exit(i.code)},async run(r=process.argv.slice(2)){return(await ku(n,xu(n,r))).code}}}import Dt from"fs";import Du from"path";var Ze=(e)=>(e.map=(t)=>Ze((n)=>t(e(n))),e.or=(t)=>Ze((n)=>{try{return e(n)}catch(r){return t(n)}}),e),F=()=>"bad banditype"();var vr=()=>Ze((e)=>e),J=(e)=>Ze((t)=>e.includes(t)?t:F()),ci=(e)=>Ze((t)=>typeof t===typeof e?t:F()),I=()=>ci(""),X=()=>ci(0),Q=()=>ci(!0);var ne=()=>ci(),$t=()=>Ze((e)=>e===null?e:F()),Mo=(e)=>Ze((t)=>t instanceof e?t:F()),kr=(e)=>Mo(Object).map((t)=>{let n={};for(let r in t){let o=e(t[r]);o!==void 0&&(n[r]=o)}return n}),N=(e)=>Mo(Object).map((t)=>{let n={};for(let r in e){let o=e[r](t[r]);o!==void 0&&(n[r]=o)}return n});var Z=(e)=>Mo(Array).map((t)=>t.map(e));import xr from"fs";var T_=".lock",A_=".break",bm=10,C_=1e4,O_=5000;function wm(e,t){let n=`${e}${T_}`,r=crypto.randomUUID();P_(n,r);try{return t()}finally{Sm(n,r)}}function P_(e,t){let n=Date.now()+C_;while(!Rm(e,t)){if(Date.now()>n)throw Error(`timed out waiting for ${e}, which another process holds`);if(Ou(e))I_(e,t);else Bun.sleepSync(bm)}}function Sm(e,t){if(N_(e)===t)xr.rmSync(e,{force:!0})}function I_(e,t){let n=`${e}${A_}`;if(!Rm(n,t)){if(Ou(n))xr.rmSync(n,{force:!0});else Bun.sleepSync(bm);return}try{if(Ou(e))xr.rmSync(e,{force:!0})}finally{Sm(n,t)}}function Rm(e,t){try{return xr.writeFileSync(e,t,{flag:"wx"}),!0}catch(n){if($m(n)==="EEXIST")return!1;throw n}}function Ou(e){let t=xr.statSync(e,{throwIfNoEntry:!1})?.mtimeMs;return t!==void 0&&Date.now()-t>O_}function N_(e){try{return xr.readFileSync(e,"utf8")}catch(t){if($m(t)==="ENOENT")return;throw t}}function $m(e){return e instanceof Error?Reflect.get(e,"code"):void 0}import Pu from"fs";import Un from"path";var D_="..",L_=40;function vm(e){let{root:t}=Un.parse(Un.resolve(e)),n=Em(Un.resolve(e)),r=t,o=0;for(let s=n.shift();s!==void 0;s=n.shift()){if(s===D_){r=Un.dirname(Pu.realpathSync(r));continue}let i=Un.join(r,s);if(!Pu.lstatSync(i,{throwIfNoEntry:!1})?.isSymbolicLink()){r=i;continue}if(o+=1,o>L_)throw Error(`too many symbolic links in ${e}`);let a=Pu.readlinkSync(i);if(Un.isAbsolute(a))r=t;n.unshift(...Em(a))}return r}function Em(e){return e.split(Un.sep).filter((t)=>t!==""&&t!==".")}function Nu(e,t){JSON.parse(e);let n=JSON.parse(JSON.stringify(t)),r=M_(e),o=e.match(/^[\t ]+(?=\S)/m)?.[0]??" ",s=e.includes(`\r
85
74
  `)?`\r
86
75
  `:`
87
- `,s=/\s/.test(e[r.start+1]??"")||r.entries.some((u)=>/:\s+$/.test(e.slice(u.start,u.node.start)))?" ":"";function c(u,d){let p=e.slice(u.start,u.end);if(JSON.stringify(u.value)===JSON.stringify(d))return p;let m=Array.isArray(d);if(d===null||typeof d!=="object"||u.value===null||typeof u.value!=="object"||Array.isArray(u.value)!==m)return a(d,u.start,p.includes(`
88
- `));let h=m?d.map((S,A)=>String(A)):[...new Set([...u.entries.map((S)=>S.key).filter((S)=>Object.hasOwn(d,S)),...Object.keys(d)])];if(h.length===0)return m?"[]":"{}";let f=u.entries[0],w=u.entries.at(-1);if(!f||!w)return a(d,u.start,p.includes(`
89
- `));let v=(S)=>m?d[Number(S)]:d[S];if(h.length===u.entries.length&&h.every((S,A)=>S===u.entries[A]?.key)){let S=u.start,A="";for(let J of u.entries)A+=e.slice(S,J.node.start)+c(J.node,v(J.key)),S=J.node.end;return A+e.slice(S,u.end)}let C=e.slice(u.start+1,f.start),R=e.slice(w.node.end,u.end-1),P=u.entries[1],H=P?e.slice(f.node.end,P.start):`,${C.includes(`
90
- `)?C:s}`,k=m?"":e.slice(f.start,f.node.start).match(/:\s*$/)?.[0]??": ",D=new Map(u.entries.map((S)=>[S.key,S])),N=h.map((S)=>{let A=D.get(S);if(A)return e.slice(A.start,A.node.start)+c(A.node,v(S));return(m?"":JSON.stringify(S)+k)+a(v(S),f.start,C.includes(`
91
- `))});return`${m?"[":"{"}${C}${N.join(H)}${R}${m?"]":"}"}`}function a(u,d,p){if(!p)return dr(u,s);let m=e.lastIndexOf(`
92
- `,d-1)+1,h=e.slice(m,d).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(u,null,o).replaceAll(`
93
- `,i+h)}return e.slice(0,r.start)+c(r,n)+e.slice(r.end)}function dr(e,t){if(Array.isArray(e))return`[${e.map((o)=>dr(o,t)).join(`,${t}`)}]`;if(e===null||typeof e!=="object")return JSON.stringify(e);let n=Object.entries(e);if(n.length===0)return"{}";let r=n.map(([o,i])=>`${JSON.stringify(o)}:${t}${dr(i,t)}`);return`{${t}${r.join(`,${t}`)}${t}}`}function Nu(e){let t=e.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),n=t.next().value;function r(){if(!n)throw Error("Unexpected end of JSON");let i=n;return n=t.next().value,i}function o(){let i=r(),s=[],c=i[0]==="{";if(!c&&i[0]!=="[")return{end:i.index+i[0].length,entries:s,start:i.index,value:JSON.parse(i[0])};let a=c?"}":"]";while(n&&n[0]!==a){let d=n.index,p=c?JSON.parse(r()[0]):String(s.length);if(c)r();if(s.push({key:p,node:o(),start:d}),n?.[0]===",")r()}let u=r().index+1;return{end:u,entries:s,start:i.index,value:JSON.parse(e.slice(i.index,u))}}return o()}var Du=2,Gu=Jt(Object);class fr{config;configPath;defaultConfig;loadError;loadFailure;constructor(e,t,n={}){this.configPath=ni.resolve(e),this.defaultConfig=t,this.config=this.loadConfig(n)}get path(){return this.configPath}get failure(){return this.loadFailure}get(e){return this.assertLoaded(),this.config[e]}set(e,t){this.assertLoaded(),this.config={...this.config,[e]:t},this.save()}delete(e){this.assertLoaded(),delete this.config[e],this.save()}exists(){return se.existsSync(this.configPath)}getAll(){return this.assertLoaded(),structuredClone(this.config)}save(e){if(this.assertLoaded(),this.loadError)throw Error(`Cannot overwrite unreadable config at ${this.configPath}; repair the file and try again`,{cause:this.loadError});if(e)this.config={...e};this.ensureDirectoryExists();let t=this.exists()?se.realpathSync(this.configPath):this.configPath,n=`${t}.${crypto.randomUUID()}.tmp`;try{let r=this.exists()?se.statSync(this.configPath).mode:void 0,o=this.exists()?pr(se.readFileSync(this.configPath,"utf-8"),this.config):`${JSON.stringify(this.config,null,Du)}
94
- `;if(se.writeFileSync(n,o,{flag:"wx",mode:r}),r!==void 0)se.chmodSync(n,r);se.renameSync(n,t)}catch(r){throw Error(`Failed to save config to ${this.configPath}`,{cause:r})}finally{se.rmSync(n,{force:!0})}}assertLoaded(){if(this.loadFailure)throw this.loadFailure}ensureDirectoryExists(){let e=ni.dirname(this.configPath);if(!se.existsSync(e))try{se.mkdirSync(e,{recursive:!0})}catch(t){throw Error(`Failed to create config directory at ${e}`,{cause:t})}}loadConfig({parse:e,strict:t}){if(!t&&!se.existsSync(this.configPath))return structuredClone(this.defaultConfig);try{let n=this.readConfigFile();if(n===void 0)return structuredClone(this.defaultConfig);let r=JSON.parse(n);if(Array.isArray(r))throw Error("Config must be an object");let o=Kt(structuredClone(this.defaultConfig),Gu(r));return e?e(o):o}catch(n){if(t){let r=n instanceof Error?n.message:String(n);return this.loadFailure=Error(`Cannot read config at ${this.configPath}: ${r}`,{cause:n}),structuredClone(this.defaultConfig)}return this.loadError=n,console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),structuredClone(this.defaultConfig)}}readConfigFile(){try{return se.readFileSync(this.configPath,"utf-8")}catch(e){if(e.code==="ENOENT")return;throw e}}}var ri="0.13.0";class x extends yt{}var qt="hydra",$t="default",oi={profiles:{}},ii=!1,si=24,zt=7,ai=["logs","shared"],ui=!1,ci=!0,li=!0,di=!0,pi=120,fi=["github.com","api.github.com","objects.githubusercontent.com","pipelines.actions.githubusercontent.com"];import{readFileSync as Fu,statSync as mr}from"fs";import{homedir as Uu}from"os";import{basename as ju,dirname as gr,isAbsolute as hi,join as Te,resolve as Yt}from"path";var Xt=".hydra",ae="HYDRA_HOME",j="--home",Zt={description:"Use this state directory (absolute path)",displayDefault:`${ae} or ~/.hydra`,type:"string"},yr="config.json",Bu="runners",Ku="shared",Vu="--",Ju=`Pass ${j} <absolute path> or set ${ae}`;function gi(e){return Te(e.HOME||Uu(),Xt)}function yi(e,t){let{flag:n,rest:r}=Wu(e);if(n!==void 0)return{argv:r,home:mi(n,j),source:"flag"};let o=t[ae];if(o)return{argv:r,home:mi(o,ae),source:"environment"};return{argv:r,home:gi(t),source:"default"}}function Ce(e){return{config:Te(e,yr),home:e,runners:Te(e,Bu),shared:Te(e,Ku)}}function fe(e){return gr(e.path)}function br(e,t){if(hi(t))return t;return Yt(ju(e)===Xt?gr(e):e,t)}function bi(e,t){let n=Te(t,Xt);return $i(n)&&!hr(n,e)?n:void 0}function Qt(e,t,n){let r=[...wi(t).map((i)=>Te(i,Xt)),gi(n)],o=[];for(let i of r){if(!$i(i)||hr(i,e))continue;if(o.some((s)=>hr(s,i)))continue;o.push(i)}return o.map((i)=>({counts:qu(i),path:i}))}function Wu(e){let t=[],n;for(let r=0;r<e.length;r++){let o=e[r];if(o===Vu){t.push(...e.slice(r));break}let i=o.startsWith(`${j}=`);if(o!==j&&!i){t.push(o);continue}if(n!==void 0)throw new y(`${j} can only be provided once`);let s=i?o.slice(j.length+1):e[r+1];if(!s||!i&&s.startsWith("-"))throw new y(`${j} needs a directory`,`Use ${j} <absolute path>`);if(n=s,!i)r++}return{flag:n,rest:t}}function mi(e,t){if(!hi(e))throw new y(`${t} must be an absolute path: ${e}`,Ju);return Yt(e)}function wi(e){let t=gr(e);return t===e?[e]:[e,...wi(t)]}function $i(e){try{return mr(Te(e,yr)).isFile()}catch{return!1}}function hr(e,t){if(Yt(e)===Yt(t))return!0;try{let n=mr(e),r=mr(t);return n.dev===r.dev&&n.ino===r.ino}catch{return!1}}function vi(e){let t=Ri(e);if(!t)return;return(Array.isArray(t.runners)?t.runners:[]).flatMap((r)=>{if(typeof r!=="object"||r===null)return[];let{id:o,name:i}=r;return[o,i].filter((s)=>typeof s==="string")})}function qu(e){let t=Ri(e);if(!t)return;let{profiles:n,runners:r}=t;return{profiles:typeof n==="object"&&n!==null?Object.keys(n).length:0,runners:Array.isArray(r)?r.length:0}}function Ri(e){try{let t=JSON.parse(Fu(Te(e,yr),"utf-8"));return typeof t==="object"&&t!==null?t:void 0}catch{return}}var zu="https://api.github.com",Xe="HYDRA_GITHUB_API_URL",Yu="2022-11-28",Xu="r5n-hydra",Zu=3,Ti=500,Qu=60000,Pi=30000,en=1000,ec=100,Ci=100,tc=200,nc=403,Si=429,rc=204,oc=500,xi="[redacted]",ic=new Set(["DELETE","GET","PUT"]),sc=new Set(["127.0.0.1","[::1]"]),ac=[/\bgh[opsur]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_\w{20,}\b/g,/\beyJ[\w-]+\.[\w-]+\.[\w-]+/g],uc=/[\p{Cc}\p{Cf}]+/gu,cc=/<([^>]+)>;\s*rel="next"/,lc=/\/+$/,dc=/^\/+/,pc=/\s+/g;class V extends Error{operation;method;path;status;_tag="GitHubApiError";constructor(e,t,n,r,o){let i=r===void 0?"got no response":`returned ${r}`;super(`${e} failed: ${t} ${n} ${i}${o?` (${o})`:""}`);this.operation=e;this.method=t;this.path=n;this.status=r;this.name="GitHubApiError"}}function tn(e){let t=e[Xe];if(!t)return zu;let n="Use an https URL, or http on 127.0.0.1 or [::1], with no credentials, query or fragment",r;try{r=new URL(t)}catch{throw new y(`${Xe} is not a URL`,n)}if(!(r.protocol==="https:"||r.protocol==="http:"&&sc.has(r.hostname))||r.username||r.password||r.search||r.hash)throw new y(`${Xe} is not an API root Hydra may send tokens to`,n);return r.href.replace(lc,"")}function wr({apiUrl:e,auth:t}){let n=new URL(`${e}/`);async function r(a,u,d,p,m){let h=i(u);for(let f=1;;f++){let w=await t.token(),v=f<Zu,C;try{C=await fetch(u,{body:p===void 0?void 0:JSON.stringify(p),headers:mc(w,p!==void 0),method:a,redirect:"manual",signal:AbortSignal.timeout(Pi)})}catch(H){if(m&&v){await Bun.sleep(Ei(f));continue}throw new V(d,a,h,void 0,_i(ki(H),w))}if(C.ok)return C;let R=hc(C);if(R!==void 0&&v&&R<=Qu){await C.body?.cancel(),await Bun.sleep(R);continue}if(R===void 0&&C.status>=oc&&m&&v){await C.body?.cancel(),await Bun.sleep(Ei(f));continue}let P=[R===void 0?"":gc(C),await yc(C)].filter(Boolean).join("; ");throw new V(d,a,h,C.status,_i(P,w))}}async function o(a,u,d,p,m){let h=i(m),f;try{f=a.status===rc?"":await a.text()}catch(v){throw new V(d,p,h,a.status,ki(v))}let w;try{w=f===""?void 0:JSON.parse(f)}catch{throw new V(d,p,h,a.status,"the response is not JSON")}try{return u(w)}catch{throw new V(d,p,h,a.status,"the response has an unexpected shape")}}function i(a){return a.pathname.slice(n.pathname.length-1)+a.search}function s(a){return new URL(a.replace(dc,""),n)}function c(a){return a.origin===n.origin&&a.pathname.startsWith(n.pathname)}return{async paginate({item:a,key:u,operation:d,path:p}){let m=[],h=s(p);if(!h.searchParams.has("per_page"))h.searchParams.set("per_page",String(ec));let f=h;for(let w=1;f;w++){if(w>Ci)throw new V(d,"GET",p,void 0,`stopped after ${Ci} pages`);let v=await r("GET",f,d,void 0,!0),C=v.headers.get("link"),R=await o(v,fc(a,u),d,"GET",f);m.push(...R);let P=C?.match(cc)?.[1];if(f=P?new URL(P):void 0,f&&!c(f))throw new V(d,"GET",p,v.status,"refused a next page outside the API root")}return m},async request({body:a,idempotent:u,method:d="GET",operation:p,path:m,schema:h}){let f=s(m),w=await r(d,f,p,a,u??ic.has(d));return o(w,h,p,d,f)}}}function Ai(e){let t,n=()=>(t??=e(),t);return{async paginate(r){return n().paginate(r)},async request(r){return n().request(r)}}}function fc(e,t){return(n)=>{let r=t===void 0?n:n?.[t];if(!Array.isArray(r))throw TypeError("not a list");return r.map((o)=>e(o))}}function mc(e,t){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"User-Agent":Xu,"X-GitHub-Api-Version":Yu,...t?{"Content-Type":"application/json"}:{}}}function Ei(e){return Ti*2**(e-1)}function hc(e){if(e.status!==nc&&e.status!==Si)return;let t=e.headers.get("retry-after");if(t!==null&&t.trim()!==""&&Number.isFinite(Number(t)))return Math.max(0,Number(t)*en);if(e.headers.get("x-ratelimit-remaining")==="0"){let n=e.headers.get("x-ratelimit-reset")?.trim(),r=n?Number(n):Number.NaN;return Number.isFinite(r)?Math.max(0,r*en-Date.now()):Number.POSITIVE_INFINITY}return e.status===Si?Ti:void 0}function gc(e){let t=Number(e.headers.get("x-ratelimit-reset")),n=Number(e.headers.get("retry-after"));if(Number.isFinite(n)&&n>0)return`rate limited; retry in ${n} s`;if(Number.isFinite(t)&&t>0)return`rate limited until ${new Date(t*en).toISOString()}`;return"rate limited"}async function yc(e){try{let n=JSON.parse(await e.text())?.message;return typeof n==="string"?n:""}catch{return""}}function ki(e){if(e instanceof Error&&e.name==="TimeoutError")return`timed out after ${Pi/en} s`;return e instanceof Error?e.message:String(e)}function _i(e,t){let n=t?e.replaceAll(t,xi):e;return ac.reduce((r,o)=>r.replace(o,xi),n).replace(uc," ").replace(pc," ").trim().slice(0,tc)}import{createPrivateKey as bc,sign as wc}from"crypto";import{constants as Ii}from"fs";import{open as $c,stat as vc}from"fs/promises";var Hi="github.com",Rc=60,Cc=540,Sc=300000,xc=1000,Ec=63,kc=511,_c=8,Tc=4,Pc=Ii.O_RDONLY|Ii.O_NONBLOCK,$r="Check the GitHub App's id, installation id and private key in credentials",vr=U().map((e)=>e.trim()===""?F():e),Ac=ge({expires_at:U(),token:vr}),Oi=new WeakMap;class Me extends y{_tag="GitHubCredentialsError"}function Ic(e,t){let n,r=()=>{if(n)return n;let o=tn(t),i=e?.mode==="app"?Oc(e,o):Hc();return n={client:wr({apiUrl:o,auth:i}),credentials:i},n};return{client:Ai(()=>r().client),credentials:{kind:e?.mode??"gh",async token(){return r().credentials.token()}}}}function nn(e){let t=Oi.get(e);if(t)return t;let n=Ic(e.get("credentials"),process.env);return Oi.set(e,n),n}function Ni(e){return e?.mode==="app"?`GitHub App ${e.appId}, installation ${e.installationId}, key ${e.privateKeyPath}`:"the gh login (gh auth token)"}async function Di(e){try{return Gi(await vc(e))}catch(t){return`cannot be read (${t.code??"unknown error"})`}}function Hc(){let e;return{kind:"gh",token(){return e??=Lc().catch((t)=>{throw e=void 0,t}),e}}}function Oc(e,t){let n=wr({apiUrl:t,auth:{token:async()=>Dc(e.appId,await Nc(e.privateKeyPath))}}),r,o;async function i(){try{let{expires_at:s,token:c}=await n.request({idempotent:!0,method:"POST",operation:`Mint an installation token for GitHub App ${e.appId}`,path:`/app/installations/${e.installationId}/access_tokens`,schema:Ac});return{expiresAt:Date.parse(s),token:c}}catch(s){throw s instanceof V?new Me(s.message,$r):s}}return{kind:"app",async token(){if(r&&r.expiresAt-Sc>Date.now())return r.token;o??=i().finally(()=>{o=void 0});let s=await o;return r=Number.isFinite(s.expiresAt)?s:void 0,s.token}}}async function Lc(){let e=await Bun.$`gh auth token --hostname ${Hi}`.quiet().nothrow(),t=e.stdout.toString().trim();if(e.exitCode===0&&t)return t;let n=e.stderr.toString().trim();throw new Me(`gh auth token failed for ${Hi}${n?`: ${n}`:""}`,"Run gh auth login, or configure a GitHub App in credentials")}async function Nc(e){let n;try{n=await $c(e,Pc)}catch(r){throw new Me(`Cannot open the GitHub App private key ${e} (${r.code??"unknown error"})`,"credentials.privateKeyPath must name a PEM file owned by the user running Hydra, with mode 0600")}try{let r=Gi(await n.stat());if(r)throw new Me(`The GitHub App private key ${e} ${r}`,"credentials.privateKeyPath must name a PEM file owned by the user running Hydra, with mode 0600");let o;try{o=bc(await n.readFile("utf8"))}catch{throw new Me(`The GitHub App private key ${e} is not a PEM private key`,"credentials.privateKeyPath must name a PEM file owned by the user running Hydra, with mode 0600")}if(o.asymmetricKeyType!=="rsa")throw new Me(`The GitHub App private key ${e} is not an RSA key`,"credentials.privateKeyPath must name a PEM file owned by the user running Hydra, with mode 0600");return o}finally{await n.close()}}function Gi(e){let t=process.getuid?.();if(!e.isFile())return"is not a regular file";if(t===void 0)return"cannot be checked for its owner on this platform";if(e.uid!==t)return`is owned by uid ${e.uid}, not by the user running Hydra (uid ${t})`;if((e.mode&Ec)!==0)return`is open to its group or others (mode ${(e.mode&kc).toString(_c).padStart(Tc,"0")})`;return}function Dc(e,t){let n=Math.floor(Date.now()/xc)-Rc,r=Li(JSON.stringify({alg:"RS256",typ:"JWT"})),o=Li(JSON.stringify({exp:n+Cc,iat:n,iss:e})),i=wc("sha256",Buffer.from(`${r}.${o}`),t).toString("base64url");return`${r}.${o}.${i}`}function Li(e){return Buffer.from(e).toString("base64url")}var Gc=new Set(["github.com","www.github.com"]);var Mi=/\.git$/;function ue(e){let t;try{t=new URL(e)}catch{throw Error(`Invalid GitHub URL: ${e}`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error(`Invalid GitHub URL (expected http(s)): ${e}`);if(!Gc.has(t.hostname))throw Error(`Invalid GitHub URL (host must be github.com): ${e}`);let n=t.pathname.split("/").filter(Boolean);if(n.length===1){let r=n[0]?.replace(Mi,"");if(!r)throw Error(`Invalid GitHub URL: ${e}`);return{kind:"org",org:r}}if(n.length===2){let r=n[0],o=n[1]?.replace(Mi,"");if(!r||!o)throw Error(`Invalid GitHub URL: ${e}`);return{kind:"repo",owner:r,repo:o}}throw Error(`Invalid GitHub URL (expected github.com/<owner>/<repo> or github.com/<org>): ${e}`)}function Pe(e){return e.kind==="repo"?`${e.owner}/${e.repo}`:e.org}var Fi=404,Mc=422,Fc="offline",Uc=Q().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),rn=ge({busy:te(),id:Uc,name:U(),status:U()}),jc=()=>{return};function Rr(e){return`/${e.kind==="repo"?`repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`:`orgs/${encodeURIComponent(e.org)}`}/actions/runners`}function on(e){return e.status===Fc}async function sn(e,t){return e.paginate({item:rn,key:"runners",operation:`List the runners of ${Pe(t)}`,path:Rr(t)})}async function Ze(e,t,n){try{return await e.request({operation:`Read runner ${n} of ${Pe(t)}`,path:`${Rr(t)}/${n}`,schema:rn})}catch(r){if(r instanceof V&&r.status===Fi)return;throw r}}async function Ui(e,t,n){try{return await e.request({method:"DELETE",operation:`Delete runner ${n} of ${Pe(t)}`,path:`${Rr(t)}/${n}`,schema:jc}),"deleted"}catch(r){if(!(r instanceof V))throw r;if(r.status===Fi)return"gone";if(r.status===Mc)return"busy";throw r}}function an(e,t){switch(e){case"app":return t.kind==="repo"?"The GitHub App needs the Administration repository permission (read and write) on the repository":"The GitHub App needs the Self-hosted runners organisation permission (read and write)";case"gh":return t.kind==="repo"?"gh needs admin access to the repository":"gh needs the admin:org scope"}}var ji="selected",Bi=Q().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),Ki=ge({allows_public_repositories:te().or(ti()),default:te(),id:Bi,name:U(),visibility:U()}).map((e)=>({allowsPublicRepositories:e.allows_public_repositories,default:e.default,id:e.id,name:e.name,visibility:e.visibility})),Bc=ge({id:Bi}),Kc=()=>{return};function vt(e){return`/orgs/${encodeURIComponent(e)}/actions/runner-groups`}async function Vc(e,t){return e.paginate({item:Ki,key:"runner_groups",operation:`List the runner groups of ${t}`,path:vt(t)})}async function Vi(e,t,n){return(await Vc(e,t)).find((o)=>o.name.toLowerCase()===n.toLowerCase())}async function Ji(e,t,n){return e.request({body:{allows_public_repositories:!1,name:n,selected_repository_ids:[],visibility:ji},method:"POST",operation:`Create the runner group ${n} in ${t}`,path:vt(t),schema:Ki})}async function Wi(e,t,n){return(await e.paginate({item:Bc,key:"repositories",operation:`List the repositories that may use the runner group ${n.name} of ${t}`,path:`${vt(t)}/${n.id}/repositories`})).length}async function qi(e,t,n){return e.paginate({item:rn,key:"runners",operation:`List the runners in the runner group ${n.name} of ${t}`,path:`${vt(t)}/${n.id}/runners`})}async function zi(e,t,n,r){await e.request({method:"PUT",operation:`Move runner ${r} of ${t} into the runner group ${n.name}`,path:`${vt(t)}/${n.id}/runners/${r}`,schema:Kc})}function Yi(e,t){if(e.default)return"it is the default group, which every repository may use";if(e.visibility!==ji)return`its visibility is ${e.visibility}, not selected`;if(e.allowsPublicRepositories)return"it allows public repositories";if(t>0)return`${t} repository(ies) may use it`;return}import{spawn as Cl}from"child_process";import{once as Sl}from"events";import{existsSync as Ue}from"fs";import{cp as xl,link as El,mkdir as hn,mkdtemp as kl,readdir as cs,readFile as ls,readlink as _l,rename as Tl,rm as je,stat as ds,symlink as Pl,unlink as ps,writeFile as Al}from"fs/promises";import{join as I,resolve as Ir}from"path";import{chmod as Wc,mkdir as qc,readFile as zc,rename as Yc,rm as Xc,stat as Zc,writeFile as ts}from"fs/promises";import{dirname as Qc,join as kr,resolve as cn}from"path";import{isAbsolute as Jc}from"path";var Cr="# Generated by Hydra; hydra update rewrites this file.";function Xi(e){return`'${e.replaceAll("'","'\\''")}'`}function Zi(){return`#!/usr/bin/env bash
95
- ${Cr}
76
+ `,i=/\s/.test(e[r.start+1]??"")||r.entries.some((u)=>/:\s+$/.test(e.slice(u.start,u.node.start)))?" ":"";function a(u,l){let d=e.slice(u.start,u.end);if(JSON.stringify(u.value)===JSON.stringify(l))return d;let f=Array.isArray(l);if(l===null||typeof l!=="object"||u.value===null||typeof u.value!=="object"||Array.isArray(u.value)!==f)return c(l,u.start,d.includes(`
77
+ `));let m=f?l.map((R,A)=>String(A)):[...new Set([...u.entries.map((R)=>R.key).filter((R)=>Object.hasOwn(l,R)),...Object.keys(l)])];if(m.length===0)return f?"[]":"{}";let g=u.entries[0],h=u.entries.at(-1);if(!g||!h)return c(l,u.start,d.includes(`
78
+ `));let E=(R)=>f?l[Number(R)]:l[R];if(m.length===u.entries.length&&m.every((R,A)=>R===u.entries[A]?.key)){let R=u.start,A="";for(let k of u.entries)A+=e.slice(R,k.node.start)+a(k.node,E(k.key)),R=k.node.end;return A+e.slice(R,u.end)}let v=e.slice(u.start+1,g.start),S=e.slice(h.node.end,u.end-1),_=u.entries[1],C=_?e.slice(g.node.end,_.start):`,${v.includes(`
79
+ `)?v:i}`,w=f?"":e.slice(g.start,g.node.start).match(/:\s*$/)?.[0]??": ",x=new Map(u.entries.map((R)=>[R.key,R])),y=m.map((R)=>{let A=x.get(R);if(A)return e.slice(A.start,A.node.start)+a(A.node,E(R));return(f?"":JSON.stringify(R)+w)+c(E(R),g.start,v.includes(`
80
+ `))});return`${f?"[":"{"}${v}${y.join(C)}${S}${f?"]":"}"}`}function c(u,l,d){if(!d)return Iu(u,i);let f=e.lastIndexOf(`
81
+ `,l-1)+1,m=e.slice(f,l).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(u,null,o).replaceAll(`
82
+ `,s+m)}return e.slice(0,r.start)+a(r,n)+e.slice(r.end)}function Iu(e,t){if(Array.isArray(e))return`[${e.map((o)=>Iu(o,t)).join(`,${t}`)}]`;if(e===null||typeof e!=="object")return JSON.stringify(e);let n=Object.entries(e);if(n.length===0)return"{}";let r=n.map(([o,s])=>`${JSON.stringify(o)}:${t}${Iu(s,t)}`);return`{${t}${r.join(`,${t}`)}${t}}`}function M_(e){let t=e.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),n=t.next().value;function r(){if(!n)throw Error("Unexpected end of JSON");let s=n;return n=t.next().value,s}function o(){let s=r(),i=[],a=s[0]==="{";if(!a&&s[0]!=="[")return{end:s.index+s[0].length,entries:i,start:s.index,value:JSON.parse(s[0])};let c=a?"}":"]";while(n&&n[0]!==c){let l=n.index,d=a?JSON.parse(r()[0]):String(i.length);if(a)r();if(i.push({key:d,node:o(),start:l}),n?.[0]===",")r()}let u=r().index+1;return{end:u,entries:i,start:s.index,value:JSON.parse(e.slice(s.index,u))}}return o()}var H_=2,Lu="ConfigError",G_=Mo(Object);class Mu{loaded;configPath;defaultConfig;options;constructor(e,t,n={}){this.configPath=Du.resolve(e),this.defaultConfig=t,this.options=n}get path(){return this.configPath}get failure(){return this.state().failure}get(e){return this.current()[e]}set(e,t){let n=this.writable();this.update((r)=>({...r,[e]:t})),n.config={...n.config,[e]:t}}delete(e){let t=this.writable();this.update((n)=>(delete n[e],n)),delete t.config[e]}exists(){return Dt.existsSync(this.configPath)}getAll(){return structuredClone(this.current())}save(e){let t=this.writable();if(e)t.config={...e};this.update(()=>t.config)}state(){return this.loaded??=this.load(),this.loaded}current(){let{config:e,failure:t}=this.state();if(t)throw t;return e}writable(){let e=this.state();if(e.failure)throw e.failure;if(e.error)throw this.unreadable(e.error);return e}unreadable(e){return new b(`Cannot overwrite unreadable config at ${this.configPath}`,"Repair the file and try again",void 0,{cause:e,tag:Lu})}readStored(){try{let e=this.readConfigFile();if(e===void 0)return structuredClone(this.defaultConfig);return Lo(structuredClone(this.defaultConfig),km(e))}catch(e){throw this.unreadable(e)}}update(e){try{let t=this.savePath();wm(t,()=>this.write(t,e(this.readStored())))}catch(t){throw t instanceof b?t:this.saveFailure(t)}}savePath(){let e=this.exists()?Dt.realpathSync(this.configPath):vm(this.configPath);return Dt.mkdirSync(Du.dirname(e),{recursive:!0}),e}write(e,t){let n=`${e}.${crypto.randomUUID()}.tmp`;try{let r=this.exists()?Dt.statSync(this.configPath).mode:void 0,o=this.exists()?Nu(Dt.readFileSync(this.configPath,"utf-8"),t):`${JSON.stringify(t,null,H_)}
83
+ `;if(Dt.writeFileSync(n,o,{flag:"wx",mode:r}),r!==void 0)Dt.chmodSync(n,r);Dt.renameSync(n,e)}finally{Dt.rmSync(n,{force:!0})}}saveFailure(e){return new b(`Cannot save config at ${this.configPath}: ${xm(e)}`,`Check that ${Du.dirname(this.configPath)} is writable and that no other process is saving the file`,void 0,{cause:e,tag:Lu})}load(){let{parse:e,strict:t}=this.options;try{let n=this.readConfigFile();if(n===void 0)return{config:structuredClone(this.defaultConfig)};let r=Lo(structuredClone(this.defaultConfig),km(n));return{config:e?e(r):r}}catch(n){if(t)return{config:structuredClone(this.defaultConfig),failure:this.loadFailure(n)};return T.warn(p.yellow(`Config file corrupted at ${this.configPath}. Using defaults.`),{output:Us()}),{config:structuredClone(this.defaultConfig),error:n}}}loadFailure(e){return new b(`Cannot read config at ${this.configPath}: ${xm(e)}`,"Repair the file and try again",void 0,{cause:e,tag:Lu})}readConfigFile(){try{return Dt.readFileSync(this.configPath,"utf-8")}catch(e){if(e.code==="ENOENT")return;throw e}}}function km(e){let t=JSON.parse(e);if(Array.isArray(t))throw Error("Config must be an object");return G_(t)}function xm(e){return e instanceof Error?e.message:String(e)}import{isAbsolute as TA}from"path";var ui="hydra",_r="default",_m={profiles:{}},Tm=!1,Am=24,li=7,Cm=["logs","shared"],Om=!1,Pm=!0,Im=!0,Nm=!0,Dm=120,Lm=["github.com","api.github.com","objects.githubusercontent.com","pipelines.actions.githubusercontent.com"];import{readFileSync as F_,statSync as Hu}from"fs";import{homedir as U_}from"os";import{basename as j_,dirname as Fu,isAbsolute as Hm,join as bn,resolve as di}from"path";var pi=".hydra",et="HYDRA_HOME",ye="--home",Uu={description:"Use this state directory (absolute path)",displayDefault:`${et} or ~/.hydra`,type:"string"},ju="config.json",B_="runners",V_="shared",q_="--",K_=`Pass ${ye} <absolute path> or set ${et}`;function Gm(e){return bn(e.HOME||U_(),pi)}function Fm(e,t){let{flag:n,rest:r}=W_(e);if(n!==void 0)return{argv:r,home:Mm(n,ye),source:"flag"};let o=t[et];if(o)return{argv:r,home:Mm(o,et),source:"environment"};return{argv:r,home:Gm(t),source:"default"}}function wn(e){return{config:bn(e,ju),home:e,runners:bn(e,B_),shared:bn(e,V_)}}function ee(e){return Fu(e.path)}function Bu(e,t){if(Hm(t))return t;return di(j_(e)===pi?Fu(e):e,t)}function Um(e,t){let n=bn(t,pi);return Bm(n)&&!Gu(n,e)?n:void 0}function fi(e,t,n){let r=[...jm(t).map((s)=>bn(s,pi)),Gm(n)],o=[];for(let s of r){if(!Bm(s)||Gu(s,e))continue;if(o.some((i)=>Gu(i,s)))continue;o.push(s)}return o.map((s)=>({counts:J_(s),path:s}))}function W_(e){let t=[],n;for(let r=0;r<e.length;r++){let o=e[r];if(o===q_){t.push(...e.slice(r));break}let s=o.startsWith(`${ye}=`);if(o!==ye&&!s){t.push(o);continue}if(n!==void 0)throw new W(`${ye} can only be provided once`);let i=s?o.slice(ye.length+1):e[r+1];if(!i||!s&&i.startsWith("-"))throw new W(`${ye} needs a directory`,`Use ${ye} <absolute path>`);if(n=i,!s)r++}return{flag:n,rest:t}}function Mm(e,t){if(!Hm(e))throw new W(`${t} must be an absolute path: ${e}`,K_);return di(e)}function jm(e){let t=Fu(e);return t===e?[e]:[e,...jm(t)]}function Bm(e){try{return Hu(bn(e,ju)).isFile()}catch{return!1}}function Gu(e,t){if(di(e)===di(t))return!0;try{let n=Hu(e),r=Hu(t);return n.dev===r.dev&&n.ino===r.ino}catch{return!1}}function Vm(e){let t=qm(e);if(!t)return;return(Array.isArray(t.runners)?t.runners:[]).flatMap((r)=>{if(typeof r!=="object"||r===null)return[];let{id:o,name:s}=r;return[o,s].filter((i)=>typeof i==="string")})}function J_(e){let t=qm(e);if(!t)return;let{profiles:n,runners:r}=t;return{profiles:typeof n==="object"&&n!==null?Object.keys(n).length:0,runners:Array.isArray(r)?r.length:0}}function qm(e){try{let t=JSON.parse(F_(bn(e,ju),"utf-8"));return typeof t==="object"&&t!==null?t:void 0}catch{return}}var Km="Runner count must be a positive safe integer",Y_=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,X_="Runner name prefix must start with a letter or digit and use only letters, digits, '.', '_' and '-'",Vu=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F());function Tr(e){try{return Vu(typeof e==="string"?Number(e):e)}catch{throw new W(Km)}}function qu(e){return e!==void 0&&Y_.test(e)?void 0:X_}function Wm(e){let t=qu(e);if(t)throw new W(t,`Got ${JSON.stringify(e)}`);return e}function Jm(e){try{Tr(e);return}catch{return Km}}function Ar(e,t){if(e.length===0)return t;for(let n of e)if(!t.includes(n))throw new b(`Runner "${n}" not found`);return e}function pt(e,t){let n=e.get("profiles");if(Object.keys(n).length===0)throw new b("No profiles configured","Run hydra legacy init to set up a profile");let r=t??e.get("defaultProfile")??_r,o=Object.hasOwn(n,r)?n[r]:void 0;if(!o)throw new b(`Profile "${r}" not found`);return{name:r,profile:o}}import{isAbsolute as Xm}from"path";var Sn=["discord","command"];function mi(e){return Sn.includes(e)}function Et(e){return Sn.filter((t)=>e?.[t]!==void 0)}function jn(e){return"webhookFile"in e}function pe(e,t){if(typeof e==="object"&&e!==null&&!Array.isArray(e))return e;throw Error(`${t} must be an object`)}function _e(e,t,n,r){let o=Object.keys(e).find((s)=>!t.includes(s));if(o)throw Error(`${n}.${o} is not a setting of ${r}`)}function re(e,t,n,r){if(e===void 0)throw Error(`${n} is missing; expected ${r}`);se(e,t,n,r)}function se(e,t,n,r){if(e===void 0)return;try{t(e)}catch{throw Error(`${n} must be ${r}`)}}var z_=["command","discord"],Q_=["webhookFile"],Z_=["botTokenFile","channelId"],eT=["argv"],zm=32,tT=1024,Qm=/[\p{Cc}\p{Cf}]/u,nT=/^[1-9]\d{15,19}$/,Ym=I().map((e)=>Xm(e)&&!Qm.test(e)?e:F()),rT=I().map((e)=>nT.test(e)?e:F()),oT=I().map((e)=>e.length<=tT&&!Qm.test(e)?e:F()),sT=Z(oT).map((e)=>e.length>0&&e.length<=zm&&Xm(e[0])?e:F()),Ku=`a list of 1 to ${zm} arguments without control characters, the first an absolute path to the program`;function Zm(e){if(e===void 0)return;let t=pe(e,"alerts");if(_e(t,z_,"alerts","alerts"),t.discord!==void 0)Wu(t.discord);if(t.command!==void 0)Ju(t.command);let n=t;if(Et(n).length===0)throw Error("alerts must name at least one sink: discord or command");return n}function Wu(e){let n=pe(e,"alerts.discord");if(n.webhookFile!==void 0)return _e(n,Q_,"alerts.discord","a Discord webhook sink, which takes no bot token or channel"),re(n.webhookFile,Ym,"alerts.discord.webhookFile","an absolute path"),n;if(_e(n,Z_,"alerts.discord","a Discord sink"),n.botTokenFile===void 0)throw Error("alerts.discord needs webhookFile, or botTokenFile with channelId");return re(n.botTokenFile,Ym,"alerts.discord.botTokenFile","an absolute path"),re(n.channelId,rT,"alerts.discord.channelId","a Discord channel id, as a string of digits"),n}function Ju(e){let n=pe(e,"alerts.command");return _e(n,eT,"alerts.command","a command sink"),re(n.argv,sT,"alerts.command.argv",Ku),n}var eg=32,iT=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"];var aT=/^(0|[1-9]\d{0,2})$/,cT=/^(0|[1-9]\d?)$/,uT=iT.map((e)=>st(e)),lT=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.2.0/24","192.168.0.0/16","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","224.0.0.0/4","240.0.0.0/4"].map((e)=>st(e));function Cr(e){let t=e.split(".");if(t.length!==4||!t.every((n)=>aT.test(n)&&Number(n)<=255))return;return t.reduce((n,r)=>n*256+Number(r),0)}function st(e){let[t,n,r]=e.split("/"),o=t===void 0?void 0:Cr(t),s=Number(n);if(o===void 0||r!==void 0||!cT.test(n??""))return;if(s<0||s>32||(o&~gi(s))>>>0!==0)return;return{base:o,prefix:s}}function hi(e){let t=Cr(e);return t!==void 0&&!lT.some((n)=>Or(n,t))}function yi(e){return uT.some((t)=>t.prefix<=e.prefix&&Or(t,e.base))}function Or(e,t){return(t&gi(e.prefix))>>>0===e.base}function bi(e,t){let n=Math.min(e.prefix,t.prefix);return(e.base&gi(n))>>>0===(t.base&gi(n))>>>0}function tg(e){return Array.from({length:4},(t,n)=>e>>>8*(3-n)&255).join(".")}function gi(e){return e===0?0:4294967295<<32-e>>>0}var tn=[];var ng=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,dT={"apple-container":["-v","--volume","--mount","--ssh","-p","--publish","--publish-socket"],firecracker:tn,native:tn,"podman-gvisor":["-v","--volume","--mount","--device","-p","--publish","-P","--publish-all"],tart:["--dir","--disk","--net-softnet-expose","--net-softnet-allow","--net-bridged","--net-host","--vnc","--vnc-experimental","--serial-path"]},pT={"apple-container":tn,firecracker:tn,native:tn,"podman-gvisor":tn,tart:["--suspendable"]},fT={"apple-container":tn,firecracker:tn,native:tn,"podman-gvisor":["checkpoint"],tart:["suspend"]},mT={"apple-container":["--virtualization"],firecracker:["--virtualization"],native:["--virtualization"],"podman-gvisor":["--virtualization"],tart:["--virtualization","--nested"]},gT={"host-share":"it would share a host path, socket, port or network with the guest","jit-config":"it holds the just-in-time runner configuration, which goes over stdin only",suspend:"it would write the guest's memory to disk",virtualization:"it would give the guest nested virtualisation"},hT={"foreign-driver":"it belongs to another driver","foreign-name":"its name lacks this fleet's prefix",protected:"its name is protected",unrecorded:"the ledger does not record it"};class wi extends Error{driver;reason;index;option;_tag="ArgvRefusedError";constructor(e,t,n,r){super(`Refused argument ${n} of a ${e} command${r?` (${r})`:""}: ${gT[t]}`);this.driver=e;this.reason=t;this.index=n;this.option=r;this.name="ArgvRefusedError"}}class Ho extends Error{slot;reason;_tag="DestroyRefusedError";constructor(e,t){super(`Refused to destroy ${e.driver} slot ${e.name} of pool ${e.pool}: ${hT[t]}`);this.slot=e;this.reason=t;this.name="DestroyRefusedError"}}function nn(e,t,n){let r=[["host-share",dT[e]],["suspend",pT[e]],["virtualization",mT[e]]];for(let[o,s]of t.entries()){if(n?.contains(s))throw new wi(e,"jit-config",o,void 0);if(fT[e].includes(s))throw new wi(e,"suspend",o,s);for(let[i,a]of r){let c=a.find((u)=>yT(s,u));if(c)throw new wi(e,i,o,c)}}return t}function Bn(e,t){if(!ng.test(t))throw Error(`Invalid fleet prefix "${t}"`);let n=e.startsWith(`${t}-`)?e.slice(t.length+1):"";return ng.test(n)}async function rg(e,t,n){if(t.driver!==e.capabilities().id)throw new Ho(t,"foreign-driver");if(!Bn(t.name,n.fleetPrefix))throw new Ho(t,"foreign-name");if(n.protectedNames.includes(t.name))throw new Ho(t,"protected");if(!await n.recorded(t))throw new Ho(t,"unrecorded");await e.destroy(t)}function yT(e,t){if(e===t||e.startsWith(`${t}=`))return!0;if(t.startsWith("--")||t.length!==2)return!1;return e.startsWith("-")&&!e.startsWith("--")&&e.slice(1).includes(t.slice(1))}async function ft(e,t){let n=Bun.spawn([...e],{env:t.env,stderr:"pipe",stdin:t.input??"ignore",stdout:"pipe"}),r=!1,o=setTimeout(()=>{r=!0,n.kill("SIGKILL")},t.timeoutMs),s=Promise.withResolvers(),i=setTimeout(s.resolve,t.timeoutMs+2000),a=t.maxOutputChars??Number.POSITIVE_INFINITY,c=og(n.stdout,t.echo?process.stdout:void 0,a),u=og(n.stderr,t.echo?process.stderr:void 0,a);try{let l=await Promise.race([n.exited,s.promise]);if(!await bT([c,u],2000))await Promise.all([c.stop(),u.stop()]);return{exitCode:l===void 0||n.signalCode!==null?l||1:l,stderr:u.text(),stdout:c.text(),timedOut:r}}finally{clearTimeout(o),clearTimeout(i)}}async function bT(e,t){let n,r=new Promise((o)=>{n=setTimeout(()=>o(!1),t)});try{return await Promise.race([Promise.all(e.map((o)=>o.done)).then(()=>!0),r])}finally{clearTimeout(n)}}function og(e,t,n){let r=e.getReader(),o=new TextDecoder,s="";return{done:(async()=>{for(let c=await r.read();!c.done;c=await r.read())if(t?.write(c.value),s+=o.decode(c.value,{stream:!0}),s.length>2*n)s=sg(s,n)})().catch(()=>{return}).then(()=>{s+=o.decode()}),stop:()=>r.cancel().catch(()=>{return}),text:()=>sg(s,n)}}function sg(e,t){return e.length>t?e.slice(e.length-t):e}class Ce extends Error{reason;operation;target;_tag="AppleContainerError";constructor(e,t,n,r,o){super(`Could not ${t} ${n}: ${r}`,o);this.reason=e;this.operation=t;this.target=n;this.name="AppleContainerError"}}var ag="container",Si=3,Vn=1000,wT=10,ST="[redacted]",RT=4194304,cg={callMs:60*Vn,createMs:600*Vn,pollMs:Vn,readyMs:300*Vn,runnerMs:60*Vn,stopMs:120*Vn};function ug(e,t){let n=0,r=!1;return{binary:e,limits:t,recover:()=>{n=0,r=!1},run:async(i,a,c,u={})=>{nn("apple-container",c,u.stdin);let l=u.timeoutMs??t.callMs,d=u.stdin?new TextEncoder().encode(u.stdin.line()):void 0;try{let f=u.maxOutputChars??RT,m=await $T(i,a,[e,...c],{input:d,maxOutputChars:f,timeoutMs:l});if(m.timedOut){n+=1,r||=n>=Si;let h=l/Vn;throw new Ce("timeout",i,a,`${e} did not finish within ${h} s`)}n=0;let g={exitCode:m.exitCode,stderr:ig(m.stderr,u.stdin),stdout:ig(m.stdout,u.stdin)};if(g.exitCode===0||u.check===!1)return g;throw new Ce("failed",i,a,ET(e,g))}finally{d?.fill(0)}},unavailable:()=>r}}async function $T(e,t,n,r){try{return await ft(n,r)}catch(o){let s=o instanceof Error?o.message:String(o);throw new Ce("missing",e,t,`${n[0]} could not start (${s})`,{cause:o})}}function ig(e,t){return t?.contains(e)?ST:e}function ET(e,t){let n=t.stderr.trim().split(`
84
+ `).slice(-wT).join(`
85
+ `);return`${e} exited with code ${t.exitCode}${n?`
86
+ ${n}`:""}`}var vT=["running","stopped","stopping","unknown"],kT="container",xT="container-apiserver",_T=/(?:^|\s)version\s+(\S+)/,TT=["mounts","networks","publishedPorts","publishedSockets","ssh","virtualization"],rn=Ze((e)=>typeof e==="string"?e:void 0),lg=Ze((e)=>typeof e==="boolean"?e:void 0),Pr=Ze((e)=>Array.isArray(e)?e:void 0),pg=Ze((e)=>{if(typeof e!=="object"||e===null||Array.isArray(e))return{};return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]==="string"))}),AT=N({network:rn}),CT=N({destination:rn,type:Ze((e)=>typeof e==="object"&&e!==null&&Object.hasOwn(e,"tmpfs"))}),OT=N({id:I(),labels:pg,mounts:Pr,networks:Pr,publishedPorts:Pr,publishedSockets:Pr,ssh:lg,virtualization:lg}),PT=N({networks:Pr,startedDate:vr(),state:rn}),IT=N({configuration:OT,networks:Pr,status:vr()}),NT=Ze((e)=>Ri(()=>N({ipv4Subnet:rn})(e))?.ipv4Subnet),DT=N({configuration:N({ipv4Subnet:rn,labels:pg,name:rn}),id:rn,status:NT}),LT=Z(N({appName:rn,version:rn}));async function Ir(e){let t=await e.run("list","containers",["list","--all","--format","json"]);return Yu(t.stdout,"list","containers",(n)=>Z(IT)(n).map(MT))}async function fg(e){let t=await e.run("list","networks",["network","list","--format","json"]);return Yu(t.stdout,"list","networks",(n)=>Z(DT)(n).flatMap((r)=>{let o=r.configuration.name??r.id;if(!o)return[];return[{labels:r.configuration.labels,name:o,subnet:r.configuration.ipv4Subnet??r.status}]}))}async function mg(e){let t=await e.run("read the version of","Apple container",["system","version","--format","json"]);return Yu(t.stdout,"read the version of","Apple container",(n)=>{let r=LT(n),o=r.find((i)=>i.appName===kT)?.version,s=r.find((i)=>i.appName===xT)?.version;return{cli:o,services:s===void 0?void 0:_T.exec(s)?.[1]??s}})}function MT(e){let{configuration:t}=e,n=HT(e.status,e.networks??[]),r=[...t.networks??[],...n.networks].flatMap((o)=>{let s=Ri(()=>AT(o).network);return s?[s]:[]});return{id:t.id,labels:t.labels,mounts:(t.mounts??[]).map((o)=>{let s=Ri(()=>CT(o));return{destination:s?.destination??"",tmpfs:s?.type??!1}}),networks:[...new Set(r)],publishedPorts:t.publishedPorts?.length??0,publishedSockets:t.publishedSockets?.length??0,ssh:t.ssh??!1,started:n.started,state:n.state,unread:TT.filter((o)=>t[o]===void 0),virtualization:t.virtualization??!1}}function HT(e,t){if(typeof e==="string")return{networks:t,started:!1,state:dg(e)};let n=Ri(()=>PT(e));return{networks:n?.networks??[],started:n?.startedDate!==void 0&&n?.startedDate!==null,state:dg(n?.state)}}function dg(e){return vT.find((t)=>t===e)??"unknown"}function Ri(e){try{return e()}catch{return}}function Yu(e,t,n,r){try{return r(JSON.parse(e))}catch(o){throw new Ce("failed",t,n,"container printed JSON in an unexpected shape",{cause:o})}}var Go="org.r5nlabs.hydra.fleet",gg=16,hg=28,yg=256,Sg="network-unknown";function Xu(e,t){let n=st(t.range);if(!n)throw Error(`The network range "${t.range}" is not an IPv4 CIDR block without host bits`);if(!yi(n))throw Error(`The network range ${t.range} must lie inside 10.0.0.0/8, 172.16.0.0/12 or 192.168.0.0/16`);let{subnetPrefix:r}=t;if(!Number.isInteger(r)||r<gg||r>hg)throw Error(`The subnet prefix must be a whole number from ${gg} to ${hg}`);if(r<n.prefix)throw Error(`A /${r} subnet does not fit in ${t.range}`);let o=2**(r-n.prefix);if(o>yg)throw Error(`${t.range} holds ${o} /${r} subnets; a fleet has at most ${yg}`);let s=2**(eg-r);return Array.from({length:o},(i,a)=>({name:`hydra-${e}-net-${a+1}`,subnet:`${tg(n.base+a*s)}/${r}`}))}function Rg(e,t,n){let r=Xu(t,n),o=new Map,s=Promise.resolve(),i=async()=>{let[d,f]=await Promise.all([fg(e),Ir(e)]);return{containers:f,networks:new Map(d.map((m)=>[m.name,m]))}},a=(d)=>{let f=new Set(d.containers.flatMap((S)=>S.networks)),m=new Set(o.values()),g=d.containers.filter((S)=>S.unread.includes("networks")),h=[...bg(r,d.networks),...wg(t,r,d.networks),...GT(g)],E=r.filter((S)=>d.networks.get(S.name)?.subnet===S.subnet),v=g.length>0?[]:E.filter((S)=>!f.has(S.name));return{findings:h,free:v.filter((S)=>!m.has(S.name)).map($i),inUse:E.filter((S)=>f.has(S.name)||m.has(S.name)).map($i),missing:r.filter((S)=>!d.networks.has(S.name)).map($i),unplanned:$g(t,r,d.networks)}},c=async(d)=>{let f=a(await i()),m=f.free[0];if(!m){let g=f.findings.find((h)=>h.code===Sg)?.detail;throw new Ce("no-network","find a free network for",d,g??`all ${f.inUse.length} usable networks of the fleet are in use${f.missing.length>0?`, and ${f.missing.length} are not created yet`:""}`)}return o.set(d,m),m},u=async()=>{let d=await i(),f=[],m=[...bg(r,d.networks),...wg(t,r,d.networks)];for(let g of r){if(d.networks.has(g.name))continue;let h=FT(g,d.networks);if(h){m.push(UT(g,h));continue}await e.run("create",`network ${g.name}`,["network","create","--subnet",g.subnet,"--label",`${Go}=${t}`,g.name]),f.push(g.name)}return{created:f,findings:m}},l=(d)=>{let f=s.then(d);return s=f.catch(()=>{return}),f};return{networkOf:(d)=>o.get(d),plan:r,prepare:()=>l(u),release:(d)=>{o.delete(d)},status:async()=>a(await i()),take:(d)=>l(()=>c(d))}}function bg(e,t){return e.flatMap((n)=>{let r=t.get(n.name);if(!r||r.subnet===n.subnet)return[];return[{code:"network-subnet",detail:`Network ${n.name} has subnet ${r.subnet??"(none)"}, not ${n.subnet}; Hydra leaves it alone and starts no guest on it`,fix:`Delete ${n.name} once no container uses it, so Hydra can create it again, or change the fleet's network range`,level:"error"}]})}function $g(e,t,n){let r=new Set(t.map($i)),o=`hydra-${e}-net-`;return[...n.keys()].filter((s)=>s.startsWith(o)&&!r.has(s))}function wg(e,t,n){return $g(e,t,n).map((r)=>({code:"network-unplanned",detail:`Network ${r} carries the fleet's prefix but lies outside its network range; Hydra leaves it alone`,fix:`Delete ${r} if nothing uses it`,level:"warning"}))}function GT(e){if(e.length===0)return[];return[{code:Sg,detail:`container list does not show the networks of ${e.map((t)=>t.id).join(", ")}, so Hydra cannot tell which networks are free and starts no guest`,fix:"Check that the installed Apple container version is the one Hydra is pinned to",level:"error"}]}function FT(e,t){let n=st(e.subnet);return[...t.values()].find((r)=>{let o=r.subnet===void 0?void 0:st(r.subnet);return o!==void 0&&bi(n,o)})}function UT(e,t){return{code:"network-overlap",detail:`Network ${e.name} would use ${e.subnet}, which overlaps ${t.name} (${t.subnet}); Hydra did not create it`,fix:"Choose a fleet network range that no other container network uses",level:"error"}}function $i(e){return e.name}var zu=["arm64"],Eg=["arm64","x86_64"];var Rn=2,Oe={"apple-container":{capabilities:{docker:"full",foreignArch:"rosetta",guestOs:["linux"],guiSession:!1,hostFilter:"host-side",hostOs:"darwin",id:"apple-container",isolation:"vm",secretBearing:!0},requires:{arch:zu,minMacos:26}},firecracker:{capabilities:{docker:"full",foreignArch:"qemu",guestOs:["linux"],guiSession:!1,hostFilter:"host-side",hostOs:"linux",id:"firecracker",isolation:"vm",secretBearing:!0},requires:{arch:Eg,cgroupV2:"error",kvm:!0}},native:{capabilities:{docker:"none",foreignArch:"rosetta",guestOs:["macos"],guiSession:!1,hostFilter:"host-side",hostOs:"darwin",id:"native",isolation:"host-user",secretBearing:!1},requires:{arch:zu,minMacos:13}},"podman-gvisor":{capabilities:{docker:"limited",foreignArch:"none",guestOs:["linux"],guiSession:!1,hostFilter:"host-side",hostOs:"linux",id:"podman-gvisor",isolation:"user-space-kernel",secretBearing:!1},requires:{arch:Eg,cgroupV2:"warning"}},tart:{capabilities:{docker:"full",foreignArch:"rosetta",guestOs:["macos","linux"],guiSession:!0,hostFilter:"host-side",hostOs:"darwin",id:"tart",isolation:"vm",maxMacosGuests:2,secretBearing:!0},requires:{arch:zu,minMacos:13}}},Ei={darwin:{linux:["apple-container","tart"],macos:["tart"]},linux:{linux:["firecracker","podman-gvisor"],macos:[]}},$n={darwin:"macOS",linux:"Linux"},on={linux:"Linux",macos:"macOS"};import{constants as vg,existsSync as jT}from"fs";import{access as BT}from"fs/promises";var VT=1e4,Fo="/dev/kvm",qT="/sys/fs/cgroup/cgroup.controllers",kg="unknown",KT=10,xg={Darwin:"darwin",Linux:"linux"},_g={aarch64:"arm64",amd64:"x86_64",arm64:"arm64",x86_64:"x86_64"};async function En(){let[e,t]=await Promise.all([Qu(["uname","-s"]),Qu(["uname","-m"])]),n=e&&Object.hasOwn(xg,e)?xg[e]:void 0,r=await Qu(n==="darwin"?["sw_vers","-productVersion"]:["uname","-r"]);return{arch:(t&&Object.hasOwn(_g,t)?_g[t]:t)??kg,cgroupV2:jT(qT),kvm:await WT(),os:n,osName:n?$n[n]:e??kg,version:r}}function vi(e){let t=[`${e.osName} ${e.version??"(version unknown)"}`,e.arch];if(e.os==="linux")t.push(`KVM ${e.kvm}`,e.cgroupV2?"cgroup v2":"no cgroup v2");return t.join(" \xB7 ")}function Uo(e){let t=Number.parseInt(e??"",KT);return Number.isSafeInteger(t)?t:void 0}async function WT(){try{return await BT(Fo,vg.R_OK|vg.W_OK),"usable"}catch(e){return e.code==="ENOENT"?"missing":"denied"}}async function Qu(e){try{let t=Bun.spawn(e,{stderr:"ignore",stdin:"ignore",stdout:"pipe",timeout:VT}),[n,r]=await Promise.all([new Response(t.stdout).text(),t.exited]),o=n.trim();return r===0&&o?o:void 0}catch{return}}var vt=["apple-container","tart","firecracker","podman-gvisor","native"],mt="auto";function Tg(e){return vt.includes(e)}var JT=60000,YT=1000,Ag=["none","limited","full"],Og="pick another driver from hydra driver list",XT=Object.keys(Ei);function Pg(e){return vt.filter((t)=>Oe[t].capabilities.hostOs===e)}function xi(e,t,n){return e===mt?QT(t,n):zT(e,t,n)}function Ig(e,t){if(e!==mt)return ki(Oe[e].capabilities,t);let n=Dg(t.guestOs).map((r)=>ki(Oe[r].capabilities,t));return n.some((r)=>r.length===0)?[]:n.flat()}function Nr(e,t){if(t!=="macos")return;return(e===mt?Dg(t):[e]).flatMap((o)=>{let s=Oe[o].capabilities.maxMacosGuests;return s===void 0?[]:[{driver:o,guests:s}]}).sort((o,s)=>o.guests-s.guests)[0]}function _i(e,t){let{capabilities:n,requires:r}=Oe[e];if(t.os!==n.hostOs){let s=$n[n.hostOs];return[sn("host-os",Lg(e,t),`Run ${e} on a ${s} host, or ${Og}`)]}let o=[];if(!r.arch.includes(t.arch)){let s=r.arch.join(" or ");o.push(sn("host-arch",`${e} supports ${s} hosts; this host is ${t.arch}`,`Use an ${s} host`))}if(r.minMacos!==void 0)o.push(...nA(e,r.minMacos,t.version));if(r.kvm&&t.kvm!=="usable")o.push(rA(e,t.kvm));if(r.cgroupV2&&!t.cgroupV2)o.push({code:"cgroup-v2",detail:r.cgroupV2==="error"?`${e} needs cgroup v2, the unified hierarchy at /sys/fs/cgroup`:`${e} cannot enforce CPU and memory limits without cgroup v2`,fix:"Boot the host with the unified cgroup hierarchy (systemd.unified_cgroup_hierarchy=1)",level:r.cgroupV2});return o}async function Ng(e,t,n,r=JT){let o=_i(e,t),s=Cg(o)?[]:await tA(e,n[e],r),i=[...o,...s];return{driver:e,findings:i,status:Cg(i)?"unavailable":"available"}}function Cg(e){return e.some((t)=>t.level==="error")}function zT(e,t,n){let r=Oe[e].capabilities.hostOs,s=[...n.os===r?[]:[{code:"host-os",detail:Lg(e,n),driver:e}],...ki(Oe[e].capabilities,t)];return s.length>0?{kind:"refused",refusals:s}:{driver:e,kind:"resolved",passedOver:[]}}function QT(e,t){if(!t.os)return{kind:"refused",refusals:[{code:"host-os",detail:`Hydra has no slot driver for ${t.osName} hosts`}]};let n=Ei[t.os][e.guestOs];if(n.length===0)return{kind:"refused",refusals:[{code:"guest-os",detail:`No driver runs ${on[e.guestOs]} guests on ${$n[t.os]} hosts`}]};let r=[];for(let o of n){let s=[...ki(Oe[o].capabilities,e),...eA(o,t)];if(s.length===0)return{driver:o,kind:"resolved",passedOver:r};r.push(...s)}return{kind:"refused",refusals:r}}function Dg(e){return[...new Set(XT.flatMap((t)=>Ei[t][e]))]}function ki(e,t){let n=e.id;return[[!e.guestOs.includes(t.guestOs),"guest-os",`${n} runs no ${on[t.guestOs]} guests`],[Ag.indexOf(e.docker)<Ag.indexOf(t.docker),"docker",e.docker==="none"?`${n} runs no Docker`:`${n} offers only limited Docker, without iptables or binfmt emulation`],[t.foreignArch&&e.foreignArch==="none","foreign-arch",`${n} cannot run binaries built for another architecture`],[t.guiSession&&!e.guiSession,"gui-session",`${n} gives the runner no desktop session`],[t.secretBearing&&!ZT(e,t),"secret-bearing",e.isolation==="host-user"?`${n} runs jobs as a host user and never serves a secret-bearing pool`:`${n} isolates jobs with a user-space kernel, not a VM; a secret-bearing pool must allow weaker isolation to use it`]].filter(([o])=>o).map(([,o,s])=>({code:o,detail:s,driver:n}))}function ZT(e,t){return e.secretBearing||e.isolation==="user-space-kernel"&&t.allowWeakerIsolation}function eA(e,t){return _i(e,t).filter((n)=>n.level==="error").map((n)=>({code:"host",detail:n.detail,driver:e}))}async function tA(e,t,n){if(!t)return[sn("not-included",`This version of Hydra does not include the ${e} driver`,`Update Hydra, or ${Og}`)];let r=Promise.withResolvers(),o=setTimeout(r.resolve,n);try{let s=await Promise.race([t.checkHost(),r.promise]);if(s)return s.findings;return[sn("check-timeout",`The ${e} host check did not finish within ${n/YT} seconds`,"Check that the driver's tools and services respond, then run hydra driver check again")]}catch(s){let i=s instanceof Error?s.message:String(s);return[sn("check-failed",`The ${e} host check failed: ${i}`,"Fix the cause and run hydra driver check again")]}finally{clearTimeout(o)}}function nA(e,t,n){let r=Uo(n);if(r===void 0)return[sn("os-version","Could not read the macOS version","Check that sw_vers -productVersion prints it")];if(r>=t)return[];return[sn("os-version",`${e} needs macOS ${t} or later; this host runs ${n}`,`Upgrade macOS to ${t} or later`)]}function rA(e,t){return t==="missing"?sn("kvm",`${e} needs ${Fo}, which this host does not have`,"Run on bare metal or on a VM with nested virtualisation, with the kvm module loaded"):sn("kvm",`${Fo} is not readable and writable by this user`,`Give this user read and write access to ${Fo}, for example through the kvm group`)}function Lg(e,t){return`${e} runs on ${$n[Oe[e].capabilities.hostOs]} hosts; this host runs ${t.osName}`}function sn(e,t,n){return{code:e,detail:t,fix:n,level:"error"}}var oA=new Set(["github.com","www.github.com"]);var Mg=/\.git$/;function de(e){let t;try{t=new URL(e)}catch{throw Error(`Invalid GitHub URL: ${e}`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error(`Invalid GitHub URL (expected http(s)): ${e}`);if(!oA.has(t.hostname))throw Error(`Invalid GitHub URL (host must be github.com): ${e}`);let n=t.pathname.split("/").filter(Boolean);if(n.length===1){let r=n[0]?.replace(Mg,"");if(!r)throw Error(`Invalid GitHub URL: ${e}`);return{kind:"org",org:r}}if(n.length===2){let r=n[0],o=n[1]?.replace(Mg,"");if(!r||!o)throw Error(`Invalid GitHub URL: ${e}`);return{kind:"repo",owner:r,repo:o}}throw Error(`Invalid GitHub URL (expected github.com/<owner>/<repo> or github.com/<org>): ${e}`)}function De(e){return e.kind==="repo"?`${e.owner}/${e.repo}`:e.org}var Hg=["scaleset","poll"],fe="none";function Ti(e){return{allowWeakerIsolation:e.allowWeakerIsolation??!1,docker:e.docker??"none",foreignArch:e.foreignArch??!1,guestOs:e.guestOs,guiSession:e.guiSession??!1,secretBearing:e.secretBearing??!1}}var Ci=16,Kn=24,sA=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,iA=/^[a-z0-9]+$/,Gg=7200,Fg=100,aA=["linux","macos"],Ug=[mt,...vt],cA=["none","limited","full"],uA=["dns","id","networks"],lA=["range","subnetPrefix"],dA=["cpus","diskGiB","memoryMiB"],pA=["allowWeakerIsolation","ceiling","demand","docker","driver","foreignArch","guestOs","guiSession","labels","maxJobMinutes","priority","resources","runnerGroup","secretBearing","url"],fA=",",Bg=/[\p{Cc}\p{Cf}]/u,Ai="https://github.com",jg=/^[A-Za-z0-9_-]+$/,mA=/^[A-Za-z0-9._-]+$/,gA=`${Ai}/<org> or ${Ai}/<owner>/<repo>, with nothing else`,qn=(e,t=Number.MAX_SAFE_INTEGER)=>X().map((n)=>Number.isSafeInteger(n)&&n>=e&&n<=t?n:F()),hA=I().map((e)=>e.trim().length>0&&!Bg.test(e)?e:F()),yA=I().map((e)=>e.length>0&&e===e.trim()&&!e.includes(fA)&&!Bg.test(e)?e:F()),bA=qn(1).or(J([fe])),wA=I().map((e)=>hi(e)?e:F()),SA=I().map((e)=>Kg(e)?e:F());function jo(e){return e.length<=Kn&&sA.test(e)}function Wn(e){return e.length<=Ci&&iA.test(e)}function Vg(e){if(e===void 0)return;let t=pe(e,"fleet");_e(t,uA,"fleet","the fleet");let n=I().map((r)=>Wn(r)?r:F());if(re(t.id,n,"fleet.id",`lowercase letters and digits without hyphens, at most ${Ci} characters, so no fleet's name prefix starts another's`),se(t.dns,Z(wA),"fleet.dns","a list of public IPv4 addresses"),Array.isArray(t.dns)&&t.dns.length===0)throw Error("fleet.dns must name at least one server");return RA(t.networks,t.id),t}function RA(e,t){if(e===void 0)return;let n=pe(e,"fleet.networks");_e(n,lA,"fleet.networks","the fleet's networks"),re(n.range,I(),"fleet.networks.range","a private IPv4 CIDR block"),re(n.subnetPrefix,qn(0),"fleet.networks.subnetPrefix","a whole number");try{Xu(t,n)}catch(r){throw Error(`fleet.networks: ${r.message}`)}}function qg(e,t){if(e===void 0)return;let n=pe(e,"pools"),r=Object.keys(n);if(r.length>0&&!t)throw Error("pools need a fleet: add fleet.id, which names the fleet's guests");for(let o of r)Bo(o,n[o])}function Bo(e,t){if(!jo(e))throw Error(`Pool name "${e}" must be lowercase letters and digits in hyphen-separated words, at most ${Kn} characters`);let n=`pools.${e}`,r=pe(t,n);_e(r,pA,n,"a pool"),re(r.url,SA,`${n}.url`,gA),re(r.guestOs,J(aA),`${n}.guestOs`,"linux or macos"),re(r.driver,J(Ug),`${n}.driver`,`one of ${Ug.join(", ")}`),re(r.demand,J(Hg),`${n}.demand`,"scaleset or poll"),re(r.ceiling,bA,`${n}.ceiling`,`a positive whole number or "${fe}"`),vA(r.labels,`${n}.labels`),kA(r.runnerGroup,Kg(r.url),`${n}.runnerGroup`),xA(r.resources,`${n}.resources`),se(r.docker,J(cA),`${n}.docker`,"none, limited or full");for(let s of["foreignArch","guiSession","secretBearing","allowWeakerIsolation"])se(r[s],Q(),`${n}.${s}`,"a boolean");se(r.maxJobMinutes,qn(1,Gg),`${n}.maxJobMinutes`,`whole minutes from 1 to ${Gg}`),se(r.priority,qn(0,Fg),`${n}.priority`,`a whole number from 0 to ${Fg}`);let o=r;return EA(o,n),o}function $A(e,t,n){let r=Nr(e,t);if(r===void 0||n!==fe&&n<=r.guests)return;let o=e===mt?`auto picks ${r.driver} for macOS guests, and ${r.driver}`:r.driver;return`must be at most ${r.guests}: ${o} runs at most ${r.guests} macOS guests per host`}function EA(e,t){let n=Ti(e);if(n.allowWeakerIsolation&&!n.secretBearing)throw Error(`${t}.allowWeakerIsolation applies only to a secret-bearing pool`);let r=Ig(e.driver,n);if(r.length>0)throw Error(`${t}: ${r.map((s)=>s.detail).join("; ")}`);let o=$A(e.driver,e.guestOs,e.ceiling);if(o)throw Error(`${t}.ceiling ${o}`)}function vA(e,t){re(e,Z(yA),t,"a list of labels without commas, control characters or surrounding spaces");let n=e;if(n.length===0)throw Error(`${t} must name at least one label`);let r=new Set;for(let o of n){let s=o.toLowerCase();if(r.has(s))throw Error(`${t} lists "${o}" twice; GitHub compares labels without case`);r.add(s)}}function kA(e,t,n){if(t.kind==="org"){re(e,hA,n,"the name of the organisation's runner group that the pool's runners join");return}if(e!==void 0)throw Error(`${n} does not apply: repository runners belong to no runner group`)}function xA(e,t){if(e===void 0)throw Error(`${t} is missing; expected cpus, memoryMiB and diskGiB per guest`);let n=pe(e,t);_e(n,dA,t,"pool resources"),re(n.cpus,qn(1),`${t}.cpus`,"a positive whole number of virtual CPUs"),re(n.memoryMiB,qn(1),`${t}.memoryMiB`,"a positive whole number of MiB"),re(n.diskGiB,qn(1),`${t}.diskGiB`,"a positive whole number of GiB")}function Zu(e){return e.kind==="org"?`${Ai}/${e.org}`:`${Ai}/${e.owner}/${e.repo}`}function Kg(e){try{let t=de(e);return Zu(t)===e&&_A(t)?t:void 0}catch{return}}function _A(e){return e.kind==="org"?jg.test(e.org):jg.test(e.owner)&&mA.test(e.repo)}var Vo=I().map((e)=>e.trim().length>0?e:F()),AA=/[/\\\0]/,CA=new Set([".",".."]),Wg=Vo.map((e)=>AA.test(e)||CA.has(e)?F():e),OA=J(["osx","linux","windows"]),Jg=J(["github","gitlab"]),PA=Z(J(["logs","work","shared"])),IA=J(["app","gh"]),el=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),NA=I().map((e)=>TA(e)?e:F()),DA={app:["mode","appId","installationId","privateKeyPath"],gh:["mode"]};function Oi(e){return new Mu(wn(e).config,_m,{parse:(t)=>LA(t,e),strict:!0})}function Pi(e){if(!e.failure)return;return new b(e.failure.message,`Repair ${e.path} or select another home with ${ye}; hydra doctor lists the homes it finds`)}function LA(e,t){let n=pe(e,"the config");se(n.defaultProfile,I(),"defaultProfile","a string"),GA(n.cleanup),FA(n.credentials),Zm(n.alerts);let r=Vg(n.fleet);qg(n.pools,r);let o=Object.fromEntries(Object.entries(pe(n.profiles,"profiles")).map(([i,a])=>[i,MA(a,`profiles.${i}`,t)])),s=n.runners===void 0?void 0:HA(n.runners,t);return{...e,profiles:o,...s?{runners:s}:{}}}function MA(e,t,n){let r=pe(e,t);if(re(r.url,Vo,`${t}.url`,"a URL"),re(r.name,Wg,`${t}.name`,"a runner name prefix without path separators"),re(r.directory,Vo,`${t}.directory`,"a directory"),re(r.os,OA,`${t}.os`,"osx, linux or windows"),re(r.provider,Jg,`${t}.provider`,"github or gitlab"),se(r.labels,I(),`${t}.labels`,"a comma-separated string"),se(r.runnerGroup,I(),`${t}.runnerGroup`,"a string"),se(r.numberOfMachines,Vu,`${t}.numberOfMachines`,"a positive safe integer"),se(r.overwrite,Q(),`${t}.overwrite`,"a boolean"),se(r.run,Q(),`${t}.run`,"a boolean"),r.jobHooks!==void 0)pe(r.jobHooks,`${t}.jobHooks`);let o=e;return{...o,directory:Bu(n,o.directory)}}function HA(e,t){if(!Array.isArray(e))throw Error("runners must be a list");return e.map((n,r)=>{let o=`runners[${r}]`,s=pe(n,o);re(s.id,Wg,`${o}.id`,"a runner id without path separators"),re(s.profile,Vo,`${o}.profile`,"a profile name"),re(s.directory,Vo,`${o}.directory`,"a directory");for(let a of["name","url","createdAt"])se(s[a],I(),`${o}.${a}`,"a string");se(s.provider,Jg,`${o}.provider`,"github or gitlab"),se(s.agentId,el,`${o}.agentId`,"a positive GitHub runner id");let i=n;return{...i,directory:Bu(t,i.directory)}})}function GA(e){if(e===void 0)return;let t=pe(e,"cleanup");se(t.auto,Q(),"cleanup.auto","a boolean"),se(t.intervalHours,X(),"cleanup.intervalHours","a number of hours"),se(t.olderThanDays,X(),"cleanup.olderThanDays","a number of days"),se(t.targets,PA,"cleanup.targets","a list of logs, work and shared"),se(t.lastRun,I(),"cleanup.lastRun","a timestamp")}function FA(e){if(e===void 0)return;let t=pe(e,"credentials");re(t.mode,IA,"credentials.mode","app or gh");let n=t.mode;if(_e(t,DA[n],"credentials",`the ${n} mode`),n==="gh")return;re(t.appId,el,"credentials.appId","a GitHub App id"),re(t.installationId,el,"credentials.installationId","an installation id"),re(t.privateKeyPath,NA,"credentials.privateKeyPath","an absolute path")}var Xg="@r5n/hydra";var vn="1.1.0";var P=Ms();import{accessSync as JC,constants as YC,statSync as XC}from"fs";var UA=/[\p{Cc}\p{Cf}]+/gu,jA=/\s+/g;function qo(e){let t=e.argv.length-1;return`command ${e.argv[0]}${t>0?` with ${t} ${t===1?"argument":"arguments"}`:""}`}function zg(e,t={}){let n=t.timeoutMs??30000,r=e.argv[0],o={HOME:t.home??process.env.HOME??"/",PATH:"/usr/bin:/bin:/usr/sbin:/sbin"};return{describe:qo(e),name:"command",async send(s){let i;try{i=Bun.spawn({cmd:e.argv,env:o,killSignal:"SIGKILL",stderr:"pipe",stdin:new Blob([s]),stdout:"ignore",timeout:n})}catch(f){let m=f.code??"unknown error";return{detail:`Cannot start ${r} (${m})`,outcome:"failed"}}let a=i.stderr.getReader(),c=BA(a),u=await i.exited,l=await Promise.race([c,Bun.sleep(1000).then(()=>{return})]);if(l===void 0)await a.cancel().catch(()=>{return});if(i.signalCode!==null)return{detail:`${r} was stopped by ${i.signalCode} after at most ${n/1000} s`,outcome:"failed"};if(u===0)return{exitCode:u,outcome:"delivered"};let d=(l??"").replace(UA," ").replace(jA," ").trim().slice(0,200);return{detail:`${r} exited with ${u}${d?`: ${d}`:""}`,outcome:"failed"}},signature(){return JSON.stringify(e)}}}async function BA(e){let t=new TextDecoder,n="";try{for(let r=await e.read();!r.done;r=await e.read())n+=t.decode(r.value,{stream:!0})}catch{return n}return n+t.decode()}import{constants as tl,lstatSync as Qg}from"fs";import{open as VA}from"fs/promises";var qA=384,KA=511,WA=8,JA=4,nl=4096,YA=tl.O_RDONLY|tl.O_NOFOLLOW|tl.O_NONBLOCK,XA=/\r?\n$/,zA=/[\r\n]/,Zg="Keep it as a regular file owned by the user running Hydra, with mode 0600";class Jn extends Error{_tag="SecretFileError";constructor(e,t,n){super(`The ${e} ${t} ${n}`);this.name="SecretFileError"}}function eh(e){try{return nh(Qg(e))}catch(t){return`cannot be read (${t.code??"unknown error"})`}}function th(e){try{let t=Qg(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}catch{return"missing"}}async function rl(e,t){let n;try{n=await VA(e,YA)}catch(r){let o=r.code;throw new Jn(t,e,o==="ELOOP"?"is a symbolic link":`cannot be opened (${o})`)}try{let r=nh(await n.stat());if(r)throw new Jn(t,e,r);let o=Buffer.alloc(nl+1),{bytesRead:s}=await n.read(o,0,o.length,0);if(s>nl)throw new Jn(t,e,`is longer than ${nl} bytes`);let i=o.subarray(0,s).toString("utf8").replace(XA,"");if(i.trim().length===0||zA.test(i)||i!==i.trim())throw new Jn(t,e,"must hold one line with no surrounding spaces");return i}finally{await n.close()}}function nh(e){let t=process.getuid?.();if(e.isSymbolicLink())return"is a symbolic link";if(!e.isFile())return"is not a regular file";if(t===void 0)return"cannot be checked for its owner on this platform";if(e.uid!==t)return`is owned by uid ${e.uid}, not by the user running Hydra (uid ${t})`;let n=e.mode&KA;if(n!==qA)return`has mode ${n.toString(WA).padStart(JA,"0")}, not 0600`;return}var ol={"alert-undelivered":"an alert waited over an hour for a sink","anchor-drift":"the loaded pf anchor differs from the rendered one","disk-pressure":"free disk space left the normal state","driver-unavailable":"a driver check failed","foreign-guest":"a guest Hydra did not create","foreign-network":"a guest network Hydra did not create","foreign-runner":"a runner registration Hydra did not mint","foreign-scale-set":"a scale set Hydra did not create","guard-drift":"runner group or organisation policy changed","guard-failed":"the guard could not read GitHub three times in a row","host-daemon-unreachable":"the host daemon did not answer","host-listener":"a host listener outside the known list","native-verify-failed":"a native slot failed its verification","pool-degraded":"a pool is degraded","pool-unavailable":"a pool is unavailable","reconcile-failed":"reconcile failed three times in a row","registration-refused":"GitHub refused to delete a runner registration","runner-outdated":"the runner version is older than 30 days","runner-update-required":"a runner exited asking for a newer version","session-conflict":"a scale set session stayed in conflict","sink-stopped":"an alert sink stopped after a refusal","slot-quarantined":"a slot was quarantined","slot-undestroyed":"a slot's guest could not be destroyed",test:"a test alert","unknown-message":"a scale set message of an unknown type","world-writable":"a new world-writable directory"},Ii={now:()=>Date.now(),sleep:(e)=>Bun.sleep(e)};function rh(e){return Object.hasOwn(ol,e)}var QA="https://discord.com/api/v10",Dr="HYDRA_DISCORD_API_URL",ZA=new Set(["discord.com","discordapp.com","canary.discord.com","ptb.discord.com"]),eC=/^\/api(?:\/v\d+)?\/webhooks\/(\d{16,20})\/([A-Za-z0-9_-]{1,128})$/,tC=/^[A-Za-z0-9._-]{1,256}$/,nC=new Set(["127.0.0.1","[::1]"]),rC=/\/+$/,oC=15000,sC=3,iC=30000,aC=1,cC=1000,oh=429,uC=new Set([401,403,404]),lC={parse:[]},sh="```",dC=N({id:I()}),pC=N({retry_after:X().or(ne())});function Ni(e){let t=e[Dr];if(!t)return QA;let n="Use an https URL, or http on 127.0.0.1 or [::1], with no credentials, query or fragment",r;try{r=new URL(t)}catch{throw new b(`${Dr} is not a URL`,n)}if(!(r.protocol==="https:"||r.protocol==="http:"&&nC.has(r.hostname))||r.username||r.password||r.search||r.hash)throw new b(`${Dr} is not an API root Hydra may send its Discord secrets to`,n);return r.href.replace(rC,"")}function fC(e){let t;try{t=new URL(e)}catch{return}if(t.protocol!=="https:"||!ZA.has(t.hostname))return;if(t.port||t.username||t.password||t.search||t.hash)return;let n=t.pathname.match(eC);return n?{id:n[1],token:n[2]}:void 0}async function sl(e){if(jn(e)){let n=fC(await rl(e.webhookFile,"Discord webhook file"));if(!n)throw Error(`The Discord webhook file ${e.webhookFile} does not hold a https://discord.com/api/webhooks/<id>/<token> URL`);return{path:`/webhooks/${n.id}/${n.token}?wait=true`}}let t=await rl(e.botTokenFile,"Discord bot token file");if(!tC.test(t))throw Error(`The Discord bot token file ${e.botTokenFile} does not hold a bot token`);return{authorization:`Bot ${t}`,path:`/channels/${e.channelId}/messages`}}function Ko(e){return jn(e)?`Discord webhook from ${e.webhookFile}`:`Discord channel ${e.channelId} as the bot in ${e.botTokenFile}`}function ah(e,t){let n=t.clock??Ii,r=0;function o(a){let c=a!==void 0&&Number.isFinite(a)&&a>=0?a:aC;r=Math.max(r,n.now()+c*cC)}function s(a){if(a.headers.get("x-ratelimit-remaining")!=="0")return;o(ih(a,"x-ratelimit-reset-after"))}async function i(a,c){try{return await fetch(`${t.apiUrl}${a.path}`,{body:JSON.stringify({allowed_mentions:lC,content:`${sh}
87
+ ${c}
88
+ ${sh}`}),headers:{...a.authorization?{Authorization:a.authorization}:{},"Content-Type":"application/json","User-Agent":t.userAgent},method:"POST",redirect:"manual",signal:AbortSignal.timeout(oC)})}catch(u){return{detail:`Discord did not answer (${u.code??u.name??"unknown error"})`,outcome:"failed"}}}return{describe:Ko(e),name:"discord",async send(a){let c;try{c=await sl(e)}catch(u){return{detail:u.message,outcome:"failed"}}for(let u=1;u<=sC;u++){let l=r-n.now();if(l>iC)return{detail:"Discord asked Hydra to wait",outcome:"failed",retryAfterMs:l};if(l>0)await n.sleep(l);let d=await i(c,a);if(!(d instanceof Response))return d;if(s(d),d.ok)return{messageId:await gC(d),outcome:"delivered",status:d.status};if(d.status===oh){o(await hC(d)??ih(d,"retry-after"));continue}if(await d.body?.cancel(),uC.has(d.status))return{detail:`Discord refused the ${mC(e)}`,outcome:"stopped",status:d.status};return{detail:`Discord returned ${d.status}`,outcome:"failed",status:d.status}}return{detail:"Discord kept answering 429",outcome:"failed",retryAfterMs:Math.max(0,r-n.now()),status:oh}},signature(){return JSON.stringify([e,th(jn(e)?e.webhookFile:e.botTokenFile)])}}}function mC(e){return jn(e)?"webhook":`bot token for channel ${e.channelId}`}function ih(e,t){let n=e.headers.get(t);return n===null||n.trim()===""?void 0:Number(n)}async function gC(e){try{return dC(await e.json()).id}catch{return}}async function hC(e){try{return pC(await e.json()).retry_after}catch{return}}function yC(e){return[e.pool??"",e.reason].join("/")}function ch(e,t,n){let r=yC(t),o=e[r];if(o&&n<o.sentAt+900000){e[r]={...o,alert:t,firstRepeatAt:o.firstRepeatAt??n,repeats:o.repeats+1};return}return e[r]={alert:t,repeats:0,sentAt:n},o&&o.repeats>0?{alert:t,count:o.repeats+1,since:o.firstRepeatAt}:{alert:t,count:1}}function uh(e,t){let n=[];for(let[r,o]of Object.entries(e)){if(t<o.sentAt+900000)continue;if(o.repeats===0){delete e[r];continue}n.push({alert:o.alert,count:o.repeats,since:o.firstRepeatAt}),e[r]={alert:o.alert,repeats:0,sentAt:t}}return n}function lh(e,t){return e!==void 0&&t>=e.start+600000}function dh(e){return e!==void 0&&e.sent>=10}import{randomUUID as bh}from"crypto";var ph=1500,bC=64,wC=300,SC=/[^A-Za-z0-9._-]/g,RC=/^([A-Za-z0-9_.-]{1,100})\/([A-Za-z0-9_.-]{1,100})$/,$C=/[\p{Cc}\p{Cf}`]+/gu,EC=/\s+/g,fh="\u2026",vC=/\.\d{3}Z$/,kC="\x00",mh=" \xB7 ";function Di(e,t){let n=[t.fleet?`fleet ${Wo(t.fleet)}`:"",e.pool?`pool ${Wo(e.pool)}`:"",e.slot?`slot ${Wo(e.slot)}`:""].filter(Boolean),r=[`[hydra] ${e.reason}: ${ol[e.reason]}`,n.join(mh),e.repository?`repository ${xC(e.repository)}`:"",e.detail?`detail ${Jo(e.detail)}`:"",t.count>1?`count ${t.count}${t.since?` since ${Lt(t.since)}`:""}`:"",`time ${Lt(t.at)}`];return yh(r.filter(Boolean))}function gh(e,t){let n=e.reduce((s,i)=>s+i.count,0),r=[`[hydra] digest: ${n} ${n===1?"alert":"alerts"} held back from ${Lt(t.from)} to ${Lt(t.at)}`,t.fleet?`fleet ${Wo(t.fleet)}`:""].filter(Boolean),o=il(e).map((s)=>`${s.count} \xD7 ${s.reason}${s.pool?`${mh}pool ${Wo(s.pool)}`:""}`);return yh([...r,...o,`time ${Lt(t.at)}`])}function il(e){let t=new Map;for(let n of e){let r=`${n.reason}${kC}${n.pool??""}`,o=t.get(r);t.set(r,o?{...o,count:o.count+n.count}:{...n})}return[...t.values()].sort((n,r)=>r.count-n.count)}function Lt(e){return new Date(e).toISOString().replace(vC,"Z")}function Jo(e){return hh(e.replace($C," ").replace(EC," ").trim(),wC)}function Wo(e){return hh(e.replace(SC,"_"),bC)}function xC(e){let t=e.match(RC);return t?`${t[1]}/${t[2]}`:"(not a repository name)"}function hh(e,t){return e.length<=t?e:`${e.slice(0,t-1)}${fh}`}function yh(e){let t=[],n=0;for(let[r,o]of e.entries()){let s=e.length-r-1,i=`${fh} ${s+1} more ${s===0?"line":"lines"}`;if(n+o.length+1+(s>0?i.length+1:0)>ph){t.push(i);break}t.push(o),n+=o.length+1}return t.join(`
89
+ `).slice(0,ph)}var _C=3600000,TC=100,AC=30000,CC=1800000;function OC(e){return Math.min(AC*2**Math.max(0,e-1),CC)}function al(e,t,n){let r=new Map;for(let o of e.messages){if(!n.includes(o.sink))continue;let s=r.get(o.sink);if(!s){r.set(o.sink,{count:1,error:o.error,oldest:o.createdAt,sink:o.sink});continue}s.count++,s.error=o.error??s.error,s.oldest=Math.min(s.oldest,o.createdAt)}return[...r.values()].filter((o)=>t-o.oldest>=_C)}function Li(e){let t=e.clock??Ii,n=e.store.load(),r=()=>e.store.save(n);function o(g){return n.messages.filter((h)=>h.sink===g)}function s(g,h){if(h.length===0)return;let E=t.now(),v=Math.min(...h.map((y)=>y.createdAt)),S=il(h.flatMap((y)=>y.items)),_=h.findLast((y)=>y.error!==void 0)?.error,C={attempts:Math.max(...h.map((y)=>y.attempts)),createdAt:v,..._===void 0?{}:{error:_},id:bh(),items:S,kind:"digest",nextAttemptAt:Math.max(E,...h.map((y)=>y.nextAttemptAt)),sink:g,text:gh(S,{at:E,fleet:e.fleet,from:v})},w=n.messages.indexOf(h[0]),x=n.messages.filter((y)=>!h.includes(y));return x.splice(Math.min(w,x.length),0,C),n.messages=x,C}function i({alert:g,count:h,since:E},v){let S=t.now(),_=Di(g,{at:S,count:h,fleet:e.fleet,since:E}),C=g.pool?{count:h,pool:g.pool,reason:g.reason}:{count:h,reason:g.reason};for(let w of e.sinks){if(w.name===v)continue;let x=o(w.name);if(x.length>=TC)s(w.name,x);n.messages.push({attempts:0,createdAt:S,id:bh(),items:[C],kind:"alert",nextAttemptAt:S,sink:w.name,text:_})}}function a(g,h){let E=ch(n.reasons,g,t.now());if(E)i(E,h)}function c(g){let h=n.stopped[g.name];if(!h)return!1;if(h.signature===g.signature())return!0;delete n.stopped[g.name];let E=t.now();for(let v of o(g.name))v.nextAttemptAt=Math.min(v.nextAttemptAt,E);return!1}async function u(g,h){let E=await g.send(h.text),v=t.now();switch(e.onDelivery?.({delivery:E,kind:h.kind,sink:g.name}),E.outcome){case"delivered":{n.messages=n.messages.filter((_)=>_!==h);let S=n.windows[g.name]??{sent:0,start:v};return n.windows[g.name]={...S,sent:S.sent+1},r(),!0}case"failed":return h.attempts++,h.error=E.detail,h.nextAttemptAt=v+Math.max(OC(h.attempts),E.retryAfterMs??0),r(),!1;case"stopped":return h.error=E.detail,n.stopped[g.name]={at:v,detail:E.detail,signature:g.signature(),status:E.status},a({detail:`${g.describe}: ${E.detail} (HTTP ${E.status})`,reason:"sink-stopped"},g.name),r(),!1}}async function l(g,h){if(c(g))return;let E=()=>o(g.name).filter((w)=>w.held);if(lh(n.windows[g.name],t.now()))s(g.name,E()),delete n.windows[g.name];let v=t.now(),S=o(g.name);if(S.some((w)=>w.attempts>0&&w.nextAttemptAt>v))return;let _=S.filter((w)=>!w.held&&w.nextAttemptAt<=v);for(let w of _){if(dh(n.windows[g.name])){w.held=!0;continue}if(!await u(g,w))return r()}r();let C=h?s(g.name,E()):void 0;if(C)await u(g,C)}function d(){let g=t.now(),h=e.sinks.map((E)=>E.name);for(let E of al(n,g,h)){let v=E.count===1?"1 alert":`${E.count} alerts`;a({detail:`${v} for the ${E.sink} sink, the oldest from ${Lt(E.oldest)}`,reason:"alert-undelivered"},E.sink)}}async function f(g){for(let h of uh(n.reasons,t.now()))i(h);r();for(let h of e.sinks)await l(h,g);d(),r()}let m;return{deliver({flush:g=!1}={}){return m??=f(g).finally(()=>{m=void 0}),m},raise(g){a(g),r()},snapshot:()=>structuredClone(n)}}var PC="https://www.npmjs.com/package/@r5n/hydra";function Mi(e,t){let n=(o)=>t.only===void 0||t.only===o,r=[];if(e?.discord&&n("discord"))r.push(ah(e.discord,{apiUrl:Ni(t.env),clock:t.clock,userAgent:`DiscordBot (${PC}, ${t.version})`}));if(e?.command&&n("command"))r.push(zg(e.command,{home:t.env.HOME}));return r}import{mkdirSync as IC,readFileSync as NC,renameSync as DC,rmSync as LC,writeFileSync as MC}from"fs";import{join as Rh}from"path";var $h="alerts",Eh=1,HC="queue.json",GC=448,FC=384,Lr=()=>I().or(ne()),Hi=()=>X().map((e)=>Number.isSafeInteger(e)&&e>=0?e:F()),vh=I().map((e)=>rh(e)?e:F()),UC=J(Sn),jC=N({count:Hi(),pool:Lr(),reason:vh}),BC=N({detail:Lr(),pool:Lr(),reason:vh,repository:Lr(),slot:Lr()}),VC=N({attempts:Hi(),createdAt:X(),error:Lr(),held:Q().or(ne()),id:I(),items:Z(jC),kind:J(["alert","digest"]),nextAttemptAt:X(),sink:UC,text:I()}),qC=N({alert:BC,firstRepeatAt:X().or(ne()),repeats:Hi(),sentAt:X()}),wh=N({at:X(),detail:I(),signature:I(),status:X()}),Sh=N({sent:Hi(),start:X()}),KC=N({messages:Z(VC),reasons:kr(qC),stopped:N({command:wh.or(ne()),discord:wh.or(ne())}),version:J([Eh]),windows:N({command:Sh.or(ne()),discord:Sh.or(ne())})});function kh(){return{messages:[],reasons:{},stopped:{},version:Eh,windows:{}}}function WC(e){return Rh(e,$h,HC)}function xh(e=kh()){let t=structuredClone(e);return{load:()=>structuredClone(t),save(n){t=structuredClone(n)}}}function Gi(e){let t=WC(e);return{load(){let n;try{n=NC(t,"utf-8")}catch(r){if(r.code==="ENOENT")return kh();throw Error(`Cannot read the alert queue ${t}`,{cause:r})}try{return KC(JSON.parse(n))}catch(r){throw Error(`The alert queue ${t} is damaged; move it aside to start an empty queue`,{cause:r})}},save(n){IC(Rh(e,$h),{mode:GC,recursive:!0});let r=`${t}.${process.pid}.tmp`;try{MC(r,`${JSON.stringify(n)}
90
+ `,{flag:"wx",mode:FC}),DC(r,t)}finally{LC(r,{force:!0})}}}}var zC=K({argv:{description:"The command sink's program and arguments, as a JSON array",type:"string"},botTokenFile:{description:"Absolute path of a 0600 file holding a Discord bot token",type:"string"},channelId:{description:"The Discord channel the bot posts to",type:"string"},webhookFile:{description:"Absolute path of a 0600 file holding a Discord webhook URL",type:"string"}}),QC=ae({sink:{description:"Sink to set: discord or command"}}),Yo="Use --webhook-file <path>, or --bot-token-file <path> with --channel-id <id>",cl=`Use --argv '["/usr/local/bin/notify", "--from", "hydra"]'`,Th=P({name:"set",description:"Send alerts to Discord or to a fixed command",args:zC,positionals:QC,run:async(e)=>{let t=e.positionals.sink;if(t===void 0||!mi(t))throw new b(`Unknown alert sink "${t??""}"`,`Choose one of: ${Sn.join(", ")}`);let n=e.config.get("alerts");if(t==="discord"){let o=await ZC(e.args);e.config.set("alerts",{...n,discord:o}),_h(Ko(o),t);return}let r=eO(e.args);e.config.set("alerts",{...n,command:r}),_h(qo(r),t)}});async function ZC(e){if(e.argv!==void 0)throw new b("--argv applies to the command sink",Yo);let{botTokenFile:t,channelId:n,webhookFile:r}=e;if(r!==void 0&&(t!==void 0||n!==void 0))throw new b("Choose a webhook or a bot, not both",Yo);if(r===void 0&&t===void 0)throw new b("Name a webhook or a bot",Yo);let o;try{o=Wu(r!==void 0?{webhookFile:r}:{botTokenFile:t,channelId:n})}catch(s){throw new b(s.message,Yo)}try{await sl(o)}catch(s){throw new b(s.message,s instanceof Jn?Zg:Yo)}return o}function eO(e){let{argv:t,botTokenFile:n,channelId:r,webhookFile:o}=e;if(o!==void 0||n!==void 0||r!==void 0)throw new b("--webhook-file, --bot-token-file and --channel-id apply to the discord sink",cl);if(t===void 0)throw new b("Name the command with --argv",cl);let s;try{s=Ju({argv:JSON.parse(t)})}catch{throw new b(`--argv must be a JSON array: ${Ku}`,cl)}let i=s.argv[0];try{if(JC(i,YC.X_OK),!XC(i).isFile())throw Error("not a file")}catch{throw new b(`${i} is not an executable file`,"Hydra runs the command directly, without a shell")}return s}function _h(e,t){T.success([`Alerts go to the ${e}`,p.dim(`Run hydra alerts test --sink ${t} to send a test message`)].join(`
91
+ `))}var Yn="Run hydra alerts set discord --webhook-file <path>, or hydra alerts set command --argv <json>";function Ah(e,{env:t,home:n,now:r,pools:o}){if(Et(e).length===0)return o?[`${p.bold("Alerts")} ${p.yellow("no sink")}`]:[];let s=[p.bold("Alerts")];if(e?.discord){let i=jn(e.discord)?e.discord.webhookFile:e.discord.botTokenFile,a=eh(i);if(s.push(` discord: ${Ko(e.discord)}`),a)s.push(p.yellow(` The file ${a}`));s.push(...tO(t))}if(e?.command)s.push(` command: ${qo(e.command)}`);return[...s,...nO(n,r,Et(e))]}function tO(e){if(!e[Dr])return[];try{let t=p.dim(`(from ${Dr}; Hydra sends the webhook or bot token there)`);return[` API ${Ni(e)} ${t}`]}catch(t){if(!(t instanceof b))throw t;return[p.yellow(` ${t.message}`),...t.hint?[p.dim(` ${t.hint}`)]:[]]}}function nO(e,t,n){let r;try{r=Gi(e).load()}catch(i){return[p.yellow(` ${i.message}`)]}let o=n.flatMap((i)=>{let a=r.stopped[i];return a?[p.yellow(` ${i} stopped at ${Lt(a.at)} after HTTP ${a.status}: ${a.detail}; change its settings or its file to resume`)]:[]}),s=al(r,t,n).map(({count:i,error:a,oldest:c,sink:u})=>p.yellow(` ${i} ${i===1?"alert":"alerts"} for ${u} undelivered since ${Lt(c)}${a?`: ${a}`:""}`));return[...o,...s]}var rO=K({burst:{description:"Raise this many test alerts through the rate limits, then send the held ones as one digest",type:"number"},sink:{description:"Test only this sink: discord or command",type:"string"}}),Ch=50,Oh=P({name:"test",description:"Send a test alert to each sink and print what each sink answered",args:rO,run:async(e)=>{let t=e.config.get("alerts"),n=Et(t);if(n.length===0)throw new b("No alert sink is configured",Yn);let r=oO(e.args.sink,n),o=sO(e.args.burst),s=Mi(t,{env:process.env,only:r,version:vn}),i=e.config.get("fleet")?.id,a=o===void 0?await iO(s,i):await aO(s,i,o);if(a===0)return;throw new b(`${a} test ${a===1?"delivery":"deliveries"} failed`,"Each line above names what the sink answered")}});function oO(e,t){if(e===void 0)return;if(!mi(e))throw new b(`Unknown alert sink "${e}"`,`Choose one of: ${Sn.join(", ")}`);if(!t.includes(e))throw new b(`The ${e} sink is not configured`,Yn);return e}function sO(e){if(e===void 0)return;if(Number.isSafeInteger(e)&&e>=1&&e<=Ch)return e;throw new b(`--burst must be a whole number from 1 to ${Ch}`)}async function iO(e,t){let n=Di({detail:"hydra alerts test",reason:"test"},{at:Date.now(),count:1,fleet:t}),r=0;for(let o of e){let s=await o.send(n);if(s.outcome!=="delivered")r++;T.info(Ph(o.name,"test alert",s))}return r}async function aO(e,t,n){let r=[],o=Li({fleet:t,onDelivery(s){r.push(s),T.info(Ph(s.sink,s.kind,s.delivery))},sinks:e,store:xh()});for(let s=1;s<=n;s++)o.raise({detail:`test alert ${s} of ${n}`,pool:`burst-${s}`,reason:"test"});await o.deliver({flush:!0});for(let s of e){let i=r.filter((c)=>c.sink===s.name&&c.delivery.outcome==="delivered"),a=i.filter((c)=>c.kind==="digest").length;T.info(p.dim(`${s.name} took ${i.length-a} of ${n} test alerts and ${a} ${a===1?"digest":"digests"}`))}return r.filter((s)=>s.delivery.outcome!=="delivered").length}function Ph(e,t,n){let r=[n.status===void 0?"":`HTTP ${n.status}`,n.outcome==="delivered"&&n.exitCode!==void 0?`exit ${n.exitCode}`:"",n.outcome==="delivered"&&n.messageId?`message ${n.messageId}`:"",n.outcome==="delivered"?"":`${n.outcome}: ${n.detail}`].filter(Boolean).join(" \xB7 ");return`${n.outcome==="delivered"?p.green("\u2713"):p.red("\u2717")} ${e} ${t} ${r}`}var ul=P({name:"alerts",description:"Choose where Hydra sends alerts and test it",subcommands:[Th,Oh]});import{existsSync as RD}from"fs";import{join as $D}from"path";var cO=/^(?:W\/)?"[\x21\x23-\x7e]*"$/;function Ih(e){return cO.test(e)}function Mr(e=256){let t=new Map,n=(r,o)=>{t.delete(r),t.set(r,o)};return{get(r){let o=t.get(r);if(o)n(r,o);return o},set(r,o){n(r,o);for(let s of t.keys()){if(t.size<=e)return;t.delete(s)}}}}var ll="https://api.github.com",Hr="HYDRA_GITHUB_API_URL",uO="2022-11-28",lO="r5n-hydra",dO=3,Uh=500,pO=60000,jh=30000,Fi=1000,fO=100,Nh=100,mO=200,gO=403,Dh=429,hO=204,Lh=304,yO=500,Mh="[redacted]",bO=new Set(["DELETE","GET","PUT"]),wO=new Set(["127.0.0.1","[::1]"]),SO=[/\bgh[opsur]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_\w{20,}\b/g,/\beyJ[\w-]+\.[\w-]+\.[\w-]+/g],RO=/[\p{Cc}\p{Cf}]+/gu,$O=/<([^>]+)>;\s*rel="next"/,EO=/\/+$/,vO=/^\/+/,kO=/\s+/g;class Re extends Error{operation;method;path;status;_tag="GitHubApiError";constructor(e,t,n,r,o){let s=r===void 0?"got no response":`returned ${r}`;super(`${e} failed: ${t} ${n} ${s}${o?` (${o})`:""}`);this.operation=e;this.method=t;this.path=n;this.status=r;this.name="GitHubApiError"}}function kn(e){let t=e[Hr];if(!t)return ll;let n="Use an https URL, or http on 127.0.0.1 or [::1], with no credentials, query or fragment",r;try{r=new URL(t)}catch{throw new b(`${Hr} is not a URL`,n)}if(!(r.protocol==="https:"||r.protocol==="http:"&&wO.has(r.hostname))||r.username||r.password||r.search||r.hash)throw new b(`${Hr} is not an API root Hydra may send tokens to`,n);return r.href.replace(EO,"")}function dl({apiUrl:e,auth:t}){let n=new URL(`${e}/`);async function r(c,u,l,d,f,m){let g=s(u);for(let h=1;;h++){let E=await t.token(),v=h<dO,S;try{S=await fetch(u,{body:d===void 0?void 0:JSON.stringify(d),headers:_O(E,d!==void 0,m),method:c,redirect:"manual",signal:AbortSignal.timeout(jh)})}catch(w){if(f&&v){await Bun.sleep(Hh(h));continue}throw new Re(l,c,g,void 0,Fh(Gh(w),E))}if(S.ok||m!==void 0&&S.status===Lh)return S;let _=TO(S);if(_!==void 0&&v&&_<=pO){await S.body?.cancel(),await Bun.sleep(_);continue}if(_===void 0&&S.status>=yO&&f&&v){await S.body?.cancel(),await Bun.sleep(Hh(h));continue}let C=[_===void 0?"":AO(S),await CO(S)].filter(Boolean).join("; ");throw new Re(l,c,g,S.status,Fh(C,E))}}async function o(c,u,l,d,f){let m=s(f),g;try{g=c.status===hO?"":await c.text()}catch(E){throw new Re(l,d,m,c.status,Gh(E))}let h;try{h=g===""?void 0:JSON.parse(g)}catch{throw new Re(l,d,m,c.status,"the response is not JSON")}try{return u(h)}catch{throw new Re(l,d,m,c.status,"the response has an unexpected shape")}}function s(c){return c.pathname.slice(n.pathname.length-1)+c.search}function i(c){return new URL(c.replace(vO,""),n)}function a(c){return c.origin===n.origin&&c.pathname.startsWith(n.pathname)}return{async paginate({cache:c,item:u,key:l,operation:d,path:f}){let m=[],g=i(f);if(!g.searchParams.has("per_page"))g.searchParams.set("per_page",String(fO));let h=g;for(let E=1;h;E++){if(E>Nh)throw new Re(d,"GET",f,void 0,`stopped after ${Nh} pages`);let v=h,S=c?.get(v.href),_=await r("GET",v,d,void 0,!0,S?.etag);if(S&&_.status===Lh){await _.body?.cancel(),m.push(...S.items),h=S.next===void 0?void 0:new URL(S.next);continue}let C=_.headers.get("link"),w=await o(_,xO(u,l),d,"GET",v);m.push(...w);let x=C?.match($O)?.[1];if(h=x?new URL(x):void 0,h&&!a(h))throw new Re(d,"GET",f,_.status,"refused a next page outside the API root");let y=_.headers.get("etag");if(c&&y!==null&&Ih(y))c.set(v.href,{etag:y,items:w,next:h?.href})}return m},async request({body:c,idempotent:u,method:l="GET",operation:d,path:f,schema:m}){let g=i(f),h=await r(l,g,d,c,u??bO.has(l));return o(h,m,d,l,g)}}}function Bh(e){let t,n=()=>(t??=e(),t);return{async paginate(r){return n().paginate(r)},async request(r){return n().request(r)}}}function xO(e,t){return(n)=>{let r=t===void 0?n:n?.[t];if(!Array.isArray(r))throw TypeError("not a list");return r.map((o)=>e(o))}}function _O(e,t,n){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"User-Agent":lO,"X-GitHub-Api-Version":uO,...t?{"Content-Type":"application/json"}:{},...n===void 0?{}:{"If-None-Match":n}}}function Hh(e){return Uh*2**(e-1)}function TO(e){if(e.status!==gO&&e.status!==Dh)return;let t=e.headers.get("retry-after");if(t!==null&&t.trim()!==""&&Number.isFinite(Number(t)))return Math.max(0,Number(t)*Fi);if(e.headers.get("x-ratelimit-remaining")==="0"){let n=e.headers.get("x-ratelimit-reset")?.trim(),r=n?Number(n):Number.NaN;return Number.isFinite(r)?Math.max(0,r*Fi-Date.now()):Number.POSITIVE_INFINITY}return e.status===Dh?Uh:void 0}function AO(e){let t=Number(e.headers.get("x-ratelimit-reset")),n=Number(e.headers.get("retry-after"));if(Number.isFinite(n)&&n>0)return`rate limited; retry in ${n} s`;if(Number.isFinite(t)&&t>0)return`rate limited until ${new Date(t*Fi).toISOString()}`;return"rate limited"}async function CO(e){try{let n=JSON.parse(await e.text())?.message;return typeof n==="string"?n:""}catch{return""}}function Gh(e){if(e instanceof Error&&e.name==="TimeoutError")return`timed out after ${jh/Fi} s`;return e instanceof Error?e.message:String(e)}function Fh(e,t){let n=t?e.replaceAll(t,Mh):e;return SO.reduce((r,o)=>r.replace(o,Mh),n).replace(RO," ").replace(kO," ").trim().slice(0,mO)}import{createPrivateKey as OO,sign as PO}from"crypto";import{constants as Vh}from"fs";import{open as IO,stat as NO}from"fs/promises";var qh="github.com",DO=60,LO=540,MO=300000,HO=1000,GO=63,FO=511,UO=8,jO=4,BO=Vh.O_RDONLY|Vh.O_NONBLOCK,pl="Check the GitHub App's id, installation id and private key in credentials",fl=I().map((e)=>e.trim()===""?F():e),VO=N({expires_at:I(),token:fl}),Kh=new WeakMap;class Xn extends b{_tag="GitHubCredentialsError"}function qO(e,t){let n,r=()=>{if(n)return n;let o=kn(t),s=e?.mode==="app"?WO(e,o):KO();return n={client:dl({apiUrl:o,auth:s}),credentials:s},n};return{client:Bh(()=>r().client),credentials:{kind:e?.mode??"gh",async token(){return r().credentials.token()}}}}function Mt(e){let t=Kh.get(e);if(t)return t;let n=qO(e.get("credentials"),process.env);return Kh.set(e,n),n}function Jh(e){return e?.mode==="app"?`GitHub App ${e.appId}, installation ${e.installationId}, key ${e.privateKeyPath}`:"the gh login (gh auth token)"}async function Yh(e){try{return Xh(await NO(e))}catch(t){return`cannot be read (${t.code??"unknown error"})`}}function KO(){let e;return{kind:"gh",token(){return e??=JO().catch((t)=>{throw e=void 0,t}),e}}}function WO(e,t){let n=dl({apiUrl:t,auth:{token:async()=>XO(e.appId,await YO(e.privateKeyPath))}}),r,o;async function s(){try{let{expires_at:i,token:a}=await n.request({idempotent:!0,method:"POST",operation:`Mint an installation token for GitHub App ${e.appId}`,path:`/app/installations/${e.installationId}/access_tokens`,schema:VO});return{expiresAt:Date.parse(i),token:a}}catch(i){throw i instanceof Re?new Xn(i.message,pl):i}}return{kind:"app",async token(){if(r&&r.expiresAt-MO>Date.now())return r.token;o??=s().finally(()=>{o=void 0});let i=await o;return r=Number.isFinite(i.expiresAt)?i:void 0,i.token}}}async function JO(){let e=await Bun.$`gh auth token --hostname ${qh}`.quiet().nothrow(),t=e.stdout.toString().trim();if(e.exitCode===0&&t)return t;let n=e.stderr.toString().trim();throw new Xn(`gh auth token failed for ${qh}${n?`: ${n}`:""}`,"Run gh auth login, or configure a GitHub App in credentials")}async function YO(e){let n;try{n=await IO(e,BO)}catch(r){throw new Xn(`Cannot open the GitHub App private key ${e} (${r.code??"unknown error"})`,"credentials.privateKeyPath must name a PEM file owned by the user running Hydra, with mode 0600")}try{let r=Xh(await n.stat());if(r)throw new Xn(`The GitHub App private key ${e} ${r}`,"credentials.privateKeyPath must name a PEM file owned by the user running Hydra, with mode 0600");let o;try{o=OO(await n.readFile("utf8"))}catch{throw new Xn(`The GitHub App private key ${e} is not a PEM private key`,"credentials.privateKeyPath must name a PEM file owned by the user running Hydra, with mode 0600")}if(o.asymmetricKeyType!=="rsa")throw new Xn(`The GitHub App private key ${e} is not an RSA key`,"credentials.privateKeyPath must name a PEM file owned by the user running Hydra, with mode 0600");return o}finally{await n.close()}}function Xh(e){let t=process.getuid?.();if(!e.isFile())return"is not a regular file";if(t===void 0)return"cannot be checked for its owner on this platform";if(e.uid!==t)return`is owned by uid ${e.uid}, not by the user running Hydra (uid ${t})`;if((e.mode&GO)!==0)return`is open to its group or others (mode ${(e.mode&FO).toString(UO).padStart(jO,"0")})`;return}function XO(e,t){let n=Math.floor(Date.now()/HO)-DO,r=Wh(JSON.stringify({alg:"RS256",typ:"JWT"})),o=Wh(JSON.stringify({exp:n+LO,iat:n,iss:e})),s=PO("sha256",Buffer.from(`${r}.${o}`),t).toString("base64url");return`${r}.${o}.${s}`}function Wh(e){return Buffer.from(e).toString("base64url")}var zh=404,zO=422,QO="offline",ZO=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),Ui=N({busy:Q(),id:ZO,name:I(),status:I()}),eP=()=>{return};function Gr(e){return`/${e.kind==="repo"?`repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`:`orgs/${encodeURIComponent(e.org)}`}/actions/runners`}function Fr(e){return e.status===QO}async function Ht(e,t){return e.paginate({item:Ui,key:"runners",operation:`List the runners of ${De(t)}`,path:Gr(t)})}async function Gt(e,t,n){try{return await e.request({operation:`Read runner ${n} of ${De(t)}`,path:`${Gr(t)}/${n}`,schema:Ui})}catch(r){if(r instanceof Re&&r.status===zh)return;throw r}}async function zn(e,t,n){try{return await e.request({method:"DELETE",operation:`Delete runner ${n} of ${De(t)}`,path:`${Gr(t)}/${n}`,schema:eP}),"deleted"}catch(r){if(!(r instanceof Re))throw r;if(r.status===zh)return"gone";if(r.status===zO)return"busy";throw r}}function Xo(e,t){switch(e){case"app":return t.kind==="repo"?"The GitHub App needs the Administration repository permission (read and write) on the repository":"The GitHub App needs the Self-hosted runners organisation permission (read and write)";case"gh":return t.kind==="repo"?"gh needs admin access to the repository":"gh needs the admin:org scope"}}var Qh=1,tP="_work",nP=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),Zh=N({busy:Q(),id:nP,labels:Z(N({name:I()})),name:I(),status:I()}).map((e)=>({busy:e.busy,id:e.id,labels:e.labels.map((t)=>t.name),name:e.name,status:e.status})),rP=N({encoded_jit_config:I().map((e)=>e.trim()===""?F():e),runner:Zh}).map((e)=>({encodedJitConfig:e.encoded_jit_config,runner:e.runner}));function oP(e){return`${Gr(e)}/generate-jitconfig`}async function ey(e,t,{labels:n,name:r,runnerGroupId:o,workFolder:s=tP}){return e.request({body:{labels:[...n],name:r,runner_group_id:o,work_folder:s},method:"POST",operation:`Generate a just-in-time configuration for runner ${r} of ${De(t)}`,path:oP(t),schema:rP})}async function ty(e,t,n){return(await e.paginate({item:Zh,key:"runners",operation:`Find the runner ${n} of ${De(t)}`,path:`${Gr(t)}?name=${encodeURIComponent(n)}`})).find((o)=>o.name===n)}var sP=["queued","in_progress"],ny=4096,iP="queued",aP=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),cP=N({id:aP}),uP=N({labels:Z(I()),status:I()});function ji(e,t){if(e.length===0)return!1;let n=new Set(t.map((r)=>r.toLowerCase()));return e.every((r)=>n.has(r.toLowerCase()))}function Bi({owner:e,repo:t}){return`/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function ry({owner:e,repo:t}){return`${e}/${t}`.toLowerCase()}function oy(){return{jobs:Mr(ny),runs:Mr(ny)}}async function sy(e,t,n,r){let o=`${t.owner}/${t.repo}`,s=Bi(t),i=new Set;for(let c of sP){r.throwIfAborted();let u=await e.paginate({cache:n.runs,item:cP,key:"workflow_runs",operation:`List the ${c} workflow runs of ${o}`,path:`${s}/actions/runs?status=${c}`});for(let l of u)i.add(l.id)}let a=[];for(let c of i){r.throwIfAborted();let u=await e.paginate({cache:n.jobs,item:uP,key:"jobs",operation:`List the jobs of workflow run ${c} of ${o}`,path:`${s}/actions/runs/${c}/jobs?filter=latest`});for(let l of u)if(l.status===iP)a.push(l.labels)}return a}var iy="selected",ay=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),cy=N({allows_public_repositories:Q().or(ne()),default:Q(),id:ay,name:I(),visibility:I()}).map((e)=>({allowsPublicRepositories:e.allows_public_repositories,default:e.default,id:e.id,name:e.name,visibility:e.visibility})),lP=N({id:ay}),dP=()=>{return};function Ft(e){return`/orgs/${encodeURIComponent(e)}/actions/runner-groups`}async function pP(e,t,n){return e.paginate({cache:n,item:cy,key:"runner_groups",operation:`List the runner groups of ${t}`,path:Ft(t)})}async function Ur(e,t,n,r){return(await pP(e,t,r)).find((s)=>s.name.toLowerCase()===n.toLowerCase())}async function uy(e,t,n){return e.request({body:{allows_public_repositories:!1,name:n,selected_repository_ids:[],visibility:iy},method:"POST",operation:`Create the runner group ${n} in ${t}`,path:Ft(t),schema:cy})}async function ly(e,t,n){return(await e.paginate({item:lP,key:"repositories",operation:`List the repositories that may use the runner group ${n.name} of ${t}`,path:`${Ft(t)}/${n.id}/repositories`})).length}async function Vi(e,t,n){return e.paginate({item:Ui,key:"runners",operation:`List the runners in the runner group ${n.name} of ${t}`,path:`${Ft(t)}/${n.id}/runners`})}async function dy(e,t,n,r){await e.request({method:"PUT",operation:`Move runner ${r} of ${t} into the runner group ${n.name}`,path:`${Ft(t)}/${n.id}/runners/${r}`,schema:dP})}function py(e,t){if(e.default)return"it is the default group, which every repository may use";if(e.visibility!==iy)return`its visibility is ${e.visibility}, not selected`;if(e.allowsPublicRepositories)return"it allows public repositories";if(t>0)return`${t} repository(ies) may use it`;return}var fP=["all","private","selected"],mP=/^[A-Za-z0-9._-]+$/,fy=I().map((e)=>mP.test(e)?e:F()),my=N({archived:Q().or(ne()),name:fy,owner:N({login:fy}),private:Q()}).map((e)=>({archived:e.archived??!1,owner:e.owner.login,private:e.private,repo:e.name}));function gy(e){return fP.includes(e)}async function gP(e,t,n){return e.paginate({cache:n,item:my,operation:`List the repositories of ${t}`,path:`/orgs/${encodeURIComponent(t)}/repos?type=all`})}async function hP(e,t,n,r){return e.paginate({cache:r,item:my,key:"repositories",operation:`List the repositories that may use the runner group ${n.name} of ${t}`,path:`${Ft(t)}/${n.id}/repositories`})}async function hy(e,t,n,r){return(n.visibility==="selected"?await hP(e,t,n,r):await gP(e,t,r)).filter((s)=>!s.archived).filter((s)=>n.visibility==="private"?s.private:!0).filter((s)=>s.private||n.allowsPublicRepositories===!0).map(({owner:s,repo:i})=>({owner:s,repo:i}))}import{existsSync as xn}from"fs";import{cp as O0,link as P0,mkdir as na,mkdtemp as I0,readdir as Gy,readFile as N0,readlink as D0,rename as L0,rm as Zn,stat as Fy,symlink as M0,unlink as H0}from"fs/promises";import{join as me,relative as G0,resolve as ra,sep as Uy}from"path";import{chmod as bP,mkdir as wP,readFile as SP,rename as RP,rm as $P,stat as EP,writeFile as Ry}from"fs/promises";import{dirname as vP,join as bl,resolve as Ki}from"path";import{isAbsolute as yP}from"path";var ml="# Generated by Hydra; hydra update rewrites this file.";function yy(e){return`'${e.replaceAll("'","'\\''")}'`}function by(){return`#!/usr/bin/env bash
92
+ ${ml}
96
93
  # Disabled in the Hydra profile; kept so runners started before the change still find it.
97
94
  exit 0
98
- `}function Qi(e){return`#!/usr/bin/env bash
99
- ${Cr}
95
+ `}function wy(e){return`#!/usr/bin/env bash
96
+ ${ml}
100
97
  # Waits until every host resolves, then lets the job start; fails the job on timeout.
101
98
  set +e
102
99
 
103
- hosts=(${e.hosts.map(Xi).join(" ")})
100
+ hosts=(${e.hosts.map(yy).join(" ")})
104
101
  timeout_seconds=${e.timeoutSeconds}
105
102
 
106
103
  if command -v dscacheutil >/dev/null 2>&1; then
@@ -138,15 +135,15 @@ while :; do
138
135
  pending=("\${unresolved[@]}")
139
136
  sleep 1
140
137
  done
141
- `}function es(e,t){if(!Jc(e)||e==="/")throw Error(`Refusing to generate a workspace cleanup hook for runner directory "${e}"`);return`#!/usr/bin/env bash
142
- ${Cr}
138
+ `}function Sy(e,t){if(!yP(e)||e==="/")throw Error(`Refusing to generate a workspace cleanup hook for runner directory "${e}"`);return`#!/usr/bin/env bash
139
+ ${ml}
143
140
  # Removes this job's workspace and temporary files from this runner's _work directory.
144
141
  # Always exits 0 so a cleanup problem never fails a finished job; problems become warnings.
145
142
  set +e
146
143
  trap 'exit 0' EXIT
147
144
  shopt -s dotglob nullglob
148
145
 
149
- runner_root=${Xi(e)}
146
+ runner_root=${yy(e)}
150
147
  keep_tool_cache=${t.keepToolCache}
151
148
 
152
149
  note() { echo "Hydra cleanup: $*"; }
@@ -234,29 +231,403 @@ cd -- "$work_root" || exit 0
234
231
  clean_job_workspace "\${RUNNER_WORKSPACE:-\${GITHUB_WORKSPACE:-}}"
235
232
  clear_dir "$work_root/_temp" _runner_file_commands _github_workflow
236
233
  [ "$keep_tool_cache" = true ] || clear_dir "$work_root/_tool"
237
- `}var el="hydra-hooks",ns=".env",ln={started:{envKey:"ACTIONS_RUNNER_HOOK_JOB_STARTED",file:"job-started.sh"},completed:{envKey:"ACTIONS_RUNNER_HOOK_JOB_COMPLETED",file:"job-completed.sh"}},tl=Object.keys(ln),nl=493,rl=253,ol=/^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/,Er="Fix the profile's jobHooks in config.json in the Hydra home; see the Hydra reference for the allowed values",Sr={dns:["enabled","hosts","timeoutSeconds"],workspaceCleanup:["enabled","keepToolCache"]},il=U().map((e)=>e.length<=rl&&ol.test(e)?e:F()),sl=Wt(il).map((e)=>e.length>0?e:F()),al=Q().map((e)=>Number.isSafeInteger(e)&&e>0?e:F());function rs(){return{dns:{enabled:di,hosts:[...fi],timeoutSeconds:pi},workspaceCleanup:{enabled:ui,keepToolCache:li}}}function dn(){let e=rs();return{...e,workspaceCleanup:{...e.workspaceCleanup,enabled:ci}}}function Se(e){let t=rs(),n=xr(e,"jobHooks",Object.keys(Sr)),r=xr(n.dns,"jobHooks.dns",Sr.dns),o=xr(n.workspaceCleanup,"jobHooks.workspaceCleanup",Sr.workspaceCleanup);return{dns:{enabled:Rt(te(),r.enabled,t.dns.enabled,"jobHooks.dns.enabled","a boolean"),hosts:Rt(sl,r.hosts,t.dns.hosts,"jobHooks.dns.hosts","a non-empty list of hostnames"),timeoutSeconds:Rt(al,r.timeoutSeconds,t.dns.timeoutSeconds,"jobHooks.dns.timeoutSeconds","a positive whole number of seconds")},workspaceCleanup:{enabled:Rt(te(),o.enabled,t.workspaceCleanup.enabled,"jobHooks.workspaceCleanup.enabled","a boolean"),keepToolCache:Rt(te(),o.keepToolCache,t.workspaceCleanup.keepToolCache,"jobHooks.workspaceCleanup.keepToolCache","a boolean")}}}function os(e,t){return kr(cn(e),el,ln[t].file)}function is(e,t,n){switch(e){case"started":return n.dns.enabled?Qi(n.dns):null;case"completed":return n.workspaceCleanup.enabled?es(cn(t),n.workspaceCleanup):null}}function ul(e,t){let n=new Map(t.map((s)=>[s.key,s])),r=new Set,o=e.split(`
238
- `);if(o.at(-1)==="")o.pop();let i=[];for(let s of o){let c=s.indexOf("="),a=c>0?n.get(s.slice(0,c)):void 0;if(!a){i.push(s);continue}if(a.value===null){if(s.slice(c+1)!==a.managedPath)i.push(s);continue}if(r.has(a.key))continue;r.add(a.key),i.push(`${a.key}=${a.value}`)}for(let s of t)if(s.value!==null&&!r.has(s.key))i.push(`${s.key}=${s.value}`);return i.length>0?`${i.join(`
234
+ `}var kP="hydra-hooks",$y=".env",Wi={started:{envKey:"ACTIONS_RUNNER_HOOK_JOB_STARTED",file:"job-started.sh"},completed:{envKey:"ACTIONS_RUNNER_HOOK_JOB_COMPLETED",file:"job-completed.sh"}},xP=Object.keys(Wi),_P=493,TP=253,AP=/^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/,yl="Fix the profile's jobHooks in config.json in the Hydra home; see the Hydra reference for the allowed values",gl={dns:["enabled","hosts","timeoutSeconds"],workspaceCleanup:["enabled","keepToolCache"]},CP=I().map((e)=>e.length<=TP&&AP.test(e)?e:F()),OP=Z(CP).map((e)=>e.length>0?e:F()),PP=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F());function Ey(){return{dns:{enabled:Nm,hosts:[...Lm],timeoutSeconds:Dm},workspaceCleanup:{enabled:Om,keepToolCache:Im}}}function wl(){let e=Ey();return{...e,workspaceCleanup:{...e.workspaceCleanup,enabled:Pm}}}function an(e){let t=Ey(),n=hl(e,"jobHooks",Object.keys(gl)),r=hl(n.dns,"jobHooks.dns",gl.dns),o=hl(n.workspaceCleanup,"jobHooks.workspaceCleanup",gl.workspaceCleanup);return{dns:{enabled:zo(Q(),r.enabled,t.dns.enabled,"jobHooks.dns.enabled","a boolean"),hosts:zo(OP,r.hosts,t.dns.hosts,"jobHooks.dns.hosts","a non-empty list of hostnames"),timeoutSeconds:zo(PP,r.timeoutSeconds,t.dns.timeoutSeconds,"jobHooks.dns.timeoutSeconds","a positive whole number of seconds")},workspaceCleanup:{enabled:zo(Q(),o.enabled,t.workspaceCleanup.enabled,"jobHooks.workspaceCleanup.enabled","a boolean"),keepToolCache:zo(Q(),o.keepToolCache,t.workspaceCleanup.keepToolCache,"jobHooks.workspaceCleanup.keepToolCache","a boolean")}}}function vy(e,t){return bl(Ki(e),kP,Wi[t].file)}function ky(e,t,n){switch(e){case"started":return n.dns.enabled?wy(n.dns):null;case"completed":return n.workspaceCleanup.enabled?Sy(Ki(t),n.workspaceCleanup):null}}function IP(e,t){let n=new Map(t.map((i)=>[i.key,i])),r=new Set,o=e.split(`
235
+ `);if(o.at(-1)==="")o.pop();let s=[];for(let i of o){let a=i.indexOf("="),c=a>0?n.get(i.slice(0,a)):void 0;if(!c){s.push(i);continue}if(c.value===null){if(i.slice(a+1)!==c.managedPath)s.push(i);continue}if(r.has(c.key))continue;r.add(c.key),s.push(`${c.key}=${c.value}`)}for(let i of t)if(i.value!==null&&!r.has(i.key))s.push(`${i.key}=${i.value}`);return s.length>0?`${s.join(`
239
236
  `)}
240
- `:""}async function pn(e,t){let n=[],r=!1;for(let c of tl){let a=os(e,c),u=is(c,e,t),d=await un(a),p=u??(d===null?null:Zi());if(p!==null&&p!==d)await pl(a,p),r=!0;n.push({key:ln[c].envKey,managedPath:a,value:u===null?null:a})}let o=kr(cn(e),ns),i=await un(o)??"",s=ul(i,n);if(s===i)return{envChanged:!1,scriptsChanged:r};return await ts(o,s),{envChanged:!0,scriptsChanged:r}}async function _r(e,t){let n=kr(cn(e),ns),r=await un(n)??"",o=(i)=>cl(os(e,i),ll(r,ln[i].envKey),is(i,e,t));return{envModifiedAt:await dl(n),states:{completed:await o("completed"),started:await o("started")}}}async function cl(e,t,n){if(n===null){if(t===void 0)return"off";return t===e?"outdated":"foreign"}if(t===void 0)return"missing";if(t!==e)return"foreign";return await un(e)===n?"configured":"outdated"}function ll(e,t){let n=`${t}=`;return e.split(`
241
- `).filter((r)=>r.startsWith(n)).map((r)=>r.slice(n.length)).at(-1)}async function dl(e){try{return(await Zc(e)).mtime}catch(t){if(t.code==="ENOENT")return null;throw t}}function xr(e,t,n){if(e===void 0)return{};if(typeof e!=="object"||e===null||Array.isArray(e))throw new y(`Invalid ${t}: expected an object`,Er);let r=Object.keys(e).find((o)=>!n.includes(o));if(r!==void 0)throw new y(`Unknown ${t} setting: ${r}`,Er);return e}function Rt(e,t,n,r,o){if(t===void 0)return n;try{return e(t)}catch{throw new y(`Invalid ${r}: expected ${o}`,Er)}}async function un(e){try{return await zc(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function pl(e,t){let n=`${e}.${process.pid}.tmp`;await qc(Qc(e),{recursive:!0});try{await ts(n,t),await Wc(n,nl),await Yc(n,e)}finally{await Xc(n,{force:!0})}}import{existsSync as fl}from"fs";import{readdir as ml,stat as hl}from"fs/promises";import{join as gl}from"path";var fn="_diag",ss={runner:/^Runner_.+\.log$/,worker:/^Worker_.+\.log$/},as=1024,us=["B","KB","MB","GB"],yl=1;function bl(e){if(ss.worker.test(e))return"worker";if(ss.runner.test(e))return"runner";return null}function Tr(e){return[...e].sort((t,n)=>n.mtime.getTime()-t.mtime.getTime())}async function mn(e){if(!fl(e))return[];let t=await ml(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile())continue;let o=bl(r.name);if(!o)continue;let i=gl(e,r.name),s=await hl(i);n.push({mtime:s.mtime,name:r.name,path:i,size:s.size,type:o})}return Tr(n)}function Pr(e,t){let n=e.find((o)=>o.type===t);if(n)return{fallback:!1,file:n};let r=e[0];return r?{fallback:!0,file:r}:null}function Ar(e,t){if(t<=0)return"";let n=e.endsWith(`
237
+ `:""}async function Ji(e,t){let n=[],r=!1;for(let a of xP){let c=vy(e,a),u=ky(a,e,t),l=await qi(c),d=u??(l===null?null:by());if(d!==null&&d!==l)await MP(c,d),r=!0;n.push({key:Wi[a].envKey,managedPath:c,value:u===null?null:c})}let o=bl(Ki(e),$y),s=await qi(o)??"",i=IP(s,n);if(i===s)return{envChanged:!1,scriptsChanged:r};return await Ry(o,i),{envChanged:!0,scriptsChanged:r}}async function Sl(e,t){let n=bl(Ki(e),$y),r=await qi(n)??"",o=(s)=>NP(vy(e,s),DP(r,Wi[s].envKey),ky(s,e,t));return{envModifiedAt:await LP(n),states:{completed:await o("completed"),started:await o("started")}}}async function NP(e,t,n){if(n===null){if(t===void 0)return"off";return t===e?"outdated":"foreign"}if(t===void 0)return"missing";if(t!==e)return"foreign";return await qi(e)===n?"configured":"outdated"}function DP(e,t){let n=`${t}=`;return e.split(`
238
+ `).filter((r)=>r.startsWith(n)).map((r)=>r.slice(n.length)).at(-1)}async function LP(e){try{return(await EP(e)).mtime}catch(t){if(t.code==="ENOENT")return null;throw t}}function hl(e,t,n){if(e===void 0)return{};if(typeof e!=="object"||e===null||Array.isArray(e))throw new b(`Invalid ${t}: expected an object`,yl);let r=Object.keys(e).find((o)=>!n.includes(o));if(r!==void 0)throw new b(`Unknown ${t} setting: ${r}`,yl);return e}function zo(e,t,n,r,o){if(t===void 0)return n;try{return e(t)}catch{throw new b(`Invalid ${r}: expected ${o}`,yl)}}async function qi(e){try{return await SP(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function MP(e,t){let n=`${e}.${process.pid}.tmp`;await wP(vP(e),{recursive:!0});try{await Ry(n,t),await bP(n,_P),await RP(n,e)}finally{await $P(n,{force:!0})}}import{existsSync as HP}from"fs";import{readdir as GP,stat as FP}from"fs/promises";import{join as UP}from"path";var Yi="_diag",xy={runner:/^Runner_.+\.log$/,worker:/^Worker_.+\.log$/},_y=1024,Ty=["B","KB","MB","GB"],jP=1;function BP(e){if(xy.worker.test(e))return"worker";if(xy.runner.test(e))return"runner";return null}function Rl(e){return[...e].sort((t,n)=>n.mtime.getTime()-t.mtime.getTime())}async function Xi(e){if(!HP(e))return[];let t=await GP(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile())continue;let o=BP(r.name);if(!o)continue;let s=UP(e,r.name),i=await FP(s);n.push({mtime:i.mtime,name:r.name,path:s,size:i.size,type:o})}return Rl(n)}function $l(e,t){let n=e.find((o)=>o.type===t);if(n)return{fallback:!1,file:n};let r=e[0];return r?{fallback:!0,file:r}:null}function El(e,t){if(t<=0)return"";let n=e.endsWith(`
242
239
  `)?e.slice(0,-1):e;if(n==="")return"";return n.split(`
243
240
  `).slice(-t).join(`
244
- `)}function Fe(e){let t=e,n=0;while(t>=as&&n<us.length-1)t/=as,n++;return`${n===0?String(t):t.toFixed(yl)} ${us[n]??"B"}`}import{readFile as wl}from"fs/promises";import{join as $l}from"path";var Qe="unknown";var xe=".runner",vl=/^\uFEFF/;async function Ct(e){try{let t=await wl($l(e,xe),"utf-8"),n=JSON.parse(t.replace(vl,""));return{agentId:Number.isSafeInteger(n.agentId)?n.agentId:void 0,name:typeof n.agentName==="string"?n.agentName:Qe}}catch{return{name:Qe}}}var Rl=/(?:^|\/)github\/([^/]+)\/externals$/;function et(e){return e.match(Rl)?.[1]??null}var fs="actions/runner",Il={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},Hr=["bin"],Or=["externals"],Hl=1,Ol=5000,Ll=50,Nl=5000,Dl=50,Gl="ACTIONS_RUNNER_INPUT_TOKEN",Ml=/^\d+\.\d+\.\d+$/,Fl=/^v/,Ul=ge({token:vr}),jl=ge({tag_name:U()}),Bl={app:$r,gh:"Check the gh login with gh auth status"},Kl={"registration-token":"Mint a runner registration token","remove-token":"Mint a runner removal token"};class Lr{profile;sharedDir;github;sharedPath=null;constructor(e,t,n){this.profile=e;this.sharedDir=t;this.github=n}async download(){let e=Il[this.profile.os],t=await this.getLatestVersion(),n=I(this.sharedDir,"github",t);if(await this.isCompleteDownload(n))return this.sharedPath=n,{path:n,version:t};let r=I(this.sharedDir,"github");await hn(r,{recursive:!0});let o=await kl(I(this.sharedDir,`.github-${t}-`)),i=`actions-runner-${e}-${t}.tar.gz`,s=I(o,i),c=`https://github.com/${fs}/releases/download/v${t}/${i}`;try{if(await Bun.$`curl --fail --silent --show-error --location -o ${s} ${c}`,await Bun.$`tar xzf ${s} -C ${o}`,await ps(s),!await this.isCompleteDownload(o))throw new y(`Runner v${t} archive is incomplete`);await this.publishDownload(o,n,t)}finally{await je(o,{force:!0,recursive:!0})}return this.sharedPath=n,{path:n,version:t}}async create(e){let t=Se(this.profile.jobHooks),n=await this.ensureDownloaded(),r=[];for(let o of e){let i=I(this.profile.directory,o);if(Ue(i))throw new y(`Runner directory already exists: ${i}`,"Remove or recover this runner before creating it again");try{await this.setupRunnerDir(n,i),await this.registerRunner(i,o,t)}catch(s){if(!Ue(I(i,".runner")))await je(i,{force:!0,recursive:!0});throw s}r.push({directory:i,id:o,name:o,status:"registered"})}return r}async remove(e){for(let t of e){let n=I(this.profile.directory,t);if(!Ue(I(n,".runner"))){await this.stop([t]);continue}let r=await this.fetchRemovalToken(n);await this.stop([t]);let o=await Bun.$`bash ./config.sh remove`.cwd(n).env(ms(r)).quiet().nothrow();if(o.exitCode!==0)throw new y(`Failed to deregister runner ${t}`,o.stderr.toString().trim()||"Runner files have been preserved; retry removal")}}async start(e){for(let t of e){let n=I(this.profile.directory,t),r=await this.readPidFile(n);if(r&&this.isProcessRunning(r))continue;let o=Cl("bash",["./run.sh"],{cwd:Ir(n),detached:!0,stdio:"ignore"});if(await Sl(o,"spawn"),o.pid===void 0)throw new y(`Failed to start runner ${t}`);o.unref(),await this.writePidFile(n,o.pid)}}async stop(e){for(let t of e){let n=I(this.profile.directory,t),r=await this.readPidFile(n);if(r&&this.isProcessRunning(r)){try{process.kill(-r,"SIGTERM")}catch(i){if(i.code!=="ESRCH")throw i;try{process.kill(r,"SIGTERM")}catch(s){if(s.code!=="ESRCH")throw s}}let o=Date.now()+Ol;while(this.isProcessRunning(r)){if(Date.now()>=o)throw new y(`Runner ${t} did not stop`,"Wait for its current job to finish and retry");await Bun.sleep(Ll)}}await this.removePidFile(n)}}async list(){let e=this.profile.directory;if(!Ue(e))return[];let t=await cs(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let o=I(e,r.name);n.push(await this.getRunnerStatus(o,r.name))}return n}async currentVersion(e){let t=I(this.profile.directory,e);return this.detectVersion(t)}async logFiles(e){return mn(I(this.profile.directory,e,fn))}async update(e){let t=Se(this.profile.jobHooks),n=await this.ensureDownloaded();for(let r of e){let o=I(this.profile.directory,r);await this.removeRunnerBinaries(o),await this.setupRunnerDir(n,o),await pn(o,t)}}async configureJobHooks(e){let t=Se(this.profile.jobHooks),n=I(this.profile.directory,e);if(!Ue(I(n,".runner")))return{envChanged:!1,scriptsChanged:!1};return pn(n,t)}async getRunnerStatus(e,t){let{agentId:n,name:r}=await Ct(e),o=await this.readPidFile(e),i=o!==null&&this.isProcessRunning(o),s="unknown";if(i)s="running";else if(Ue(I(e,".runner")))s="registered";let c=i?await this.readStartTime(e):void 0;return{agentId:n,directory:e,id:t,name:r,pid:i?o:void 0,startedAt:c,status:s}}async ensureDownloaded(){if(this.sharedPath)return this.sharedPath;let{path:e}=await this.download();return e}async isCompleteDownload(e){try{return(await Promise.all(["bin","externals","config.sh","run.sh"].map((n)=>ds(I(e,n))))).every((n,r)=>r<Hr.length+Or.length?n.isDirectory():n.isFile())}catch(t){if(t.code==="ENOENT")return!1;throw t}}async publishDownload(e,t,n){let r=I(this.sharedDir,`.github-${n}.lock`),o=Date.now()+Nl;while(!0)try{await hn(r);break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()>=o)throw new y(`Runner download is locked: ${r}`,"Retry after other Hydra downloads finish; remove a stale lock only when no download is running");await Bun.sleep(Dl)}try{if(await this.isCompleteDownload(t))return;await je(t,{force:!0,recursive:!0}),await Tl(e,t)}finally{await je(r,{force:!0,recursive:!0})}}async setupRunnerDir(e,t){await hn(t,{recursive:!0});for(let n of Hr)await this.hardLinkDir(I(e,n),I(t,n));for(let n of Or){let r=Ir(e,n),o=I(t,n);if(!Ue(o))await Pl(r,o)}for(let n of["*.sh","*.sh.template"]){let r=await Array.fromAsync(new Bun.Glob(n).scan(e));for(let o of r)await xl(I(e,o),I(t,o))}}async registerRunner(e,t,n){let r=await this.fetchRegistrationToken(),o=["--url",this.profile.url,"--name",t,"--unattended","--disableupdate"];if(this.profile.labels)o.push("--labels",this.profile.labels);if(this.profile.runnerGroup)o.push("--runnergroup",this.profile.runnerGroup);await Bun.$`bash ./config.sh ${o}`.cwd(e).env(ms(r)).quiet(),await pn(e,n)}async fetchRegistrationToken(){return this.fetchRunnerToken(ue(this.profile.url),"registration-token")}async fetchRemovalToken(e){let t=await ls(I(e,".runner"),"utf-8"),r=JSON.parse(this.stripBom(t)).gitHubUrl;if(!r)throw Error("Cannot determine GitHub URL from runner config");return this.fetchRunnerToken(ue(r),"remove-token")}async fetchRunnerToken(e,t){let n=e.kind==="repo"?`repos/${e.owner}/${e.repo}`:`orgs/${e.org}`,{token:r}=await this.callGitHub({idempotent:!0,method:"POST",operation:`${Kl[t]} for ${Pe(e)}`,path:`/${n}/actions/runners/${t}`,schema:Ul},an(this.github.credentials.kind,e));return r}async getLatestVersion(){let{tag_name:e}=await this.callGitHub({operation:"Read the latest runner release",path:`/repos/${fs}/releases/latest`,schema:jl},Bl[this.github.credentials.kind]),t=e.replace(Fl,"");if(!Ml.test(t))throw new y(`The latest runner release has an unexpected tag: ${e}`);return t}async callGitHub(e,t){try{return await this.github.client.request(e)}catch(n){throw n instanceof V?new y(n.message,t):n}}pidFilePath(e){return Ir(e,".pid")}async writePidFile(e,t){await Al(this.pidFilePath(e),String(t))}async readPidFile(e){try{let t=await ls(this.pidFilePath(e),"utf-8"),n=Number(t.trim());return Number.isSafeInteger(n)&&n>Hl?n:null}catch{return null}}async readStartTime(e){try{return(await ds(this.pidFilePath(e))).mtime}catch{return}}async removePidFile(e){try{await ps(this.pidFilePath(e))}catch{}}async hardLinkDir(e,t){await hn(t,{recursive:!0});let n=await cs(e,{withFileTypes:!0});for(let r of n){let o=I(e,r.name),i=I(t,r.name);if(r.isDirectory())await this.hardLinkDir(o,i);else await El(o,i)}}async detectVersion(e){try{let t=await _l(I(e,"externals"));return et(t)}catch{return null}}async removeRunnerBinaries(e){for(let t of Hr)await je(I(e,t),{force:!0,recursive:!0});for(let t of Or)await je(I(e,t),{force:!0});for(let t of["*.sh","*.sh.template"]){let n=await Array.fromAsync(new Bun.Glob(t).scan(e));for(let r of n)await je(I(e,r),{force:!0})}}stripBom(e){return e.replace(/^\uFEFF/,"")}isProcessRunning(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}}function ms(e){return{...process.env,[Gl]:e}}import{existsSync as Nr}from"fs";import{readdir as Dr,readFile as Vl,readlink as Jl,rm as Gr,stat as Wl}from"fs/promises";import{join as Ae}from"path";var ql="_work",zl="externals",Yl=".pid",Xl="github",Zl=["runner","worker"],Ql=24,gs=3600000,hs=10,ed=1,td=Q().map((e)=>Number.isSafeInteger(e)&&e>ed?e:F());function gn(e){return{auto:e?.auto??ii,intervalHours:e?.intervalHours??si,lastRun:e?.lastRun,olderThanDays:e?.olderThanDays??zt,targets:e?.targets??ai}}function nd(e,t){return e-t*Ql*gs}function Mr(e,t){if(!e.lastRun)return!0;let n=Date.parse(e.lastRun);if(Number.isNaN(n))return!0;return t-n>=e.intervalHours*gs}function rd(e,t){let n=Tr(e),r=new Set;for(let o of Zl){let i=n.find((s)=>s.type===o);if(i)r.add(i.path)}return n.filter((o)=>!r.has(o.path)&&o.mtime.getTime()<t)}function od(e){return[...e].sort(dd)[0]??null}function id(e,t){let n=od(e),r=new Set(t);return e.filter((o)=>o!==n&&!r.has(o))}function yn(e){return Object.values(e).reduce((t,n)=>t+n.freedBytes,0)}async function sd(e){let t;try{t=await Vl(Ae(e,Yl),"utf-8")}catch(r){if(r.code==="ENOENT")return!1;throw r}let n;try{n=td(Number(t.trim()))}catch{return!1}try{return process.kill(n,0),!0}catch(r){let o=r.code;if(o==="EPERM")return!0;if(o==="ESRCH")return!1;throw r}}async function Fr(e){if(!Nr(e))return 0;let t=await Dr(e,{withFileTypes:!0}),n=0;for(let r of t){if(r.isSymbolicLink())continue;let o=Ae(e,r.name);if(r.isDirectory()){n+=await Fr(o);continue}if(r.isFile()){let i=await Wl(o);n+=i.size}}return n}async function bn(e){let t=nd(e.now,e.olderThanDays),n={};for(let r of e.targets)switch(r){case"logs":n.logs=await ad(e.entries,t,e.dryRun);break;case"work":n.work=await ud(e.entries,e.dryRun);break;case"shared":n.shared=await cd(e.entries,e.dryRun,e.sharedDir);break}return n}async function ad(e,t,n){let r={freedBytes:0,removed:0,skipped:[]};for(let o of e){let i=await mn(Ae(o.directory,fn));for(let s of rd(i,t)){if(!n)await Gr(s.path,{force:!0});r.removed++,r.freedBytes+=s.size}}return r}async function ud(e,t){let n={freedBytes:0,removed:0,skipped:[]};for(let r of e){if(await sd(r.directory)){n.skipped.push(r.id);continue}let o=Ae(r.directory,ql);if(!Nr(o))continue;let i=await Dr(o);if(i.length===0)continue;if(n.freedBytes+=await Fr(o),n.removed+=i.length,t)continue;for(let s of i)await Gr(Ae(o,s),{force:!0,recursive:!0})}return n}async function cd(e,t,n){let r={freedBytes:0,removed:0,skipped:[]},o=Ae(n,Xl);if(!Nr(o))return r;let s=(await Dr(o,{withFileTypes:!0})).filter((a)=>a.isDirectory()).map((a)=>a.name),c=await ld(e);for(let a of id(s,c)){let u=Ae(o,a);if(r.freedBytes+=await Fr(u),r.removed++,!t)await Gr(u,{force:!0,recursive:!0})}return r}async function ld(e){let t=[];for(let n of e)try{let r=await Jl(Ae(n.directory,zl)),o=et(r);if(o)t.push(o)}catch{}return t}function dd(e,t){let n=e.split(".").map((i)=>Number.parseInt(i,hs)),r=t.split(".").map((i)=>Number.parseInt(i,hs)),o=Math.max(n.length,r.length);for(let i=0;i<o;i++){let s=n[i]??0,c=r[i]??0,a=Number.isNaN(s)?0:s,u=Number.isNaN(c)?0:c;if(a!==u)return u-a}return 0}import{readFile as pd}from"fs/promises";var fd=1e4,md="/etc/resolv.conf",hd=/^\s*nameserver\[\d+\]\s*:\s*(\S+)/gm,gd=/^\s*nameserver\s+(\S+)/gm,yd=/^(?:ip|ipv6)_address:\s*(\S+)/gm,bd=/^(\S+)\s/gm;async function Ur(){let[e,t]=Bun.which("scutil")?[await ys(["scutil","--dns"]),hd]:[await wd(),gd];return ws(bs(e,t))}function jr(){return Bun.which("dscacheutil")!==null||Bun.which("getent")!==null}async function Br(e){let[t,n]=Bun.which("dscacheutil")?[["dscacheutil","-q","host","-a","name",e],yd]:[["getent","hosts",e],bd],r=performance.now(),o=await ys(t);return{addresses:ws(bs(o,n)),durationMs:Math.round(performance.now()-r),host:e}}async function ys(e){let t=Bun.spawn(e,{stderr:"ignore",stdin:"ignore",stdout:"pipe",timeout:fd}),[n]=await Promise.all([new Response(t.stdout).text(),t.exited]);return n}async function wd(){try{return await pd(md,"utf-8")}catch(e){if(e.code==="ENOENT")return"";throw e}}function bs(e,t){return[...e.matchAll(t)].flatMap((n)=>n[1]?[n[1]]:[])}function ws(e){return[...new Set(e)]}function M(e,t){switch(e.provider){case"github":return new Lr(e,Ce(fe(t)).shared,nn(t));default:throw Error(`Runner provider "${e.provider}" is not yet implemented`)}}var vs=0,$d={logs:"file(s)",shared:"version(s)",work:"item(s)"},$s=L({days:{alias:"d",default:vs,description:"Override log retention",displayDefault:`config or ${zt} days`,type:"number"},dryRun:{alias:"n",default:!1,description:"Preview cleanup without deleting",type:"boolean"},logs:{alias:"l",default:!1,description:"Remove old diagnostic logs",type:"boolean"},shared:{alias:"s",default:!1,description:"Remove unused runner versions",type:"boolean"},work:{alias:"w",default:!1,description:"Clear stopped runners' workspaces",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip workspace confirmation",type:"boolean"}});class wn extends x{name="cleanup";description="Remove logs, workspaces, and old runner versions";args=$s;async execute(e){T(e.args,$s,"Run 'hydra cleanup --help' for supported options");let t=e.config.get("profiles");if(Object.keys(t).length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let n=gn(e.config.get("cleanup")),r=this.explicitTargets(e),o=r.length>0?r:n.targets,i=e.args.days>vs?e.args.days:n.olderThanDays;if(o.includes("work")&&!e.args.dryRun&&!e.args.yes){if(!await pe({message:"Delete _work contents (checkouts and caches) of stopped runners?"}))o=o.filter((a)=>a!=="work")}let s=await bn({dryRun:e.args.dryRun,entries:e.config.get("runners")??[],now:Date.now(),olderThanDays:i,sharedDir:Ce(fe(e.config)).shared,targets:o});if(this.printReport(s,e.args.dryRun),e.args.dryRun)return;e.config.set("cleanup",{...e.config.get("cleanup"),lastRun:new Date().toISOString()})}explicitTargets(e){let t=[];if(e.args.logs)t.push("logs");if(e.args.work)t.push("work");if(e.args.shared)t.push("shared");return t}printReport(e,t){let n=[];for(let[i,s]of Object.entries(e)){if(!s)continue;let c=$d[i],a=Fe(s.freedBytes),u=t?`would remove ${s.removed} ${c}, ${a}`:`removed ${s.removed} ${c}, freed ${a}`;if(n.push(`${l.bold(i)}: ${s.removed>0?u:l.dim("nothing to do")}`),s.skipped.length>0)n.push(l.dim(` skipped running runner(s): ${s.skipped.join(", ")}`))}if(n.length===0){b.info(l.dim("Nothing to clean."));return}let r=yn(e),o=t?"Would free":"Freed";n.push(l.dim(`${o} ${Fe(r)} total`)),b.info(n.join(`
245
- `))}}async function $n(e){try{let t=gn(e.config.get("cleanup"));if(!t.auto)return;if(!Mr(t,Date.now()))return;let n=await bn({dryRun:!1,entries:e.config.get("runners")??[],now:Date.now(),olderThanDays:t.olderThanDays,sharedDir:Ce(fe(e.config)).shared,targets:t.targets});e.config.set("cleanup",{...e.config.get("cleanup"),lastRun:new Date().toISOString()});let r=yn(n);if(r>0)b.info(l.dim(`Auto cleanup freed ${Fe(r)}`))}catch(t){let n=t instanceof Error?t.message:String(t);b.warn(l.yellow(`Auto cleanup failed: ${n}`))}}import{existsSync as Cs}from"fs";import{join as Ss}from"path";var Rs="Runner count must be a positive safe integer",Kr=Q().map((e)=>Number.isSafeInteger(e)&&e>0?e:F());function Be(e){try{return Kr(typeof e==="string"?Number(e):e)}catch{throw new y(Rs)}}function vn(e){try{Be(e);return}catch{return Rs}}function tt(e,t){if(e.length===0)return t;for(let n of e)if(!t.includes(n))throw new y(`Runner "${n}" not found`);return e}function q(e,t){let n=e.get("profiles");if(Object.keys(n).length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let r=t??e.get("defaultProfile")??$t,o=Object.hasOwn(n,r)?n[r]:void 0;if(!o)throw new y(`Profile "${r}" not found`);return{name:r,profile:o}}async function ce(e){let t=e.get("profiles"),n=Object.keys(t);if(n.length===0)throw new y("No profiles configured","Run hydra init to set up a profile");if(n.length===1)return n[0];return De({message:"Select profile",options:n.map((r)=>({label:r,value:r,hint:t[r]?.url}))})}var vd=B({profile:{description:"Profile to use"},count:{description:"Runner count override"}});class Rn extends x{name="create";description="Download and register runners";positionals=vd;async execute(e){T(e.args,this.args,"Run 'hydra create --help' for supported options");let{name:t,profile:n}=e.interactive?q(e.config,await ce(e.config)):q(e.config,e.positionals.profile),r=e.interactive?await this.promptCount(n.numberOfMachines):Be(e.positionals.count??n.numberOfMachines),o=e.config.get("runners")??[],i=o.filter((f)=>f.profile===t),s=r-i.length;if(s<=0){b.warn(`Already have ${i.length} runner(s) for profile "${t}". Nothing to create.`);return}let c=M(n,e.config),a=Z();a.start("Downloading runner binary...");let{version:u}=await c.download();a.stop(`Runner v${u} ready`);let d=new Set(o.map((f)=>f.id)),p=1;for(let f=0;f<s;){let w=`${n.name}-${p++}`;if(d.has(w))continue;f++;let v={createdAt:new Date().toISOString(),directory:Ss(n.directory,w),id:w,name:w,profile:t,provider:n.provider,url:n.url},C=Cs(v.directory);a.start(`Registering ${w}...`);try{await c.create([w])}finally{if(!C&&Cs(Ss(v.directory,xe))){let{agentId:R}=await Ct(v.directory);o.push(R===void 0?v:{...v,agentId:R}),e.config.set("runners",o)}}a.stop(`${l.green("+")} ${w}`)}let h=t===e.config.get("defaultProfile")?"":` ${t}`;b.info(`${l.green("Created")} ${s} runner(s) for "${t}". Run ${l.green(`hydra start${h}`)} to start them.`)}async promptCount(e){let t=await ve({initialValue:String(e),message:"Number of runners to create",validate:vn});return Be(t)}}import{isAbsolute as Rd}from"path";var nt=U().map((e)=>e.trim().length>0?e:F()),Cd=wt(["osx","linux","windows"]),xs=wt(["github","gitlab"]),Sd=Wt(wt(["logs","work","shared"])),xd=wt(["app","gh"]),Vr=Q().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),Ed=U().map((e)=>Rd(e)?e:F()),kd={app:["mode","appId","installationId","privateKeyPath"],gh:["mode"]};function Es(e){return new fr(Ce(e).config,oi,{parse:(t)=>_d(t,e),strict:!0})}function Cn(e){if(!e.failure)return;return new y(e.failure.message,`Repair ${e.path} or select another home with ${j}; hydra doctor lists the homes it finds`)}function _d(e,t){let n=Ke(e,"the config");X(n.defaultProfile,U(),"defaultProfile","a string"),Ad(n.cleanup),Id(n.credentials);let r=Object.fromEntries(Object.entries(Ke(n.profiles,"profiles")).map(([i,s])=>[i,Td(s,`profiles.${i}`,t)])),o=n.runners===void 0?void 0:Pd(n.runners,t);return{...e,profiles:r,...o?{runners:o}:{}}}function Td(e,t,n){let r=Ke(e,t);if(le(r.url,nt,`${t}.url`,"a URL"),le(r.name,nt,`${t}.name`,"a runner name prefix"),le(r.directory,nt,`${t}.directory`,"a directory"),le(r.os,Cd,`${t}.os`,"osx, linux or windows"),le(r.provider,xs,`${t}.provider`,"github or gitlab"),X(r.labels,U(),`${t}.labels`,"a comma-separated string"),X(r.runnerGroup,U(),`${t}.runnerGroup`,"a string"),X(r.numberOfMachines,Kr,`${t}.numberOfMachines`,"a positive safe integer"),X(r.overwrite,te(),`${t}.overwrite`,"a boolean"),X(r.run,te(),`${t}.run`,"a boolean"),r.jobHooks!==void 0)Ke(r.jobHooks,`${t}.jobHooks`);let o=e;return{...o,directory:br(n,o.directory)}}function Pd(e,t){if(!Array.isArray(e))throw Error("runners must be a list");return e.map((n,r)=>{let o=`runners[${r}]`,i=Ke(n,o);le(i.id,nt,`${o}.id`,"a runner id"),le(i.profile,nt,`${o}.profile`,"a profile name"),le(i.directory,nt,`${o}.directory`,"a directory");for(let c of["name","url","createdAt"])X(i[c],U(),`${o}.${c}`,"a string");X(i.provider,xs,`${o}.provider`,"github or gitlab"),X(i.agentId,Vr,`${o}.agentId`,"a positive GitHub runner id");let s=n;return{...s,directory:br(t,s.directory)}})}function Ad(e){if(e===void 0)return;let t=Ke(e,"cleanup");X(t.auto,te(),"cleanup.auto","a boolean"),X(t.intervalHours,Q(),"cleanup.intervalHours","a number of hours"),X(t.olderThanDays,Q(),"cleanup.olderThanDays","a number of days"),X(t.targets,Sd,"cleanup.targets","a list of logs, work and shared"),X(t.lastRun,U(),"cleanup.lastRun","a timestamp")}function Id(e){if(e===void 0)return;let t=Ke(e,"credentials");le(t.mode,xd,"credentials.mode","app or gh");let n=t.mode,r=Object.keys(t).find((o)=>!kd[n].includes(o));if(r)throw Error(`credentials.${r} is not a setting of the ${n} mode`);if(n==="gh")return;le(t.appId,Vr,"credentials.appId","a GitHub App id"),le(t.installationId,Vr,"credentials.installationId","an installation id"),le(t.privateKeyPath,Ed,"credentials.privateKeyPath","an absolute path")}function Ke(e,t){if(typeof e==="object"&&e!==null&&!Array.isArray(e))return e;throw Error(`${t} must be an object`)}function le(e,t,n,r){if(e===void 0)throw Error(`${n} is missing; expected ${r}`);X(e,t,n,r)}function X(e,t,n,r){if(e===void 0)return;try{t(e)}catch{throw Error(`${n} must be ${r}`)}}var Hd={configured:{paint:l.green,text:"configured"},foreign:{paint:l.yellow,text:"set to another script"},missing:{paint:l.yellow,text:"missing"},off:{paint:l.dim,text:"off"},outdated:{paint:l.yellow,text:"outdated"}},ks=new Set(["missing","outdated"]);class Sn extends x{name="doctor";description="Check DNS and each runner's job hooks";async execute(e){T(e.args,this.args,"Run 'hydra doctor --help' for supported options");let t=fe(e.config),n=Qt(t,process.cwd(),process.env),r=Cn(e.config),o=r?[]:await this.credentialLines(e.config.get("credentials"));if(b.info([...this.homeLines(t,n),...o].join(`
246
- `)),r)throw r;let i=e.config.get("profiles");if(Object.keys(i).length===0)throw new y("No profiles configured",n.length>0?`Run hydra init, or pass ${j} with one of the homes above`:"Run hydra init to set up a profile");let s=e.config.get("runners")??[],c=await Ur(),a=[`${l.bold("DNS servers")} ${c.length>0?c.join(", "):l.dim("unknown")}`],u=!1,d=!1;for(let[p,m]of Object.entries(i)){let h=Se(m.jobHooks);a.push("",`${l.bold(p)} ${l.dim(m.url)}`),a.push(...await this.dnsLines(h.dns)),a.push(this.cleanupLine(h));let f=await this.runnerLines(e.config,m,h,s.filter((w)=>w.profile===p));a.push(...f.lines),u||=f.needsUpdate,d||=f.needsRestart}if(u)a.push("",l.yellow(`Run ${l.green("hydra update")} to write the missing hooks.`));if(d)a.push("",l.yellow('Restart runners marked "restart" once they are idle: hydra stop <profile> && hydra start <profile>'));b.info(a.join(`
247
- `))}homeLines(e,t){let n=[`${l.bold("Home")} ${e}`];if(t.length===0)return n;n.push(l.yellow("Other Hydra homes, not used by this run:"));for(let r of t){let o=r.counts?`${_s(r.counts.profiles,"profile")}, ${_s(r.counts.runners,"runner")}`:"unreadable config";n.push(` ${r.path} ${l.dim(o)}`)}return n.push(l.dim(` Manage one with ${j} <path> or ${ae}=<path>`)),n}async dnsLines(e){let t=[` DNS wait: ${e.enabled?`on, up to ${e.timeoutSeconds} s`:l.dim("off")}`];if(!jr())return[...t,l.yellow(" No dscacheutil or getent to look hosts up with")];for(let n of e.hosts){let r=await Br(n);t.push(r.addresses.length>0?` ${l.green("\u2713")} ${n} ${l.dim(`${r.durationMs} ms \xB7 ${r.addresses.join(", ")}`)}`:` ${l.red("\u2717")} ${n} ${l.red(`no address after ${r.durationMs} ms`)}`)}return t}cleanupLine(e){let{enabled:t,keepToolCache:n}=e.workspaceCleanup;return` Workspace cleanup: ${t?`on, ${n?"keeps _tool":"empties _tool"}`:l.dim("off")}`}async credentialLines(e){let t=[`${l.bold("GitHub credentials")} ${Ni(e)}`,...this.apiRootLines()];if(e?.mode!=="app")return t;let n=await Di(e.privateKeyPath);return n?[...t,l.yellow(` The private key ${n}`)]:t}apiRootLines(){if(!process.env[Xe])return[];try{let e=l.dim(`(from ${Xe}; Hydra sends its tokens there)`);return[`${l.bold("GitHub API")} ${tn(process.env)} ${e}`]}catch(e){if(!(e instanceof y))throw e;return[l.yellow(` ${e.message}`),...e.hint?[l.dim(` ${e.hint}`)]:[]]}}async runnerLines(e,t,n,r){if(r.length===0)return{lines:[l.dim(" No runners.")],needsRestart:!1,needsUpdate:!1};let o=new Map((await M(t,e).list()).map((u)=>[u.id,u])),i=[...r].sort((u,d)=>u.id.localeCompare(d.id,void 0,{numeric:!0})),s=[],c=!1,a=!1;for(let u of i){let d=o.get(u.id),{envModifiedAt:p,states:m}=await _r(u.directory,n),h=this.loadedBefore(d,p);c||=h,a||=ks.has(m.started)||ks.has(m.completed),s.push([` ${u.id}`,l.dim(d?.status??"unknown"),`DNS wait ${this.stateLabel(m.started)}`,`cleanup ${this.stateLabel(m.completed)}`,h?l.yellow("restart"):""].filter(Boolean).join(" "))}return{lines:s,needsRestart:c,needsUpdate:a}}stateLabel(e){let{paint:t,text:n}=Hd[e];return t(n)}loadedBefore(e,t){if(e?.status!=="running"||!e.startedAt||!t)return!1;return t>e.startedAt}}function _s(e,t){return`${e} ${t}${e===1?"":"s"}`}import{mkdir as Jr}from"fs/promises";var Ts=1,Od=448,Ld=B({url:{description:"GitHub repository or organization URL"}}),Nd=L({force:{alias:"f",default:!1,description:"Overwrite an existing profile",type:"boolean"},labels:{alias:"l",description:"Set comma-separated runner labels",type:"string"},name:{alias:"n",description:"Set the runner name prefix",type:"string"},profile:{alias:"p",description:"Set the profile name",type:"string"},runners:{alias:"c",description:"Set the runner count",type:"number"}});class xn extends x{name="init";description="Set up a runner profile";positionals=Ld;args=Nd;prompts=!0;async execute(e){T(e.args,this.args,"Run 'hydra init --help' for supported options");let t=e.interactive?await this.promptProfileName(e):e.args.profile??$t,n=!e.config.exists();if(!n&&Object.hasOwn(e.config.get("profiles"),t)&&!e.args.force){if(!e.interactive)throw new y(`Profile "${t}" already exists. Use --force to overwrite.`);if(!await pe({initialValue:!1,message:`Profile "${t}" already exists. Overwrite?`}))return}let o=Ce(fe(e.config)),i=e.interactive?await this.runInitForm(o.runners):this.buildProfileFromArgs(e,o.runners);await this.ensureDirectories(o);let s={...n?{}:e.config.get("profiles"),[t]:i};if(e.config.set("profiles",s),!e.config.get("defaultProfile"))e.config.set("defaultProfile",t);We([`${l.dim("Profile:")} ${t}`,`${l.dim("URL:")} ${i.url}`,`${l.dim("Runners:")} ${i.numberOfMachines}`,`${l.dim("Name:")} ${i.name}`,i.labels?`${l.dim("Labels:")} ${i.labels}`:"","",`Run ${l.green(`${qt} create${t!==e.config.get("defaultProfile")?` ${t}`:""}`)} to provision runners.`].filter(Boolean).join(`
248
- `),l.green(n?"Hydra initialized":`Profile "${t}" added`))}async promptProfileName(e){return ve({initialValue:e.args.profile??$t,message:"Profile name"})}async ensureDirectories(e){await Jr(e.home,{mode:Od,recursive:!0}),await Jr(e.shared,{recursive:!0}),await Jr(e.runners,{recursive:!0})}async runInitForm(e){let t=await Lt({url:()=>ve({message:"GitHub repository or organization URL",placeholder:"https://github.com/owner/repo",validate:(n)=>{if(!n)return"URL is required";try{ue(n)}catch{return"Must be a GitHub repository or organization URL (https://github.com/<owner>/<repo> or https://github.com/<org>)"}return}}),name:()=>ve({initialValue:"runner",message:"Base name for runners",placeholder:"runner"}),runners:()=>ve({initialValue:String(Ts),message:"Number of runners",placeholder:"1",validate:vn}),labels:()=>ve({message:"Additional labels (comma-separated, optional)",placeholder:"self-hosted,macOS,ARM64"})},{onCancel:()=>{throw new de}});return{directory:e,jobHooks:dn(),labels:t.labels||void 0,name:t.name,numberOfMachines:Be(t.runners),os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:t.url}}buildProfileFromArgs(e,t){if(!e.positionals.url)throw new y("URL is required","Usage: hydra init <url>");return this.validateUrl(e.positionals.url),{directory:t,jobHooks:dn(),labels:e.args.labels,name:e.args.name??"runner",numberOfMachines:Be(e.args.runners??Ts),os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:e.positionals.url}}validateUrl(e){try{ue(e)}catch(t){throw new y(t instanceof Error?t.message:`Invalid GitHub URL: ${e}`,"Expected https://github.com/<owner>/<repo> or https://github.com/<org>")}}detectOs(){let e=process.platform;if(e==="darwin")return"osx";if(e==="win32")return"windows";return"linux"}}import{existsSync as Fd}from"fs";import{join as Ud}from"path";var Dd=/[.*+?^${}()|[\]\\]/g,Gd="-[1-9][0-9]*",Md=["unrecorded","online","busy","foreign","local","elsewhere"];function Os({elsewhere:e,elsewhereUnreadable:t,github:n,local:r,prefixes:o}){let i=o.map((h)=>new RegExp(`^${h.replace(Dd,"\\$&")}${Gd}$`)),s=r.filter((h)=>!h.orphaned),c=r.filter((h)=>h.orphaned),a=Hs(s),u=Hs(r),d=new Set([...e].map(St)),p=new Set,m=[];for(let h of n){let f=St(h.name),w=Is(h,s,p);if(w){p.add(w),m.push({github:h,local:w,placement:"both"});continue}let v={elsewhere:d.has(f),foreign:!i.some((P)=>P.test(h.name))},C=Is(h,c,p);if(!C){let P=As({...v,local:u.has(f),unrecorded:!0});m.push({github:h,keep:P,placement:"github"});continue}p.add(C);let R=As({...v,busy:h.busy,local:a.has(f),online:!on(h)});m.push({github:h,keep:R.length===0&&t?["unreadable"]:R,local:C,placement:"recorded"})}for(let h of r)if(!p.has(h))m.push({local:h,placement:"local"});return m.sort((h,f)=>Ps(h).localeCompare(Ps(f),void 0,{numeric:!0}))}function Ie(e){return e.placement==="recorded"&&e.keep.length===0}function Ls(e){return e.placement==="recorded"&&e.keep.includes("unreadable")}function Ps(e){return e.placement==="github"?e.github.name:e.local.name}function As(e){return Md.filter((t)=>e[t])}function Is(e,t,n){let r=t.filter((o)=>!n.has(o));return r.find((o)=>o.agentId===e.id)??r.find((o)=>o.agentId===void 0&&o.names.some((i)=>St(i)===St(e.name)))}function Hs(e){return new Set(e.flatMap((t)=>t.names.map(St)))}function St(e){return e.toLowerCase()}var jd=new Set([401,403,404]),Bd="Nothing was changed; retry once GitHub answers",Kd="Registrations reported as deleted stay deleted; run hydra reconcile again to finish";function rt(e){return nn(e)}async function En(e,t){let n=await Vd(e),r=qd(e),o=[];for(let i of n){let s=await ne(t,i.target,Bd,()=>sn(t.client,i.target)),c=Os({elsewhere:r.names,elsewhereUnreadable:r.unreadable.length>0,github:s,local:i.local,prefixes:i.prefixes});o.push({...i,rows:c})}return{scopes:o,unreadableHomes:r.unreadable}}async function kn(e,t,n,r=Kd){return ne(e,t,r,async()=>{let o=await Ze(e.client,t,n.id);if(!o)return"gone";if(o.name!==n.name)return"renamed";if(!on(o)||o.busy)return"changed";return Ui(e.client,t,n.id)})}function Ds(e){return Fd(Ud(e.directory,xe))}async function Vd(e){let t=e.get("runners")??[],n=new Map;for(let[r,o]of Object.entries(e.get("profiles"))){if(o.provider!=="github")continue;let i=Wr(r,o.url),s=ot(i),c=n.get(s)??{key:s,local:[],prefixes:[],target:i};n.set(s,c),c.prefixes.push(o.name);let a=await M(o,e).list(),u=t.filter((d)=>d.profile===r);c.local.push(...Jd(u,a))}return[...n.values()]}function Jd(e,t){let n=new Map(t.map((o)=>[o.id,o]));return[...e.map((o)=>{let i=n.get(o.id);return n.delete(o.id),Ns(o.id,o.directory,i,o)}),...[...n.values()].map((o)=>Ns(o.id,o.directory,o,void 0))]}function Ns(e,t,n,r){let o=n?Wd(n):void 0,i=n?.status??"unknown",s=[...new Set([o,r?.name,e].filter((c)=>Boolean(c)))];return{agentId:n?.agentId??r?.agentId,directory:t,id:e,name:o??r?.name??e,names:s,orphaned:r!==void 0&&i==="unknown",status:i}}function Wd(e){return e.name===Qe?void 0:e.name}function qd(e){let t=new Set,n=[];for(let r of Qt(fe(e),process.cwd(),process.env)){let o=vi(r.path);if(!o)n.push(r.path);for(let i of o??[])t.add(i)}return{names:t,unreadable:n}}function Wr(e,t){try{return ue(t)}catch(n){throw new y(`profiles.${e}.url: ${n.message}`,"Use a github.com repository or organisation URL")}}function ot(e){return(e.kind==="repo"?`repo:${e.owner}/${e.repo}`:`org:${e.org}`).toLowerCase()}async function ne(e,t,n,r){try{return await r()}catch(o){if(!(o instanceof V))throw o;let i=o.status!==void 0&&jd.has(o.status);throw new y(o.message,i?an(e.credentials.kind,t):n)}}var Gs="hydra-drain",Ms="Nothing was changed; retry once GitHub answers",zd="Drained runners move only into a group no repository can use; name another one with --group";async function _n(e,t,n){return ne(e,t,Ms,async()=>{let r=await Vi(e.client,t.org,n);if(!r)return;await Us(e,t,r);let o=await qi(e.client,t.org,r);return{group:r,members:new Map(o.map((i)=>[i.id,i]))}})}async function Fs(e,t,n){let r=await _n(e,t,n);if(r)return r;return ne(e,t,Ms,async()=>{let o=await Ji(e.client,t.org,n);return await Us(e,t,o),{group:o,members:new Map}})}async function Us(e,t,n){let r=Yi(n,await Wi(e.client,t.org,n));if(r)throw new y(`The runner group ${n.name} of ${t.org} is not closed: ${r}`,zd)}function Ve(e){return e.kind==="org"?e:void 0}async function it(e,t,n){let r=new Map;for(let o of t){let i=Ve(o.target),s=i?await _n(e,i,n):void 0;if(s)r.set(o.key,s)}return r}function xt(e,t){return t.github!==void 0&&t.scope!==void 0?e.get(t.scope.key)?.members.has(t.github.id)??!1:!1}var He=L({dryRun:{alias:"n",default:!1,description:"List what would change, change nothing",type:"boolean"},yes:{alias:"y",default:!1,description:"Go ahead without a confirmation prompt",type:"boolean"}}),st=L({group:{default:Gs,description:"Runner group that drained runners move into; no repository may use it",type:"string"}});function Oe(e){if(e.dryRun&&e.yes)throw new y("Pass either --dry-run or --yes, not both")}async function Le(e,t){if(e.yes)return!0;if(!process.stdout.isTTY)throw new y("This step requires confirmation","Pass --yes to go ahead, or --dry-run to only list what it would do");return pe({initialValue:!1,message:t})}function re(e){let t="worker"in e&&e.worker?", running a job":"";switch(e.kind){case"stopped":return"stopped";case"running":return`running, pid ${e.pid}${t}`;case"stale":return`stale .pid: pid ${e.pid} runs no runner from its directory`;case"unproven":return`running outside Hydra's record, pid ${e.pids.join(", ")}${t}`}}function at(e){switch(e.kind){case"stale":return`delete its .pid file once you have checked that pid ${e.pid} is not this runner`;case"unproven":return"Hydra signals only a process group it can prove, so stop those processes by hand";case"running":case"stopped":return"run hydra legacy stop first"}}function Yd(e){let t=e.registration&&!e.registration.disableUpdate?", updates itself":"";return`${Zd(e.layout)}${t}`}function Xd(e,t){if(!e.scope)return"no GitHub profile";if(!e.github)return e.registration?.agentId===void 0?"no runner id":"not on GitHub";let{busy:n,id:r,status:o}=e.github;return`${o}, ${n?"busy":"idle"} \xB7 id ${r}${t?" \xB7 drained":""}`}function js(e,t){let n=` ${e.name} ${[re(e.process),Xd(e,t),Yd(e)].join(" \xB7 ")}`;return e.refusal?`${n} \xB7 ${l.dim(`left alone: ${e.refusal}`)}`:n}function ee(e,t){return` ${l.dim("leave")} ${e.name} \xB7 ${t}`}function me(e,t,n=""){return` ${e} ${t.name}${n?` \xB7 ${n}`:""}`}function Zd(e){switch(e.kind){case"shared":return`shared ${e.version}`;case"self-updated":return`self-updated ${e.version}`;case"copied":return"own copy of the runner";case"missing":return"no runner binaries";case"unknown":return"unrecognised externals link"}}import{lstat as bp,readdir as wp}from"fs/promises";import{basename as $p,dirname as vp,join as Rp,resolve as An}from"path";import{readdir as Qd,readFile as ep,readlink as tp}from"fs/promises";import{join as Bs}from"path";var np="externals",rp=/(?:^|\/)externals\.(\d+\.\d+\.\d+)$/,op=/^(?:bin|externals)\.\d+\.\d+\.\d+$/,ip=/^[\w.-]+\.sh(?:\.template)?$/,sp=/^\uFEFF/,ap=new Set([".DS_Store",".credentials",".credentials_migrated",".credentials_rsaparams",".env",".path",".pid",".runner",".runner_migrated","_diag","_update","_work","bin","externals","hydra-hooks"]);async function Ks(e){try{let t=await tp(Bs(e,np)),n=et(t);if(n)return{kind:"shared",version:n};let r=t.match(rp)?.[1];return r?{kind:"self-updated",version:r}:{kind:"unknown"}}catch(t){return t.code==="EINVAL"?{kind:"copied"}:{kind:"missing"}}}async function Vs(e){let t;try{t=JSON.parse((await ep(Bs(e,".runner"),"utf-8")).replace(sp,""))}catch{return}if(typeof t!=="object"||t===null)return;let{agentId:n,agentName:r,disableUpdate:o,gitHubUrl:i}=t;return{agentId:Number.isSafeInteger(n)&&n>0?n:void 0,agentName:typeof r==="string"&&r?r:void 0,disableUpdate:o===!0,gitHubUrl:typeof i==="string"?i:void 0}}async function qr(e){return(await Qd(e)).filter((n)=>!Ws(n)).sort()}function Js(e){return e.filter(Ws)}function Ws(e){return ap.has(e)||op.test(e)||ip.test(e)}import{realpathSync as up}from"fs";import{readFile as cp,unlink as lp}from"fs/promises";import{join as zs}from"path";var Ys=".pid",dp=1,pp=30000,fp=200,mp=/^\s*(\d+)\s+(\d+)\s+(.*)$/,hp=/[.*+?^${}()|[\]\\]/g,qs="Listener";async function Tn(){let e=await Bun.$`ps -A -o pid= -o pgid= -o command=`.quiet().nothrow();if(e.exitCode!==0)throw new y("Cannot list the host's processes with ps",e.stderr.toString().trim()||"Nothing was changed");return e.stdout.toString().split(`
249
- `).flatMap((t)=>{let n=t.match(mp);return n?[{command:n[3],pgid:Number(n[2]),pid:Number(n[1])}]:[]})}async function zr(e){try{let t=Number((await cp(zs(e,Ys),"utf-8")).trim());return Number.isSafeInteger(t)&&t>dp?t:void 0}catch{return}}function Pn(e,t,n){let r=gp(e),o=n.flatMap((u)=>{let d=u.command.match(r)?.[1];return d?[{...u,role:d}]:[]}),i=o.some((u)=>u.role!==qs),s=t!==void 0&&n.some((u)=>u.pid===t);if(o.length===0)return s&&t!==void 0?{kind:"stale",pid:t}:{kind:"stopped"};if(s&&o.some((u)=>u.role===qs)&&o.every((u)=>u.pgid===t)&&t!==void 0)return{kind:"running",pid:t,worker:i};return{kind:"unproven",pids:[...new Set([...s&&t!==void 0?[t]:[],...o.map(({pid:u})=>u)])],worker:i}}async function Xs(e,t){try{process.kill(-t,"SIGTERM")}catch(r){if(r.code!=="ESRCH")throw r}let n=Date.now()+pp;while(Date.now()<n){if(Pn(e,t,await Tn()).kind==="stopped")return await lp(zs(e,Ys)).catch(()=>{return}),"stopped";await Bun.sleep(fp)}return"timeout"}function gp(e){let t=[...new Set([e,yp(e)])].map((n)=>n.replace(hp,"\\$&"));return new RegExp(`(?:^|\\s)(?:${t.join("|")})/bin(?:\\.[^/\\s]+)?/Runner\\.(Listener|Worker)(?:\\s|$)`)}function yp(e){try{return up(e)}catch{return e}}var Cp="Nothing was changed; retry once GitHub answers",Zs="config.json does not record it",Qs="its directory is missing";async function Sp(e,t){let n=e.get("profiles"),r=new Map;for(let[a,u]of Object.entries(n)){if(u.provider!=="github")continue;let d=Wr(a,u.url);r.set(ot(d),{key:ot(d),registered:new Map,target:d})}for(let a of r.values()){let u=await ne(t,a.target,Cp,()=>sn(t.client,a.target));for(let d of u)a.registered.set(d.id,d)}let o=await Tn(),i=[],s=new Set;for(let a of e.get("runners")??[]){s.add(An(a.directory));let u=Object.hasOwn(n,a.profile)?n[a.profile]:void 0;i.push(await xp(a,u,r,o))}let c=new Set(Object.values(n).filter((a)=>a.provider==="github").map((a)=>An(a.directory)));for(let a of c)for(let u of await Tp(a)){if(s.has(u))continue;s.add(u),i.push(await Ep(u,r,o))}return{runners:i,scopes:[...r.values()]}}function ye(e){return e.refusal===void 0&&e.entry!==void 0&&e.scope!==void 0}function ea(e){return e.refusal===Qs&&e.entry!==void 0&&e.scope!==void 0&&e.process.kind==="stopped"}function ta(e){let{agentId:t,id:n,name:r}=e.entry;return[...e.scope.registered.values()].find((o)=>t===void 0?[n,r].some((i)=>typeof i==="string"&&Yr(i,o.name)):o.id===t)}async function Je(e){return Pn(e.directory,await zr(e.directory),await Tn())}async function xp(e,t,n,r){let o=await na(An(e.directory),r),i=t?.provider==="github"?n.get(ot(ue(t.url))):void 0,s=o.registration?.agentId===void 0?void 0:i?.registered.get(o.registration.agentId),c={...o,entry:e,github:s,name:e.id,profile:e.profile,scope:i};return{...c,refusal:await kp(c,t)}}async function Ep(e,t,n){let r=await na(e,n),o=_p(r.registration,t),i=r.registration?.agentId,s=i===void 0?void 0:o?.registered.get(i),c=r.registration?.agentName??$p(e);return{...r,github:s,name:c,refusal:Zs,scope:o}}async function na(e,t){let n=await zr(e);return{directory:e,layout:await Ks(e),pid:n,process:Pn(e,n,t),registration:await Vs(e)}}async function kp(e,t){let{directory:n,entry:r,github:o,registration:i,scope:s}=e;if(!r)return Zs;if(!t)return`its profile ${r.profile} is not in config.json`;if(t.provider!=="github"||!s)return"its profile does not use GitHub";if(vp(n)!==An(t.directory))return"its directory is not in its profile's directory";let c=await Xr(n);if(c==="missing")return Qs;if(c!=="directory")return"its directory is a symbolic link or not a directory";if(!i)return"it has no readable .runner file";if(i.agentId===void 0||i.agentName===void 0)return"its .runner file records no runner id or name";if(![r.id,r.name].filter((u)=>typeof u==="string").some((u)=>Yr(u,i.agentName)))return`it is registered as ${i.agentName}, not as ${r.id}`;if(ra(i)!==s.key)return"its .runner file names another organisation or repository";if(o&&!Yr(o.name,i.agentName))return`GitHub lists runner ${o.id} as ${o.name}`;return}function _p(e,t){let n=ra(e);return n===void 0?void 0:t.get(n)}function ra(e){if(!e?.gitHubUrl)return;try{return ot(ue(e.gitHubUrl))}catch{return}}async function Tp(e){try{return(await wp(e,{withFileTypes:!0})).filter((n)=>n.isDirectory()).map((n)=>Rp(e,n.name))}catch{return[]}}async function Xr(e){try{return(await bp(e)).isDirectory()?"directory":"other"}catch(t){return t.code==="ENOENT"?"missing":"other"}}function Yr(e,t){return e.toLowerCase()===t.toLowerCase()}async function be(e){if(Object.keys(e.get("profiles")).length===0)throw new y("No profiles configured",`Select the 0.x fleet's home with ${j} <path> or ${ae}`);let t=rt(e);return{github:t,inventory:await Sp(e,t)}}var Pp={busy:"busy",elsewhere:"recorded in another Hydra home",foreign:"name not managed here",local:"name used by a runner in this home",unreadable:"another Hydra home cannot be read",unrecorded:"not recorded in this home"},ia="recorded, no runner here";function Zr(e){return`${l.bold(Pe(e.target))} ${l.dim("on GitHub")}`}function In(e){return`${e.status}, ${e.busy?"busy":"idle"}`}function Qr(e){return e.keep.map((t)=>t==="online"?e.github.status:Pp[t]).join(", ")}function sa(e){let t=[Zr(e)];if(e.rows.length===0)return[...t,l.dim(" No runners here or on GitHub.")];for(let n of e.rows)t.push(` ${Ap(n)}`);return t.push(l.dim(` ${Hp(e.rows)}`)),t}function Ap(e){switch(e.placement){case"both":return`${e.local.name} ${e.local.status} \xB7 ${In(e.github)} \xB7 id ${e.github.id}`;case"local":return`${e.local.name} ${Ip(e.local)} \xB7 ${l.yellow("not on GitHub")}`;case"recorded":return`${e.local.name} ${ia} \xB7 ${oa(e)}`;case"github":return`${e.github.name} not in this home \xB7 ${oa(e)}`}}function Ip(e){return e.orphaned?ia:e.status}function oa(e){let t=Ie(e)?l.yellow("stale"):l.dim(`left alone: ${Qr(e)}`);return`${In(e.github)} \xB7 id ${e.github.id} \xB7 ${t}`}function Hp(e){let t=(c)=>e.filter((a)=>a.placement===c).length,n=t("both"),r=t("local"),o=t("recorded"),i=t("github"),s=e.filter(Ie).length;return[`${n+o+i} on GitHub, ${n+o+r} in this home:`,`${n} in both, ${o} recorded without a runner, ${r} only here, ${i} only on GitHub, ${s} stale`].join(" ")}var aa=L({...He}),Op="Registrations reported as deleted stay deleted; run hydra legacy deregister again to finish",Lp={busy:"kept: GitHub reports it busy",changed:"kept: GitHub no longer reports it offline and idle",deleted:"deregistered",gone:"already gone",renamed:"kept: GitHub lists it under another name now"};class eo extends x{name="deregister";description="Delete the GitHub registrations of stopped 0.x runners by id";args=aa;async execute(e){T(e.args,aa,"Run 'hydra legacy deregister --help' for supported options"),Oe(e.args);let{github:t,inventory:n}=await be(e.config),r=[],o=[];for(let s of n.runners)if(!ye(s))o.push(ee(s,s.refusal??"config.json does not record it"));else if(!s.github)o.push(me(l.dim("done"),s,"not registered on GitHub"));else if(s.process.kind!=="stopped")o.push(ee(s,`${re(s.process)}; ${at(s.process)}`));else{r.push(s);let c=l.red(e.args.dryRun?"would deregister":"deregister");o.push(me(c,s,`id ${s.github.id} \xB7 ${s.github.status}`))}if(b.info(o.join(`
250
- `)),r.length===0){b.info(l.dim("Nothing to deregister."));return}if(e.args.dryRun){b.info(`Would deregister ${r.length} runner(s). Run ${l.green("hydra legacy deregister --yes")} to do it.`);return}if(!await Le(e.args,`Delete ${r.length} registration(s) from GitHub?`))return;let i=0;for(let s of r){let c=await Je(s);if(c.kind!=="stopped"||!s.github){b.info(`${s.name} \xB7 ${l.yellow(`kept: ${re(c)}`)}`);continue}let a=await kn(t,s.scope.target,s.github,Op);if(a==="deleted")i++;let u=Lp[a];b.info(`${s.name} \xB7 id ${s.github.id} \xB7 ${a==="deleted"?l.green(u):u}`)}b.info(`${l.green("Deregistered")} ${i} of ${r.length} runner(s).`)}}var ua=L({...He,...st}),Np="Runners reported as moved stay drained; run hydra legacy drain again to finish";class to extends x{name="drain";description="Move a 0.x fleet's runners into a runner group no repository can use";args=ua;async execute(e){T(e.args,ua,"Run 'hydra legacy drain --help' for supported options"),Oe(e.args);let{group:t,dryRun:n}=e.args,{github:r,inventory:o}=await be(e.config),i=await it(r,o.scopes,t),s=new Map,c=[];for(let d of o.runners){if(!ye(d)){c.push(ee(d,d.refusal??"config.json does not record it"));continue}if(!d.github){c.push(ee(d,"not registered on GitHub"));continue}if(!Ve(d.scope.target)){c.push(ee(d,"repository runners have no runner groups; stop it with hydra stop once idle"));continue}if(i.get(d.scope.key)?.members.has(d.github.id)){c.push(me(l.dim("drained"),d,`already in ${t}`));continue}s.set(d.scope,[...s.get(d.scope)??[],{id:d.github.id,runner:d}]);let p=d.github.busy?"busy, its job keeps running":"idle";c.push(me(l.yellow(n?"would move":"move"),d,`id ${d.github.id} \xB7 ${p}`))}for(let d of s.keys())if(!i.has(d.key))c.push(l.dim(` ${n?"would create":"create"} ${t}`));b.info(c.join(`
251
- `));let a=[...s.values()].reduce((d,p)=>d+p.length,0);if(a===0){b.info(l.dim("Nothing to drain."));return}if(n){b.info(`Would move ${a} runner(s) into ${t}. Run ${l.green("hydra legacy drain --yes")} to move them.`);return}if(!await Le(e.args,`Move ${a} runner(s) into ${t}?`))return;let u=0;for(let[d,p]of s){let m=Ve(d.target);if(!m)continue;let h=i.get(d.key)??await Fs(r,m,t);for(let{id:f,runner:w}of p)await ne(r,m,Np,()=>zi(r.client,m.org,h.group,f)),u++,b.info(`${w.name} \xB7 id ${f} \xB7 ${l.green(`moved into ${h.group.name}`)}`)}b.info(`${l.green("Drained")} ${u} runner(s). They take no new jobs; run ${l.green("hydra legacy stop --wait")} to stop them once their jobs finish.`)}}var ca=L({...st});class no extends x{name="inventory";description="List a 0.x fleet's runners, here and on GitHub";args=ca;async execute(e){T(e.args,ca,"Run 'hydra legacy inventory --help' for supported options");let{github:t,inventory:n}=await be(e.config),r=await it(t,n.scopes,e.args.group),o=e.config.get("profiles"),i=new Map;for(let u of n.runners){let d=u.entry?u.entry.profile:"";i.set(d,[...i.get(d)??[],u])}let s=[];for(let[u,d]of i){if(s.length>0)s.push("");let p=Object.hasOwn(o,u)?o[u]?.url:void 0;s.push(u?`${l.bold(u)} ${l.dim(p??"no such profile")}`:l.bold("Not recorded"));let m=d.sort((h,f)=>h.name.localeCompare(f.name,void 0,{numeric:!0}));for(let h of m)s.push(js(h,xt(r,h)))}if(s.length===0)s.push(l.dim("No runners in this home."));let c=n.runners,a=(u)=>c.filter(u).length;s.push("",l.dim([`${c.length} runner(s)`,`${a(ye)} provably this home's`,`${a((u)=>u.process.kind==="running"||u.process.kind==="unproven")} running`,`${a((u)=>u.github?.busy===!0)} busy`,`${a((u)=>xt(r,u))} drained into ${e.args.group}`,`${a((u)=>u.layout.kind==="self-updated")} self-updated`,`${a((u)=>u.refusal!==void 0)} left alone`].join(", "))),b.info(s.join(`
252
- `))}}var la=L({...He,...st,interval:{default:15,description:"Seconds between checks while waiting",type:"number"},timeout:{default:60,description:"Minutes to wait for busy runners",type:"number"},wait:{alias:"w",default:!1,description:"Wait for busy runners to finish their jobs",type:"boolean"}}),ro=1000,Dp=60,Gp="Nothing more was stopped; run hydra legacy stop again";class oo extends x{name="stop";description="Stop drained 0.x runners once GitHub and the host show them idle";args=la;async execute(e){T(e.args,la,"Run 'hydra legacy stop --help' for supported options"),Oe(e.args);let{dryRun:t,group:n,interval:r,timeout:o,wait:i}=e.args;if(!(r>0)||!(o>=0))throw new y("--interval must be above 0 and --timeout at least 0");let{github:s,inventory:c}=await be(e.config),a=await it(s,c.scopes,n),u=[],d=[],p=0;for(let f of c.runners.filter((w)=>w.process.kind!=="stopped")){let w=Mp(f,xt(a,f),n);if(w||!ye(f)){if(f.process.kind!=="stale")p++;d.push(ee(f,w??"config.json does not record it"));continue}u.push(f);let v=f.github?.busy||"worker"in f.process&&f.process.worker?"busy":"idle";d.push(me(l.yellow(t?"would stop":"stop"),f,`${re(f.process)} \xB7 ${v}`))}if(d.length===0)d.push(l.dim(" No runner of this home is running."));if(b.info(d.join(`
253
- `)),u.length===0)return da(p,0,i);if(t){b.info(`Would stop ${u.length} runner(s), each only once it is idle.`);return}if(!await Le(e.args,`Stop ${u.length} runner(s) once each is idle?`))return;let m=Date.now()+o*Dp*ro,h=u;while(!0){let f=[],w=await this.drainGroups(s,h,n);for(let v of h){let C=await this.attempt(s,v,w.get(v.scope.key));if(C==="busy")f.push(v);if(C==="left")p++}if(h=f,h.length===0||!i||Date.now()+r*ro>m)break;b.info(l.dim(`Waiting for ${h.length} busy runner(s)...`)),await Bun.sleep(r*ro)}for(let f of h)b.info(`${f.name} \xB7 ${l.yellow("still busy, left running")}`);da(p,h.length,i)}async drainGroups(e,t,n){let r=new Map;for(let o of t){let i=Ve(o.scope.target);if(!i||r.has(o.scope.key))continue;r.set(o.scope.key,await _n(e,i,n))}return r}async attempt(e,t,n){let r=t.github?.id;if(r===void 0||!n?.members.has(r))return b.info(`${t.name} \xB7 ${l.yellow("left running: it is no longer in the drain group")}`),"left";if(n.members.get(r)?.busy)return"busy";let o=await ne(e,t.scope.target,Gp,()=>Ze(e.client,t.scope.target,r));if(!o||o.name.toLowerCase()!==t.github?.name.toLowerCase())return b.info(`${t.name} \xB7 ${l.yellow("left running: GitHub no longer lists it under this id and name")}`),"left";if(o.busy)return"busy";let i=await Je(t);if(i.kind==="stopped")return b.info(`${t.name} \xB7 already stopped`),"stopped";if(i.kind==="unproven"||i.kind==="stale")return b.info(`${t.name} \xB7 ${l.yellow(`left running: ${re(i)}`)}`),"left";if(i.worker)return"busy";if(await Xs(t.directory,i.pid)==="timeout")return b.info(`${t.name} \xB7 ${l.yellow("did not stop in time; check it with hydra legacy inventory")}`),"left";return b.info(`${t.name} \xB7 ${l.green("stopped")}`),"stopped"}}function da(e,t,n){if(e+t===0)return;let r=t===0?"Check why they were left alone with hydra legacy inventory":n?"Their jobs outlasted --timeout; run hydra legacy stop --wait again":"Pass --wait to stop busy runners once their jobs finish";throw new y(`${e+t} runner(s) are still running`,r)}function Mp(e,t,n){if(e.refusal)return e.refusal;if(e.process.kind==="stale")return`${re(e.process)}; ${at(e.process)}`;if(e.process.kind==="unproven")return re(e.process);if(!e.github)return"not registered on GitHub, so Hydra cannot prove it takes no jobs";if(e.scope&&!Ve(e.scope.target))return"repository runners have no runner groups; stop it with hydra stop once idle";if(!t)return`not in ${n}; run hydra legacy drain first`;return}import{readdir as Fp,rm as pa,rmdir as Up}from"fs/promises";import{join as fa}from"path";var ma=L({...He}),jp="Nothing more was wiped; run hydra legacy wipe again",Et="Its .runner file is kept; fix the cause, then run hydra legacy wipe again",Bp="Delete what is left of the directory, then run hydra legacy wipe again to drop its record",Kp=2;class io extends x{name="wipe";description="Delete the directories and records of stopped, deregistered 0.x runners";args=ma;async execute(e){T(e.args,ma,"Run 'hydra legacy wipe --help' for supported options"),Oe(e.args);let{github:t,inventory:n}=await be(e.config),r=(d)=>l.red(e.args.dryRun?`would ${d}`:d),o=[],i=[],s=[],c=[];for(let d of n.runners)if(ea(d)){let p=ta(d);if(p){c.push(ee(d,`its directory is missing but GitHub lists id ${p.id}; run hydra reconcile`));continue}i.push(d),c.push(me(r("drop"),d,"its directory is missing, so only its record is left"))}else if(!ye(d))c.push(ee(d,d.refusal??"config.json does not record it"));else if(d.github)c.push(ee(d,`registered on GitHub as id ${d.github.id}; run hydra legacy deregister first`));else if(d.process.kind!=="stopped")c.push(ee(d,`${re(d.process)}; ${at(d.process)}`));else{let p=await ut(d,Et,()=>qr(d.directory));if(p.length>0)s.push(` ${d.name}: ${p.join(", ")}`);o.push(d),c.push(me(r("wipe"),d,d.directory))}if(b.info(c.join(`
254
- `)),s.length>0)throw b.warn(l.yellow(["Unexpected entries in runner directories:",...s].join(`
255
- `))),new y("Not wiping: a runner directory holds entries a 0.x runner does not create","Move those entries out of the runner directory, then run hydra legacy wipe again");let a=o.length+i.length;if(a===0){b.info(l.dim("Nothing to wipe."));return}if(e.args.dryRun){b.info(`Would wipe ${a} runner(s). Run ${l.green("hydra legacy wipe --yes")} to do it.`);return}if(!await Le(e.args,`Delete ${o.length} runner directory(ies) and ${a} record(s)?`))return;let u=0;for(let d of o){let p=await this.keepReason(t,d);if(p){b.info(`${d.name} \xB7 ${l.yellow(`kept: ${p}`)}`);continue}await Jp(d),ha(e.config,d.entry),u++,b.info(`${d.name} \xB7 ${l.green("wiped")}`)}for(let d of i){let p=await Vp(d);if(p){b.info(`${d.name} \xB7 ${l.yellow(`kept: ${p}`)}`);continue}ha(e.config,d.entry),u++,b.info(`${d.name} \xB7 ${l.green("record dropped")}`)}b.info(`${l.green("Wiped")} ${u} of ${a} runner(s).`)}async keepReason(e,t){let n=await Je(t);if(n.kind!=="stopped")return re(n);let r=t.registration?.agentId;if(r===void 0)return"its .runner file records no runner id";if(await ne(e,t.scope.target,jp,()=>Ze(e.client,t.scope.target,r)))return`GitHub lists it again as id ${r}`;let i=await ut(t,Et,()=>qr(t.directory));return i.length>0?`unexpected entries: ${i.join(", ")}`:void 0}}async function Vp(e){let t=await Je(e);if(t.kind!=="stopped")return re(t);return await Xr(e.directory)==="missing"?void 0:"its directory exists again"}async function Jp(e){let{directory:t}=e;for(let n=0;n<Kp;n++){let r=await ut(e,Et,()=>Fp(t));for(let o of Js(r).filter((i)=>i!==xe))await ut(e,Et,()=>pa(fa(t,o),{force:!0,recursive:!0}))}await ut(e,Et,()=>pa(fa(t,xe),{force:!0})),await ut(e,Bp,()=>Up(t))}async function ut(e,t,n){try{return await n()}catch(r){throw new y(`Cannot wipe ${e.name} in ${e.directory}: ${r.message}`,t)}}function ha(e,t){e.set("runners",(e.get("runners")??[]).filter((n)=>n.id!==t.id||n.profile!==t.profile))}class Hn extends x{name="legacy";description="Drain, stop, deregister and wipe a 0.x fleet";init(){this.registerSubcommands([new no,new to,new oo,new eo,new io])}}import{existsSync as Wp}from"fs";import{readFile as qp}from"fs/promises";var zp=100,Yp={runner:"runner daemon log",worker:"job log"},Xp=L({lines:{alias:"n",default:zp,description:"Number of lines to show",type:"number"},list:{alias:"l",default:!1,description:"List log files instead of showing one",type:"boolean"},open:{alias:"o",default:!1,description:"Open the log file",type:"boolean"},runner:{alias:"r",default:!1,description:"Show the runner log instead of a job log",type:"boolean"}}),Zp=B({id:{description:"Runner ID"}});class On extends x{name="logs";description="Show recent runner logs";args=Xp;positionals=Zp;async execute(e){let t=e.config.get("runners")??[];if(t.length===0)throw new y("No runners found","Run hydra create to provision runners");let n=await this.resolveEntry(e,t),r=e.config.get("profiles"),o=Object.hasOwn(r,n.profile)?r[n.profile]:void 0;if(!o)throw new y(`Profile "${n.profile}" not found for runner "${n.id}"`,"Run hydra init to set it up");if(!Wp(n.directory))throw new y(`Runner directory not found: ${n.directory}`,"Run hydra create to provision this runner");let s=await M(o,e.config).logFiles(n.id);if(s.length===0)this.noLogs(n.id);if(e.args.list){this.printList(n,s);return}let c=this.selectFile(e,n,s);if(e.args.open){await this.openFile(c);return}await this.printTail(n,c,e.args.lines)}async resolveEntry(e,t){let n=e.positionals.id;if(n){let o=t.find((i)=>i.id===n);if(!o)throw new y(`Runner "${n}" not found`,`Known runners: ${t.map((i)=>i.id).join(", ")}`);return o}if(e.interactive)return De({message:"Select runner",options:t.map((o)=>({hint:o.profile,label:o.name,value:o}))});let r=t[0];if(t.length===1&&r)return r;throw new y("Multiple runners found",`Pass a runner id: hydra logs <id> (${t.map((o)=>o.id).join(", ")})`)}selectFile(e,t,n){if(e.args.runner){let o=n.find((i)=>i.type==="runner");if(!o)throw new y(`No runner daemon logs found for "${t.id}"`,"Start the runner first: hydra start");return o}let r=Pr(n,"worker");if(!r)this.noLogs(t.id);if(r.fallback)b.warn(l.yellow("No job (Worker) logs yet; showing the runner daemon log instead"));return r.file}noLogs(e){throw new y(`No logs found for runner "${e}"`,"Logs appear once the runner has started; run hydra start")}printList(e,t){let n=[`${l.bold(e.name)} ${l.dim(e.directory)}`];for(let r of t){let o=r.type==="worker"?l.green("worker"):l.blue("runner");n.push(` ${o} ${r.name} ${l.dim(`${r.mtime.toISOString()} \xB7 ${Fe(r.size)}`)}`)}b.info(n.join(`
256
- `))}async printTail(e,t,n){let r=await qp(t.path,"utf-8"),o=[`${l.bold(e.name)} ${l.dim(Yp[t.type])}`,l.dim(t.path),l.dim(`Last modified: ${t.mtime.toISOString()}`)];b.info(o.join(`
257
- `)),console.log(Ar(r,n))}async openFile(e){let t=(process.env.EDITOR??"").split(" ").filter(Boolean),n=t[0];if(n){await Bun.spawn([n,...t.slice(1),e.path],{stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited;return}if(process.platform==="darwin"){await Bun.$`open ${e.path}`.quiet();return}throw new y("No editor configured","Set $EDITOR to open log files")}}var Qp=B({name:{description:"Profile name to set as default"}});class so extends x{name="default";description="Set the default profile";positionals=Qp;async execute(e){T(e.args,this.args,"Run 'hydra profile default --help' for supported options");let t=e.interactive?await ce(e.config):e.positionals.name;if(!t)throw new y("Profile name is required","Usage: hydra profile default <name>");let{name:n}=q(e.config,t);if(e.config.get("defaultProfile")===n){b.info(`"${n}" is already the default profile.`);return}e.config.set("defaultProfile",n),b.info(`${l.green("Default profile set to")} "${n}".`)}}class ao extends x{name="list";description="List profiles";async execute(e){let t=e.config.get("profiles"),n=Object.keys(t);if(n.length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let r=e.config.get("runners")??[],o=e.config.get("defaultProfile");for(let i of n){let s=t[i],a=await M(s,e.config).list(),u=r.filter((w)=>w.profile===i),d=new Set(a.filter((w)=>w.status==="running").map((w)=>w.id)),p=u.filter((w)=>d.has(w.id)).length,m=i===o,h=[`${l.dim("URL:")} ${s.url}`,`${l.dim("Provider:")} ${s.provider}`,`${l.dim("OS:")} ${s.os}`,`${l.dim("Name:")} ${s.name}`,`${l.dim("Runners:")} ${u.length}/${s.numberOfMachines} created, ${l.green(`${p} running`)}`];if(s.labels)h.push(`${l.dim("Labels:")} ${s.labels}`);let f=m?`${i} ${l.dim("(default)")}`:i;We(h.join(`
258
- `),f)}b.info(l.dim(`${n.length} profile(s)`))}}import{rm as ef}from"fs/promises";import{join as tf}from"path";var nf=B({name:{description:"Profile name to remove"}}),rf=L({yes:{alias:"y",default:!1,description:"Skip runner removal confirmation",type:"boolean"}});class uo extends x{name="remove";description="Delete a profile and its runners";positionals=nf;args=rf;async execute(e){T(e.args,this.args,"Run 'hydra profile remove --help' for supported options");let t=e.interactive?await ce(e.config):e.positionals.name;if(!t)throw new y("Profile name is required","Usage: hydra profile remove <name>");let{profile:n}=q(e.config,t),r=e.config.get("runners")??[],o=r.filter((a)=>a.profile===t);if(o.length>0){if(!e.args.yes){if(!process.stdout.isTTY)throw new y("Runner removal requires confirmation","Pass --yes to remove the profile and its runners without a prompt");if(!await pe({initialValue:!0,message:`This will stop and remove ${o.length} runner(s). Continue?`}))return}await this.removeRunners(e,n,o.map((u)=>u.id));let a=r.filter((u)=>u.profile!==t);e.config.set("runners",a)}let{[t]:i,...s}=e.config.get("profiles");if(e.config.set("profiles",s),e.config.get("defaultProfile")===t){let a=Object.keys(s);e.config.set("defaultProfile",a[0])}b.info(`${l.green("Removed")} profile "${t}".`)}async removeRunners(e,t,n){let r=M(t,e.config),o=Z();for(let i of n)o.start(`Stopping and removing ${i}...`),await r.remove([i]),await ef(tf(t.directory,i),{force:!0,recursive:!0}),e.config.set("runners",(e.config.get("runners")??[]).filter((s)=>s.id!==i)),o.stop(`${l.red("-")} ${i}`)}}class Ln extends x{name="profile";description="Manage profiles";init(){this.registerSubcommands([new ao,new uo,new so])}}var ga=L({dryRun:{alias:"n",default:!1,description:"List what would be deleted, delete nothing",type:"boolean"},yes:{alias:"y",default:!1,description:"Delete without a confirmation prompt",type:"boolean"}}),of={busy:"kept: GitHub reports it busy",changed:"kept: it is no longer offline and idle",deleted:"deleted",gone:"already gone",renamed:"kept: GitHub lists it under another name now",returned:"kept: its directory in this home holds a runner again"};class Nn extends x{name="reconcile";description="Delete stale GitHub registrations of this home's runners";args=ga;async execute(e){if(T(e.args,ga,"Run 'hydra reconcile --help' for supported options"),e.args.dryRun&&e.args.yes)throw new y("Pass either --dry-run or --yes, not both");if(Object.keys(e.config.get("profiles")).length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let t=rt(e.config),{scopes:n,unreadableHomes:r}=await En(e.config,t);if(n.length===0){b.info(l.dim("No GitHub profiles to reconcile."));return}let o=n.flatMap((i)=>i.rows.filter(Ie).map((s)=>({row:s,scope:i})));b.info(this.planLines(n,e.args.dryRun).join(`
259
- `));for(let i of r)b.warn(l.yellow(`Cannot read the runner records of ${i}`));if(n.some((i)=>i.rows.some(Ls)))throw new y("Not deleting: another Hydra home may record these runners","Repair or move the home named above, then run hydra reconcile again");if(o.length===0){b.info(l.dim("Nothing to delete."));return}if(e.args.dryRun){b.info(`Would delete ${o.length} registration(s). Run ${l.green("hydra reconcile --yes")} to delete them.`);return}if(!await this.confirmed(e,o.length))return;await this.deleteStale(t,o)}planLines(e,t){let n=[];for(let r of e){if(n.length>0)n.push("");n.push(Zr(r));let o=r.rows.filter((i)=>i.placement!=="both");if(o.length===0)n.push(l.dim(" Every runner here matches a registration on GitHub."));for(let i of o){if(i.placement==="local"){n.push(` ${i.local.name} ${l.dim("is in this home but not registered on GitHub")}`);continue}let s=`${i.github.name} \xB7 id ${i.github.id}`;n.push(Ie(i)?` ${l.red(t?"would delete":"delete")} ${s} \xB7 ${In(i.github)}`:` ${l.dim("keep")} ${s} \xB7 ${Qr(i)}`)}}return n}async confirmed(e,t){if(e.args.yes)return!0;if(!process.stdout.isTTY)throw new y("Deleting registrations requires confirmation","Pass --yes to delete them, or --dry-run to only list them");return pe({initialValue:!1,message:`Delete ${t} registration(s) from GitHub?`})}async deleteStale(e,t){let n=0;for(let{row:r,scope:o}of t){let i=Ds(r.local)?"returned":await kn(e,o.target,r.github);if(i==="deleted")n++;let s=of[i];b.info(`${r.github.name} \xB7 id ${r.github.id} \xB7 ${i==="deleted"?l.green(s):s}`)}b.info(`${l.green("Deleted")} ${n} of ${t.length} registration(s).`)}}import{rm as sf}from"fs/promises";import{join as af}from"path";var uf=B({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class Dn extends x{name="remove";description="Deregister and delete runners";positionals=uf;async execute(e){T(e.args,this.args,"Run 'hydra remove --help' for supported options");let{name:t,profile:n}=e.interactive?q(e.config,await ce(e.config)):q(e.config,e.positionals.profile),o=(e.config.get("runners")??[]).filter((a)=>a.profile===t);if(o.length===0)throw new y(`No runners found for profile "${t}"`,"Run hydra create to provision runners");let i=e.interactive?await this.promptRunnerSelection(o.map((a)=>a.id)):tt(e.positionals.ids??[],o.map((a)=>a.id)),s=M(n,e.config),c=Z();for(let a of i)c.start(`Stopping and removing ${a}...`),await s.remove([a]),await sf(af(n.directory,a),{force:!0,recursive:!0}),e.config.set("runners",(e.config.get("runners")??[]).filter((u)=>u.id!==a)),c.stop(`${l.red("-")} ${a}`);b.info(`${l.green("Removed")} ${i.length} runner(s).`)}async promptRunnerSelection(e){return Ge({message:"Select runners to remove",options:e.map((t)=>({label:t,value:t})),required:!0})}}var cf=B({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class Gn extends x{name="start";description="Start runners";positionals=cf;async execute(e){T(e.args,this.args,"Run 'hydra start --help' for supported options");let{name:t,profile:n}=e.interactive?q(e.config,await ce(e.config)):q(e.config,e.positionals.profile),o=(e.config.get("runners")??[]).filter((m)=>m.profile===t);if(o.length===0)throw new y(`No runners found for profile "${t}"`,"Run hydra create to provision runners");let i=M(n,e.config),s=Z();s.start("Fetching runner status...");let c=await i.list();s.stop("Runner status fetched");let a=new Set(c.filter((m)=>m.status==="running").map((m)=>m.id)),u=o.map((m)=>m.id).filter((m)=>!a.has(m)),d=e.interactive?await this.promptRunnerSelection(u):tt(e.positionals.ids??[],o.map((m)=>m.id)),p=0;for(let m of d){if(a.has(m)){s.start(""),s.stop(`${l.dim("\u25CF")} ${m} ${l.dim("already running")}`);continue}s.start(`Starting ${m}...`),await i.start([m]),s.stop(`${l.green("\u25B6")} ${m}`),p++}b.info(`${l.green("Started")} ${p} runner(s).`),await $n(e)}async promptRunnerSelection(e){if(e.length===0)throw new y("All runners are already running");return Ge({message:"Select runners to start",options:e.map((t)=>({label:t,value:t})),required:!0})}}var ya=L({github:{alias:"g",default:!1,description:"Compare with the runners registered on GitHub",type:"boolean"}}),lf={registered:l.yellow,running:l.green,stopped:l.red,unknown:l.dim};class Mn extends x{name="status";description="Show status across profiles";args=ya;async execute(e){T(e.args,ya,"Run 'hydra status --help' for supported options");let t=e.config.get("profiles"),n=Object.keys(t);if(n.length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let r=e.config.get("runners")??[],o=0,i=0,s=[];for(let c of n){let a=t[c],d=await M(a,e.config).list();if(s.length>0)s.push("");s.push(`${l.bold(c)} ${l.dim(a.url)}`);let p=new Set(r.filter((h)=>h.profile===c).map((h)=>h.id)),m=d.filter((h)=>p.has(h.id)).sort((h,f)=>h.name.localeCompare(f.name,void 0,{numeric:!0}));this.formatRunners(m,s),o+=m.length,i+=m.filter((h)=>h.status==="running").length}if(s.push(""),s.push(l.dim(`${o} runner(s) total, ${i} running`)),b.info(s.join(`
260
- `)),e.args.github)await this.printGitHubComparison(e)}async printGitHubComparison(e){let{scopes:t,unreadableHomes:n}=await En(e.config,rt(e.config));if(t.length===0){b.info(l.dim("No GitHub profiles to compare."));return}let r=t.flatMap((i,s)=>[...s>0?[""]:[],...sa(i)]),o=t.flatMap((i)=>i.rows.filter(Ie)).length;if(o>0)r.push("",l.yellow(`Run ${l.green("hydra reconcile --dry-run")} to review ${o} stale registration(s).`));b.info(r.join(`
261
- `));for(let i of n)b.warn(l.yellow(`Cannot read the runner records of ${i}`))}formatRunners(e,t){if(e.length===0){t.push(l.dim(" No runners."));return}for(let n of e){let r=lf[n.status]??l.dim,o=n.pid?l.dim(` (pid: ${n.pid})`):"";t.push(` ${r("\u25CF")} ${n.name} ${r(n.status)}${o}`)}}}var df=B({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class Fn extends x{name="stop";description="Stop runners";positionals=df;async execute(e){T(e.args,this.args,"Run 'hydra stop --help' for supported options");let{name:t,profile:n}=e.interactive?q(e.config,await ce(e.config)):q(e.config,e.positionals.profile),o=(e.config.get("runners")??[]).filter((m)=>m.profile===t);if(o.length===0)throw new y(`No runners found for profile "${t}"`,"Run hydra create to provision runners");let i=M(n,e.config),s=Z();s.start("Fetching runner status...");let c=await i.list();s.stop("Runner status fetched");let a=new Set(c.filter((m)=>m.status==="running").map((m)=>m.id)),u=o.map((m)=>m.id).filter((m)=>a.has(m)),d=e.interactive?await this.promptRunnerSelection(u):tt(e.positionals.ids??[],o.map((m)=>m.id)),p=0;for(let m of d){if(!a.has(m)){s.start(""),s.stop(`${l.dim("\u25CF")} ${m} ${l.dim("not running")}`);continue}s.start(`Stopping ${m}...`),await i.stop([m]),s.stop(`${l.red("\u25A0")} ${m}`),p++}b.info(`${l.green("Stopped")} ${p} runner(s).`)}async promptRunnerSelection(e){if(e.length===0)throw new y("No runners are currently running");return Ge({message:"Select runners to stop",options:e.map((t)=>({label:t,value:t})),required:!0})}}class Un extends x{name="update";description="Update runner binaries and job hooks";async execute(e){T(e.args,this.args,"Run 'hydra update --help' for supported options");let t=e.config.get("profiles"),n=e.config.get("runners")??[];if(n.length===0)throw new y("No runners found","Run hydra create to provision runners");let r=Z(),o=Map.groupBy(n,(a)=>a.profile);for(let a of o.keys()){let u=Object.hasOwn(t,a)?t[a]:void 0;if(u)Se(u.jobHooks)}let i=0,s=0,c=new Map;for(let[a,u]of o){let d=Object.hasOwn(t,a)?t[a]:void 0;if(!d)continue;let p=M(d,e.config);r.start(`Checking for updates for "${a}"...`);let{version:m}=await p.download();r.stop(`Latest: v${m}`);let h=await p.list(),f=new Set(h.filter((w)=>w.status==="running").map((w)=>w.id));for(let w of u){let v=f.has(w.id);if(await p.currentVersion(w.id)===m){let R=await p.configureJobHooks(w.id);if(!R.envChanged&&!R.scriptsChanged)continue;if(s++,R.envChanged&&v){let P=c.get(a)??{ids:[],total:u.length};c.set(a,{...P,ids:[...P.ids,w.id]})}r.start(""),r.stop(`${l.green("\u2713")} ${w.id} ${l.dim("(job hooks)")}`);continue}if(r.start(`Updating ${w.id}...`),v)await p.stop([w.id]);if(await p.update([w.id]),v)await p.start([w.id]);i++;let C=v?` ${l.dim("(restarted)")}`:"";r.stop(`${l.green("\u2713")} ${w.id}${C}`)}}if(b.info(i>0?`${l.green("Updated")} ${i} runner(s).`:"All runners are already on the latest version."),s>0)b.info(`${l.green("Refreshed")} job hooks on ${s} runner(s).`);this.printRestartHint(c),await $n(e)}printRestartHint(e){if(e.size===0)return;let t=["Running runners load job hook settings only when they start. Restart them once they are idle:"];for(let[n,{ids:r,total:o}]of e){let i=r.length===o?n:`${n} ${r.join(" ")}`;t.push(` ${l.green(`hydra stop ${i} && hydra start ${i}`)}`)}b.warn(t.join(`
262
- `))}}var pf="--",ff=new Set(["--help","-h"]),mf="help",hf="doctor",ba=new Set(["logs","profile list","status"]),gf={...cr,home:Zt};function wa(e){let t=yf(e);if(!t)return"write";let{command:n,flags:r,restArgs:o}=t;if(!n)return r.version||!r.interactive?"help":"write";if(n===mf)return"help";if(n===hf)return"diagnose";if(bf(Boolean(r.help),o))return"help";return ba.has(n)||ba.has(`${n} ${o[0]}`)?"read":"write"}function $a({home:e,source:t},n,r){if(n==="help"||n==="diagnose")return;let o=bi(e,r);if(!o||t!=="default"||n!=="write")return o;throw new y(`This directory holds the Hydra home ${o}, but no home was selected, so this command would act on ${e}`,`Pass ${j} <path> or set ${ae} to choose ${o} or ${e}`)}function yf(e){try{return gt([...e],gf)}catch{return}}function bf(e,t){let[n]=t;if(e&&(n===void 0||n.startsWith("-")))return!0;let r=t.indexOf(pf);return(r<0?t:t.slice(0,r)).some((o)=>ff.has(o))}class va extends lr{constructor(e,t){super(e,{bin:qt,clearOnStart:t,description:"Manage GitHub Actions runners on this machine.",exitLabel:"Exit",goodbyeMessage:"Heads down.",name:"HYDRA",promptMessage:"What do you need?",version:ri})}init(){this.globalArgs.home=Zt,this.registerCommands([new xn,new Rn,new Gn,new Fn,new Mn,new Nn,new On,new Sn,new wn,new Dn,new Un,new Ln,new Hn])}}function wf(e,t){b.warn(l.yellow(`Ignoring ${t}: Hydra keeps its state in ${e}`)),b.info(l.dim(`To manage that fleet, pass ${j} ${t} or set ${ae}=${t}`))}function $f(e){if(e instanceof y){if(b.warn(l.yellow(e.message)),e.hint)b.info(l.dim(e.hint));process.exit(e.exitCode)}b.error(l.red(e instanceof Error?e.message:String(e))),process.exit(1)}async function vf(){let e=yi(process.argv.slice(2),process.env),t=wa(e.argv),n=$a(e,t,process.cwd()),r=Es(e.home);if(n)wf(e.home,n);let o=t==="read"||t==="write"?Cn(r):void 0;if(o)throw o;await new va(r,n===void 0).run(e.argv)}vf().catch($f);
241
+ `)}function kt(e){let t=e,n=0;while(t>=_y&&n<Ty.length-1)t/=_y,n++;return`${n===0?String(t):t.toFixed(jP)} ${Ty[n]??"B"}`}import{realpathSync as VP}from"fs";import{readFile as qP,stat as KP,unlink as WP}from"fs/promises";import{join as vl}from"path";var jr=".pid",JP=30000,YP=1,XP=200,zP=/^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/,QP=/[.*+?^${}()|[\]\\]/g,Ay="Listener",ZP="Worker",e0=1000,t0=60,n0=3600,r0=86400,o0=2000,s0=10,i0=/^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/;async function Ut(){let e=await Bun.$`ps -A -o pid= -o pgid= -o etime= -o command=`.env({...process.env,LC_ALL:"C"}).quiet().nothrow();if(e.exitCode!==0)throw new b("Cannot list the host's processes with ps",e.stderr.toString().trim()||"Nothing was changed");return e.stdout.toString().split(`
242
+ `).flatMap((t)=>{let n=t.match(zP);if(!n)return[];let r=u0(n[3]),o={command:n[4],pgid:Number(n[2]),pid:Number(n[1])};return[r===void 0?o:{...o,elapsedSeconds:r}]})}async function zi(e){try{let t=Number((await qP(vl(e,jr),"utf-8")).trim());return Number.isSafeInteger(t)&&t>YP?t:void 0}catch{return}}async function Qi(e,t,n=Date.now()){let r=await zi(e);if(r===void 0)return{kind:"absent"};let o=t.find((a)=>a.pid===r);if(!o)return{kind:"dead",pid:r};let s=await c0(e);if(s===void 0)return{kind:"dead",pid:r};if(o.elapsedSeconds===void 0)return{kind:"alive",pid:r};return{kind:n-o.elapsedSeconds*e0>s+o0?"recycled":"alive",pid:r}}function Zi(e,t,n){let r=Py(e,n),o=r.some((c)=>c.role!==Ay),s=t!==void 0&&n.some((c)=>c.pid===t);if(r.length===0)return s&&t!==void 0?{kind:"stale",pid:t}:{kind:"stopped"};if(s&&r.some((c)=>c.role===Ay)&&r.every((c)=>c.pgid===t)&&t!==void 0)return{kind:"running",pid:t,worker:o};return{kind:"unproven",pids:[...new Set([...s&&t!==void 0?[t]:[],...r.map(({pid:c})=>c)])],worker:o}}function Cy(e,t){return Py(e,t).some((n)=>n.role===ZP)}async function Oy(e,t){return a0(t),kl(e,t)}function a0(e){try{process.kill(-e,"SIGTERM")}catch(t){if(t.code!=="ESRCH")throw t}}async function kl(e,t,n=JP){let r=Date.now()+n;while(Date.now()<r){if(Zi(e,t,await Ut()).kind==="stopped")return await WP(vl(e,jr)).catch(()=>{return}),"stopped";await Bun.sleep(XP)}return"timeout"}function Py(e,t){let n=l0(e);return t.flatMap((r)=>{let o=r.command.match(n)?.[1];return o?[{...r,role:o}]:[]})}async function c0(e){try{return(await KP(vl(e,jr))).mtimeMs}catch{return}}function u0(e){let t=e.match(i0);if(!t)return;let[n,r,o,s]=[t[1],t[2],t[3],t[4]].map((i)=>i===void 0?0:Number.parseInt(i,s0));return n*r0+r*n0+o*t0+s}function l0(e){let t=[...new Set([e,d0(e)])].map((n)=>n.replace(QP,"\\$&"));return new RegExp(`(?:^|\\s)(?:${t.join("|")})/bin(?:\\.[^/\\s]+)?/Runner\\.(Listener|Worker)(?:\\s|$)`)}function d0(e){try{return VP(e)}catch{return e}}import{readFile as p0}from"fs/promises";import{join as f0}from"path";var Br="unknown";var ke=".runner",m0=/^\uFEFF/;async function Qn(e){try{let t=await p0(f0(e,ke),"utf-8"),n=JSON.parse(t.replace(m0,""));return{agentId:Number.isSafeInteger(n.agentId)?n.agentId:void 0,gitHubUrl:typeof n.gitHubUrl==="string"?n.gitHubUrl:void 0,name:typeof n.agentName==="string"?n.agentName:Br}}catch{return{name:Br}}}import{spawn as g0}from"child_process";import{once as h0}from"events";import{existsSync as xl}from"fs";import{unlink as y0,writeFile as b0}from"fs/promises";import{join as ea,resolve as w0}from"path";var Iy="run.sh",S0=new Set(["HOME","HTTPS_PROXY","HTTP_PROXY","LANG","LOGNAME","NO_PROXY","PATH","SHELL","TERM","TMPDIR","TZ","USER","http_proxy","https_proxy","no_proxy"]),R0=["LC_"],$0={incomplete:"its runner files are incomplete (no run.sh)","missing-directory":"its directory is missing",unregistered:"it has no .runner file, so it is not registered"};function E0(e){return Object.fromEntries(Object.entries(e).filter((t)=>t[1]!==void 0&&(S0.has(t[0])||R0.some((n)=>t[0].startsWith(n)))))}function _l(e){if(!xl(e))return"missing-directory";if(!xl(ea(e,ke)))return"unregistered";if(!xl(ea(e,Iy)))return"incomplete";return}function Tl(e,t,n,r){let o=n==="incomplete"?"Run hydra legacy update to restore its runner files":`Drop its record with hydra legacy remove <profile> ${e}, then run hydra legacy create; hydra legacy reconcile deletes a leftover GitHub registration`;return new b(`Cannot ${r} runner ${e}: ${$0[n]} (${t})`,o,void 0,{tag:"RunnerNotProvisioned"})}async function Ny(e,t){let n=_l(t);if(n)throw Tl(e,t,n,"start");let r=await Qi(t,await Ut());if(r.kind==="alive")return"running";if(r.kind!=="absent")await Hy(t);let o=await v0(e,t);return await b0(ea(t,jr),String(o)),"started"}async function Dy(e,t){let n=await Qi(t,await Ut());if(n.kind==="absent")return"not-running";if(n.kind!=="alive")return await Hy(t),n.kind==="recycled"?"stale-pid":"not-running";if(k0(e,n.pid),await kl(t,n.pid)==="stopped")return"stopped";throw new b(`Runner ${e} is still shutting down`,`Hydra sent SIGTERM to pid ${n.pid} and its process group, which cancels a running job; check it with hydra legacy status and retry`,void 0,{tag:"RunnerStillStopping"})}async function Ly(e,t){let n=await Qi(e,t);return n.kind==="alive"?n.pid:void 0}function My(e,t){return Cy(e,t)}async function v0(e,t){try{let n=g0("bash",[`./${Iy}`],{cwd:w0(t),detached:!0,env:E0(process.env),stdio:"ignore"});if(await h0(n,"spawn"),n.pid===void 0)throw Error("the process has no pid");return n.unref(),n.pid}catch(n){throw new b(`Cannot start runner ${e} in ${t}`,"Check that bash is installed",void 0,{cause:n,tag:"RunnerStartFailed"})}}function k0(e,t){for(let n of[-t,t])try{process.kill(n,"SIGTERM");return}catch(r){let o=r.code;if(o==="ESRCH")continue;throw new b(`Cannot signal runner ${e} (pid ${t}): ${o??r.message}`,"Nothing was stopped; check who owns that process",void 0,{cause:r,tag:"RunnerSignalRefused"})}}async function Hy(e){await y0(ea(e,jr)).catch(()=>{return})}var x0=/(?:^|\/)github\/([^/]+)\/externals$/;function Vr(e){return e.match(x0)?.[1]??null}import{stripVTControlCharacters as _0}from"util";var T0=10,A0="[redacted]";function ta({stderr:e,stdout:t},n=[]){let r=[e.toString(),t.toString()].map(C0).find((s)=>s.length>0);if(!r)return;let o=r.split(`
243
+ `).slice(-T0).join(`
244
+ `);return n.filter(Boolean).reduce((s,i)=>s.replaceAll(i,A0),o)}function C0(e){return _0(e).trim()}var jy="actions/runner",F0={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},Al=["bin"],Cl=["externals"],U0=5000,j0=50,B0="ACTIONS_RUNNER_INPUT_TOKEN",V0=/^\d+\.\d+\.\d+$/,q0=/^v/,K0=N({token:fl}),W0=N({tag_name:I()}),J0={app:pl,gh:"Check the gh login with gh auth status"},Y0={"registration-token":"Mint a runner registration token","remove-token":"Mint a runner removal token"};class Ol{profile;sharedDir;github;sharedPath=null;constructor(e,t,n){this.profile=e;this.sharedDir=t;this.github=n}async download(){let e=F0[this.profile.os],t=await this.getLatestVersion(),n=me(this.sharedDir,"github",t);if(await this.isCompleteDownload(n))return this.sharedPath=n,{path:n,version:t};let r=me(this.sharedDir,"github");await na(r,{recursive:!0});let o=await I0(me(this.sharedDir,`.github-${t}-`)),s=`actions-runner-${e}-${t}.tar.gz`,i=me(o,s),a=`https://github.com/${jy}/releases/download/v${t}/${s}`;try{if(await By(Bun.$`curl --fail --silent --show-error --location -o ${i} ${a}`.quiet().nothrow(),`Download actions/runner v${t} from ${a}`,"RunnerDownloadFailed"),await By(Bun.$`tar xzf ${i} -C ${o}`.quiet().nothrow(),`Unpack ${s}`,"RunnerDownloadFailed"),await H0(i),!await this.isCompleteDownload(o))throw new b(`Runner v${t} archive is incomplete`);await this.publishDownload(o,n,t)}finally{await Zn(o,{force:!0,recursive:!0})}return this.sharedPath=n,{path:n,version:t}}async create(e){let t=an(this.profile.jobHooks),n=await this.ensureDownloaded(),r=[];for(let o of e){let s=this.runnerDirectory(o);if(xn(s))throw new b(`Runner directory already exists: ${s}`,"Remove or recover this runner before creating it again");try{await this.setupRunnerDir(n,s),await this.registerRunner(s,o,t)}catch(i){if(!xn(me(s,".runner")))await Zn(s,{force:!0,recursive:!0});throw i}r.push({directory:s,id:o,name:o,status:"registered"})}return r}async remove(e){for(let t of e){let n=this.runnerDirectory(t.id);if(!xn(me(n,ke))){await this.refuseListedRegistration(t),await this.stop([t.id]);continue}let r=await this.fetchRemovalToken(n);await this.stop([t.id]);let o=await Bun.$`bash ./config.sh remove`.cwd(n).env(Vy(r)).quiet().nothrow();if(o.exitCode!==0)throw new b(`Failed to deregister runner ${t.id}`,ta(o,[r])??"Runner files have been preserved; retry removal",void 0,{tag:"RunnerDeregistrationFailed"})}}async start(e){let t=[];for(let n of e)t.push(await Ny(n,this.runnerDirectory(n)));return t}async stop(e){let t=[];for(let n of e)t.push(await Dy(n,this.runnerDirectory(n)));return t}async busy(e){return My(this.runnerDirectory(e),await Ut())}registered(e){return xn(me(this.runnerDirectory(e),ke))}async list(){let e=this.profile.directory;if(!xn(e))return[];let t=await Gy(e,{withFileTypes:!0}),n=await Ut(),r=[];for(let o of t){if(!o.isDirectory())continue;let s=me(e,o.name);r.push(await this.getRunnerStatus(s,o.name,n))}return r}async currentVersion(e){return this.detectVersion(this.runnerDirectory(e))}async logFiles(e){return Xi(me(this.runnerDirectory(e),Yi))}async update(e){let t=an(this.profile.jobHooks),n=await this.ensureDownloaded();for(let r of e){let o=this.runnerDirectory(r),s=_l(o);if(s==="missing-directory"||s==="unregistered")throw Tl(r,o,s,"update");await this.removeRunnerBinaries(o),await this.setupRunnerDir(n,o),await Ji(o,t)}}async configureJobHooks(e){let t=an(this.profile.jobHooks),n=this.runnerDirectory(e);if(!xn(me(n,ke)))return{envChanged:!1,scriptsChanged:!1};return Ji(n,t)}async getRunnerStatus(e,t,n){let{agentId:r,name:o}=await Qn(e),s=await Ly(e,n),i=xn(me(e,ke)),a=s!==void 0?"running":i?"registered":"unknown",c=s!==void 0?await this.readStartTime(e):void 0;return{agentId:r,directory:e,id:t,name:o,pid:s,startedAt:c,status:a}}runnerDirectory(e){let t=ra(this.profile.directory),n=ra(t,e),r=G0(t,n);if(r===""||r.startsWith(`..${Uy}`)||r===".."||r.includes(Uy))throw new b(`Runner id ${JSON.stringify(e)} leaves the runners directory ${t}`,"Repair config.json",void 0,{tag:"RunnerIdInvalid"});return me(this.profile.directory,e)}async refuseListedRegistration(e){let t=de(e.url||this.profile.url),n=Xo(this.github.credentials.kind,t),{agentId:r}=e,o=(e.name||e.id).toLowerCase(),s=r===void 0?(await this.guard(n,()=>Ht(this.github.client,t))).find((i)=>i.name.toLowerCase()===o):await this.guard(n,()=>Gt(this.github.client,t,r));if(!s)return;throw new b(`Runner ${e.id} has no .runner file here, but GitHub still lists it as id ${s.id}`,"Its record is kept; run hydra legacy reconcile to delete the registration once it is offline, then run hydra legacy remove again",void 0,{tag:"RunnerStillRegistered"})}async guard(e,t){try{return await t()}catch(n){throw n instanceof Re?new b(n.message,e):n}}async ensureDownloaded(){if(this.sharedPath)return this.sharedPath;let{path:e}=await this.download();return e}async isCompleteDownload(e){try{return(await Promise.all(["bin","externals","config.sh","run.sh"].map((n)=>Fy(me(e,n))))).every((n,r)=>r<Al.length+Cl.length?n.isDirectory():n.isFile())}catch(t){if(t.code==="ENOENT")return!1;throw t}}async publishDownload(e,t,n){let r=me(this.sharedDir,`.github-${n}.lock`),o=Date.now()+U0;while(!0)try{await na(r);break}catch(s){if(s.code!=="EEXIST")throw s;if(Date.now()>=o)throw new b(`Runner download is locked: ${r}`,"Retry after other Hydra downloads finish; remove a stale lock only when no download is running");await Bun.sleep(j0)}try{if(await this.isCompleteDownload(t))return;await Zn(t,{force:!0,recursive:!0}),await L0(e,t)}finally{await Zn(r,{force:!0,recursive:!0})}}async setupRunnerDir(e,t){await na(t,{recursive:!0});for(let n of Al)await this.hardLinkDir(me(e,n),me(t,n));for(let n of Cl){let r=ra(e,n),o=me(t,n);if(!xn(o))await M0(r,o)}for(let n of["*.sh","*.sh.template"]){let r=await Array.fromAsync(new Bun.Glob(n).scan(e));for(let o of r)await O0(me(e,o),me(t,o))}}async registerRunner(e,t,n){let r=await this.fetchRegistrationToken(),o=["--url",this.profile.url,"--name",t,"--unattended","--disableupdate"];if(this.profile.labels)o.push("--labels",this.profile.labels);if(this.profile.runnerGroup)o.push("--runnergroup",this.profile.runnerGroup);let s=await Bun.$`bash ./config.sh ${o}`.cwd(e).env(Vy(r)).quiet().nothrow();if(s.exitCode!==0){let i=ta(s,[r]);throw new b(`Failed to register runner ${t} with ${this.profile.url}${this.profile.runnerGroup?` in runner group ${this.profile.runnerGroup}`:""}`,[i,"The partial runner directory was removed"].filter(Boolean).join(`
245
+ `),void 0,{tag:"RunnerRegistrationFailed"})}await Ji(e,n)}async fetchRegistrationToken(){return this.fetchRunnerToken(de(this.profile.url),"registration-token")}async fetchRemovalToken(e){let t=await N0(me(e,".runner"),"utf-8"),r=JSON.parse(this.stripBom(t)).gitHubUrl;if(!r)throw Error("Cannot determine GitHub URL from runner config");return this.fetchRunnerToken(de(r),"remove-token")}async fetchRunnerToken(e,t){let n=e.kind==="repo"?`repos/${e.owner}/${e.repo}`:`orgs/${e.org}`,{token:r}=await this.callGitHub({idempotent:!0,method:"POST",operation:`${Y0[t]} for ${De(e)}`,path:`/${n}/actions/runners/${t}`,schema:K0},Xo(this.github.credentials.kind,e));return r}async getLatestVersion(){let{tag_name:e}=await this.callGitHub({operation:"Read the latest runner release",path:`/repos/${jy}/releases/latest`,schema:W0},J0[this.github.credentials.kind]),t=e.replace(q0,"");if(!V0.test(t))throw new b(`The latest runner release has an unexpected tag: ${e}`);return t}async callGitHub(e,t){return this.guard(t,()=>this.github.client.request(e))}pidFilePath(e){return ra(e,".pid")}async readStartTime(e){try{return(await Fy(this.pidFilePath(e))).mtime}catch{return}}async hardLinkDir(e,t){await na(t,{recursive:!0});let n=await Gy(e,{withFileTypes:!0});for(let r of n){let o=me(e,r.name),s=me(t,r.name);if(r.isDirectory())await this.hardLinkDir(o,s);else await P0(o,s)}}async detectVersion(e){try{let t=await D0(me(e,"externals"));return Vr(t)}catch{return null}}async removeRunnerBinaries(e){for(let t of Al)await Zn(me(e,t),{force:!0,recursive:!0});for(let t of Cl)await Zn(me(e,t),{force:!0});for(let t of["*.sh","*.sh.template"]){let n=await Array.fromAsync(new Bun.Glob(t).scan(e));for(let r of n)await Zn(me(e,r),{force:!0})}}stripBom(e){return e.replace(/^\uFEFF/,"")}}async function By(e,t,n){let r=await e;if(r.exitCode===0)return;throw new b(`${t} failed with exit code ${r.exitCode}`,ta(r),void 0,{tag:n})}function Vy(e){return{...process.env,[B0]:e}}import{existsSync as Pl}from"fs";import{readdir as oa,readFile as X0,readlink as z0,rm as Il,stat as Q0}from"fs/promises";import{join as cn,resolve as qy}from"path";var Z0="_work",eI="externals",tI=".pid",nI="github",rI=["runner","worker"],oI=24,Wy=3600000,Ky=10,sI=1,iI=X().map((e)=>Number.isSafeInteger(e)&&e>sI?e:F()),aI=new Set(["EINVAL","ENOENT","ENOTDIR"]);function sa(e){return{auto:e?.auto??Tm,intervalHours:e?.intervalHours??Am,lastRun:e?.lastRun,olderThanDays:e?.olderThanDays??li,targets:e?.targets??Cm}}function cI(e,t){return e-t*oI*Wy}function Nl(e,t){if(!e.lastRun)return!0;let n=Date.parse(e.lastRun);if(Number.isNaN(n))return!0;return t-n>=e.intervalHours*Wy}function uI(e,t){let n=Rl(e),r=new Set;for(let o of rI){let s=n.find((i)=>i.type===o);if(s)r.add(s.path)}return n.filter((o)=>!r.has(o.path)&&o.mtime.getTime()<t)}function lI(e,t){let[n]=[...e].sort(yI),r=new Set(t);return e.filter((o)=>o!==n&&!r.has(o))}function ia(e){return Object.values(e).reduce((t,n)=>t+n.freedBytes,0)}async function dI(e){let t;try{t=await X0(cn(e,tI),"utf-8")}catch(r){if(r.code==="ENOENT")return!1;throw r}let n;try{n=iI(Number(t.trim()))}catch{return!1}try{return process.kill(n,0),!0}catch(r){let o=r.code;if(o==="EPERM")return!0;if(o==="ESRCH")return!1;throw r}}async function Dl(e){if(!Pl(e))return 0;let t=await oa(e,{withFileTypes:!0}),n=0;for(let r of t){if(r.isSymbolicLink())continue;let o=cn(e,r.name);if(r.isDirectory()){n+=await Dl(o);continue}if(r.isFile()){let s=await Q0(o);n+=s.size}}return n}async function Ll(e){let t=cI(e.now,e.olderThanDays),n={};for(let r of e.targets)switch(r){case"logs":n.logs=await pI(e.entries,t,e.dryRun);break;case"work":n.work=await fI(e.entries,e.dryRun);break;case"shared":n.shared=await mI(e);break}return n}async function pI(e,t,n){let r={freedBytes:0,removed:0,skipped:[]};for(let o of e){let s=await Xi(cn(o.directory,Yi));for(let i of uI(s,t)){if(!n)await Il(i.path,{force:!0});r.removed++,r.freedBytes+=i.size}}return r}async function fI(e,t){let n={freedBytes:0,removed:0,skipped:[]};for(let r of e){if(await dI(r.directory)){n.skipped.push(r.id);continue}let o=cn(r.directory,Z0);if(!Pl(o))continue;let s=await oa(o);if(s.length===0)continue;if(n.freedBytes+=await Dl(o),n.removed+=s.length,t)continue;for(let i of s)await Il(cn(o,i),{force:!0,recursive:!0})}return n}async function mI({dryRun:e,entries:t,profileDirectories:n,sharedDir:r}){let o={freedBytes:0,removed:0,skipped:[]},s=cn(r,nI);if(!Pl(s))return o;let a=(await oa(s,{withFileTypes:!0})).filter((u)=>u.isDirectory()).map((u)=>u.name),c;try{c=await hI(await gI(t,n))}catch(u){return{...o,error:u.message}}for(let u of lI(a,c)){let l=cn(s,u);if(o.freedBytes+=await Dl(l),o.removed++,!e)await Il(l,{force:!0,recursive:!0})}return o}async function gI(e,t){let n=new Set(e.map((r)=>qy(r.directory)));for(let r of new Set(t.map((o)=>qy(o)))){let o;try{o=await oa(r,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw Error(`cannot read ${r}: ${s.code??s.message}`)}for(let s of o)if(s.isDirectory())n.add(cn(r,s.name))}return[...n]}async function hI(e){let t=[];for(let n of e){let r=cn(n,eI);try{let o=Vr(await z0(r));if(o)t.push(o)}catch(o){let s=o.code;if(s&&aI.has(s))continue;throw Error(`cannot read ${r}: ${s??o.message}`)}}return t}function yI(e,t){let n=e.split(".").map((s)=>Number.parseInt(s,Ky)),r=t.split(".").map((s)=>Number.parseInt(s,Ky)),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){let i=n[s]??0,a=r[s]??0,c=Number.isNaN(i)?0:i,u=Number.isNaN(a)?0:a;if(c!==u)return u-c}return 0}import{readFile as bI}from"fs/promises";var wI=1e4,SI="/etc/resolv.conf",RI=/^\s*nameserver\[\d+\]\s*:\s*(\S+)/gm,$I=/^\s*nameserver\s+(\S+)/gm,EI=/^(?:ip|ipv6)_address:\s*(\S+)/gm,vI=/^(\S+)\s/gm;async function Ml(){let[e,t]=Bun.which("scutil")?[(await Yy(["scutil","--dns"])).output,RI]:[await kI(),$I];return Fl(Xy(e,t))}function Hl(){return Bun.which("dscacheutil")!==null||Bun.which("getent")!==null}async function Jy(e){let[t,n]=Bun.which("dscacheutil")?[["dscacheutil","-q","host","-a","name",e],EI]:[["getent","hosts",e],vI],r=performance.now(),{output:o,timedOut:s}=await Yy(t),i=Math.round(performance.now()-r);return{addresses:Fl(Xy(o,n)),durationMs:i,host:e,timedOut:s}}async function Gl(e){let t=await Promise.all(Fl([...e]).map(Jy));return new Map(t.map((n)=>[n.host,n]))}async function Yy(e){let t=Bun.spawn(e,{stderr:"ignore",stdin:"ignore",stdout:"pipe",timeout:wI}),[n]=await Promise.all([new Response(t.stdout).text(),t.exited]);return{output:n,timedOut:t.signalCode!==null}}async function kI(){try{return await bI(SI,"utf-8")}catch(e){if(e.code==="ENOENT")return"";throw e}}function Xy(e,t){return[...e.matchAll(t)].flatMap((n)=>n[1]?[n[1]]:[])}function Fl(e){return[...new Set(e)]}function ve(e,t){switch(e.provider){case"github":return new Ol(e,wn(ee(t)).shared,Mt(t));default:throw Error(`Runner provider "${e.provider}" is not yet implemented`)}}var Zy=new Set(["missing","outdated"]),xI={configured:{paint:p.green,text:"configured"},foreign:{paint:p.yellow,text:"set to another script"},missing:{paint:p.yellow,text:"missing"},off:{paint:p.dim,text:"off"},outdated:{paint:p.yellow,text:"outdated"}};function eb(e,t){let n=[`${p.bold("Home")} ${e}`];if(t.length===0)return n;n.push(p.yellow("Other Hydra homes, not used by this run:"));for(let r of t){let o=r.counts?`${Qy(r.counts.profiles,"profile")}, ${Qy(r.counts.runners,"runner")}`:"unreadable config";n.push(` ${r.path} ${p.dim(o)}`)}return n.push(p.dim(` Manage one with ${ye} <path> or ${et}=<path>`)),n}function tb(e){let t=[];for(let n of e.dns.lookups??[]){if(n.addresses.length>0)continue;t.push({detail:`${n.host} did not resolve${n.timedOut?" before the lookup timed out":""}`,id:`dns:${e.name}:${n.host}`,status:e.dns.enabled?"fail":"warn"})}for(let n of e.runners){let r=`runner:${e.name}:${n.id}`;if(!n.hooks){t.push({detail:`${n.id} is recorded, but no runner is registered in its directory`,id:r,status:"warn"});continue}let o=[n.hooks.started,n.hooks.completed];if(o.some((s)=>Zy.has(s)))t.push({detail:`${n.id} has missing or outdated job hooks`,id:r,status:"fail"});else if(o.includes("foreign"))t.push({detail:`${n.id} runs another job hook script`,id:r,status:"warn"});if(n.restart)t.push({detail:`${n.id} needs a restart to load its job hooks`,id:r,status:"warn"})}return t}function nb(e){let t=e.dnsServers??[],n=[`${p.bold("DNS servers")} ${t.length>0?t.join(", "):p.dim("unknown")}`];for(let s of e.profiles)n.push("",`${p.bold(s.name)} ${p.dim(s.url)}`,..._I(s));let r=e.profiles.flatMap((s)=>s.runners);if(r.flatMap((s)=>s.hooks?[s.hooks.started,s.hooks.completed]:[]).some((s)=>Zy.has(s)))n.push("",p.yellow(`Run ${p.green("hydra legacy update")} to write the missing hooks.`));if(r.some((s)=>!s.hooks))n.push("",p.yellow(`Drop records marked "no runner here" with ${p.green("hydra legacy remove <profile> <id>")}.`));if(r.some((s)=>s.restart))n.push("",p.yellow('Restart runners marked "restart" once they are idle: hydra legacy halt <profile> && hydra legacy start <profile>'));return n.join(`
246
+ `)}function _I(e){let{dns:t,workspaceCleanup:n}=e,r=[` DNS wait: ${t.enabled?`on, up to ${t.timeoutSeconds} s`:p.dim("off")}`];if(!t.lookups)r.push(p.yellow(" No dscacheutil or getent to look hosts up with"));for(let s of t.lookups??[])r.push(TI(s));let o=n.keepToolCache?"keeps _tool":"empties _tool";if(r.push(` Workspace cleanup: ${n.enabled?`on, ${o}`:p.dim("off")}`),e.runners.length===0)return[...r,p.dim(" No runners.")];return[...r,...e.runners.map(AI)]}function TI({addresses:e,durationMs:t,host:n,timedOut:r}){if(e.length>0)return` ${p.green("\u2713")} ${n} ${p.dim(`${t} ms \xB7 ${e.join(", ")}`)}`;let o=r?`timed out after ${t} ms`:`no address after ${t} ms`;return` ${p.red("\u2717")} ${n} ${p.red(o)}`}function AI(e){if(!e.hooks)return` ${e.id} ${p.yellow("no runner here")}`;return[` ${e.id}`,p.dim(e.status),`DNS wait ${zy(e.hooks.started)}`,`cleanup ${zy(e.hooks.completed)}`,e.restart?p.yellow("restart"):""].filter(Boolean).join(" ")}function zy(e){let{paint:t,text:n}=xI[e];return t(n)}function Qy(e,t){return`${e} ${t}${e===1?"":"s"}`}import{isAbsolute as CI}from"path";class qr extends Error{_tag="AccountLookupError";constructor(e){super(`Could not read this account's directory entry: ${e}`);this.name="AccountLookupError"}}var OI=1e4,PI={darwin:{argv:()=>["/usr/bin/id","-P"],home:8},linux:{argv:()=>["getent","passwd",String(process.getuid?.())],home:5}};function rb(){let e=PI[process.platform];if(!e)throw new qr(`no lookup for ${process.platform}`);let t=Bun.spawnSync(e.argv(),{stderr:"pipe",stdin:"ignore",timeout:OI});if(t.exitCode!==0)throw new qr(t.stderr.toString().trim()||"the lookup failed");let n=t.stdout.toString().trim().split(":"),r=n[0],o=n[e.home];if(!r||!o||!CI(o))throw new qr("it names no user or no absolute home");return{home:o,name:r}}import{lstatSync as CN,readdirSync as ON}from"fs";import{isAbsolute as PN,join as ha}from"path";var er="/opt/hydra",II=`${er}/bin`,ob="/usr/local",Qo=[II,`${ob}/bin`,"/usr/bin","/bin","/usr/sbin","/sbin"],Ul=["--no-env-file","--no-install"],Kr=Xg,tr=vn;function Wr(e=er,t=ob){return{bun:`${e}/bin/bun`,cli:`${e}/lib/hydra/${tr}/dist/cli.js`,containerRoot:t,hydra:`${e}/bin/hydra`,manifest:`${e}/etc/toolchain.sha256`,prefix:e,softnet:`${e}/bin/softnet`,tart:`${e}/bin/tart`}}function jl(e=Wr()){return[e.bun,...Ul,e.cli]}import{isAbsolute as bN}from"path";import{statfsSync as YI}from"fs";import{availableParallelism as XI,freemem as zI,homedir as QI}from"os";var sb=`#!/bin/sh
247
+ set -eu
248
+ . "\${0%/*}/layout"
249
+
250
+ fail() {
251
+ printf 'hydra-guest accept: %s\\n' "$1" >&2
252
+ exit 1
253
+ }
254
+
255
+ umask 077
256
+ "\${0%/*}/ready" >/dev/null 2>&1 || fail "the guest is not waiting for a runner configuration"
257
+ [ ! -e "$HYDRA_RUN_DIR/jit" ] || fail "the guest already holds a runner configuration"
258
+
259
+ line=
260
+ IFS= read -r line || [ -n "$line" ] || fail "standard input holds no runner configuration"
261
+ [ -n "$line" ] || fail "the runner configuration is empty"
262
+ case $line in
263
+ *[!A-Za-z0-9+/=]*) fail "the runner configuration is not one line of base64" ;;
264
+ esac
265
+ extra=
266
+ if IFS= read -r extra || [ -n "$extra" ]; then
267
+ fail "standard input holds more than one line"
268
+ fi
269
+
270
+ staged="$HYDRA_RUN_DIR/jit.$$"
271
+ rm -f "$staged"
272
+ (
273
+ set -C
274
+ printf '%s\\n' "$line" >"$staged"
275
+ ) || fail "could not stage the runner configuration"
276
+ line=
277
+ chmod 0600 "$staged"
278
+ if ! ln "$staged" "$HYDRA_RUN_DIR/jit" 2>/dev/null; then
279
+ rm -f "$staged"
280
+ fail "the guest already holds a runner configuration"
281
+ fi
282
+ rm -f "$staged"
283
+ `;var ib=`#!/bin/bash
284
+ set -euo pipefail
285
+ . "\${0%/*}/layout"
286
+
287
+ fail() {
288
+ printf '::error::Hydra stopped this job: %s\\n' "$1"
289
+ exit 1
290
+ }
291
+
292
+ [ ! -e "$HYDRA_RUN_DIR/jit" ] || fail "the runner configuration is still on the guest"
293
+ (set -C && : >"$HYDRA_STATE_DIR/job-started") 2>/dev/null || fail "this guest has already started a job"
294
+
295
+ workspace=\${GITHUB_WORKSPACE:-}
296
+ if [ -n "$workspace" ] && [ -d "$workspace" ] && [ -n "$(ls -A "$workspace")" ]; then
297
+ fail "the workspace is not empty"
298
+ fi
299
+
300
+ current=$(cd "$HYDRA_RUNNER_HOME" && find . -mindepth 1 | LC_ALL=C sort)
301
+ expected=$(cat "$HYDRA_HOME_MANIFEST")
302
+ [ "$current" = "$expected" ] || fail "the home holds files the image does not"
303
+ `;var ab=`#!/bin/sh
304
+ set -eu
305
+ . "\${0%/*}/layout"
306
+
307
+ fail() {
308
+ printf 'hydra-guest init: %s\\n' "$1" >&2
309
+ exit 1
310
+ }
311
+
312
+ wait_for() {
313
+ limit=$1
314
+ shift
315
+ waited=0
316
+ until "$@"; do
317
+ waited=$((waited + 1))
318
+ [ "$waited" -le "$limit" ] || return 1
319
+ sleep 1
320
+ done
321
+ }
322
+
323
+ has_config() {
324
+ [ -f "$HYDRA_RUN_DIR/jit" ]
325
+ }
326
+
327
+ docker_answers() {
328
+ docker info >/dev/null 2>&1
329
+ }
330
+
331
+ umask 077
332
+ mkdir -p "$HYDRA_RUN_DIR"
333
+ chmod 0711 "$HYDRA_RUN_DIR"
334
+ [ ! -e "$HYDRA_RUN_DIR/jit" ] || fail "a runner configuration arrived before the guest was ready"
335
+
336
+ if [ "$HYDRA_DOCKER" = 1 ]; then
337
+ dockerd --group docker >"$HYDRA_RUN_DIR/dockerd.log" 2>&1 &
338
+ wait_for "$HYDRA_DOCKER_WAIT_SECONDS" docker_answers || fail "dockerd did not answer within $HYDRA_DOCKER_WAIT_SECONDS s"
339
+ fi
340
+
341
+ printf '%s\\n' "$$" >"$HYDRA_RUN_DIR/ready.new"
342
+ mv -f "$HYDRA_RUN_DIR/ready.new" "$HYDRA_RUN_DIR/ready"
343
+
344
+ wait_for "$HYDRA_JIT_WAIT_SECONDS" has_config || fail "no runner configuration arrived within $HYDRA_JIT_WAIT_SECONDS s"
345
+ rm -f "$HYDRA_RUN_DIR/ready"
346
+ jit=
347
+ IFS= read -r jit <"$HYDRA_RUN_DIR/jit" || :
348
+ rm -f "$HYDRA_RUN_DIR/jit"
349
+ [ -n "$jit" ] || fail "the runner configuration is empty"
350
+
351
+ ACTIONS_RUNNER_INPUT_JITCONFIG=$jit HOME=$HYDRA_RUNNER_HOME USER=$HYDRA_RUNNER_USER LOGNAME=$HYDRA_RUNNER_USER \\
352
+ setpriv --reuid="$HYDRA_RUNNER_UID" --regid="$HYDRA_RUNNER_GID" --init-groups --inh-caps=-all --no-new-privs -- \\
353
+ "$HYDRA_RUNNER_DIR/bin/Runner.Listener" run &
354
+ runner=$!
355
+ jit=
356
+ trap 'kill -TERM "$runner" 2>/dev/null || :' TERM INT HUP
357
+
358
+ while :; do
359
+ status=0
360
+ wait "$runner" || status=$?
361
+ kill -0 "$runner" 2>/dev/null || break
362
+ done
363
+ exit "$status"
364
+ `;var cb=`#!/bin/sh
365
+ set -eu
366
+ . "\${0%/*}/layout"
367
+
368
+ fail() {
369
+ printf 'hydra-guest ready: %s\\n' "$1" >&2
370
+ exit 1
371
+ }
372
+
373
+ [ -f "$HYDRA_RUN_DIR/ready" ] || fail "the guest is not waiting for a runner configuration"
374
+ pid=
375
+ IFS= read -r pid <"$HYDRA_RUN_DIR/ready" || :
376
+ case $pid in
377
+ '' | *[!0-9]*) fail "the guest init left no process id" ;;
378
+ esac
379
+ kill -0 "$pid" 2>/dev/null || fail "the guest init is not running"
380
+ `;var jt="/opt/hydra-guest",Zo=`${jt}/init`,ca=`${jt}/accept`,ua=`${jt}/ready`,Bl=`${jt}/canary.sh`,ub=`${jt}/layout`,la=`${jt}/home.manifest`,es="/run/hydra",Vl="/var/lib/hydra-guest",_n="runner",tt=1001,ql=`/home/${_n}`,Tn="/opt/actions-runner",ts="/opt/hostedtoolcache",HI="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",GI=900,FI=120,UI=/^[A-Za-z0-9_./:-]*$/,aa=365,jI=292;function lb(e){return{docker:e,dockerWaitSeconds:FI,homeManifest:la,jitWaitSeconds:GI,path:HI,runDir:es,runnerDir:Tn,runnerGid:tt,runnerHome:ql,runnerUid:tt,runnerUser:_n,stateDir:Vl}}function BI(e){return`${[...[["PATH",e.path],["HYDRA_RUN_DIR",e.runDir],["HYDRA_STATE_DIR",e.stateDir],["HYDRA_RUNNER_DIR",e.runnerDir],["HYDRA_RUNNER_HOME",e.runnerHome],["HYDRA_RUNNER_USER",e.runnerUser],["HYDRA_RUNNER_UID",e.runnerUid],["HYDRA_RUNNER_GID",e.runnerGid],["HYDRA_HOME_MANIFEST",e.homeManifest],["HYDRA_JIT_WAIT_SECONDS",e.jitWaitSeconds],["HYDRA_DOCKER",e.docker?1:0],["HYDRA_DOCKER_WAIT_SECONDS",e.dockerWaitSeconds]].map(([r,o])=>`${r}='${VI(r,String(o))}'`),"export PATH"].join(`
381
+ `)}
382
+ `}function db(e){return[{content:ab,mode:aa,name:"init"},{content:sb,mode:aa,name:"accept"},{content:cb,mode:aa,name:"ready"},{content:ib,mode:aa,name:"canary.sh"},{content:BI(e),mode:jI,name:"layout"}]}function VI(e,t){if(!UI.test(t))throw Error(`Refused guest layout value for ${e}: ${JSON.stringify(t)}`);return t}var Kl="org.r5nlabs.hydra.pool",Wl="org.r5nlabs.hydra.secret-bearing",qI=["SETGID","SETUID"],KI=["AUDIT_WRITE","CHOWN","DAC_OVERRIDE","FOWNER","FSETID","KILL","MKNOD","NET_ADMIN","NET_BIND_SERVICE","NET_RAW","SETFCAP","SETGID","SETPCAP","SETUID","SYS_ADMIN","SYS_CHROOT","SYS_PTRACE"],da="Runner.Listener",pa="Runner.Worker",WI=30,JI='for f in /proc/[0-9]*/comm; do IFS= read -r n <"$f" && printf "%s\\n" "$n"; done 2>/dev/null; exit 0';function pb(e){let{spec:t}=e,n=t.docker?KI:qI;return["create","--name",t.name,"--network",e.network,"--cpus",String(t.cpus),"--memory",`${t.memoryMiB}M`,...e.dns.flatMap((r)=>["--dns",r]),"--label",`${Go}=${e.fleet}`,"--label",`${Kl}=${t.pool}`,"--label",`${Wl}=${t.secretBearing}`,"--cap-drop","ALL",...n.flatMap((r)=>["--cap-add",r]),"--tmpfs",es,...t.foreignArch?["--rosetta"]:[],t.image,Zo]}function fb(e){return["start",e]}function mb(e){return["exec",e,ua]}function gb(e){return["exec","--interactive",e,ca]}function hb(e){return["exec",e,"/bin/sh","-c",JI]}function yb(e){return["stop","--time",String(WI),e]}function bb(e){return["delete","--force",e]}function wb(e){return["logs",e]}var nr="1.7.1",Jl=["1.1.1.1"],Yl=-1,fa="apple-container",ZI=/^[a-z0-9]+$/,eN=/^[A-Za-z0-9][^\s@]*@sha256:[0-9a-f]{64}$/,Rb=1048576,tN=1024*Rb,nN=1000,rN="console.log",oN=/[^\P{Cc}\n\t]/gu;function ma(e={}){let t={...cg,...e.limits},n=ug(e.binary??ag,t),r=e.fleet?sN(n,e.fleet):void 0,o=new Set,s=(w)=>{if(r)return r;throw Error(`The apple-container driver needs a fleet to ${w}`)},i=(w,x)=>{let y=s(x);if(w.driver!==fa||!Bn(w.name,y.prefix))throw new Ce("invalid-name",x,w.name,`it is not a guest of fleet ${y.id}`);return y},a=async(w)=>(await Ir(n)).find((x)=>x.id===w),c=async(w,x,y,R)=>{let A=Date.now()+w;while(!await R()){if(Date.now()>=A)throw new Ce("not-ready",x,y,`no answer within ${w/nN} s`);await Bun.sleep(t.pollMs)}},u=async(w)=>{i(w,"read the state of a guest");let x=await a(w.name);if(!x)return{kind:"gone"};if(x.state==="stopped")return x.started||o.has(w.name)?{code:Yl,kind:"exited"}:{kind:"preparing"};if(x.state!=="running")return{kind:"running"};let y=await n.run("list the processes of",w.name,hb(w.name),{check:!1}),R=y.exitCode===0?y.stdout.split(`
383
+ `).map((A)=>A.trim()):[];return R.includes(da)?{busy:R.includes(pa),kind:"runner-alive"}:{kind:"running"}},l=async(w)=>{let x=await a(w);if(!x)return;if(x.state!=="stopped")await n.run("stop",w,yb(w),{check:!1,timeoutMs:t.stopMs});await n.run("delete",w,bb(w))},d=async(w)=>{let x=s("create a guest"),y={driver:fa,name:w.name,pool:w.pool};if(i(y,"create"),w.guestOs!=="linux")throw new Ce("wrong-guest","create",w.name,"Apple container runs only Linux guests");if(!eN.test(w.image))throw new Ce("refused-config","create",w.name,"the image must be pinned by its sha256 digest");if(n.unavailable())throw new Ce("unavailable","create",w.name,`${Si} container calls in a row timed out; a host check that finds the tool answering lifts this`);let R=await x.pool.take(w.name);try{await n.run("create",w.name,pb({dns:x.dns,fleet:x.id,network:R,spec:w}),{timeoutMs:t.createMs});let A=iN(await a(w.name),R);if(A.length===0)return y;throw await l(w.name),new Ce("refused-config","create",w.name,A.join("; "))}catch(A){throw x.pool.release(w.name),A}},f=async(w)=>{i(w,"start"),await n.run("start",w.name,fb(w.name)),o.add(w.name),await c(t.readyMs,"wait for the guest init of",w.name,async()=>{if((await n.run("check the guest init of",w.name,mb(w.name),{check:!1})).exitCode===0)return!0;if((await a(w.name))?.state==="running")return!1;throw new Ce("not-ready","start",w.name,"the guest stopped before its init was ready")})},m=async(w,x)=>{i(w,"hand the runner configuration to"),await n.run("hand the runner configuration to",w.name,gb(w.name),{stdin:x}),await c(t.runnerMs,"wait for the runner of",w.name,async()=>{let y=await u(w);if(y.kind==="runner-alive")return!0;if(y.kind==="running")return!1;throw new Ce("not-ready","start the runner of",w.name,"the guest stopped first")})},g=async(w)=>{let x=i(w,"destroy");await l(w.name),x.pool.release(w.name),o.delete(w.name)},h=async(w)=>{i(w,"verify the removal of");let y=(await Ir(n)).filter((R)=>R.id===w.name).map((R)=>`container ${R.id} (${R.state})`);return{checked:["container"],leftovers:y}},E=async()=>{let w=s("list its guests");return(await Ir(n)).filter((x)=>x.labels[Go]===w.id&&Bn(x.id,w.prefix)).map((x)=>({driver:fa,name:x.id,pool:x.labels[Kl]??""}))};async function*v(w,x){if(i(w,"read the logs of"),(await a(w.name))?.labels[Wl]!=="false")return;let A=(await n.run("read the logs of",w.name,wb(w.name),{maxOutputChars:x.bytes})).stdout.replace(oN,"");yield{file:rN,text:A.slice(Math.max(0,A.length-x.bytes))}}return{capabilities:()=>Oe[fa].capabilities,capacity:async()=>{let w=s("report its capacity"),x=YI(QI());return{cpus:XI(),diskGiB:Math.floor(x.bavail*x.bsize/tN),guests:(await w.pool.status()).free.length,memoryMiB:Math.floor(zI()/Rb)}},checkHost:async()=>{let w=await Sb(n,nr);if(w.answered)n.recover();return{findings:w.findings}},create:d,destroy:g,health:async()=>{let w=[...(await Sb(n,nr)).findings];if(n.unavailable())w.push(uN());if(r)w.push(...await aN(r.pool));return{findings:w}},list:E,logs:v,networks:()=>s("manage its networks").pool,runJit:m,start:f,state:u,verifyGone:h}}function sN(e,t){if(!ZI.test(t.id))throw Error(`Invalid fleet id "${t.id}"`);let n=t.dns??Jl;if(n.length===0)throw Error("A fleet needs at least one DNS server for its guests");for(let r of n)if(!hi(r))throw Error(`The guest DNS server "${r}" must be a public IPv4 address`);return{dns:n,id:t.id,pool:Rg(e,t.id,t.networks),prefix:`hydra-${t.id}`}}function iN(e,t){if(!e)return["the guest is missing after create"];return[e.unread.length>0?`its configuration does not show ${e.unread.join(", ")}`:"",e.mounts.some((r)=>!r.tmpfs||r.destination!==es)?"it mounts more than its RAM disk":"",e.publishedPorts>0?"it publishes ports":"",e.publishedSockets>0?"it publishes sockets":"",e.ssh?"it forwards the SSH agent":"",e.virtualization?"it has nested virtualisation":"",e.networks.length===1&&e.networks[0]===t?"":`it is not only on ${t}`].filter(Boolean)}async function Sb(e,t){let n;try{n=await mg(e)}catch(o){return{answered:!1,findings:[cN(o,t)]}}let r=[];if(n.cli!==t)r.push({code:"tool-version",detail:`${e.binary} is version ${n.cli??"(unknown)"}; Hydra is pinned to ${t}`,fix:`Install Apple container ${t} from its signed release package`,level:"error"});if(n.services===void 0)r.push({code:"services",detail:"The container services do not answer for this user",fix:"Start them as this user with container system start",level:"error"});else if(n.services!==t)r.push({code:"services-version",detail:`The container services run version ${n.services}; Hydra is pinned to ${t}`,fix:"Restart them with container system stop and container system start once no guest runs",level:"error"});return{answered:!0,findings:r}}async function aN(e){try{return(await e.status()).findings}catch(t){return[{code:"network-pool",detail:t instanceof Error?t.message:String(t),fix:"Check that container network list answers",level:"error"}]}}function cN(e,t){let n=e instanceof Ce?e.reason:"failed",r=e instanceof Error?e.message:String(e);if(n==="missing")return{code:"tool-missing",detail:r,fix:`Install Apple container ${t} from its signed release package`,level:"error"};if(n==="timeout")return{code:"tool-timeout",detail:r,fix:"Check that container system status answers; on macOS 27 container commands can hang while no process holds a pf enable reference",level:"error"};return{code:"tool-failed",detail:r,fix:"Run container system version and fix what it reports",level:"error"}}function uN(){return{code:"unresponsive",detail:`${Si} container calls in a row timed out, so Hydra starts no new guests on this driver`,fix:"Running guests keep their jobs; new guests start again once a host check finds the tool answering",level:"error"}}var ns=["arm64","amd64"];function Xl(e,t,n){let r=`https://nodejs.org/dist/v${e}/node-v${e}`;return{amd64:{sha256:n,url:`${r}-linux-x64.tar.xz`},arm64:{sha256:t,url:`${r}-linux-arm64.tar.xz`},version:e}}var Ve={base:{digest:"sha256:562111b88caa79c71391c0c4d3c2114a7d5c35915c20561fd893cb1e07929e6b",image:"docker.io/library/ubuntu:24.04"},bun:{amd64:{sha256:"94559b3b528995a49452f9f2404cec74f2efd7d06e0a000a8cd214b02c3666eb",url:"https://github.com/oven-sh/bun/releases/download/bun-v1.4.5/bun-linux-x64.zip"},arm64:{sha256:"18656a3bf0ea5641f5796ae4213b75255579a70a0fded2f337933785568cdf84",url:"https://github.com/oven-sh/bun/releases/download/bun-v1.4.5/bun-linux-aarch64.zip"},version:"1.4.5"},docker:{codename:"noble",key:{sha256:"1500c1f56fa9e26b9b8f42452a553675796ade0807cdce11975eb98170b3a570",url:"https://download.docker.com/linux/ubuntu/gpg"},packages:{"containerd.io":"2.4.2-4~ubuntu.24.04~noble","docker-buildx-plugin":"0.39.1-1~ubuntu.24.04~noble","docker-ce":"5:29.10.1-1~ubuntu.24.04~noble","docker-ce-cli":"5:29.10.1-1~ubuntu.24.04~noble"},repository:"https://download.docker.com/linux/ubuntu"},node:[Xl("22.23.5","2babb9eb5264860d540849f4b064a6fbdebcdc323657d9d382ce23d313fd5e09","cdeb8670a0c81f51b4dc4ac61919f9b1ad917b304bf8221eb939570663d240f8"),Xl("24.22.3","6e51a2ada00f0011cc266f65d98922b403d7ad88f809ca2aa615a5fe1ce6e86c","4f2b175a6d53a5c617a80dba2676238a0688cef28c6da4eba35c7d844e66fcfb"),Xl("26.13.1","89e1853138db51e8b82d3e98ba9c0d3f2956a28e5e55ea1b7e12d25aae92d5dd","5c063e46bab0fbc1c17cc445d7ff129cbdcd0471be6ed83b6ab864f8143bc864")],runner:{amd64:{sha256:"baebf204307bac6193480852732f0aba2ae97b6c5597c244f4d5558390147c40",url:"https://github.com/actions/runner/releases/download/v2.338.2/actions-runner-linux-x64-2.338.2.tar.gz"},arm64:{sha256:"670adb2f268fe21dcbb58b3db0e0aa9d5b3bddfe2c651481336e561ff86de945",url:"https://github.com/actions/runner/releases/download/v2.338.2/actions-runner-linux-arm64-2.338.2.tar.gz"},version:"2.338.2"}},$b={sha256:"25a065af409ffa317ab4d5a3b614dd15fc9c40f2172bc1b35a1b1258e919a388",url:"https://github.com/actions/runner/releases/download/v2.338.2/actions-runner-osx-arm64-2.338.2.tar.gz"};function Eb(e){return ns.includes(e)}class ga extends Error{integrity;_tag="IntegrityError";constructor(e){super(`"${e}" is not an npm sha512 integrity value`);this.integrity=e;this.name="IntegrityError"}}var _b="Developer ID Installer: Apple Inc. - Containerization (UPBK2H6LZM)",vb=Ve.bun.version,kb="2.42.0",xb="0.26.0",lN="https://registry.npmjs.org",dN=64,pN=/^sha512-([A-Za-z0-9+/]{86}==)$/,fN={algorithm:"sha256",digest:"b5d6bc2e13caf14e57c89661e89efd073ff16165b41bfe43882616410609cd10",file:"bun-darwin-aarch64.zip",url:`https://github.com/oven-sh/bun/releases/download/bun-v${vb}/bun-darwin-aarch64.zip`,version:vb},mN={algorithm:"sha256",digest:"b6739caf3d47ca53a78f1a7edf32521420a75c7941838c3cefa75f30b80f5a97",file:`container-${nr}-installer-signed.pkg`,url:`https://github.com/apple/container/releases/download/${nr}/container-${nr}-installer-signed.pkg`,version:nr},gN={algorithm:"sha256",digest:"a95dda214b5f676298430d665a8174992e6b300dd20c653385b60481ae819ddf",file:"tart.tar.gz",url:`https://github.com/openai/tart/releases/download/${kb}/tart.tar.gz`,version:kb},hN={algorithm:"sha256",digest:"8469759f9cdfaaba52a150b629877985129308461702bc074c3ad7727837db82",file:"softnet.tar.gz",url:`https://github.com/openai/softnet/releases/download/${xb}/softnet.tar.gz`,version:xb};function Tb(e){let n=`${Kr.split("/").pop()}-${tr}.tgz`;return{bun:fN,container:mN,hydra:{algorithm:"sha512",digest:yN(e),file:n,url:`${lN}/${Kr}/-/${n}`,version:tr},softnet:hN,tart:gN}}function yN(e){let t=pN.exec(e.trim()),n=t?Buffer.from(t[1],"base64"):void 0;if(!n||n.length!==dN)throw new ga(e);return n.toString("hex")}function Ab(e){return Object.values(e).map((t)=>`${t.file} ${t.algorithm} ${t.digest} ${t.url}
384
+ `).join("")}class Jr extends Error{option;_tag="InstallScriptError";constructor(e,t){super(`${e} ${t}`);this.option=e;this.name="InstallScriptError"}}var xt="com.apple.quarantine",wN=/^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/,SN=/\p{Cc}/u,RN=new Set(["wheel","admin","staff","everyone"]),$N="/usr/bin:/bin:/usr/sbin:/sbin",zl="tar --no-same-owner --no-same-permissions -xzf",EN={sha256:256,sha512:512};function gt(e){return`'${e.replaceAll("'","'\\''")}'`}function vN(e){if(!bN(e.stage)||SN.test(e.stage))throw new Jr("--stage","must be an absolute path without control characters");if(!wN.test(e.group))throw new Jr("--group","must be a group name");if(RN.has(e.group))throw new Jr("--group",`must be the group of the fleet account that runs macOS VMs, not ${e.group}, which would let every member run softnet as root`)}function kN(e=Wr()){let t=[e.bun,...Ul,e.cli].map(gt).join(" ");return["#!/bin/sh","set -eu",'if [ "$(/usr/bin/id -u)" = 0 ]; then',' echo "hydra: run hydra as a fleet account; the host daemon runs from its LaunchDaemon" >&2'," exit 1","fi","home=$(/usr/bin/id -P | /usr/bin/cut -d : -f 9)",'case "$home" in'," /*) ;;",' *) echo "hydra: this account has no home directory in its directory entry" >&2; exit 1 ;;',"esac","cd /",`exec /usr/bin/env -i PATH=${gt(Qo.join(":"))} HOME="$home" HYDRA_HOME="$home/.hydra" TART_NO_AUTO_PRUNE=1 TERM="\${TERM:-dumb}" ${t} "$@"`,""].join(`
385
+ `)}function Cb(e,t=Wr()){vN(e);let{bun:n,container:r,hydra:o,softnet:s,tart:i}=e.pins,a=t.prefix,c=`"$work/${r.file}"`;return["#!/bin/sh","set -eu","umask 022",`PATH=${$N}`,"export PATH","cd /","",`prefix=${gt(a)}`,`stage=${gt(e.stage)}`,`group=${gt(e.group)}`,`container_root=${gt(t.containerRoot)}`,"",'fail() { echo "hydra toolchain: $*" >&2; exit 1; }',"","trusted_dir() {",' [ -e "$1" ] || return 0',' { [ -d "$1" ] && [ ! -L "$1" ]; } || fail "$1 is not a directory"',' [ "$(stat -f %u "$1")" = 0 ] || fail "$1 is not owned by root"',' case "$(stat -f %03Lp "$1")" in',' ?[2367]? | ??[2367]) fail "$1 is writable by its group or by other users" ;;'," esac","}","","take() {",' file="$stage/$1"',' { [ -f "$file" ] && [ ! -L "$file" ]; } || fail "$file is missing or not a regular file"',` if xattr -p ${xt} "$file" >/dev/null 2>&1; then`,` fail "$file carries ${xt}; download it again with curl and check where it came from"`," fi",' cat "$file" > "$work/$1"',' actual=$(shasum -a "$3" "$work/$1" | cut -d " " -f 1)',' [ "$actual" = "$2" ] || fail "$1 has SHA-$3 $actual, expected $2"',"}","",'[ "$(id -u)" = 0 ] || fail "run this script as root"','{ [ "$(uname -s)" = Darwin ] && [ "$(uname -m)" = arm64 ]; } || fail "this toolchain is for macOS on Apple silicon"','dscl . -read "/Groups/$group" PrimaryGroupID >/dev/null 2>&1 || fail "the group $group does not exist"','{ [ -d "$stage" ] && [ ! -L "$stage" ]; } || fail "$stage is not a directory"','for dir in / /opt "$prefix" "$prefix/bin" "$prefix/lib" "$prefix/etc" "$container_root" "$container_root/bin"; do trusted_dir "$dir"; done',"",'install -d -o root -g wheel -m 0755 "$prefix" "$prefix/bin" "$prefix/lib" "$prefix/lib/hydra" "$prefix/etc"','work=$(mktemp -d "$prefix/.install.XXXXXX")',`trap 'rm -rf "$work"' EXIT`,"",...[n,r,i,s,o].map((u)=>`take ${gt(u.file)} ${u.digest} ${EN[u.algorithm]}`),"",`echo "Checking the signature of Apple container ${r.version}"`,`pkgutil --check-signature ${c} > "$work/signature" || fail "${r.file} is not validly signed"`,`grep -q -F 'signed by a developer certificate issued by Apple for distribution' "$work/signature" || fail "${r.file} is not signed for distribution"`,`grep -q -F ${gt(_b)} "$work/signature" || fail "${r.file} is not signed by Apple's container team"`,"",`echo "Installing Bun ${n.version}"`,'mkdir "$work/bun"',`unzip -q "$work/${n.file}" -d "$work/bun"`,'install -o root -g wheel -m 0755 "$work/bun/bun-darwin-aarch64/bun" "$prefix/bin/bun"',"",`echo "Installing hydra ${o.version}"`,'mkdir "$work/hydra"',`${zl} "$work/${o.file}" -C "$work/hydra"`,'[ -f "$work/hydra/package/dist/cli.js" ] || fail "the hydra package holds no dist/cli.js"',`rm -rf "$prefix/lib/hydra/${o.version}"`,`mv "$work/hydra/package" "$prefix/lib/hydra/${o.version}"`,`cat > "$work/wrapper" <<'HYDRA_WRAPPER'`,kN(t).trimEnd(),"HYDRA_WRAPPER",'install -o root -g wheel -m 0755 "$work/wrapper" "$prefix/bin/hydra"',"",`echo "Installing Tart ${i.version}"`,'mkdir "$work/tart"',`${zl} "$work/${i.file}" -C "$work/tart"`,'[ -x "$work/tart/tart.app/Contents/MacOS/tart" ] || fail "the Tart archive holds no tart.app"','rm -rf "$prefix/tart.app"','mv "$work/tart/tart.app" "$prefix/tart.app"','ln -sfh "$prefix/tart.app/Contents/MacOS/tart" "$prefix/bin/tart"',"",'chown -R root:wheel "$prefix/bin" "$prefix/lib" "$prefix/etc" "$prefix/tart.app"','chmod -R go-w "$prefix/bin" "$prefix/lib" "$prefix/etc" "$prefix/tart.app"','chmod -R -N "$prefix" 2>/dev/null || true',"",`echo "Installing softnet ${s.version} for the group $group"`,'mkdir "$work/softnet"',`${zl} "$work/${s.file}" -C "$work/softnet"`,'{ [ -f "$work/softnet/softnet" ] && [ ! -L "$work/softnet/softnet" ]; } || fail "the softnet archive holds no softnet"','install -o root -g "$group" -m 4750 "$work/softnet/softnet" "$prefix/bin/softnet"',"",`echo "Installing Apple container ${r.version}"`,`installer -pkg ${c} -target /`,"",`if find "$prefix" -xattrname ${xt} | grep -q .; then fail "a file under $prefix carries ${xt}"; fi`,"",'echo "Recording checksums in $prefix/etc/toolchain.sha256"',"{",' find "$prefix/bin" "$prefix/lib" "$prefix/tart.app" -type f -exec shasum -a 256 {} +',` pkgutil --payload-files ${c} | sed -n 's|^\\./||p' | while IFS= read -r entry; do`,' path="$container_root/$entry"',' if [ -f "$path" ] && [ ! -L "$path" ]; then shasum -a 256 "$path"; fi'," done",'} > "$work/manifest"','install -o root -g wheel -m 0644 "$work/manifest" "$prefix/etc/toolchain.sha256"',"",'for dir in / /opt "$prefix" "$prefix/bin" "$prefix/lib" "$prefix/etc" "$container_root" "$container_root/bin"; do trusted_dir "$dir"; done',`echo "Installed. Run ${t.hydra} toolchain verify as each fleet's account."`,""].join(`
386
+ `)}class rs extends Error{key;_tag="PlistValueError";constructor(e){super(`The launchd property ${e} holds a control character or a value a property list cannot carry`);this.key=e;this.name="PlistValueError"}}var xN=['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">'],Ob=" ",_N=/\p{Cc}/u,TN={'"':"&quot;","&":"&amp;","'":"&apos;","<":"&lt;",">":"&gt;"};function Zl(e){return[...xN,...Pb(e,"",""),"</plist>",""].join(`
387
+ `)}function Pb(e,t,n){let r=`${t}${Ob}`,o=[`${t}<dict>`];for(let[s,i]of Object.entries(e)){let a=n?`${n}.${s}`:s;o.push(`${r}<key>${Ql(s,a)}</key>`,...AN(i,r,a))}return o.push(`${t}</dict>`),o}function AN(e,t,n){if(typeof e==="boolean")return[`${t}<${e}/>`];if(typeof e==="number"){if(!Number.isSafeInteger(e))throw new rs(n);return[`${t}<integer>${e}</integer>`]}if(typeof e==="string")return[`${t}<string>${Ql(e,n)}</string>`];if(Array.isArray(e))return[`${t}<array>`,...e.map((r)=>`${t}${Ob}<string>${Ql(r,n)}</string>`),`${t}</array>`];return Pb(e,t,n)}function Ql(e,t){if(_N.test(e))throw new rs(t);return e.replace(/["&'<>]/g,(n)=>TN[n])}class ya extends Error{option;_tag="ServiceOptionError";constructor(e,t){super(`${e} ${t}`);this.option=e;this.name="ServiceOptionError"}}var ed="org.r5nlabs.hydra",Ib=`${ed}.host`,Lb="/Library/LaunchDaemons",Nb="/var/log/hydra-host.log",IN="serve.log",NN="/var/root",DN=0,Mb=30,LN=30,MN=60,Db=90,HN=18,GN=63,FN=18,UN="/usr/bin/xattr",jN=1e4,BN="/usr/bin:/bin:/usr/sbin:/sbin",VN=/\p{Cc}/u;function qN(e){return`${ed}.fleet.${e}`}function Hb(e={}){let t=e.budget===void 0?[]:["--budget",os("--budget",e.budget)],n={Label:Ib,ProgramArguments:[...jl(),"host","serve",...t],EnvironmentVariables:{HOME:NN,PATH:Qo.join(":")},WorkingDirectory:"/",Umask:HN,RunAtLoad:!0,KeepAlive:!0,ThrottleInterval:Mb,ExitTimeOut:LN,AbandonProcessGroup:!1,StandardOutPath:Nb,StandardErrorPath:Nb};return{label:Ib,plist:Zl(n)}}function Gb(e){let t=os("the Hydra home",e.home),n=e.socket===void 0?[]:["--socket",os("--socket",e.socket)],r=qN(e.fleet),o=ha(t,IN),s={Label:r,UserName:e.account,ProgramArguments:[...jl(),"serve",...n],EnvironmentVariables:{HOME:os("the account's home directory",e.accountHome),HYDRA_HOME:t,PATH:Qo.join(":"),TART_NO_AUTO_PRUNE:"1"},WorkingDirectory:"/",Umask:GN,RunAtLoad:!0,KeepAlive:!0,ThrottleInterval:Mb,ExitTimeOut:MN,AbandonProcessGroup:!0,StandardOutPath:o,StandardErrorPath:o};return{label:r,plist:Zl(s)}}function Fb(e){let t=os("--stage",e.stage),{label:n,plist:r}=e.service,o=`${n}.plist`,s=new Bun.CryptoHasher("sha256").update(r).digest("hex");return["#!/bin/sh","set -eu","umask 022",`PATH=${BN}`,"export PATH","cd /","",`label=${gt(n)}`,`staged=${gt(ha(t,o))}`,`target=${gt(ha(Lb,o))}`,`expected=${s}`,"",'fail() { echo "hydra service: $*" >&2; exit 1; }',"",'[ "$(id -u)" = 0 ] || fail "run this script as root"','{ [ -f "$staged" ] && [ ! -L "$staged" ]; } || fail "$staged is missing or not a regular file"',`if xattr -p ${xt} "$staged" >/dev/null 2>&1; then`,` fail "$staged carries ${xt}, and launchd refuses to load such property lists"`,"fi","work=$(mktemp -d /tmp/hydra-service.XXXXXX)",`trap 'rm -rf "$work"' EXIT`,'cat "$staged" > "$work/plist"','actual=$(shasum -a 256 "$work/plist" | cut -d " " -f 1)','[ "$actual" = "$expected" ] || fail "$staged has SHA-256 $actual, but hydra service print rendered $expected"','plutil -lint -s "$work/plist" || fail "$staged is not a valid property list"',"",'if launchctl print "system/$label" >/dev/null 2>&1; then',' echo "Stopping $label"',' launchctl bootout "system/$label" || fail "launchctl could not stop $label"'," waited=0",' while launchctl print "system/$label" >/dev/null 2>&1; do',` [ "$waited" -lt ${Db} ] || fail "$label did not stop within ${Db} s"`," sleep 1"," waited=$((waited + 1))"," done","fi",'install -o root -g wheel -m 0644 "$work/plist" "$target"',`if xattr -p ${xt} "$target" >/dev/null 2>&1; then fail "$target carries ${xt}"; fi`,'launchctl bootstrap system "$target"','echo "Loaded $label from $target"',""].join(`
388
+ `)}async function Ub(e={}){let t=e.directory??Lb,n=e.owners??[DN],r=e.quarantined??KN,o;try{o=ON(t).filter((i)=>i.startsWith(`${ed}.`)&&i.endsWith(".plist"))}catch{return[]}let s=[];for(let i of o.sort()){let a=ha(t,i),c=CN(a),u="Install it again with the script from hydra service print --script";if(!c.isFile())s.push({detail:"is not a regular file",fix:"Install it again with the script from hydra service print --script",path:a});else if(!n.includes(c.uid))s.push({detail:`is owned by uid ${c.uid}, not root`,fix:"Install it again with the script from hydra service print --script",path:a});else if((c.mode&FN)!==0)s.push({detail:"is writable by its group or by other users",fix:"Install it again with the script from hydra service print --script",path:a});if(c.isFile()&&await r(a))s.push({detail:`carries ${xt}, so launchd will not load it`,fix:"Install it again with the script from hydra service print --script",path:a})}return s}async function KN(e){if(process.platform!=="darwin")return!1;return await Bun.spawn([UN,"-p",xt,e],{stderr:"ignore",stdin:"ignore",stdout:"ignore",timeout:jN}).exited===0}function os(e,t){if(PN(t)&&!VN.test(t))return t;throw new ya(e,"must be an absolute path without control characters")}import{lstatSync as WN,readdirSync as JN,readFileSync as YN,readlinkSync as XN,realpathSync as zN}from"fs";import{dirname as jb,isAbsolute as QN,join as ss}from"path";var ZN=0,eD=18,tD=4095,nD=2536,rD=/^([0-9a-f]{64}) [ *](\/.*)$/,oD=8,sD=32,Yr="Run the install script from hydra toolchain print --script again";async function Bb(e={}){let t=e.layout??Wr(),n=dD(e.owners??[ZN]),r=yD(t.manifest);if(r===void 0)return{files:0,findings:[],installed:!1,manifest:t.manifest,unreadable:[]};n.check(t.manifest),n.findings.push(...r.problems);for(let i of aD(t))if(!r.entries.has(i))n.findings.push({detail:"is not in the recorded checksums",fix:Yr,path:i});let{files:o,unreadable:s}=await cD(r.entries,n);uD(t.softnet,n);for(let i of e.pathDirs??iD(t))lD(i,n);return{files:o,findings:wD(n.findings),installed:!0,manifest:t.manifest,unreadable:s}}function iD(e){return[ss(e.prefix,"bin"),ss(e.containerRoot,"bin")]}function aD(e){return[e.hydra,e.bun,e.softnet,gD(e.tart)??e.tart,e.cli,ss(e.containerRoot,"bin","container")]}async function cD(e,t){let n=0,r=[];for(let[o,s]of e){if(t.check(o),!ba(o)?.isFile()){t.findings.push({detail:"is missing or no longer a regular file",fix:Yr,path:o});continue}let a=await bD(o).catch((c)=>c);if(a instanceof Error){if(a.code==="EACCES")r.push(o);else t.findings.push({detail:`cannot be read (${a.message})`,fix:Yr,path:o});continue}if(a===s){n+=1;continue}t.findings.push({detail:`has SHA-256 ${a}, but ${s} was recorded at install`,fix:`Find out who changed it, then ${Yr.toLowerCase()}`,path:o})}return{files:n,unreadable:r}}function uD(e,t){let n=ba(e);if(!n?.isFile())return;let r=n.mode&tD;if(t.owners.includes(n.uid)&&r===nD)return;t.findings.push({detail:`is owned by uid ${n.uid} with mode ${r.toString(oD).padStart(4,"0")}; Tart needs it setuid root and runnable only by its group (4750)`,fix:"chown root:<the fleet's group> and chmod 4750 it, as the install script does",path:e})}function lD(e,t){t.check(e);let n;try{n=JN(e)}catch{return}for(let r of n)t.check(ss(e,r))}function dD(e){let t=[],n=new Map,r=(s,i)=>{let a=n.get(s);if(a!==void 0)return a;let c=ba(s),u=c?fD(c,e):void 0;if(u)t.push({detail:i?`${u} (reached from ${i})`:u,fix:mD(s),path:s});return n.set(s,u===void 0),u===void 0};return{check:(s)=>{let i=[],{end:a,links:c}=pD(s,i),u=new Set(Vb(s)),l=i.some((d)=>!u.has(d))?s:void 0;for(let d of i)r(d,u.has(d)?void 0:l);if(a==="loop")t.push({detail:"leads through too many links",fix:"Remove the link",path:s});if(a==="missing"&&c>0)t.push({detail:"leads through a link to a missing file",fix:"Remove the link",path:s})},findings:t,owners:e}}function pD(e,t){let n=e.split("/").filter(Boolean),r="/",o=0;t.push(r);while(n.length>0){let s=n.shift();if(s==="."||s===".."){r=s===".."?jb(r):r;continue}let i=ss(r,s),a=ba(i);if(!a)return{end:"missing",links:o};if(t.push(i),!a.isSymbolicLink()){r=i;continue}if(o+=1,o>sD)return{end:"loop",links:o};let c=hD(i);if(c===void 0)return{end:"missing",links:o};r=QN(c)?"/":r,n.unshift(...c.split("/").filter(Boolean))}return{end:"found",links:o}}function fD(e,t){if(!t.includes(e.uid))return`is owned by uid ${e.uid}, not root`;if(e.isSymbolicLink())return;return(e.mode&eD)===0?void 0:"is writable by its group or by other users"}function mD(e){return`Make ${e} owned by root and writable only by root, or move it out of the path Hydra runs from`}function Vb(e){let t=jb(e);return t===e?[e]:[...Vb(t),e]}function gD(e){try{return zN(e)}catch{return}}function hD(e){try{return XN(e)}catch{return}}function ba(e){try{return WN(e)}catch{return}}function yD(e){let t;try{t=YN(e,"utf-8")}catch(o){if(o.code==="ENOENT")return;return{entries:new Map,problems:[{detail:`cannot be read (${o.message})`,fix:Yr,path:e}]}}let n=new Map,r=[];for(let[o,s]of t.split(`
389
+ `).entries()){if(s==="")continue;let i=rD.exec(s);if(i)n.set(i[2],i[1]);else r.push({detail:`line ${o+1} is not a SHA-256 checksum line`,fix:Yr,path:e})}return{entries:n,problems:r}}async function bD(e){let t=new Bun.CryptoHasher("sha256");return t.update(await Bun.file(e).bytes()),t.digest("hex")}function wD(e){let t=new Set;return e.filter((n)=>{let r=`${n.path}\x00${n.detail}`;if(t.has(r))return!1;return t.add(r),!0})}async function wa(){let e=await Bb(),t=e.installed?[...e.findings,...await Ub()]:[];return{findings:t,lines:SD(e,t),report:e}}function SD(e,t){if(!e.installed)return[`${p.bold("Toolchain")} ${p.dim(`not installed: ${e.manifest} is missing`)}`,p.dim(" Install it with the script from hydra toolchain print --script")];let n=e.unreadable.length===0?"":`; ${e.unreadable.length} this account cannot read, so only their owners and modes were checked`,r=`${e.files} recorded files match their checksums${n}`;if(t.length===0)return[`${p.bold("Toolchain")} ${p.green("\u2713")} ${r}; every path Hydra runs from is writable only by root`];return[`${p.bold("Toolchain")} ${p.red(`${t.length} problem${t.length===1?"":"s"}`)} ${p.dim(`(${r})`)}`,...t.flatMap((o)=>[` ${p.red("\u2717")} ${o.path} ${o.detail}`,p.dim(` ${o.fix}`)])]}function Sa(e){return`The toolchain in ${er} has ${e.length} problem${e.length===1?"":"s"}`}var ED=1,vD=0,td=P({name:"doctor",description:"Check the home, credentials, alert sinks and host toolchain, and each 0.x runner's DNS and job hooks; exits 1 when a check fails",json:!0,examples:["hydra doctor","hydra doctor --json"],run:async(e)=>{let t=ee(e.config),n=fi(t,process.cwd(),process.env),r=Pi(e.config),o=n.map((S)=>({detail:`another Hydra home exists at ${S.path}`,id:`home:${S.path}`,status:"warn"})),s=r?[]:await kD(e.config.get("credentials"),o),i=r?!1:Object.keys(e.config.get("pools")??{}).length>0,a=r?[]:Ah(e.config.get("alerts"),{env:process.env,home:t,now:Date.now(),pools:i}),c=await wa();if(T.info([...eb(t,n),...s,...a,...c.lines].join(`
390
+ `)),r)throw r;if(i&&Et(e.config.get("alerts")).length===0)throw new b("Pools need an alert sink",Yn);if(c.findings.length>0)throw new b(Sa(c.findings),"Fix each path above, then run hydra toolchain verify");let u=Object.entries(e.config.get("profiles"));if(u.length===0){if(!i)throw new b("No pools configured",n.length>0?`Run hydra pool add, or pass ${ye} with one of the homes above`:"Run hydra pool add to add a pool");let S={checks:o,home:t,ok:qb(o),profiles:[]};return e.output.result(S),Kb(o)}let l=new Map(u.map(([S,_])=>[S,an(_.jobHooks)])),d=[...l.values()].flatMap((S)=>S.dns.hosts),f=Hl();if(!f)o.push({detail:"no dscacheutil or getent to look hosts up with",id:"dns",status:"warn"});let[m,g]=await Promise.all([Ml(),f?Gl(d):Promise.resolve(void 0)]),h=e.config.get("runners")??[],E=[];for(let[S,_]of u){let C=l.get(S),w=h.filter((x)=>x.profile===S);E.push({dns:{enabled:C.dns.enabled,lookups:g?C.dns.hosts.flatMap((x)=>g.get(x)??[]):void 0,timeoutSeconds:C.dns.timeoutSeconds},name:S,runners:await _D(e.config,_,C,w),url:_.url,workspaceCleanup:C.workspaceCleanup})}o.push(...E.flatMap(tb));let v={checks:o,dnsServers:m,home:t,ok:qb(o),profiles:E};return e.output.result(v,nb),Kb(o)}});function qb(e){return!e.some((t)=>t.status==="fail")}function Kb(e){let t=e.filter((n)=>n.status==="fail");if(t.length===0)return vD;return T.warn(p.yellow(`Doctor found ${t.length} problem(s): ${t.map((n)=>n.detail).join("; ")}`)),ED}async function kD(e,t){let n=[`${p.bold("GitHub credentials")} ${Jh(e)}`,...xD(t)];if(e?.mode!=="app")return n;let r=await Yh(e.privateKeyPath);if(!r)return n;return t.push({detail:`the private key ${r}`,id:"credentials",status:"fail"}),[...n,p.yellow(` The private key ${r}`)]}function xD(e){if(!process.env[Hr])return[];try{let t=p.dim(`(from ${Hr}; Hydra sends its tokens there)`);return[`${p.bold("GitHub API")} ${kn(process.env)} ${t}`]}catch(t){if(!(t instanceof b))throw t;return e.push({detail:t.message,id:"api",status:"fail"}),[p.yellow(` ${t.message}`),...t.hint?[p.dim(` ${t.hint}`)]:[]]}}async function _D(e,t,n,r){if(r.length===0)return[];let o=new Map((await ve(t,e).list()).map((a)=>[a.id,a])),s=[...r].sort((a,c)=>a.id.localeCompare(c.id,void 0,{numeric:!0})),i=[];for(let a of s){let c=o.get(a.id);if(!RD($D(a.directory,ke))){i.push({id:a.id,restart:!1,status:c?.status??"unknown"});continue}let{envModifiedAt:u,states:l}=await Sl(a.directory,n);i.push({hooks:l,id:a.id,restart:TD(c,u),status:c?.status??"unknown"})}return i}function TD(e,t){if(e?.status!=="running"||!e.startedAt||!t)return!1;return t>e.startedAt}class Xr extends Error{operation;target;_tag="BudgetUnavailableError";constructor(e,t,n){super(`Could not ${e} ${t}: ${n}`);this.operation=e;this.target=t;this.name="BudgetUnavailableError"}}var Ge="/opt/hydra-guest",AD=`${Ge}/accept`,CD=`${Ge}/ready`,rd="/var/run/hydra",Wb=`${rd}/exit`,OD="rosetta",PD=30,nd="exit=",ID=`ps -axo comm= 2>/dev/null; if [ -f ${Wb} ]; then printf '${nd}%s\\n' "$(cat ${Wb})"; fi; exit 0`,ND=`f=$(ls -t ${Tn}/_diag/Runner_*.log 2>/dev/null | head -n 1); if [ -n "$f" ]; then cat "$f"; fi; exit 0`;function Ra(e,t){return["clone",e,t]}function Jb(e,t,n,r){return["set",e,"--cpu",String(t),"--memory",String(n),"--disk-size",String(r)]}function $a(e){return["run","--no-graphics","--no-audio","--net-softnet",`--net-softnet-block=${e.blocks.join(",")}`,...e.rosetta?[`--rosetta=${OD}`]:[],e.name]}function Yb(e){return["exec",e,CD]}function Xb(e){return["exec","-i",e,AD]}function zb(e){return["exec",e,"/bin/sh","-c",ID]}function Qb(e){return["exec",e,"/bin/sh","-c",ND]}function is(e){return["stop","--timeout",String(PD),e]}function as(e){return["delete",e]}function Zb(){return["--version"]}function ew(e){let t,n=[];for(let r of e.split(`
391
+ `).map((o)=>o.trim())){if(r.startsWith(nd)){let o=Number(r.slice(nd.length));t=Number.isSafeInteger(o)?o:-1;continue}if(r)n.push(r.slice(r.lastIndexOf("/")+1))}return{exitCode:t,processes:n}}import{existsSync as FL,readFileSync as UL,statfsSync as jL}from"fs";import{availableParallelism as BL,freemem as VL,homedir as kw}from"os";import{join as qL}from"path";import{randomBytes as VD}from"crypto";import{existsSync as qD,lstatSync as KD,mkdirSync as WD,readdirSync as JD,readFileSync as YD,renameSync as XD,rmSync as zD,writeFileSync as QD}from"fs";import{join as or}from"path";import{spawn as DD}from"child_process";import{closeSync as LD,constants as Ea,fchmodSync as MD,openSync as HD}from"fs";class Te extends Error{reason;operation;target;_tag="TartError";constructor(e,t,n,r,o){super(`Could not ${t} ${n}: ${r}`,o);this.reason=e;this.operation=t;this.target=n;this.name="TartError"}}var ka="tart",xa=3,va=1000,cs=60*va,GD=10,FD="[redacted]",UD=4194304,tw=384,_a={callMs:cs,cloneMs:10*cs,exitMs:10*va,pollMs:2*va,readyMs:5*cs,runnerMs:cs,stopMs:2*cs};function Ta(e){return{...process.env,TART_HOME:e,TART_NO_AUTO_PRUNE:"1"}}function Aa(e,t,n){let r=0,o=!1;return{binary:e,env:n,launch:(c,u,l)=>{nn("tart",u);let d=Ea.O_WRONLY|Ea.O_CREAT|Ea.O_TRUNC|Ea.O_NOFOLLOW,f=HD(l,d,tw);try{MD(f,tw);let m=DD(e,[...u],{detached:!0,env:n,stdio:["ignore",f,f]});if(m.pid===void 0)throw new Te("missing","start",c,`${e} could not start`);return m.on("error",()=>{return}),m.unref(),m.pid}finally{LD(f)}},limits:t,recover:()=>{r=0,o=!1},run:async(c,u,l,d={})=>{nn("tart",l,d.stdin);let f=d.timeoutMs??t.callMs,m=d.stdin?d.stdin.line():d.input,g=m===void 0?void 0:new TextEncoder().encode(m);try{let h=d.maxOutputChars??UD,E=await jD(c,u,[e,...l],{echo:d.echo,env:n,input:g,maxOutputChars:h,timeoutMs:f});if(E.timedOut)throw r+=1,o||=r>=xa,new Te("timeout",c,u,`${e} did not finish within ${f/va} s`);r=0;let v={exitCode:E.exitCode,stderr:nw(E.stderr,d.stdin),stdout:nw(E.stdout,d.stdin)};if(v.exitCode===0||d.check===!1)return v;throw new Te("failed",c,u,BD(e,v))}finally{g?.fill(0)}},unavailable:()=>o}}async function jD(e,t,n,r){try{return await ft(n,r)}catch(o){let s=o instanceof Error?o.message:String(o);throw new Te("missing",e,t,`${n[0]} could not start (${s})`,{cause:o})}}function nw(e,t){return t?.contains(e)?FD:e}function BD(e,t){let n=t.stderr.trim().split(`
392
+ `).slice(-GD).join(`
393
+ `);return`${e} exited with code ${t.exitCode}${n?`
394
+ ${n}`:""}`}var ZD=["general","secret"],eL=["candidate","promoted","previous"];class rr extends Error{reason;golden;_tag="GoldenError";constructor(e,t,n){super(`Could not promote ${t}: ${n}`);this.reason=e;this.golden=t;this.name="GoldenError"}}var iw="goldens",rw={config:"config.json",disk:"disk.img"},tL={general:86400000,secret:3600000},nL=/^golden-(macos|linux)-(general|secret)-[0-9a-f]{12}$/,rL=6,od=".json",oL=448,sL=384,iL=18,aL=/^[0-9a-f]{64}$/,cL="vms",ow=I().map((e)=>aL.test(e)?e:F()),uL=N({base:I(),builtAt:I(),guestOs:J(["linux","macos"]),name:I(),promotedAt:I().or(ne()),runner:I(),sha256:N({config:ow,disk:ow}),status:J(eL),variant:J(ZD)});function aw(e,t){return`golden-${e}-${t}-${VD(rL).toString("hex")}`}function Ca(e){let t=nL.exec(e);return t?{guestOs:t[1],variant:t[2]}:void 0}function An(e){return e?"secret":"general"}function us(e){let t=or(e,iw);if(!qD(t)||!pw(t,"directory"))return[];return JD(t).filter((n)=>n.endsWith(od)).flatMap((n)=>lL(or(t,n),n.slice(0,-od.length))).sort((n,r)=>Date.parse(r.builtAt)-Date.parse(n.builtAt))}function cw(e,t,n){return us(e).find((r)=>r.status==="promoted"&&r.guestOs===t&&r.variant===n)}function Oa(e,t){let n=or(e,iw);WD(n,{mode:oL,recursive:!0});let r=or(n,`${t.name}${od}`),o=`${r}.${process.pid}.tmp`;try{QD(o,`${JSON.stringify(t,null,2)}
395
+ `,{flag:"wx",mode:sL}),XD(o,r)}finally{zD(o,{force:!0})}}async function sd(e,t){let n=or(e,cL,t),[r,o]=await Promise.all([sw(or(n,rw.config)),sw(or(n,rw.disk))]);return{config:r,disk:o}}async function uw(e,t){try{let n=await sd(e,t.name);return n.config===t.sha256.config&&n.disk===t.sha256.disk}catch{return!1}}function lw(e,t,n=Date.now){let r=new Map,o=new Map,s=new Set,i=(a,c)=>{let u=o.get(a);if(u)return u;let l=(async()=>{let d=us(e).find((m)=>m.name===a);return d!==void 0&&(!c||d.status==="promoted")&&await uw(t,d)})().finally(()=>o.delete(a));return o.set(a,l),l};return async(a,c)=>{let u=r.get(a),l=u!==void 0&&n()-u<tL[An(c)];if(!s.has(a)&&l)return;if(s.has(a)||!await i(a,c))throw s.add(a),new Te("refused-config","clone",a,c?"the golden is no longer promoted or its disk no longer matches the hashes recorded at build":"the golden is not recorded or its disk no longer matches the hashes recorded at build");r.set(a,n())}}async function dw(e){let{home:t,name:n}=e,r=us(t),o=r.find((a)=>a.name===n);if(!o)throw new rr("missing",n,"no golden of that name is recorded in this home");if(o.status==="promoted")throw new rr("state",n,"it is already promoted");if(o.variant==="secret"&&e.approve!==o.sha256.disk)throw new rr("approval",n,"a golden for secret-bearing pools is promoted only with --approve and the SHA-256 of its disk");if(!await uw(e.store,o))throw new rr("integrity",n,"its disk or configuration no longer matches the hashes recorded at build");let s=(e.now??new Date).toISOString();for(let a of r)if(a.guestOs===o.guestOs&&a.variant===o.variant&&a.status==="promoted")Oa(t,{...a,status:"previous"});let i={...o,promotedAt:s,status:"promoted"};return Oa(t,i),i}async function sw(e){let t=new Bun.CryptoHasher("sha256");for await(let n of Bun.file(e).stream())t.update(n);return t.digest("hex")}function lL(e,t){if(!pw(e,"file"))return[];try{let n=uL(JSON.parse(YD(e,"utf8")));return n.name===t&&Ca(t)?.guestOs===n.guestOs&&Ca(t)?.variant===n.variant&&!Number.isNaN(Date.parse(n.builtAt))?[n]:[]}catch{return[]}}function pw(e,t){let n=KD(e);return(t==="directory"?n.isDirectory():n.isFile())&&n.uid===process.getuid?.()&&(n.mode&iL)===0}import{existsSync as mw,lstatSync as dL,statSync as pL}from"fs";import{delimiter as fL,join as mL}from"path";var Pa="2.42.0",gL="0.26.0",fw="softnet",hL=2048,gw=18,yL=1,bL=0,wL=/\d+\.\d+\.\d+/;async function hw(e){try{let n=(await e.run("read the version of",e.binary,Zb())).stdout.match(wL)?.[0];if(n===Pa)return{answered:!0,findings:[]};return{answered:!0,findings:[{code:"tool-version",detail:`${e.binary} is version ${n??"(unknown)"}; Hydra is pinned to ${Pa}`,fix:`Install Tart ${Pa} from its release archive into a root-owned directory`,level:"error"}]}}catch(t){let n=t instanceof Error?t.message:String(t),r=t instanceof Te?t.reason:"failed",o=r==="missing"?`Install Tart ${Pa} from its release archive into a root-owned directory on PATH`:"Run tart --version and fix what it reports";return{answered:!1,findings:[{code:r==="missing"?"tool-missing":"tool-failed",detail:n,fix:o,level:"error"}]}}}function yw(e){let t=(e??"").split(fL).filter(Boolean).map((o)=>mL(o,fw)).find((o)=>mw(o));if(!t)return[{code:"softnet-missing",detail:`${fw} is not on PATH, so Tart cannot isolate its guests' network`,fix:`Install softnet ${gL} beside Tart, owned by root with mode 4750 and the fleet's group`,level:"error"}];let n=pL(t),r=[];if(n.uid!==bL||(n.mode&hL)===0)r.push({code:"softnet-setuid",detail:`${t} is not setuid root, so softnet cannot filter guest traffic without sudo`,fix:`Run chown root ${t} and chmod 4750 ${t} as root`,level:"error"});if((n.mode&gw)!==0)r.push({code:"softnet-writable",detail:`${t} is writable by its group or by others`,fix:`Run chmod 4750 ${t} as root`,level:"error"});if((n.mode&yL)!==0)r.push({code:"softnet-open",detail:`Any user can run the setuid ${t}`,fix:`Give it the fleet's group and run chmod 4750 ${t} as root`,level:"warning"});return r}function bw(e){if(!mw(e))return[];let t=dL(e),n=[t.isDirectory()?"":"is not a directory",t.uid===process.getuid?.()?"":"belongs to another user",(t.mode&gw)===0?"":"is writable by its group or by others"].filter(Boolean);if(n.length===0)return[];return[{code:"store",detail:`The Tart store ${e} ${n.join(" and ")}`,fix:"Give the store to the fleet's user with mode 0700, or point TART_HOME at one it owns",level:"error"}]}import{networkInterfaces as SL}from"os";var ww=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.168.0.0/16","198.18.0.0/15","224.0.0.0/4","240.0.0.0/4"],RL=32,$L=ww.map((e)=>st(e));function Ia(e=SL()){let t=Object.values(e).flatMap((n)=>n??[]).filter((n)=>n.family==="IPv4").map((n)=>n.address).filter((n)=>{let r=Cr(n);return r!==void 0&&!$L.some((o)=>Or(o,r))});return[...ww,...[...new Set(t)].sort().map((n)=>`${n}/${RL}`)]}import{closeSync as EL,constants as Na,existsSync as ad,fchmodSync as vL,lstatSync as kL,mkdirSync as xL,openSync as _L,readdirSync as TL,readFileSync as $w,renameSync as AL,rmSync as id,writeSync as CL}from"fs";import{join as Da}from"path";var Ew="vms",OL="config.json",PL=448,Sw=384,IL=1e4,NL=250,DL=5000,Rw={darwin:"macos",linux:"linux"},LL=N({guestOs:J(["linux","macos"]),pid:X().or(ne()),pool:I(),rosetta:Q(),secretBearing:Q()}),ML=N({os:I()});function cd(e,t){return Da(e,Ew,t)}function ud(e){let t=Da(e,Ew);if(!ad(t))return[];return TL(t,{withFileTypes:!0}).filter((n)=>n.isDirectory()).map((n)=>({guestOs:GL(Da(t,n.name,OL)),name:n.name})).sort((n,r)=>n.name.localeCompare(r.name))}function zr(e,t){return ad(cd(e,t))}function vw(e){let t=()=>xL(e,{mode:PL,recursive:!0}),n=(r,o)=>Da(e,`${r}${o}`);return{dir:e,log:(r)=>(t(),n(r,".log")),read:(r)=>{let o=n(r,".json");if(!ad(o)||!kL(o).isFile())return;try{return LL(JSON.parse($w(o,"utf8")))}catch{return}},remove:(r)=>{id(n(r,".json"),{force:!0}),id(n(r,".log"),{force:!0})},write:(r,o)=>{t();let s=n(r,".json"),i=`${s}.${process.pid}.tmp`;id(i,{force:!0});let a=Na.O_WRONLY|Na.O_CREAT|Na.O_EXCL|Na.O_NOFOLLOW,c=_L(i,a,Sw);try{vL(c,Sw),CL(c,`${JSON.stringify(o)}
396
+ `)}finally{EL(c)}AL(i,s)}}}async function Bt(e,t){if(e===void 0||!HL(e))return!1;let n=await ft(["ps","-ww","-o","args=","-p",String(e)],{timeoutMs:IL}),r=n.stdout.trim().split(/\s+/);return n.exitCode===0&&r.includes("run")&&r.at(-1)===t}async function La(e,t,n){let r=Date.now()+n;while(await Bt(e,t)){if(Date.now()>=r)return!1;await Bun.sleep(NL)}return!0}async function Ma(e,t,n){if(e===void 0||await La(e,t,n))return!0;try{process.kill(e,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}return La(e,t,DL)}function HL(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function GL(e){try{let{os:t}=ML(JSON.parse($w(e,"utf8")));return Object.hasOwn(Rw,t)?Rw[t]:void 0}catch{return}}var Ha="tart",KL=/^[a-z0-9]+$/,xw=1048576,WL=1024*xw,JL=1000,YL=2000,XL="Runner.log",_w=/[^\P{Cc}\n\t]/gu,zL=/VZErrorDomain Code=6\b|virtualMachineLimitExceeded|number of virtual machines exceeds the limit/i;function sr(){return process.env.TART_HOME||qL(kw(),".tart")}function Ga(e={}){let t={..._a,...e.limits},n=e.store??sr(),r=Aa(e.binary??ka,t,Ta(n)),o=e.fleet?QL(e.fleet):void 0,s=e.blocks??Ia(),i=(y)=>{if(o)return o;throw Error(`The tart driver needs a fleet to ${y}`)},a=(y,R)=>{let A=i(R);if(y.driver!==Ha||!Bn(y.name,A.prefix))throw new Te("invalid-name",R,y.name,`it is not a guest of fleet ${A.id}`);return A},c=(y,R,A)=>{let k=y.files.read(R);if(k)return k;throw new Te("not-ready",A,R,"Hydra holds no record of creating it")},u=async(y,R,A,k)=>{let D=Date.now()+y;while(!await k()){if(Date.now()>=D)throw new Te("not-ready",R,A,`no answer within ${y/JL} s`);await Bun.sleep(t.pollMs)}},l=async(y,R)=>{let A=ud(n).filter((D)=>D.guestOs==="macos"&&D.name!==R);return(await Promise.all(A.map((D)=>Bt(y.files.read(D.name)?.pid,D.name)))).filter(Boolean).length},d=async(y)=>{let R={driver:Ha,name:y.name,pool:y.pool},A=a(R,"create"),k=Ca(y.image);if(!k||k.guestOs!==y.guestOs||k.variant!==An(y.secretBearing)){let D=`a ${y.secretBearing?"secret-bearing":"general"} ${y.guestOs} golden`;throw new Te("refused-config","create",y.name,`${y.image} is not ${D}`)}if(r.unavailable())throw new Te("unavailable","create",y.name,`${xa} tart calls in a row timed out; a host check that finds the tool answering lifts this`);if(!zr(n,y.image))throw new Te("refused-config","create",y.name,`the golden ${y.image} is not in the Tart store`);await e.checkImage?.(y.image,y.secretBearing),await r.run("clone",y.name,Ra(y.image,y.name),{timeoutMs:t.cloneMs});try{await r.run("size",y.name,Jb(y.name,y.cpus,y.memoryMiB,y.diskGiB)),A.files.write(y.name,{guestOs:y.guestOs,pool:y.pool,rosetta:y.guestOs==="linux"&&y.foreignArch,secretBearing:y.secretBearing})}catch(D){throw await r.run("delete",y.name,as(y.name),{check:!1}),A.files.remove(y.name),D}return R},f=async(y)=>{let R=a(y,"start"),A=c(R,y.name,"start");if(A.guestOs==="macos"&&await l(R,y.name)>=Rn)throw new Xr("start",y.name,`${Rn} macOS VMs already run on this host`);let k=R.files.log(y.name),D=r.launch(y.name,$a({blocks:s,name:y.name,rosetta:A.rosetta}),k);R.files.write(y.name,{...A,pid:D}),await u(t.readyMs,"wait for the guest of",y.name,async()=>{if((await r.run("check the guest of",y.name,Yb(y.name),{check:!1})).exitCode===0)return!0;if(await Bt(D,y.name))return!1;let q=ZL(k);if(zL.test(q))throw new Xr("start",y.name,"Virtualization.framework refused another VM on this host");throw new Te("not-ready","start",y.name,`the VM stopped before its guest was ready${q?`
397
+ ${q}`:""}`)})},m=async(y)=>{let R=a(y,"read the state of a guest");if(!zr(n,y.name))return{kind:"gone"};let A=R.files.read(y.name);if(A?.pid===void 0)return{kind:"preparing"};if(!await Bt(A.pid,y.name))return{code:Yl,kind:"exited"};let k=await r.run("list the processes of",y.name,zb(y.name),{check:!1});if(k.exitCode!==0)return{kind:"running"};let{exitCode:D,processes:B}=ew(k.stdout);if(D!==void 0)return{code:D,kind:"exited"};return B.includes(da)?{busy:B.includes(pa),kind:"runner-alive"}:{kind:"running"}},g=async(y,R)=>{a(y,"hand the runner configuration to"),await r.run("hand the runner configuration to",y.name,Xb(y.name),{stdin:R}),await u(t.runnerMs,"wait for the runner of",y.name,async()=>{let A=await m(y);if(A.kind==="runner-alive")return!0;if(A.kind==="running")return!1;throw new Te("not-ready","start the runner of",y.name,"the runner or the VM stopped first")})},h=async(y)=>{let R=a(y,"destroy"),A=R.files.read(y.name)?.pid;if(zr(n,y.name)||await Bt(A,y.name)){if(await r.run("stop",y.name,is(y.name),{check:!1,timeoutMs:t.stopMs}),!await Ma(A,y.name,t.exitMs))throw new Te("failed","stop",y.name,`its tart run process ${A} outlived SIGKILL`)}if(zr(n,y.name))await r.run("delete",y.name,as(y.name));R.files.remove(y.name)},E=async(y)=>{let A=a(y,"verify the removal of").files.read(y.name)?.pid,k=[zr(n,y.name)?`VM directory ${cd(n,y.name)}`:"",await Bt(A,y.name)?`tart run process ${A}`:""].filter(Boolean);return{checked:["store","process"],leftovers:k}},v=async()=>{let y=i("list its guests");return ud(n).filter((R)=>Bn(R.name,y.prefix)).map((R)=>({driver:Ha,name:R.name,pool:y.files.read(R.name)?.pool??""}))};async function*S(y,R){if(a(y,"read the logs of").files.read(y.name)?.secretBearing!==!1)return;let B=(await r.run("read the logs of",y.name,Qb(y.name),{maxOutputChars:R.bytes})).stdout.replace(_w,"");if(B)yield{file:XL,text:B.slice(Math.max(0,B.length-R.bytes))}}let _=async()=>{let y=await hw(r);if(y.answered)r.recover();return[...y.findings,...yw(r.env.PATH),...bw(n)]};return{capabilities:()=>Oe[Ha].capabilities,capacity:async()=>{let y=i("report its capacity"),R=jL(FL(n)?n:kw());return{cpus:BL(),diskGiB:Math.floor(R.bavail*R.bsize/WL),guests:Math.max(0,Rn-await l(y)),memoryMiB:Math.floor(VL()/xw)}},checkHost:async()=>({findings:await _()}),create:d,destroy:h,health:async()=>{let y=await _();if(r.unavailable())y.push(eM());return{findings:y}},list:v,logs:S,runJit:g,start:f,state:m,store:n,verifyGone:E}}function QL(e){if(!KL.test(e.id))throw Error(`Invalid fleet id "${e.id}"`);return{files:vw(e.stateDir),id:e.id,prefix:`hydra-${e.id}`}}function ZL(e){try{let t=UL(e,"utf8").replace(_w,"").trim();return t.slice(Math.max(0,t.length-YL))}catch{return""}}function eM(){return{code:"unresponsive",detail:`${xa} tart calls in a row timed out, so Hydra starts no new guests on this driver`,fix:"Running guests keep their jobs; new guests start again once a host check finds the tool answering",level:"error"}}function Fa(){return{"apple-container":ma(),tart:Ga()}}var tM=Symbol.for("nodejs.util.inspect.custom"),nM=/[\r\n]/;function Ua(e){if(e.length===0||nM.test(e))throw Error("A stdin secret must be one non-empty line");return Object.defineProperty({contains:(n)=>n.includes(e),line:()=>`${e}
398
+ `,toJSON:()=>"[redacted]",toString:()=>"[redacted]"},tM,{value:()=>"[redacted]"})}var rM={full:"Docker",limited:"limited Docker",none:"no Docker"},oM={none:"no other architectures",qemu:"other architectures through QEMU",rosetta:"other architectures through Rosetta"},sM={"guest-side":"guest-side network filter","host-side":"host-side network filter",none:"no network filter"},iM={"host-user":"a host user each","user-space-kernel":"a user-space kernel each",vm:"a VM each"};function Tw(e){let t=Oe[e].capabilities;return[`${t.guestOs.map((r)=>on[r]).join(" and ")} guests on ${$n[t.hostOs]}, ${iM[t.isolation]}`,rM[t.docker],oM[t.foreignArch],t.guiSession?"desktop session":"",sM[t.hostFilter],t.secretBearing?"secret-bearing pools":"no secret-bearing pools",t.maxMacosGuests===void 0?"":`at most ${t.maxMacosGuests} macOS guests per host`].filter(Boolean).join(" \xB7 ")}function Aw(e){let t=e.status==="available"?p.green("\u2713"):p.red("\u2717"),n=e.status==="available"?p.green(e.status):p.red(e.status);return[`${t} ${p.bold(e.driver)} ${n}`,...e.findings.flatMap(aM)]}function aM(e){return[` ${e.level==="error"?p.red(e.level):p.yellow(e.level)} ${e.code}: ${e.detail}`,p.dim(` Fix: ${e.fix}`)]}var cM=ae({driver:{description:"Driver to check (default: every driver for this host)"}}),Cw=P({name:"check",description:"Check whether this host can run a slot driver, with a fix for each finding",positionals:cM,json:!0,examples:["hydra driver check","hydra driver check tart --json"],run:async(e)=>{let t=e.positionals.driver;if(t!==void 0&&!Tg(t))throw new b(`Unknown driver "${t}"`,`Choose one of: ${vt.join(", ")}`);let n=await En(),r=t?[t]:n.os?Pg(n.os):[];if(r.length===0)throw new b(`Hydra has no slot driver for ${n.osName} hosts`);let o=Fa(),s=[];for(let c of r)s.push(await Ng(c,n,o));let i=s.filter((c)=>c.status==="unavailable"),a={drivers:s,host:n,ok:i.length===0};if(!e.json)T.info(uM(a));if(e.output.result(a),a.ok)return;throw new b(t?`${t} is unavailable on this host`:`${i.length} of ${s.length} drivers are unavailable on this host`,"Each error above names its fix")}});function uM(e){return[`${p.bold("Host")} ${vi(e.host)}`,"",...e.drivers.flatMap(Aw)].join(`
399
+ `)}var lM=["linux","macos"],dM={allowWeakerIsolation:!1,docker:"none",foreignArch:!1,guiSession:!1,secretBearing:!1},Pw=P({name:"list",description:"List slot drivers, what each guarantees and whether this host can run it",json:!0,examples:["hydra driver list","hydra driver list --json"],run:async(e)=>{let t=pM(await En(),Fa());if(!e.json)T.info(mM(t));e.output.result(t)}});function pM(e,t){return{auto:{linux:Ow("linux",e),macos:Ow("macos",e)},drivers:vt.map((n)=>fM(n,e,t)),host:e}}function fM(e,t,n){let{id:r,...o}=Oe[e].capabilities,s=_i(e,t).find((i)=>i.level==="error");return{...s?{blocker:s}:{},capabilities:o,fitsHost:!s,id:e,included:n[e]!==void 0}}function Ow(e,t){let n=xi(mt,{...dM,guestOs:e},t);return n.kind==="resolved"?n.driver:null}function mM(e){let t=[`${p.bold("Host")} ${vi(e.host)}`];for(let r of e.drivers){let o=r.blocker?`${p.red("\u2717")} ${r.blocker.detail}`:`${p.green("\u2713")} this host`,s=r.included?"":p.dim(" \xB7 not in this version");t.push("",`${p.bold(r.id)} ${o}${s}`,p.dim(` ${Tw(r.id)}`))}let n=lM.map((r)=>`${on[r]} guests: ${e.auto[r]??p.dim("none")}`);return t.push("",`${p.bold("auto")} ${n.join(" \xB7 ")}`),t.join(`
400
+ `)}var ld=P({name:"driver",description:"List slot drivers and check this host for them",subcommands:[Pw,Cw]});var dd=["first_time_contributors_new_to_github","first_time_contributors","all_external_contributors"],Iw="public",Nw=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),Dw=N({approval_policy:J(dd)}).map((e)=>e.approval_policy),Lw=N({require_approval_for_fork_pr_workflows:Q(),run_workflows_from_fork_pull_requests:Q(),send_secrets_and_variables:Q(),send_write_tokens_to_workflows:Q()}).map((e)=>({requireApproval:e.require_approval_for_fork_pr_workflows,runWorkflows:e.run_workflows_from_fork_pull_requests,sendSecrets:e.send_secrets_and_variables,sendWriteTokens:e.send_write_tokens_to_workflows})),gM=N({allows_public_repositories:Q(),default:Q(),id:Nw,name:I(),restricted_to_workflows:Q().or(ne()),selected_workflows:Z(I()).or(ne()),visibility:I()}).map((e)=>({allowsPublicRepositories:e.allows_public_repositories,default:e.default,id:e.id,name:e.name,restrictedToWorkflows:e.restricted_to_workflows??!1,selectedWorkflows:[...e.selected_workflows??[]].sort(),visibility:e.visibility})),hM=N({full_name:I(),id:Nw}).map((e)=>({id:e.id,name:e.full_name})),yM=N({private:Q(),visibility:J(["internal","private","public"]).or(ne())}).map((e)=>e.visibility??(e.private?"private":Iw));function bM(e){return`/orgs/${encodeURIComponent(e)}/actions/permissions`}async function Mw(e,t){let n=bM(t),r=await e.request({operation:`Read the fork pull request settings for private repositories of ${t}`,path:`${n}/fork-pr-workflows-private-repos`,schema:Lw});return{approval:await e.request({operation:`Read the fork pull request approval policy of ${t}`,path:`${n}/fork-pr-contributor-approval`,schema:Dw}),privateRepositories:r}}async function Hw(e,t,n){return e.request({operation:`Read the visibility of ${t}/${n}`,path:Bi({owner:t,repo:n}),schema:yM})}async function Gw(e,t,n,r){let o=`${Bi({owner:t,repo:n})}/actions/permissions`;if(r===Iw)return{approval:await e.request({operation:`Read the fork pull request approval policy of ${t}/${n}`,path:`${o}/fork-pr-contributor-approval`,schema:Dw})};return{privateRepositories:await e.request({operation:`Read the fork pull request settings of ${t}/${n}`,path:`${o}/fork-pr-workflows-private-repos`,schema:Lw})}}async function Fw(e,t){return e.paginate({item:gM,key:"runner_groups",operation:`List the runner groups of ${t} with their settings`,path:Ft(t)})}async function Uw(e,t,n){return(await e.paginate({item:hM,key:"repositories",operation:`List the repositories that may use the runner group ${n.name} of ${t}`,path:`${Ft(t)}/${n.id}/repositories`})).sort((o,s)=>o.id-s.id)}var wM="selected";function Ba(e){return{async snapshots(t){let n=new Map,r=new Map,o=new Map,s=new Map,i=async(l,d)=>{let f=d.visibility===wM?await Uw(e,l,d):void 0;return{runners:(await Vi(e,l,d)).map(jw),state:f?{...d,repositories:f}:d}},a=async(l,d)=>{let f=await ja(n,l,()=>Mw(e,l)),g=(await ja(r,l,()=>Fw(e,l))).find((E)=>E.name.toLowerCase()===d.toLowerCase());if(!g)return{forkPolicy:f,runners:[],scope:{groupName:d,kind:"org",org:l}};let h=await ja(o,`${l}/${g.id}`,()=>i(l,g));return{forkPolicy:f,runners:h.runners,scope:{group:h.state,groupName:d,kind:"org",org:l}}},c=async(l,d)=>{let f=`${l}/${d}`;return ja(s,f,async()=>{let m=await Hw(e,l,d),g=await Gw(e,l,d,m),h=await Ht(e,{kind:"repo",owner:l,repo:d});return{forkPolicy:g,runners:h.map(jw),scope:{kind:"repo",repository:f,visibility:m}}})},u={};for(let[l,d]of Object.entries(t)){let f=de(d.url),m=f.kind==="org"?await a(f.org,d.runnerGroup??""):await c(f.owner,f.repo);u[l]={...m,url:d.url}}return u}}}function _t(e){return e.kind==="org"?`runner group ${e.groupName} of ${e.org}`:`repository ${e.repository}`}function jw(e){return{id:e.id,name:e.name}}async function ja(e,t,n){let r=e.get(t);if(r!==void 0)return r;let o=await n();return e.set(t,o),o}var SM="public",RM="the guard record holds no baseline for this pool",Bw={requireApproval:{off:"no longer requires approval for fork pull request workflows of private repositories",on:"now requires approval for fork pull request workflows of private repositories"},runWorkflows:{off:"no longer runs workflows from fork pull requests of private repositories",on:"now runs workflows from fork pull requests of private repositories"},sendSecrets:{off:"no longer sends secrets and variables to fork pull request workflows",on:"now sends secrets and variables to fork pull request workflows"},sendWriteTokens:{off:"no longer sends write tokens to fork pull request workflows",on:"now sends write tokens to fork pull request workflows"}};function ls(e){let t=new Set,n=new Set;for(let r of e)if(r.runner)t.add(r.runner.id);else n.add(r.name);return{ids:t,names:n}}function gd(e,t){return e.ids.has(t.id)||e.names.has(t.name)}function Ka({baseline:e,config:t,minted:n,snapshot:r}){let o=hd(t,r.scope);if(!e)return[...o,{detail:RM,kind:"unrecorded"}];let s=$M(e,t,r.scope);if(s)return[...o,{detail:s,kind:"unrecorded"}];o.push(...yd(e,r));let i=new Set(e.acceptedRunners.map((a)=>a.id));for(let a of r.runners){if(gd(n,a)||i.has(a.id))continue;o.push({detail:`runner ${a.id} in ${_t(r.scope)} was not minted by this fleet`,kind:"foreign-runner",names:[a.name]})}return o}function hd(e,t){if(!e.secretBearing)return[];if(!(t.kind==="org"?t.group?.allowsPublicRepositories===!0:t.visibility===SM))return[];return[{detail:`${t.kind==="org"?`${_t(t)} allows public repositories`:`${_t(t)} is public`}, and the pool is secret-bearing`,kind:"public-access"}]}function yd(e,t){return[...EM(e.scope,t.scope),...kM(t.scope,e.forkPolicy,t.forkPolicy)]}function $M(e,t,n){if(e.url!==t.url)return`the guard record holds the pool with ${e.url}`;let r=e.scope.kind==="org"?e.scope.groupName:void 0,o=n.kind==="org"?n.groupName:void 0;if(r?.toLowerCase()!==o?.toLowerCase())return`the guard record holds the pool in runner group ${r??"(none)"}`;return}function EM(e,t){let n=_t(t);if(e.kind==="repo"&&t.kind==="repo")return e.visibility===t.visibility?[]:[Cn(`${n} is now ${t.visibility}, recorded ${e.visibility}`)];if(e.kind!=="org"||t.kind!=="org")return[Cn(`${n} is not the recorded kind of target`)];if(!t.group)return[Cn(`${n} no longer exists`)];if(!e.group)return[Cn(`${n} exists again`)];return vM(n,e.group,t.group)}function vM(e,t,n){let r=[];if(t.id!==n.id)r.push(Cn(`${e} is now id ${n.id}, recorded id ${t.id}`));if(t.visibility!==n.visibility)r.push(Cn(`${e} now admits ${Va(n.visibility)}, recorded ${Va(t.visibility)}`));r.push(...pd(e,t.allowsPublicRepositories,n.allowsPublicRepositories,{off:"no longer allows public repositories",on:"now allows public repositories"}),...pd(e,t.restrictedToWorkflows,n.restrictedToWorkflows,{off:"is no longer restricted to selected workflows",on:"is now restricted to selected workflows"}));let o=qw(n.selectedWorkflows,t.selectedWorkflows),s=qw(t.selectedWorkflows,n.selectedWorkflows);if(o.length>0)r.push(fd(`${e} lists ${md(o.length,"workflow")} more`,o));if(s.length>0)r.push(fd(`${e} lists ${md(s.length,"workflow")} fewer`,s));if(t.repositories&&n.repositories){let i=new Set(t.repositories.map((l)=>l.id)),a=new Set(n.repositories.map((l)=>l.id)),c=n.repositories.filter((l)=>!i.has(l.id)),u=t.repositories.filter((l)=>!a.has(l.id));if(c.length>0)r.push(Vw(`may now use ${e}`,c));if(u.length>0)r.push(Vw(`may no longer use ${e}`,u))}return r}function kM(e,t,n){let r=e.kind==="org"?e.org:e.repository,o=[];if(t.approval&&n.approval&&t.approval!==n.approval)o.push(Cn(`${r} now asks approval for fork pull request workflows of ${qa(n.approval)}, recorded ${qa(t.approval)}`));let s=t.privateRepositories,i=n.privateRepositories;if(!s||!i)return o;for(let a of Object.keys(Bw))o.push(...pd(r,s[a],i[a],Bw[a]));return o}function pd(e,t,n,r){return t===n?[]:[Cn(`${e} ${n?r.on:r.off}`)]}function Cn(e){return{detail:e,kind:"changed"}}function fd(e,t){return{detail:e,kind:"changed",names:t}}function Vw(e,t){let n=t.map((r)=>r.id).join(", ");return fd(`${md(t.length,"repository","repositories")} (id ${n}) ${e}`,t.map((r)=>r.name))}function qw(e,t){let n=new Set(t);return e.filter((r)=>!n.has(r))}function md(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function Va(e){if(e==="all")return"all repositories";if(e==="private")return"private repositories";if(e==="selected")return"selected repositories";return"repositories by an unknown visibility"}function qa(e){switch(e){case"all_external_contributors":return"all outside contributors";case"first_time_contributors":return"first-time contributors";case"first_time_contributors_new_to_github":return"first-time contributors new to GitHub"}}import{existsSync as mS,lstatSync as dH,mkdirSync as pH,readFileSync as fH,renameSync as mH,rmSync as gH,writeFileSync as hH}from"fs";import{dirname as Td,join as yH}from"path";import{closeSync as za,constants as un,existsSync as YM,fstatSync as kd,fsyncSync as xd,ftruncateSync as XM,lstatSync as sS,mkdirSync as zM,openSync as iS,readFileSync as aS,writeSync as QM}from"fs";import{dirname as cS,join as ZM}from"path";var xM=[/\bgh[opsur]_[A-Za-z0-9]{20,}/,/\bgithub_pat_\w{20,}/,/\bey[IJ][\w+/=-]{16,}/,/-----BEGIN [A-Z ]+-----/,/\b(?:Bearer|RemoteAuth)\s+\S{16,}/,/:\/\/[^\s/:@]+:[^\s/@]+@/,/discord(?:app)?\.com\/api\/webhooks\//i],_M=/[A-Za-z0-9+=_]{24,}/g,TM=/[A-Za-z]/,AM=/\d/,CM=/^[A-Za-z][A-Za-z0-9]{0,31}$/;function ir(e){if(xM.some((t)=>t.test(e)))return!0;return[...e.matchAll(_M)].some(([t])=>TM.test(t)&&AM.test(t))}function ds(e,t){if(!CM.test(t)||ir(t))return e;return e?`${e}.${t}`:t}function bd(e,t){if(typeof e==="string")return ir(e)?t:void 0;if(typeof e!=="object"||e===null)return;for(let[n,r]of Object.entries(e)){if(ir(n))return t;let o=bd(r,ds(t,n));if(o!==void 0)return o}return}var Kw=["lease-granted","lease-refused","prepare","ready","minted","online","job-started","exited","collected","drain","budget-unavailable","failed","canary-failed","timed-out","verified"],Ww=120;var OM={destroying:5,finishing:5,preparing:10,registering:2},PM=["verified","withdrawn","quarantined"],IM=["admitted","preparing","registering","online","busy","finishing","destroying"],NM=["requested","waiting","admitted"],DM=["online","job-started","exited","canary-failed"],LM={"budget-unavailable":["preparing"],"canary-failed":["registering","online","busy"],collected:["finishing"],drain:["requested","waiting","admitted","preparing","registering","online"],exited:["registering","online","busy"],failed:["preparing","registering","online","busy","finishing","destroying"],"job-started":["registering","online"],"lease-granted":["requested","waiting"],"lease-refused":["requested"],minted:["registering"],online:["registering"],prepare:["admitted"],ready:["preparing"],"timed-out":["preparing","registering","busy","finishing","destroying"],verified:["destroying","quarantined"]};class Wa extends Error{slot;phase;event;_tag="SlotTransitionError";constructor(e,t,n){super(`Slot ${e} cannot take "${n}" while ${t}`);this.slot=e;this.phase=t;this.event=n;this.name="SlotTransitionError"}}function Jw(e,t){return{driver:e.driver,name:e.name,phase:"requested",pool:e.pool,requestedAt:t,since:t}}function MM(e,t){if(!LM[t].includes(e.phase))return!1;if(t==="minted")return e.runner===void 0;if(DM.includes(t))return e.runner!==void 0;if(t==="verified"&&e.phase==="quarantined")return e.undestroyed===!0;return!0}function Yw(e,t,n){if(!MM(e,t.kind))throw new Wa(e.name,e.phase,t.kind);let r=(o,s={})=>({...e,...s,phase:o,since:n});switch(t.kind){case"lease-granted":return r("admitted",{lease:t.lease});case"lease-refused":return r("waiting");case"prepare":return r("preparing");case"ready":return r("registering");case"minted":return{...e,runner:{id:t.runnerId,name:t.runnerName}};case"online":return r("online");case"job-started":return r("busy");case"exited":return r("finishing",{exitCode:t.code});case"collected":return r("destroying",{teardown:"job-done"});case"drain":return NM.includes(e.phase)?r("withdrawn"):r("destroying",{teardown:"drained"});case"budget-unavailable":return r("destroying",{teardown:"budget-unavailable"});case"failed":return wd(e,{detail:t.detail,kind:"error",phase:e.phase},n);case"canary-failed":return wd(e,{detail:t.detail,kind:"canary",phase:e.phase},n);case"timed-out":return e.phase==="registering"?r("destroying",{teardown:"not-online"}):wd(e,{kind:"timeout",phase:e.phase},n);case"verified":if(e.phase==="quarantined")return{...e,undestroyed:!1};return e.fault?r("quarantined",{undestroyed:!1}):r("verified")}}function ht(e){return PM.includes(e)}function Xw(e){return IM.includes(e.phase)||qe(e)}function qe(e){return e.phase==="destroying"||e.phase==="quarantined"&&e.undestroyed===!0}function zw(e,t=120){let n=e.phase==="busy"?t:OM[e.phase];return n===void 0?void 0:Date.parse(e.since)+n*60000}function wd(e,t,n){if(e.phase==="destroying")return{...e,fault:e.fault??t,phase:"quarantined",since:n,undestroyed:!0};return{...e,fault:t,phase:"destroying",since:n,teardown:"fault"}}var Ja=1,HM=63,Ya=200,Rd="entry",Sd="event",GM=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,FM=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/,UM=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,jM=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,BM=/[\p{Cc}\p{Cf}]/u,tS=(e)=>I().map((t)=>t.length<=e&&GM.test(t)?t:F()),$d=(e)=>I().map((t)=>e.test(t)?t:F()),VM=$d(jM).map((e)=>Number.isNaN(Date.parse(e))?F():e),qM=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),KM=X().map((e)=>Number.isSafeInteger(e)?e:F()),Qw=I().map((e)=>e.trim().length>0&&e.length<=Ya&&!BM.test(e)?e:F()),nS=tS(HM),WM={at:VM,event:vr(),slot:nS,v:J([Ja])},Vt={},JM={"budget-unavailable":Vt,"canary-failed":{detail:Qw},collected:Vt,drain:Vt,exited:{code:KM},failed:{detail:Qw},"job-started":Vt,"lease-granted":{lease:$d(FM)},"lease-refused":Vt,minted:{runnerId:qM,runnerName:$d(UM)},online:Vt,prepare:Vt,ready:Vt,requested:{driver:J(vt),pool:tS(Kn)},"timed-out":Vt,verified:Vt};function Ed(e){let t=bd(e,"");if(t!==void 0)return{field:t||Rd,reason:"secret-shaped"};if(!eS(e))return{field:Rd,reason:"invalid"};let n=Zw(e,WM,"");if(n)return n;let r=e.event;if(!eS(r))return{field:Sd,reason:"invalid"};let o=r.kind;if(!vd(o))return{field:ds(Sd,"kind"),reason:"invalid"};return Zw(r,{...JM[o],kind:vr()},Sd)}function rS(e){try{let t=nS(e);return ir(t)?void 0:t}catch{return}}function vd(e){return e==="requested"||Kw.includes(e)}function Zw(e,t,n){let r=Object.keys(e).find((o)=>!Object.hasOwn(t,o));if(r!==void 0)return{field:ds(n,r)||Rd,reason:"invalid"};for(let[o,s]of Object.entries(t))try{s(e[o])}catch{return{field:ds(n,o),reason:"invalid"}}return}function eS(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var ps="ledger",eH="slots.jsonl",tH=448,nH=384,rH=18,uS=10,oH="ELOOP",sH={duplicate:()=>"the ledger already holds a slot of that name",invalid:(e)=>`${e} is not valid`,"secret-shaped":(e)=>`${e} looks like a secret, which the ledger never stores`,"unknown-slot":()=>"the ledger holds no slot of that name"},iH={duplicate:"requests a slot that an earlier line already requested","unknown-slot":"changes a slot that no earlier line requested"};class it extends Error{path;problem;detail;line;_tag="LedgerFileError";constructor(e,t,n,r){super(`Slot ledger ${e}${r===void 0?"":` line ${r}`} ${n}`);this.path=e;this.problem=t;this.detail=n;this.line=r;this.name="LedgerFileError"}}class lS extends Error{reason;field;slot;event;_tag="LedgerEntryError";constructor(e,t,n,r){let o=n===void 0?"a slot":`slot ${n}`,s=r===void 0?"an event":`"${r}"`;super(`Refused to record ${s} for ${o}: ${sH[e](t)}`);this.reason=e;this.field=t;this.slot=n;this.event=r;this.name="LedgerEntryError"}}function Qr(e){return ZM(e,ps,eH)}function Qa(e,t={}){let n=t.now??(()=>new Date),r=Qr(e),o=cH(r),s=pS(r,o.text),i=o.mark,a=(u)=>{let l=JSON.stringify(u),d=JSON.parse(l),f=Ed(d);if(f)throw oS(d,f.reason,f.field);let m=d,g=dS(s,m);if("refusal"in g)throw oS(m,g.refusal,void 0);return i=uH(r,`${l}
401
+ `,i),s.set(m.slot,g.record),g.record},c=()=>n().toISOString();return{destroyable:(u)=>{let l=s.get(u.name);return l?.driver===u.driver&&l.pool===u.pool&&qe(l)},droppedBytes:o.droppedBytes,get:(u)=>s.get(u),path:r,record:(u,l)=>a({at:c(),event:l,slot:u,v:Ja}),request:(u)=>a({at:c(),event:{driver:u.driver,kind:"requested",pool:u.pool},slot:u.name,v:Ja}),slots:()=>[...s.values()]}}function dS(e,t){let n=e.get(t.slot),{event:r}=t;if(r.kind==="requested"){if(n)return{refusal:"duplicate"};return{record:Jw({driver:r.driver,name:t.slot,pool:r.pool},t.at)}}if(!n)return{refusal:"unknown-slot"};return{record:Yw(n,r,t.at)}}function oS(e,t,n){let{event:r,slot:o}=e??{},s=r?.kind;return new lS(t,n,rS(o),vd(s)?s:void 0)}function pS(e,t){let n=new Map,r=t.split(`
402
+ `).slice(0,-1);for(let[o,s]of r.entries()){let i=(d)=>new it(e,"corrupt",d,o+1),a;try{a=JSON.parse(s)}catch{throw i("is not JSON")}let c=Ed(a);if(c)throw i(aH(c));let u=a,l;try{l=dS(n,u)}catch(d){if(d instanceof Wa)throw i(`asks for a change the slot cannot take: ${d.message}`);throw d}if("refusal"in l)throw i(iH[l.refusal]);n.set(u.slot,l.record)}return n}function aH(e){return e.reason==="secret-shaped"?`holds a secret-shaped ${e.field}`:`has an invalid ${e.field}`}function fS(e){let t=Qr(e),n=cS(t);Xa(n,sS(n),"directory");let r=_d(t,un.O_RDONLY|un.O_NOFOLLOW);try{Xa(t,kd(r),"file");let o=aS(r),s=o.lastIndexOf(uS)+1;return[...pS(t,o.subarray(0,s).toString("utf-8")).values()]}finally{za(r)}}function cH(e){let t=cS(e);zM(t,{mode:tH,recursive:!0}),Xa(t,sS(t),"directory");let n=!YM(e),r=_d(e,un.O_RDWR|un.O_CREAT|un.O_NOFOLLOW);try{let o=kd(r);Xa(e,o,"file");let s=aS(r),i=s.lastIndexOf(uS)+1,a=s.length-i;if(a>0)XM(r,i),xd(r);if(n)lH(t);let c={dev:o.dev,ino:o.ino,size:i};return{droppedBytes:a,mark:c,text:s.subarray(0,i).toString("utf-8")}}finally{za(r)}}function uH(e,t,n){let r=_d(e,un.O_WRONLY|un.O_APPEND|un.O_NOFOLLOW);try{let o=kd(r);if(o.dev!==n.dev||o.ino!==n.ino||o.size!==n.size)throw new it(e,"conflict","changed after it was read; open the ledger again");let s=Buffer.from(t),i=0;while(i<s.length)i+=QM(r,s,i);return xd(r),{...n,size:n.size+s.length}}finally{za(r)}}function _d(e,t){try{return iS(e,t,nH)}catch(n){if(n.code===oH)throw new it(e,"unsafe","is a symbolic link");throw Error(`Could not open the slot ledger ${e}`,{cause:n})}}function Xa(e,t,n){if(t.isSymbolicLink())throw new it(e,"unsafe","is a symbolic link");if(!(n==="directory"?t.isDirectory():t.isFile()))throw new it(e,"unsafe",`is not a ${n==="file"?"regular file":n}`);let o=process.getuid?.();if(o===void 0)throw new it(e,"unsafe","cannot be checked for its owner on this platform");if(t.uid!==o)throw new it(e,"unsafe",`is owned by uid ${t.uid}, not by the user running Hydra (uid ${o})`);if((t.mode&rH)!==0)throw new it(e,"unsafe","can be written by other users")}function lH(e){let t=iS(e,un.O_RDONLY);try{xd(t)}finally{za(t)}}var bH="guard.json",gS=1,wH=448,SH=384,RH=18,hS=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),yS=N({id:hS,name:I()}),$H=N({requireApproval:Q(),runWorkflows:Q(),sendSecrets:Q(),sendWriteTokens:Q()}),EH=N({approval:J(dd).or(ne()),privateRepositories:$H.or(ne())}),vH=N({allowsPublicRepositories:Q(),default:Q(),id:hS,name:I(),repositories:Z(yS).or(ne()),restrictedToWorkflows:Q(),selectedWorkflows:Z(I()),visibility:I()}),kH=N({group:vH,groupName:I(),kind:J(["org"]),org:I()}).map((e)=>e),xH=N({kind:J(["repo"]),repository:I(),visibility:J(["internal","private","public"])}).map((e)=>e),_H=N({acceptedRunners:Z(yS),forkPolicy:EH,scope:kH.or(xH),url:I()}),TH=N({pools:kr(_H),recordedAt:I(),v:J([gS])});class On extends Error{path;_tag="GuardRecordError";constructor(e,t){super(`Guard record ${e} ${t}`);this.path=e;this.name="GuardRecordError"}}function bS(e){return yH(e,ps,bH)}function wS(e,t){let{runners:n,...r}=e;return{...r,acceptedRunners:n.filter((o)=>!gd(t,o))}}function ec(e){let t=bS(e);if(!mS(t))return;Za(Td(t),"directory"),Za(t,"file");let n;try{n=TH(JSON.parse(fH(t,"utf8")))}catch{throw new On(t,"is not a valid guard record")}if(Number.isNaN(Date.parse(n.recordedAt)))throw new On(t,"has no valid recording time");return{pools:n.pools,recordedAt:n.recordedAt}}function SS(e,t){let n=bS(e);if(pH(Td(n),{mode:wH,recursive:!0}),Za(Td(n),"directory"),mS(n))Za(n,"file");let r=`${n}.${process.pid}.tmp`;gH(r,{force:!0}),hH(r,`${JSON.stringify({...t,v:gS},null,2)}
403
+ `,{flag:"wx",mode:SH}),mH(r,n)}function Za(e,t){let n=dH(e);if(!(t==="directory"?n.isDirectory():n.isFile()))throw new On(e,t==="file"?"is not a regular file":"is not a directory");if(n.uid!==process.getuid?.())throw new On(e,"is not owned by the user running Hydra");if((n.mode&RH)!==0)throw new On(e,"can be written by other users")}var AH="RunnerScaleSetJobMessages",RS="[redacted]",be=I().or(ne()).or($t()).map((e)=>e??""),Fe=X().or(ne()).or($t()).map((e)=>e==null?0:Number.isSafeInteger(e)&&e>=0?e:F()),Ad=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),CH=Fe.map((e)=>e>0?e:void 0),Tt=I().map((e)=>e.trim()===""?F():e),$S=Q().or(ne()).or($t()).map((e)=>e??!1),OH=Z(I()).or(ne()).or($t()).map((e)=>e??[]),Cd=N({totalAcquiredJobs:Fe,totalAssignedJobs:Fe,totalAvailableJobs:Fe,totalBusyRunners:Fe,totalIdleRunners:Fe,totalRegisteredRunners:Fe,totalRunningJobs:Fe}).map((e)=>({totalAcquiredJobs:e.totalAcquiredJobs,totalAssignedJobs:e.totalAssignedJobs,totalAvailableJobs:e.totalAvailableJobs,totalBusyRunners:e.totalBusyRunners,totalIdleRunners:e.totalIdleRunners,totalRegisteredRunners:e.totalRegisteredRunners,totalRunningJobs:e.totalRunningJobs})),PH=N({name:Tt,type:be}),fs=N({createdOn:be,id:Ad,labels:Z(PH).or(ne()).or($t()).map((e)=>e??[]),name:Tt,RunnerSetting:N({disableUpdate:$S}).or(ne()).or($t()).map((e)=>e??{disableUpdate:!1}),runnerGroupId:Fe,runnerGroupName:be,statistics:Cd.or(ne()).or($t())}).map((e)=>({createdOn:e.createdOn,disableUpdate:e.RunnerSetting.disableUpdate,id:e.id,labels:e.labels.map((t)=>({name:t.name,type:t.type})),name:e.name,runnerGroupId:e.runnerGroupId,runnerGroupName:e.runnerGroupName,...e.statistics?{statistics:e.statistics}:{}})),ES=N({id:Ad,isDefaultGroup:$S,name:Tt,size:Fe}).map((e)=>({id:e.id,isDefault:e.isDefaultGroup,name:e.name,size:e.size})),nc=N({id:Ad,name:Tt,runnerScaleSetId:CH}).map((e)=>({id:e.id,name:e.name,...e.runnerScaleSetId===void 0?{}:{scaleSetId:e.runnerScaleSetId}}));function ms(e){return N({value:Z(e).or(ne()).or($t())}).map((t)=>t.value??[])}var vS=N({value:Z(Fe).or(ne()).or($t()).map((e)=>e??[])}).map((e)=>e.value),kS=N({encodedJITConfig:Tt,runner:nc}),xS=N({messageQueueAccessToken:Tt,messageQueueUrl:Tt,ownerName:be,sessionId:Tt,statistics:Cd.or(ne()).or($t())}),_S=N({token:Tt,url:Tt}),TS=N({expires_at:be,token:Tt}),AS=N({message:be,typeName:be}),tc=N({eventName:be,finishTime:be,jobDisplayName:be,jobId:be,jobWorkflowRef:be,ownerName:be,queueTime:be,repositoryName:be,requestLabels:OH,runnerAssignTime:be,runnerRequestId:Fe,scaleSetAssignTime:be,workflowRunId:Fe}).map((e)=>({eventName:e.eventName,finishTime:e.finishTime,jobDisplayName:e.jobDisplayName,jobId:e.jobId,jobWorkflowRef:e.jobWorkflowRef,ownerName:e.ownerName,queueTime:e.queueTime,repositoryName:e.repositoryName,requestLabels:e.requestLabels,runnerAssignTime:e.runnerAssignTime,runnerRequestId:e.runnerRequestId,scaleSetAssignTime:e.scaleSetAssignTime,workflowRunId:e.workflowRunId})),IH=N({acquireJobUrl:be}),NH=N({runnerId:Fe,runnerName:be}),DH=N({result:be,runnerId:Fe,runnerName:be}),LH=N({messageType:be}),MH=N({body:be,messageId:Fe,messageType:be,statistics:Cd});function CS(e){return Object.freeze({reveal:()=>e,toJSON:()=>RS,toString:()=>RS})}function OS(e){let t=MH(e);if(t.messageType!==AH)return{kind:"unsupported",messageType:t.messageType};let n={id:t.messageId,jobsAssigned:[],jobsAvailable:[],jobsCompleted:[],jobsStarted:[],statistics:t.statistics},r=t.body===""?[]:JSON.parse(t.body);if(!Array.isArray(r))throw TypeError("the message body is not a list");for(let o of r){let{messageType:s}=LH(o);switch(s){case"JobAvailable":n.jobsAvailable.push({...tc(o),...IH(o)});break;case"JobAssigned":n.jobsAssigned.push(tc(o));break;case"JobStarted":n.jobsStarted.push({...tc(o),...NH(o)});break;case"JobCompleted":n.jobsCompleted.push({...tc(o),...DH(o)});break;default:break}}return{kind:"message",message:n}}var HH="r5n-hydra",PS="[redacted]",GH=4,FH=120000,UH=60000,jH=1000,BH=30000,VH=60000,Od=1000,qH=0.5,KH=200,WH=400,JH=401,YH=403,XH=404,zH=409,Pd=429,NS=500,QH=501,ZH=503,eG=300,tG=399,IS="\uFEFF",nG=[/\bgh[opsur]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_\w{20,}\b/g,/\beyJ[\w-]+\.[\w-]+\.[\w-]*/g,/\b(RemoteAuth|Bearer)\s+\S+/gi,/[A-Za-z0-9+/_-]{64,}={0,2}/g],rG=/[\p{Cc}\p{Cf}]+/gu,oG=/\s+/g,sG=[["AgentExistsException","runner-exists"],["AgentNotFoundException","runner-not-found"],["JobStillRunningException","job-still-running"]];class yt extends Error{operation;method;path;status;failure;_tag="ScaleSetApiError";constructor(e,t,n,r,o,s){let i=r===void 0?"got no response":`returned ${r}`;super(`${e} failed: ${t} ${n} ${i}${s?` (${s})`:""}`);this.operation=e;this.method=t;this.path=n;this.status=r;this.failure=o;this.name="ScaleSetApiError"}}function DS(e={}){let t=e.maxRetries??GH,n=e.requestTimeoutMs??UH,r=e.retryBaseMs??jH,o=e.retryMaxMs??BH,s=e.sleep??dG;function i(u){let l=Math.min(r*2**u,o);return Math.min(l+Math.random()*l*qH,o)}function a(u,l,d){if(d>=t)return;if(l.kind==="failed")return u.idempotent?i(d):void 0;let{status:f}=l.response;if(f===Pd||f===ZH&&u.idempotent){let m=LS(l.response.headers)??i(d);return m<=VH?m:void 0}if(u.retryStatuses?.includes(f))return i(d);if(f>=NS&&f!==QH&&u.idempotent)return i(d);return}async function c(u){let l=u.timeoutMs??n,d=AbortSignal.timeout(l),f=u.signal?AbortSignal.any([u.signal,d]):d;try{let m=await fetch(u.url,{body:u.body===void 0?void 0:JSON.stringify(u.body),headers:{...u.headers,"User-Agent":HH,...u.body===void 0?{}:{"Content-Type":"application/json"}},method:u.method,redirect:"manual",signal:f}),g=await m.text();return{kind:"answered",response:{headers:m.headers,status:m.status,text:lG(g)}}}catch(m){if(u.signal?.aborted)throw Pe(u,void 0,"aborted","stopped by the caller");if(d.aborted)return{detail:`timed out after ${l/Od} s`,failure:"timeout",kind:"failed"};return{detail:m instanceof Error?m.message:String(m),failure:"network",kind:"failed"}}}return{pollTimeoutMs:e.pollTimeoutMs??FH,async send(u){for(let l=0;;l++){if(u.signal?.aborted)throw Pe(u,void 0,"aborted","stopped by the caller");let d=await c(u),f=a(u,d,l);if(f===void 0){if(d.kind==="failed")throw Pe(u,void 0,d.failure,d.detail);if(uG(d.response.status))throw Pe(u,d.response.status,"redirect","refused to follow a redirect");return d.response}try{await s(f,u.signal)}catch{throw Pe(u,void 0,"aborted","stopped by the caller")}}}}}function Pe(e,t,n,r){return new yt(e.operation,e.method,e.url.pathname,t,n,iG(r,e.secrets))}function Id(e,t){let{exception:n,message:r}=aG(t),o=sG.find(([c])=>n.includes(c))?.[1],s=t.status===Pd,i=s?LS(t.headers):void 0,a=[s?`rate limited${i===void 0?"":`; retry in ${i/Od} s`}`:"",r].filter(Boolean).join("; ");return Pe(e,t.status,o??cG(t.status),a)}function gs(e,t,n){if(!n.includes(t.status))throw Id(e,t)}function Ke(e,t,n){let r;try{r=JSON.parse(t.text)}catch{throw Pe(e,t.status,"response","the response is not JSON")}try{return n(r)}catch{throw Pe(e,t.status,"response","the response has an unexpected shape")}}function iG(e,t){let n=t.reduce((r,o)=>o?r.replaceAll(o,PS):r,e);return nG.reduce((r,o)=>r.replace(o,PS),n).replace(rG," ").replace(oG," ").trim().slice(0,KH)}function aG(e){if(e.text.trim()==="")return{exception:"",message:""};if(e.headers.get("content-type")?.includes("text/plain"))return{exception:"",message:e.text};try{let t=AS(JSON.parse(e.text));return{exception:t.typeName,message:t.message}}catch{return{exception:"",message:""}}}function cG(e){switch(e){case WH:return"bad-request";case JH:return"unauthorized";case YH:return"forbidden";case XH:return"not-found";case zH:return"conflict";case Pd:return"rate-limited";default:return e>=NS?"server":"unexpected-status"}}function uG(e){return e>=eG&&e<=tG}function LS(e){let t=e.get("retry-after")?.trim();if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*Od);let r=Date.parse(t);return Number.isFinite(r)?Math.max(0,r-Date.now()):void 0}function lG(e){return e.startsWith(IS)?e.slice(IS.length):e}function dG(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e),s=()=>{clearTimeout(o),r(t?.reason)};t?.addEventListener("abort",s,{once:!0})})}var pG=60000,fG=1000,MS=200,mG=299,gG=401,hG=403,HS=".actions.githubusercontent.com",yG=new Set(["127.0.0.1","[::1]"]),GS=/\/+$/,bG=Array.from({length:mG-MS+1},(e,t)=>MS+t);function wG(e){return e.kind==="repo"?`/repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}/actions/runners/registration-token`:`/orgs/${encodeURIComponent(e.org)}/actions/runners/registration-token`}function Nd(e,t){let n;try{n=new URL(e)}catch{return"it is not a URL"}if(n.username||n.password)return"it carries credentials";let r=new URL(t);if(r.origin===ll){if(n.protocol!=="https:")return"it is not https";return n.hostname.endsWith(HS)?void 0:`its host is not under *${HS}`}if(n.hostname!==r.hostname)return`its host is not ${r.hostname}, the configured API host`;return n.protocol==="https:"||n.protocol==="http:"&&yG.has(n.hostname)?void 0:"it is not https"}function SG(e){let t=e.split(".")[1];if(!t)return;try{let r=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))?.exp;return typeof r==="number"&&Number.isFinite(r)?r*fG:void 0}catch{return}}function FS({apiUrl:e,github:t,http:n,now:r=Date.now,url:o}){let s=de(o),i=o.replace(GS,""),a=new URL(`${e.replace(GS,"")}/`),c=De(s),u,l;async function d(f){let m=await t.request({idempotent:!0,method:"POST",operation:`Create a runner registration token for ${c}`,path:wG(s),schema:TS}),g={body:{runner_event:"register",url:i},headers:{Accept:"application/json",Authorization:`RemoteAuth ${m.token}`},idempotent:!0,method:"POST",operation:`Exchange the registration token of ${c} for an Actions service connection`,retryStatuses:[gG,hG],secrets:[m.token],signal:f,url:new URL("actions/runner-registration",a)},h=await n.send(g);gs(g,h,bG);let E=Ke(g,h,_S),v={...g,secrets:[m.token,E.token]},S=Nd(E.url,e);if(S)throw Pe(v,h.status,"refused-url",`refused the Actions service URL: ${S}`);let _=SG(E.token);if(_===void 0)throw Pe(v,h.status,"response","the admin token carries no expiry");return{expiresAt:_,serviceUrl:new URL(E.url),token:E.token}}return{apiUrl:e,async connection(f){for(;;){if(u&&u.expiresAt-pG>r())return u;l??=d(f).finally(()=>{l=void 0});try{return u=await l,u}catch(m){if(f?.aborted||!(m instanceof yt)||m.failure!=="aborted")throw m}}},invalidate(f){if(u?.token===f)u=void 0},target:s}}var RG=/[\p{Cc}\p{Cf}]/u;function At(e,t){if(Number.isSafeInteger(e)&&e>0)return;throw RangeError(`${t} must be a positive integer, got ${String(e)}`)}function rc(e,t){if(Number.isSafeInteger(e)&&e>=0)return;throw RangeError(`${t} must be a whole number, got ${String(e)}`)}function qt(e,t){if(typeof e==="string"&&e.trim()!==""&&!RG.test(e))return;throw RangeError(`${t} must be a non-empty name without control characters`)}var Kt="_apis/runtime/runnerscalesets",US="_apis/runtime/runnergroups/",oc="_apis/distributedtask/pools/0/agents",$G="6.0-preview",EG=401,vG=new Set(["DELETE","GET","PUT"]),kG=/\/+$/,xG=/^\/+/;function _G(e,t,n={}){let r=new URL(e);r.pathname=`${r.pathname.replace(kG,"")}/${t.replace(xG,"")}`;for(let[o,s]of Object.entries(n))r.searchParams.set(o,s);if(!r.searchParams.has("api-version"))r.searchParams.set("api-version",$G);return r}function jS(e,t){return{admin:e,async call({bearer:n,body:r,expect:o,idempotent:s,method:i,operation:a,path:c,query:u,signal:l}){let d=await e.connection(l),f=n??d.token,m={body:r,headers:{Accept:"application/json",Authorization:`Bearer ${f}`},idempotent:s??vG.has(i),method:i,operation:a,secrets:[d.token,f],signal:l,url:_G(d.serviceUrl,c,u)},g=await t.send(m);if(o.includes(g.status))return{request:m,response:g};if(g.status===EG&&n===void 0)e.invalidate(d.token);throw Id(m,g)},http:t}}var Zr=2147483647,TG="X-ScaleSetMaxCapacity",Dd=200,AG=202,BS=204,CG=401,OG=404,PG="application/json; api-version=6.0-preview";async function VS(e,t,n,r){At(t,"The scale set id"),qt(n,"The session owner name");let o=`${Kt}/${t}/sessions`,s=`the message session of scale set ${t}`,i=await c("POST",o,`Open ${s}`,{ownerName:n},void 0,r),a;async function c(m,g,h,E,v,S){let{request:_,response:C}=await e.call({body:E,expect:[Dd],method:m,operation:h,path:g,signal:S}),w=Ke(_,C,xS),x={..._,secrets:[..._.secrets,w.messageQueueAccessToken]},y=Nd(w.messageQueueUrl,e.admin.apiUrl),R=w.statistics??v;if(y||!R)throw await u(w.sessionId).catch(()=>{return}),y?Pe(x,C.status,"refused-url",`refused the message queue URL: ${y}`):Pe(x,C.status,"response","the session carries no statistics");return{id:w.sessionId,ownerName:w.ownerName||n,queueToken:w.messageQueueAccessToken,queueUrl:new URL(w.messageQueueUrl),statistics:R}}async function u(m){await e.call({expect:[BS,OG],method:"DELETE",operation:`Close ${s}`,path:`${o}/${encodeURIComponent(m)}`})}async function l(m){if(i.queueToken!==m)return;a??=c("PATCH",`${o}/${encodeURIComponent(i.id)}`,`Refresh ${s}`,void 0,i.statistics).then((g)=>{i=g}).finally(()=>{a=void 0}),await a}async function d(m){let g=i.queueToken;try{return await m(g)}catch(h){if(!(h instanceof yt)||h.status!==CG)throw h;return await l(g),m(i.queueToken)}}function f(m,g,h,E,v){return{headers:{Authorization:`Bearer ${h}`},idempotent:!0,method:m,operation:E,secrets:[h],url:g,...v}}return{async acquireJobs(m,g){for(let h of m)rc(h,"A runner request id");if(m.length===0)return[];return d(async(h)=>{let{request:E,response:v}=await e.call({bearer:h,body:m,expect:[Dd],idempotent:!0,method:"POST",operation:`Acquire ${m.length} job(s) for scale set ${t}`,path:`${Kt}/${t}/acquirejobs`,signal:g});return Ke(E,v,vS)})},async close(){await u(i.id)},async deleteMessage(m){rc(m,"The message id"),await d(async(g)=>{let h=new URL(i.queueUrl);h.pathname=`${h.pathname}/${m}`;let E=f("DELETE",h,g,`Acknowledge message ${m} of ${s}`,{}),v=await e.http.send(E);gs(E,v,[BS])})},async getMessage(m,g,h){if(rc(m,"The last message id"),!Number.isSafeInteger(g)||g<0||g>Zr)throw RangeError(`The advertised capacity must be an integer from 0 to ${Zr}`);return d(async(E)=>{let v=new URL(i.queueUrl);if(m>0)v.searchParams.set("lastMessageId",String(m));let S=f("GET",v,E,`Poll ${s}`,{headers:{Accept:PG,Authorization:`Bearer ${E}`,[TG]:String(g)},signal:h,timeoutMs:e.http.pollTimeoutMs}),_=await e.http.send(S);if(_.status===AG)return;gs(S,_,[Dd]);let C=Ke(S,_,OS);if(C.kind==="unsupported")throw Pe(S,_.status,"unsupported-message",`unsupported message type ${JSON.stringify(C.messageType)}`);return C.message})},info(){return{id:i.id,ownerName:i.ownerName,scaleSetId:t,statistics:i.statistics}},async refresh(){await l(i.queueToken)},statistics(){return i.statistics}}}var IG=["requested","waiting","admitted","preparing","registering","online","busy"],Le={now:()=>Date.now(),sleep:NG};class We extends Error{pool;operation;problem;_tag="DemandError";constructor(e,t,n,r){super(`${t} for pool ${e} failed: ${r}`);this.pool=e;this.operation=t;this.problem=n;this.name="DemandError"}}function eo(e,t){return e.filter((n)=>n.pool===t&&IG.includes(n.phase))}function sc(e,t){return e.filter((n)=>n.pool===t&&n.phase==="busy").length}function to(e){return Number.isFinite(e)?Math.max(0,Math.min(Zr,Math.floor(e))):0}function NG(e,t){return new Promise((n)=>{if(t.aborted){n();return}let r=setTimeout(o,e);function o(){clearTimeout(r),t.removeEventListener("abort",o),n()}t.addEventListener("abort",o,{once:!0})})}var DG=300000,LG=60000,MG=3,HG="the guard has not yet compared the pool with its record";function qS(e){let t=e.clock??Le,n=e.intervalMs??DG,r=e.retryMs??LG,o=Object.keys(e.pools),s=new Map,i=new Map,a=0,c=!1,u,l,d=(v,S)=>{let _=S.map((x)=>x.detail).join("; ");if(!s.has(v))e.log(`pool ${v} takes no new jobs until the guard finds it as recorded: ${_}`);s.set(v,_);let C=i.get(v)??new Set,w=new Set;for(let x of S){let y=`${x.kind}\x00${x.detail}`;if(w.add(y),C.has(y))continue;e.alert({detail:x.detail,pool:v,reason:x.kind==="foreign-runner"?"foreign-runner":"guard-drift"})}i.set(v,w)},f=(v)=>{if(i.delete(v),!s.delete(v))return;e.log(`pool ${v} takes jobs again: the guard finds it as recorded`)},m=(v)=>{a++;let S=v instanceof Error?v.message:String(v);if(e.log(`the guard could not read the runner groups and policies (${a} in a row): ${S}`),a!==MG)return;e.alert({detail:`${a} rounds in a row failed; the last: ${GG(v)}`,reason:"guard-failed"})},g=(v)=>{let S=`the guard record cannot be read: ${v instanceof Error?v.message:String(v)}`;for(let _ of o)d(_,[{detail:S,kind:"unrecorded"}])};async function h(){let v;try{v=e.record()}catch(C){g(C);return}let S;try{S=await e.reader.snapshots(e.pools)}catch(C){m(C);return}a=0;let _=e.minted();for(let[C,w]of Object.entries(e.pools)){let x=S[C];if(!x)continue;let y=Ka({baseline:v?.pools[C],config:w,minted:_,snapshot:x});if(y.length===0)f(C);else d(C,y)}c=!0}async function E(v){while(!v.aborted){if(await t.sleep(c&&a===0?n:r,v),v.aborted)return;await h()}}return{held:(v)=>s.get(v)??(c?void 0:HG),round:h,start(){if(l)return;u=new AbortController,l=E(u.signal)},async stop(){u?.abort(),await l,u=void 0,l=void 0}}}function GG(e){if(!(e instanceof Re))return"an unexpected error";return`${e.operation} ${e.status===void 0?"got no response":`returned ${e.status}`}`}import{existsSync as AU}from"fs";var FG=20000,UG=409,jG={busy:"busy",deleted:"removed",gone:"gone"};function KS(e){let{github:t,labels:n,pool:r,reader:o}=e,s=de(e.url),i=e.clock??Le,a=e.intervalMs??FG,c=0,u,l="idle",d,f,m,g=(_,C)=>{l=_,d=C};async function h(){if(s.kind==="repo")return Qh;let _=e.runnerGroup,C=_===void 0?void 0:await Ur(t,s.org,_);if(C)return C.id;throw new We(r,"Start the polled demand","runner-group-missing",`${s.org} has no runner group named ${_??"(none set)"}`)}async function E(_){while(!_.aborted){try{if(c=await o.queued(_),_.aborted)return;g("polling"),await e.onDemand?.(_)}catch(C){if(_.aborted)return;c=0,g("retrying",C instanceof Error?C.message:String(C))}await i.sleep(a,_)}}async function v(_){if(u===void 0)throw new We(r,`Mint a runner for slot ${_}`,"not-started","the demand source has not started");return ey(t,s,{labels:n,name:_,runnerGroupId:u})}function S({encodedJitConfig:_,runner:C}){return{jit:Ua(_),runner:{id:C.id,name:C.name}}}return{desired(){return Math.min(to(e.capacity()),sc(e.slots(),r)+c)},kind:"poll",async mint(_){let C=`Mint a just-in-time runner for slot ${_}`;try{return S(await v(_))}catch(x){if(!(x instanceof Re)||x.status!==UG)throw x}let w=await ty(t,s,_);if(w&&!ji(n,w.labels))throw new We(r,C,"runner-exists",`a runner named ${_} lacks the pool's labels`);if(w&&(w.busy||await zn(t,s,w.id)==="busy"))throw new We(r,C,"runner-exists",`the runner ${_} is running a job`);return S(await v(_))},pool:r,async release(_){return jG[await zn(t,s,_.id)]},async start(){if(m)return;u=await h();let _=new AbortController;f=_,m=E(_.signal)},status:()=>({demand:c,detail:d,kind:"poll",pool:r,state:l}),async stop(){f?.abort(),await m,f=void 0,m=void 0,g("stopped")}}}var Pn=200,WS=204,In=404,BG="System",VG="_work";function Ld(e,t){let n=(r)=>[...new Set(r.map((o)=>o.toLowerCase()))].sort().join(`
404
+ `);return n(e.labels.map((r)=>r.name))===n(t)}function ic({apiUrl:e,github:t,http:n,now:r,url:o}){let s=DS(n),i=jS(FS({apiUrl:e,github:t,http:s,now:r,url:o}),s);function a(d,f,m){if(f.length<=1)return f[0];throw Pe(d.request,d.response.status,"response",`found ${f.length} ${m}`)}function c({labels:d,name:f,runnerGroupId:m}){At(m,"The runner group id"),qt(f,"The scale set name");for(let g of d)qt(g,"A scale set label")}async function u(d){c(d);let{disableUpdate:f=!0,labels:m,name:g,runnerGroupId:h}=d,E=m.length>0?m:[g],v=await i.call({body:{labels:E.map((S)=>({name:S,type:BG})),name:g,RunnerSetting:f?{disableUpdate:f}:{},runnerGroupId:h},expect:[Pn],method:"POST",operation:`Create the scale set ${g} in runner group ${h}`,path:Kt});return Ke(v.request,v.response,fs)}async function l(d,f){At(d,"The runner group id"),qt(f,"The scale set name");let m=await i.call({expect:[Pn],method:"GET",operation:`Read the scale set ${f} in runner group ${d}`,path:Kt,query:{name:f,runnerGroupId:String(d)}});return a(m,Ke(m.request,m.response,ms(fs)),"scale sets")}return{createScaleSet:u,async deleteScaleSet(d){At(d,"The scale set id");let{response:f}=await i.call({expect:[WS,In],method:"DELETE",operation:`Delete scale set ${d}`,path:`${Kt}/${d}`});return f.status===In?"gone":"deleted"},async ensureScaleSet(d){c(d);let f=await l(d.runnerGroupId,d.name),m=f??await u(d),g=d.labels.length>0?d.labels:[d.name];return{created:f===void 0,labelsMatch:Ld(m,g),scaleSet:m}},async findRunnerByName(d){qt(d,"The runner name");let f=await i.call({expect:[Pn],method:"GET",operation:`Find the runner ${d}`,path:oc,query:{agentName:d}});return a(f,Ke(f.request,f.response,ms(nc)),"runners")},async generateJitConfig(d,{name:f,workFolder:m=VG}){At(d,"The scale set id"),qt(f,"The runner name"),qt(m,"The work folder");let g=await i.call({body:{name:f,workFolder:m},expect:[Pn],method:"POST",operation:`Generate a just-in-time configuration for runner ${f} in scale set ${d}`,path:`${Kt}/${d}/generatejitconfig`}),h=Ke(g.request,g.response,kS);return{jitConfig:CS(h.encodedJITConfig),runner:h.runner}},async getRunner(d){At(d,"The runner id");let f=await i.call({expect:[Pn,In],method:"GET",operation:`Read runner ${d}`,path:`${oc}/${d}`});return f.response.status===In?void 0:Ke(f.request,f.response,nc)},async getRunnerGroup(d){qt(d,"The runner group name");let f=await i.call({expect:[Pn],method:"GET",operation:`Read the runner group ${d}`,path:US,query:{groupName:d}}),m=a(f,Ke(f.request,f.response,ms(ES)),"groups");if(m)return m;throw Pe(f.request,f.response.status,"not-found",`no runner group is named ${d}`)},getScaleSet:l,async getScaleSetById(d){At(d,"The scale set id");let f=await i.call({expect:[Pn,In],method:"GET",operation:`Read scale set ${d}`,path:`${Kt}/${d}`});return f.response.status===In?void 0:Ke(f.request,f.response,fs)},async listScaleSets(d){At(d,"The runner group id");let f=await i.call({expect:[Pn],method:"GET",operation:`List the scale sets in runner group ${d}`,path:Kt,query:{runnerGroupId:String(d)}});return Ke(f.request,f.response,ms(fs))},async openSession(d,f,m){return VS(i,d,f,m)},async removeRunner(d){At(d,"The runner id");try{let{response:f}=await i.call({expect:[WS,In],method:"DELETE",operation:`Remove runner ${d}`,path:`${oc}/${d}`});return f.status===In?"gone":"removed"}catch(f){if(f instanceof yt&&f.failure==="job-still-running")return"busy";throw f}}}}async function JS({capacity:e,handle:t,session:n,signal:r}){await t({id:-1,jobsAssigned:[],jobsAvailable:[],jobsCompleted:[],jobsStarted:[],statistics:n.statistics()},r);let o=0;while(!r.aborted){let s;try{s=await n.getMessage(o,e(),r)}catch(i){if(r.aborted)return;throw i}if(await t(s,r),!s)continue;o=s.id,await n.deleteMessage(s.id)}}var qG=60000,Md=1000,KG={alertAfterMs:5*qG,retryMs:30*Md,slowRetryMs:60*Md};function XS(e){let{client:t,labels:n,ownerName:r,pool:o,runnerGroupId:s,scaleSetId:i}=e,a=e.clock??Le,c={...KG,...e.retry},u=()=>to(e.capacity()),l=0,d="idle",f,m,g,h=(x,y)=>{d=x,f=y};async function E(){let y=await t.getScaleSetById(i);if(!y)throw new We(o,"Start the scale set demand","scale-set-missing",`scale set ${i} no longer exists; hydra pool add creates the pool's scale set`);if(y.runnerGroupId!==s)throw new We(o,"Start the scale set demand","runner-group-changed",`scale set ${y.name} moved to runner group ${y.runnerGroupId} from ${s}; remove the pool and add it again`);if(!Ld(y,n))throw new We(o,"Start the scale set demand","labels-changed",`scale set ${y.name} carries other labels than the pool; remove the pool and add it again`)}async function v(x){let y,R=!1;while(!x.aborted){h("connecting");try{return await t.openSession(i,r,x)}catch(A){if(x.aborted)return;let k=A instanceof yt&&A.failure==="conflict";y=k?y??a.now():void 0;let D=y!==void 0&&a.now()-y>=c.alertAfterMs;if(h(k?"conflict":"retrying",YS(A)),D&&!R)R=!0,e.alert?.({detail:`another session has held scale set ${i} for ${Math.round(c.alertAfterMs/Md)} s`,pool:o,reason:"session-conflict"});await a.sleep(D?c.slowRetryMs:c.retryMs,x)}}return}function S(x){return async(y,R)=>{if(y){let A=[...new Set(y.jobsAvailable.map((k)=>k.runnerRequestId).filter((k)=>k>0))];if(A.length>0)await x.acquireJobs(A,R);l=y.statistics.totalAssignedJobs}await e.onDemand?.(R)}}async function _(x,y){h("listening");try{return await JS({capacity:u,handle:S(x),session:x,signal:y}),"stopped"}catch(R){if(y.aborted)return"stopped";if(R instanceof yt&&R.failure==="unsupported-message")return h("degraded",R.message),e.alert?.({detail:R.message,pool:o,reason:"unknown-message"}),"degraded";return h("retrying",YS(R)),"retry"}}async function C(x){while(!x.aborted){let y=await v(x);if(!y)return;let R=await _(y,x);if(l=0,await y.close().catch(()=>{return}),R!=="retry")return;await a.sleep(c.retryMs,x)}}function w({jitConfig:x,runner:y}){return{jit:Ua(x.reveal()),runner:{id:y.id,name:y.name}}}return{desired:()=>Math.min(u(),l),kind:"scaleset",async mint(x){let y=`Mint a just-in-time runner for slot ${x}`;try{return w(await t.generateJitConfig(i,{name:x}))}catch(A){if(!(A instanceof yt)||A.failure!=="runner-exists")throw A}let R=await t.findRunnerByName(x);if(R&&R.scaleSetId!==i)throw new We(o,y,"runner-exists",`a runner named ${x} belongs to another scale set`);if(R&&await t.removeRunner(R.id)==="busy")throw new We(o,y,"runner-exists",`the runner ${x} is running a job`);return w(await t.generateJitConfig(i,{name:x}))},pool:o,release:(x)=>t.removeRunner(x.id),async start(){if(g)return;await E();let x=new AbortController;m=x,g=C(x.signal)},status:()=>({demand:l,detail:f,kind:"scaleset",pool:o,state:d}),async stop(){m?.abort(),await g,m=void 0,g=void 0,h("stopped")}}}function YS(e){return e instanceof Error?e.message:String(e)}import{lstatSync as fF,unlinkSync as mF}from"fs";import{chmodSync as zG,mkdirSync as eR,mkdtempSync as QG,renameSync as ZG,rmSync as tR,writeFileSync as jd}from"fs";import{tmpdir as eF}from"os";import{join as ar}from"path";var Fd="guest",Ud="Containerfile",WG=["ca-certificates","curl","git","jq","tar","unzip","util-linux","xz-utils","zstd"],JG={amd64:"x64",arm64:"arm64"},zS="apt-get install -y --no-install-recommends",Gd="rm -rf /var/lib/apt/lists/*",Hd="/etc/apt/keyrings/docker.asc";function cc(e){let{arch:t,docker:n}=e,r=Ve;return`${[`FROM ${r.base.image}@${r.base.digest}`,"ARG DEBIAN_FRONTEND=noninteractive",Nn(["apt-get update",`${zS} ${WG.join(" ")}`,Gd]),Nn([`groupadd --gid ${tt} ${_n}`,`useradd --uid ${tt} --gid ${tt} --create-home --shell /bin/bash ${_n}`]),Nn([...ac(r.runner[t],"/tmp/runner.tar.gz"),`mkdir -p ${Tn}`,`tar -xzf /tmp/runner.tar.gz -C ${Tn}`,"rm /tmp/runner.tar.gz","apt-get update",`${Tn}/bin/installdependencies.sh`,Gd,`chown -R ${tt}:${tt} ${Tn}`]),Nn([...ac(r.bun[t],"/tmp/bun.zip"),"unzip -q /tmp/bun.zip -d /tmp/bun","install -o 0 -g 0 -m 0755 /tmp/bun/*/bun /usr/local/bin/bun","ln -s bun /usr/local/bin/bunx","rm -rf /tmp/bun /tmp/bun.zip"]),...r.node.map((s)=>{let i=`${ts}/node/${s.version}/${JG[t]}`;return Nn([...ac(s[t],"/tmp/node.tar.xz"),`mkdir -p ${i}`,`tar -xJf /tmp/node.tar.xz --strip-components=1 -C ${i}`,`touch ${i}.complete`,"rm /tmp/node.tar.xz"])}),Nn([`chown -R ${tt}:${tt} ${ts}`]),...n?[XG(t)]:[],`COPY ${Fd}/ ${jt}/`,Nn([`chown -R 0:0 ${jt}`,`chmod 0755 ${jt}`,`chmod 0555 ${Zo} ${ca} ${ua} ${Bl}`,`chmod 0444 ${ub}`,`install -d -o ${tt} -g ${tt} -m 0700 ${Vl}`,`cd ${ql}`,`find . -mindepth 1 | LC_ALL=C sort > ${la}`,`chmod 0444 ${la}`,"cd /","test ! -e /usr/bin/sudo","setpriv --help > /dev/null",`test "$(id -u ${_n})" = ${tt}`,`test "$(id -g ${_n})" = ${tt}`]),`ENV LANG=C.UTF-8 RUNNER_TOOL_CACHE=${ts} AGENT_TOOLSDIRECTORY=${ts} ACTIONS_RUNNER_HOOK_JOB_STARTED=${Bl}`,`LABEL ${YG(e).map(([s,i])=>`${s}="${i}"`).join(" ")}`,"WORKDIR /",`CMD ["${Zo}"]`].join(`
405
+ `)}
406
+ `}function YG(e){return[["org.r5nlabs.hydra.image","runner-linux"],["org.r5nlabs.hydra.variant",e.docker?"docker":"plain"],["org.r5nlabs.hydra.runner",Ve.runner.version]]}function XG(e){let t=Ve.docker,n=Object.entries(t.packages).map(([r,o])=>`${r}=${o}`);return Nn(["install -d -m 0755 /etc/apt/keyrings",...ac(t.key,Hd),`chmod 0644 ${Hd}`,`echo "deb [arch=${e} signed-by=${Hd}] ${t.repository} ${t.codename} stable" > /etc/apt/sources.list.d/docker.list`,"apt-get update",`${zS} ${n.join(" ")}`,Gd,`usermod -aG docker ${_n}`])}function ac(e,t){return[`curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --tlsv1.2 --retry 3 --output ${t} ${e.url}`,`echo "${e.sha256} ${t}" | sha256sum --check --strict -`]}function Nn(e){return`RUN set -eu; \\
407
+ ${e.join(" \\\n && ")}`}var hs=["container","podman"];class Je extends Error{operation;tag;_tag="ImageBuildError";constructor(e,t,n,r){super(`Could not ${e} ${t}: ${n}`,r);this.operation=e;this.tag=t;this.name="ImageBuildError"}}var Bd="localhost/hydra/runner-linux",nR="-docker",rR="images",oR=448,sR=384,tF=3600000,nF=60000,rF=20,oF=1000,sF=/^sha256:[0-9a-f]{64}$/,Vd={container:"apple-container",podman:"podman-gvisor"},iF=Z(N({configuration:N({descriptor:N({digest:I()})})}));function uc(e){let t=e.docker?nR:"";return`${Bd}${t}:${Ve.runner.version}-${e.arch}`}function qd(e,t,n){let r=[e,"build","--platform",`linux/${t.arch}`,"--file",ar(n,Ud),"--tag",uc(t),...e==="container"?["--progress","plain"]:[],n];return nn(Vd[e],r)}function aF(e,t){let n=e==="container"?["container","image","inspect",t]:["podman","image","inspect","--format","{{.Digest}}",t];return nn(Vd[e],n)}function iR(e,t){let n=e==="container"?["container","image","delete",t]:["podman","image","rm",t];return nn(Vd[e],n)}function aR(e){let t=e.reference.slice(0,e.reference.indexOf("@"));return(t===Bd||t===`${Bd}${nR}`)&&e.tag.startsWith(`${t}:`)&&e.reference===`${t}@${e.digest}`}function cF(e,t){jd(ar(t,Ud),cc(e),{mode:sR});let n=ar(t,Fd);eR(n,{mode:oR});for(let r of db(lb(e.docker))){let o=ar(n,r.name);jd(o,r.content),zG(o,r.mode)}}async function cR(e){let t=uc(e),n=QG(ar(eF(),"hydra-image-"));try{cF(e,n);let a=qd(e.builder,e,n),c=await ZS(a,{stream:!0,timeoutMs:tF},"build",t);if(c.exitCode!==0)throw new Je("build",t,QS(e.builder,c))}finally{tR(n,{force:!0,recursive:!0})}let r=aF(e.builder,t),o=await ZS(r,{stream:!1,timeoutMs:nF},"inspect",t);if(o.exitCode!==0)throw new Je("inspect",t,QS(e.builder,o));let s=lF(e.builder,o.stdout);if(!s)throw new Je("read the digest of",t,`${e.builder} printed no sha256 digest`);let i={arch:e.arch,builder:e.builder,builtAt:new Date().toISOString(),digest:s,kind:"linux",reference:`${t.slice(0,t.lastIndexOf(":"))}@${s}`,runner:Ve.runner.version,tag:t,variant:e.docker?"docker":"plain"};return uF(e.home,i),i}function Kd(e,t){return ar(e,rR,`${t.replace(":","-")}.json`)}function uF(e,t){eR(ar(e,rR),{mode:oR,recursive:!0});let n=Kd(e,t.digest),r=`${n}.${process.pid}.tmp`;try{jd(r,`${JSON.stringify(t,null,2)}
408
+ `,{flag:"wx",mode:sR}),ZG(r,n)}finally{tR(r,{force:!0})}}function lF(e,t){let n=e==="container"?dF(t):t.trim();return n&&sF.test(n)?n:void 0}function dF(e){try{let[t]=iF(JSON.parse(e));return t?.configuration.descriptor.digest}catch{return}}function QS(e,t){let n=t.stderr.trim().split(`
409
+ `).slice(-rF).join(`
410
+ `);return`${e} exited with code ${t.exitCode}${n?`
411
+ ${n}`:""}`}async function ZS(e,t,n,r){let o=await pF(e,t,n,r);if(!o.timedOut)return{exitCode:o.exitCode,stderr:o.stderr,stdout:o.stdout};let s=`${e[0]} was stopped by SIGKILL after at most ${t.timeoutMs/oF} s`;return{exitCode:o.exitCode,stderr:`${o.stderr}
412
+ ${s}`,stdout:o.stdout}}async function pF(e,t,n,r){try{return await ft(e,{echo:t.stream,timeoutMs:t.timeoutMs})}catch(o){let s=o instanceof Error?o.message:String(o);throw new Je(n,r,`${e[0]} could not start (${s})`,{cause:o})}}class ys extends Error{operation;target;_tag="PruneError";constructor(e,t,n,r){super(`Could not ${e} ${t}: ${n}`,r);this.operation=e;this.target=t;this.name="PruneError"}}var dR=1000,gF=120*dR,hF=5;function lc(e={}){let t=e.timeoutMs??gF;return async(n)=>{let[r,...o]=iR(n.builder,n.reference),s=[e.binaries?.[n.builder]??r,...o],i=await ft(s,{timeoutMs:t}).catch((c)=>{throw new ys("delete the image",n.reference,`${r} could not start (${Wd(c)})`,{cause:c})});if(i.timedOut)throw new ys("delete the image",n.reference,`${r} did not finish within ${t/dR} s`);if(i.exitCode===0)return;let a=i.stderr.trim().split(`
413
+ `).slice(-hF).join(`
414
+ `);throw new ys("delete the image",n.reference,`${r} exited with code ${i.exitCode}${a?`: ${a}`:""}`)}}async function dc(e,t,n){let r={failed:[],freedBytes:0,images:[],logs:[]};for(let{path:o,record:s}of e.images){if(n?.aborted)return r;try{await t(s),lR(o),r.images.push(s.reference)}catch(i){r.failed.push({detail:Wd(i),item:s.reference})}}for(let o of e.logs){if(n?.aborted)return r;try{lR(o.path),r.logs.push(o.name),r.freedBytes+=o.bytes}catch(s){r.failed.push({detail:Wd(s),item:o.path})}}return r}function pc(e){let t=uR(e.images.length,"image"),n=uR(e.logs.length,"slot log");return`${t} and ${n}, freeing ${kt(e.freedBytes)} of logs`}function uR(e,t){return`${e} ${t}${e===1?"":"s"}`}function lR(e){let t=fF(e,{throwIfNoEntry:!1});if(!t)return;if(!t.isFile())throw new ys("remove",e,"it is no longer a regular file");mF(e)}function Wd(e){return e instanceof Error?e.message:String(e)}var Jd=60000,yF=1440,bF={checkMs:Jd,dailyMs:yF*Jd,repruneMs:60*Jd},pR={critical:3,low:2,normal:0,warn:1},wF={critical:"no new guest starts and running jobs finish",low:"no new macOS VM starts, and Linux and native guests get half the host's budget",normal:"guests start as the host's budget allows",warn:"Hydra prunes the images and slot logs it no longer needs"};function mR(e){let t=e.clock??Le,n={...bF,...e.timing},r,o=!1,s,i,a=new AbortController,c,u=async()=>{try{let m=await e.read();o=!1;let g=r?.state??"normal";if(r=m,m.state===g)return{reading:m,worse:!1};let h=`free disk space is ${m.state} (${m.freeGiB.toFixed(0)} GiB): ${wF[m.state]}`;e.log(h);let E=pR[m.state]>pR[g];if(E)e.alert({detail:h,reason:"disk-pressure"});return{reading:m,worse:E}}catch(m){if(!o)e.log(`could not read the host's free disk space: ${fR(m)}`);return o=!0,{worse:!1}}},l=(m,g)=>{if(s===void 0)return!0;let h=t.now()-s;if(h>=n.dailyMs)return!0;if(!m||m.state==="normal")return!1;return g||h>=n.repruneMs},d=async()=>{s=t.now();try{let m=await e.prune(a.signal);if(m.images.length+m.logs.length>0)e.log(`pruned ${pc(m)}`);for(let g of m.failed)e.log(`could not prune ${g.item}: ${g.detail}`)}catch(m){e.log(`could not prune: ${fR(m)}`)}},f=()=>(i??=(async()=>{let{reading:m,worse:g}=await u();if(l(m,g))await d()})().finally(()=>{i=void 0}),i);return{check:f,reading:()=>r,start(){if(c)return;if(a.signal.aborted)a=new AbortController;let{signal:m}=a;c=(async()=>{while(!m.aborted)await f(),await t.sleep(n.checkMs,m)})()},async stop(){a.abort(),await c,await i,c=void 0}}}function fR(e){return e instanceof Error?e.message:String(e)}import{createConnection as F1}from"net";import{closeSync as SF,constants as gR,fstatSync as RF,openSync as $F,readFileSync as EF}from"fs";import{isAbsolute as vF}from"path";var Dn=["linux","macos-vm","native"];class cr extends Error{path;_tag="HostBudgetError";constructor(e,t,n){super(`The host budget ${e} ${t}`,n);this.path=e;this.name="HostBudgetError"}}var RR="/etc/hydra/host.json",ln="/var/run/hydra",kF="/var/db/hydra",bs=100,xF=2,_F=2048,TF=1.25,AF=1,hR=100,Yd=16,yR={criticalGiB:50,lowGiB:100,path:"/",warnGiB:150},CF=18,bR=0,OF=/^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/,PF=["cpuCommitRatio","disk","fleets","freeMemoryReserveMiB","loadFactor","macosVmCap","memoryMiB","socketDir","stateDir"],IF="the IPv4 block, without host bits, inside 10.0.0.0/8, 172.16.0.0/12 or 192.168.0.0/16, that the fleet's Linux guest networks use",NF=["criticalGiB","lowGiB","path","warnGiB"],DF=["account","ceilings","guestRange","maxPriority","weight"],Me=(e,t=Number.MAX_SAFE_INTEGER)=>X().map((n)=>Number.isSafeInteger(n)&&n>=e&&n<=t?n:F()),wR=X().map((e)=>Number.isFinite(e)&&e>0&&e<=Yd?e:F()),Xd=I().map((e)=>vF(e)?e:F()),LF=Me(1).or(J([fe])),MF=I().map((e)=>{let t=st(e);return t&&yi(t)?e:F()});function $R(e){let t;try{t=HF(e)}catch(n){if(n instanceof cr)throw n;throw new cr(e,`cannot be read (${SR(n)})`,{cause:n})}try{return GF(JSON.parse(t))}catch(n){throw new cr(e,`is not valid: ${SR(n)}`,{cause:n})}}function HF(e){let t=$F(e,gR.O_RDONLY|gR.O_NONBLOCK);try{let n=zd(RF(t),"file");if(n)throw new cr(e,n);return EF(t,"utf-8")}finally{SF(t)}}function zd(e,t){if(t==="directory"?!e.isDirectory():!e.isFile())return`must be a ${t}`;let n=process.geteuid?.()??bR;if(e.uid!==n&&e.uid!==bR)return`must be owned by root or by the user running the host daemon (uid ${n})`;return(e.mode&CF)===0?void 0:"must not be writable by its group or by other users"}function GF(e){let t=pe(e,"the budget");_e(t,PF,"budget","the host budget"),re(t.memoryMiB,Me(1),"memoryMiB","the memory guests may commit, in whole MiB"),se(t.cpuCommitRatio,wR,"cpuCommitRatio",`a number above 0 and at most ${Yd}`),se(t.loadFactor,wR,"loadFactor",`a number above 0 and at most ${Yd}`),se(t.freeMemoryReserveMiB,Me(0),"freeMemoryReserveMiB","whole MiB"),se(t.macosVmCap,Me(0,Rn),"macosVmCap",`a whole number from 0 to ${Rn}, the macOS VMs a host may run at once`),se(t.socketDir,Xd,"socketDir","an absolute path"),se(t.stateDir,Xd,"stateDir","an absolute path");let n=t.macosVmCap??Rn,r=UF(t.fleets,n);return{cpuCommitRatio:t.cpuCommitRatio??xF,disk:FF(t.disk),fleets:r,freeMemoryReserveMiB:t.freeMemoryReserveMiB??_F,loadFactor:t.loadFactor??TF,macosVmCap:n,memoryMiB:t.memoryMiB,socketDir:t.socketDir??ln,stateDir:t.stateDir??kF}}function FF(e){if(e===void 0)return yR;let t=pe(e,"disk");_e(t,NF,"disk","the disk thresholds"),se(t.path,Xd,"disk.path","an absolute path on the volume that holds the guests");for(let r of["warnGiB","lowGiB","criticalGiB"])se(t[r],Me(0),`disk.${r}`,"whole GiB");let n={...yR,...t};if(n.warnGiB>n.lowGiB&&n.lowGiB>n.criticalGiB)return n;throw Error("disk.warnGiB must be above disk.lowGiB, and disk.lowGiB above disk.criticalGiB")}function UF(e,t){if(e===void 0)throw Error("fleets is missing; expected one entry per fleet that may lease guests");let n=pe(e,"fleets"),r=Object.keys(n);if(r.length===0)throw Error("fleets must name at least one fleet");let o=Object.fromEntries(r.map((i)=>[i,BF(i,n[i],t)])),s=new Map;for(let[i,a]of Object.entries(o)){let c=s.get(a.account);if(c)throw Error(`fleets.${c} and fleets.${i} share the account ${a.account}; give each its own`);s.set(a.account,i)}return jF(o),o}function jF(e){let t=Object.entries(e).flatMap(([n,r])=>r.guestRange===void 0?[]:[{cidr:st(r.guestRange),id:n,range:r.guestRange}]);for(let[n,r]of t.entries()){let o=t.slice(n+1).find((s)=>bi(r.cidr,s.cidr));if(o)throw Error(`fleets.${r.id}.guestRange (${r.range}) overlaps fleets.${o.id}.guestRange (${o.range}); give each fleet its own range`)}}function BF(e,t,n){if(!Wn(e))throw Error(`Fleet "${e}" must be lowercase letters and digits without hyphens, at most ${Ci} characters`);let r=`fleets.${e}`,o=pe(t,r);_e(o,DF,r,"a fleet's budget"),re(o.account,I().map((a)=>OF.test(a)?a:F()),`${r}.account`,"the user name the fleet runs as, which owns its socket"),se(o.weight,Me(1,hR),`${r}.weight`,`a whole number from 1 to ${hR}`),se(o.maxPriority,Me(0,bs),`${r}.maxPriority`,`a whole number from 0 to ${bs}`);let s=VF(o.ceilings,`${r}.ceilings`,n);return(s.linux===void 0?se:re)(o.guestRange,MF,`${r}.guestRange`,IF),{account:o.account,ceilings:s,...o.guestRange===void 0?{}:{guestRange:o.guestRange},maxPriority:o.maxPriority??bs,weight:o.weight??AF}}function VF(e,t,n){if(e===void 0)throw Error(`${t} is missing; expected a ceiling for each class the fleet may lease`);let r=pe(e,t);if(_e(r,Dn,t,"a fleet's ceilings"),Object.keys(r).length===0)throw Error(`${t} must allow at least one class`);for(let s of Dn)se(r[s],LF,`${t}.${s}`,`a positive whole number or "${fe}"`);let o=r["macos-vm"];if(o!==void 0&&(o===fe||o>n))throw Error(`${t}.macos-vm must be at most macosVmCap (${n})`);return r}function SR(e){return e instanceof Error?e.message:String(e)}import{closeSync as ER,fsyncSync as vR,openSync as kR,readFileSync as qF,renameSync as KF,rmSync as WF,writeFileSync as JF}from"fs";import{dirname as YF,join as XF}from"path";class no extends Error{path;operation;_tag="LeaseFileError";constructor(e,t,n,r){super(`Could not ${t} the lease file ${e}: ${n}`,r);this.path=e;this.operation=t;this.name="LeaseFileError"}}var zF="leases.json",xR=1,QF=384,ZF=64,e1=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,ur={class:J(Dn),cpus:Me(1),diskGiB:Me(1),memoryMiB:Me(1),pool:I().map((e)=>jo(e)?e:F()),priority:Me(0,bs),slot:I().map((e)=>r1(e)?e:F())},t1=N({...ur,fleet:I().map((e)=>Wn(e)?e:F()),grantedAt:I().map((e)=>Number.isNaN(Date.parse(e))?F():e),origin:J(["adopted","granted"])}),n1=N({leases:Z(t1),version:J([xR])});function r1(e){return e.length<=ZF&&e1.test(e)}function _R(e){return XF(e,zF)}function TR(e){let t;try{t=qF(e,"utf-8")}catch(n){if(n.code==="ENOENT")return[];throw new no(e,"read",Qd(n),{cause:n})}try{return n1(JSON.parse(t)).leases}catch(n){throw new no(e,"read",`it is not a valid lease file (${Qd(n)})`,{cause:n})}}function AR(e,t){let n=`${e}.${process.pid}.tmp`;try{let r=kR(n,"w",QF);try{JF(r,`${JSON.stringify({leases:t,version:xR},null,2)}
415
+ `),vR(r)}finally{ER(r)}KF(n,e),o1(YF(e))}catch(r){throw new no(e,"write",Qd(r),{cause:r})}finally{WF(n,{force:!0})}}function CR(e,t){return e.class===t.class&&e.cpus===t.cpus&&e.diskGiB===t.diskGiB&&e.memoryMiB===t.memoryMiB&&e.pool===t.pool&&e.slot===t.slot}function o1(e){let t=kR(e,"r");try{vR(t)}finally{ER(t)}}function Qd(e){return e instanceof Error?e.message:String(e)}import{statfs as s1}from"fs/promises";class Wt extends Error{reading;_tag="LiveReadingError";constructor(e,t,n){super(`Could not read ${e}: ${t}`,n);this.reading=e;this.name="LiveReadingError"}}var i1=1e4,OR=1048576,a1=1024*OR,c1=["kern.memorystatus_vm_pressure_level","hw.logicalcpu","vm.loadavg"],u1={"1":"normal","2":"warn","4":"critical"},l1=/page size of (\d+) bytes/,d1=/^Pages free:\s+(\d+)\.?$/m,p1=/^Pages inactive:\s+(\d+)\.?$/m,f1=/^\{\s*([\d.]+)\s/,PR=10;function IR(e,t={}){let n=t.now??Date.now,r=t.env??process.env;return async()=>{let[o,s,i]=await Promise.all([m1(r),g1(r),h1(e)]);return{...o,diskFreeGiB:i,freeMemoryMiB:s,readAt:n()}}}function fc(e,t){if(e<t.criticalGiB)return"critical";if(e<t.lowGiB)return"low";return e<t.warnGiB?"warn":"normal"}async function m1(e){let t=await NR(["sysctl","-n",...c1],e,"the kernel's memory pressure, CPUs and load"),[n,r,o]=t.trim().split(`
416
+ `),s=Number.parseInt(r??"",PR),i=Number.parseFloat(f1.exec(o??"")?.[1]??"");if(!Number.isSafeInteger(s)||s<1||!Number.isFinite(i))throw new Wt("the kernel's CPUs and load","sysctl printed an unexpected value");return{cores:s,load1:i,pressure:u1[n?.trim()??""]??"critical"}}async function g1(e){let t=await NR(["vm_stat"],e,"free and inactive memory"),n=Zd(l1.exec(t)?.[1]),r=Zd(d1.exec(t)?.[1]),o=Zd(p1.exec(t)?.[1]);if(n===void 0||r===void 0||o===void 0)throw new Wt("free and inactive memory","vm_stat printed no page size, free or inactive count");return Math.floor((r+o)*n/OR)}async function h1(e){try{let t=await s1(e);return t.bavail*t.bsize/a1}catch(t){throw new Wt(`free space on ${e}`,DR(t),{cause:t})}}function Zd(e){let t=Number.parseInt(e??"",PR);return Number.isSafeInteger(t)?t:void 0}async function NR(e,t,n){try{let r=Bun.spawn([...e],{env:t,killSignal:"SIGKILL",stderr:"pipe",stdin:"ignore",stdout:"pipe",timeout:i1}),[o,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);if(r.signalCode!==null)throw new Wt(n,`${e[0]} was stopped by ${r.signalCode}`);if(i!==0)throw new Wt(n,`${e[0]} exited with code ${i}: ${s.trim()}`);return o}catch(r){if(r instanceof Wt)throw r;throw new Wt(n,`${e[0]} could not start (${DR(r)})`,{cause:r})}}function DR(e){return e instanceof Error?e.message:String(e)}var y1=60000,b1=0.5,w1=1024;function hc(e){return e.reduce((t,n)=>({cpus:t.cpus+n.cpus,leases:t.leases+1,macosVms:t.macosVms+(n.class==="macos-vm"?1:0),memoryMiB:t.memoryMiB+n.memoryMiB}),{cpus:0,leases:0,macosVms:0,memoryMiB:0})}function Ln(e,t){return Math.floor(t*e.cpuCommitRatio)}function gc(e,t){return Math.min(t,e.maxPriority)}function yc(e,t,n,r){let o=n.fleets[e];if(!o)return`the host budget has no fleet ${e}`;if(o.ceilings[t.class]===void 0)return`the host budget lets fleet ${e} lease no ${t.class} guests`;if(t.memoryMiB>n.memoryMiB)return`${Ue(t.memoryMiB)} of memory is more than the host's whole budget of ${Ue(n.memoryMiB)}`;let s=Ln(n,r);if(t.cpus>s)return`${t.cpus} vCPU is more than the ${s} vCPU the host commits in all`;return}function S1(e,t){let{budget:n,leases:r,live:o,now:s}=t,{fleet:i,request:a}=e,c=n.fleets[i],u=fc(o.diskFreeGiB,n.disk),l=hc(r);if(u==="critical")return mc(`free disk space is critical (${o.diskFreeGiB.toFixed(0)} GiB)`);if(u==="low"&&a.class==="macos-vm")return mc(`free disk space is low (${o.diskFreeGiB.toFixed(0)} GiB), which stops new macOS VMs`);let d=c.ceilings[a.class]??0,f=r.filter((C)=>C.fleet===i&&C.class===a.class).length;if(d!==fe&&f>=d)return mc(`the fleet holds its ${a.class} ceiling of ${d}`);if(a.class==="macos-vm"&&l.macosVms>=n.macosVmCap)return mc(`the host runs its ${n.macosVmCap} macOS VMs`);let m=u==="low"?b1:1,g=u==="low"?", halved while free disk space is low":"",h=Math.floor(n.memoryMiB*m);if(l.memoryMiB+a.memoryMiB>h)return ro(`committed memory ${Ue(l.memoryMiB)} of ${Ue(h)}${g}`);let E=Math.floor(Ln(n,o.cores)*m);if(l.cpus+a.cpus>E)return ro(`committed vCPU ${l.cpus} of ${E}${g}`);if(o.pressure!=="normal")return ro(`the kernel reports ${o.pressure} memory pressure`);let v=r.filter((C)=>C.origin==="granted"&&s-Date.parse(C.grantedAt)<y1).reduce((C,w)=>C+w.memoryMiB,0),S=o.freeMemoryMiB-n.freeMemoryReserveMiB-v;if(S<a.memoryMiB)return ro(`free memory ${Ue(Math.max(S,0))} after the reserve`);let _=o.cores*n.loadFactor;if(o.load1>=_)return ro(`load average ${o.load1.toFixed(2)} of ${_.toFixed(2)}`);if(o.diskFreeGiB-a.diskGiB<n.disk.criticalGiB)return ro(`${a.diskGiB} GiB of disk would take free space below ${n.disk.criticalGiB} GiB`);return}function R1(e,t,n){let r=(s)=>{let i=t.fleets[s.fleet],a=gc(i,s.request.priority),c=n.filter((u)=>u.fleet===s.fleet&&gc(i,u.priority)===a).length;return{priority:a,share:c/i.weight}},o=new Map(e.map((s)=>[s.seq,r(s)]));return[...e].sort((s,i)=>{let a=o.get(s.seq),c=o.get(i.seq);return c.priority-a.priority||a.share-c.share||s.seq-i.seq})}function ws(e,t,n){let r=[...t.leases],o=[],s=new Map,i=[...e];for(let a=!0;a&&i.length>0;){a=!1,s.clear();let c=R1(i,t.budget,r);for(let[u,l]of c.entries()){let d=S1(l,{...t,leases:r});if(!d){let f=$1(l,t.now);r.push(f),o.push({lease:f,seq:l.seq}),i=i.filter((g)=>g.seq!==l.seq);let m=n?.(l);if(m)i.push(m);a=!0;break}if(s.set(l.seq,d),d.scope==="own")continue;for(let f of c.slice(u+1)){let m=f.fleet===l.fleet?l.request.slot:"another fleet's request";s.set(f.seq,{reason:`behind ${m}, which waits for ${d.reason}`,scope:"shared"})}return{granted:o,held:s}}}return{granted:o,held:s}}function $1(e,t){return{...e.request,fleet:e.fleet,grantedAt:new Date(t).toISOString(),origin:"granted"}}function mc(e){return{reason:e,scope:"own"}}function ro(e){return{reason:e,scope:"shared"}}function Ue(e){return`${(e/w1).toFixed(1)} GiB`}var E1=600000,v1=60000,LR=64,oo=32,k1=256,x1="offer",{slot:rZ,..._1}=ur,HR={..._1,assigned:Me(0),ceiling:Me(1).or(J([fe]))};function GR(){let e=new Map;return{claim(t,n,r){let o=e.get(t),s=o?.get(n);if(o&&s)o.set(n,{...s,claimedAt:r})},offers:(t)=>T1({...t,entries:[...e.values()].flatMap((n)=>[...n.values()])}),report(t,n,r){let o=e.get(t);e.set(t,new Map(n.map((s)=>[s.pool,A1(t,s,o?.get(s.pool),r)])))}}}function MR(e,t){return e.demandAt!==void 0&&t-e.demandAt<E1&&t-e.claimedAt<v1}function T1(e){let{entries:t,fleet:n,state:r}=e,o=e.open??(()=>!0),s=e.waiting.filter((u)=>o(u.request)),i=new Map(t.map((u)=>[u,C1(u,r,s,o)])),a=(u)=>i.get(u)??0,c=O1(t.filter((u)=>MR(u,r.now)&&a(u)>0),a,s,r);return t.filter((u)=>u.fleet===n).map((u)=>{let l=c.get(u)??0,d=l===0&&a(u)>0&&P1(u,s,r);return{active:MR(u,r.now),offer:d?1:l,pool:u.request.pool}})}function A1(e,t,n,r){let o=t.assigned>(n?.request.assigned??0),s=t.assigned>0?r:n?.demandAt;return{claimedAt:o||!n?r:n.claimedAt,...s===void 0?{}:{demandAt:s},fleet:e,request:t}}function C1(e,t,n,r){let o=ep(e);if(!r(o)||yc(e.fleet,o,t.budget,t.live.cores))return 0;let{ceiling:s,pool:i}=e.request;if(s===fe)return LR;let a=t.leases.filter((c)=>c.fleet===e.fleet&&c.pool===i).length+n.filter((c)=>c.fleet===e.fleet&&c.request.pool===i).length;return Math.max(0,Math.min(LR,s-a))}function O1(e,t,n,r){let o=new Map;if(e.length===0)return o;let s=new Map,i=FR(n),a=0,c=(l)=>(s.set(i,l),{fleet:l.fleet,request:ep(l),seq:i++}),u=(l)=>{let d=s.get(l.seq);if(!d)return;a++;let f=(o.get(d)??0)+1;return o.set(d,f),f<t(d)&&a<k1?c(d):void 0};return ws([...n,...e.map(c)],r,u),o}function P1(e,t,n){let r=FR(t),o={fleet:e.fleet,request:ep(e),seq:r};return ws([...t,o],n).granted.some((s)=>s.seq===r)}function FR(e){return e.reduce((t,n)=>Math.max(t,n.seq+1),0)}function ep(e){let{assigned:t,ceiling:n,...r}=e.request;return{...r,slot:x1}}var UR=["lease","net.status","offer","release","report","status"];class Jt extends Error{id;_tag="HostProtocolError";constructor(e,t){super(t);this.id=e;this.name="HostProtocolError"}}var bc=65536,jR=4096,I1=Me(0),BR=N(ur),N1=Z(BR),D1=Z(N(HR)),L1=["id","op",...Object.keys(ur)],M1={lease:L1,"net.status":["id","op"],offer:["id","op","pools"],release:["id","op","slot"],report:["id","op","slots"],status:["id","op"]};function VR(e){let t;try{t=JSON.parse(e)}catch{throw new Jt(null,"a request must be one JSON object per line")}let n=G1(t),r=lr(()=>I1(n.id),null,"id must be a whole number"),o=lr(()=>J(UR)(n.op),r,`op must be one of ${UR.join(", ")}`);switch(lr(()=>_e(n,M1[o],"the request",`a ${o} request`),r),o){case"lease":return{id:r,op:o,request:lr(()=>BR(n),r,"the lease request is invalid")};case"offer":return{id:r,op:o,pools:H1(n.pools,r)};case"release":return{id:r,op:o,slot:lr(()=>ur.slot(n.slot),r,"slot is not a slot name")};case"report":{if(Array.isArray(n.slots)&&n.slots.length>jR)throw new Jt(r,`a report lists at most ${jR} slots`);let s=lr(()=>N1(n.slots),r,"slots must list the fleet's slots");if(new Set(s.map((i)=>i.slot)).size!==s.length)throw new Jt(r,"a report lists each slot once");return{id:r,op:o,slots:s}}case"net.status":case"status":return{id:r,op:o}}}function H1(e,t){if(Array.isArray(e)&&e.length>oo)throw new Jt(t,`an offer request lists at most ${oo} pools`);let n=lr(()=>D1(e),t,"pools must list the fleet's scale-set pools");if(new Set(n.map((r)=>r.pool)).size!==n.length)throw new Jt(t,"an offer request lists each pool once");return n}function Ss(e){return`${JSON.stringify(e)}
417
+ `}function Ye(e,t,n){return{error:{code:t,message:n},id:e,ok:!1}}function G1(e){try{return pe(e,"a request")}catch{throw new Jt(null,"a request must be a JSON object")}}function lr(e,t,n){try{return e()}catch(r){throw new Jt(t,n??(r instanceof Error?r.message:String(r)))}}class Xe extends Error{socket;code;_tag="HostClientError";constructor(e,t,n,r){super(n,r);this.socket=e;this.code=t;this.name="HostClientError"}}var U1=1e4;async function so(e,t=U1){let n=await j1(e),r=new Map,o=1,s="",i=(c)=>{if(c.id===null)return;let u=r.get(c.id);if(!u)return;if(r.delete(c.id),clearTimeout(u.timer),!c.ok){u.reject(new Xe(e,c.error.code,c.error.message));return}let{id:l,ok:d,...f}=c;u.resolve(f)};n.setEncoding("utf8"),n.on("data",(c)=>{s+=c;for(let u=s.indexOf(`
418
+ `);u>=0;u=s.indexOf(`
419
+ `)){let l=s.slice(0,u);s=s.slice(u+1);try{i(JSON.parse(l))}catch{n.destroy()}}}),n.on("error",()=>n.destroy()),n.on("close",()=>{for(let c of r.values())clearTimeout(c.timer),c.reject(new Xe(e,"closed",`The host daemon closed ${e}`));r.clear()});let a=(c,u,l)=>new Promise((d,f)=>{if(n.destroyed){f(new Xe(e,"closed",`The connection to ${e} is closed`));return}let m=o++,g=l?void 0:setTimeout(()=>{r.delete(m),f(new Xe(e,"timeout",`The host daemon did not answer ${c} within ${t} ms`))},t);r.set(m,{reject:f,resolve:(h)=>d(h),timer:g}),n.write(Ss({...u,id:m,op:c}))});return{close:()=>n.end(),lease:async(c)=>(await a("lease",c,!0)).lease,netStatus:async()=>(await a("net.status",{},!1)).net,offer:async(c)=>(await a("offer",{pools:c},!1)).offers,release:(c)=>a("release",{slot:c},!1),report:(c)=>a("report",{slots:c},!1),status:async()=>(await a("status",{},!1)).status}}function j1(e){return new Promise((t,n)=>{let r=F1(e);r.once("connect",()=>{r.off("error",n),t(r)}),r.once("error",(o)=>n(new Xe(e,"unreachable",`Cannot reach the host daemon on ${e} (${o.message})`)))})}var B1=new Set(["closed","timeout","unreachable"]);function qR(e){let t,n,r=!1,o=async()=>{let a=await e.connect();try{e.reported?.(await a.report(e.slots()))}catch(c){throw a.close(),c}return n=a,a},s=()=>{if(r)return Promise.reject(new Xe("","closed","The fleet closed its host daemon link"));return t??=o().catch((a)=>{throw t=void 0,a}),t},i=async(a)=>{let c=await s();try{return await a(c)}catch(u){if(u instanceof Xe&&B1.has(u.code)&&n===c)n=void 0,t=void 0,c.close();throw u}};return{close(){r=!0,n?.close(),n=void 0,t=void 0},connected:()=>n!==void 0,lease:(a)=>i((c)=>c.lease(a)),offer:(a)=>i((c)=>c.offer(a)),release:(a)=>i((c)=>c.release(a)),status:()=>i((a)=>a.status())}}var dr=50;function Rs(e){if(e.driver==="native")return"native";return Nr(e.driver,e.guestOs)?"macos-vm":"linux"}function KR(e,t,n,r){let o=e.fleets[t];if(!o)return[{detail:`The host budget has no fleet ${t}`,level:"error"}];let s=Ln(e,r);return Object.entries(n).flatMap(([i,a])=>{let c=Rs(a),u=o.ceilings[c];if(u===void 0)return[{detail:`Pool ${i} needs ${c} leases, which fleet ${t} may not take`,level:"error"}];let l=[],{cpus:d,memoryMiB:f}=a.resources;if(f>e.memoryMiB)l.push({detail:`Pool ${i} asks for ${f} MiB, above the ${e.memoryMiB} MiB budget`,level:"error"});if(d>s)l.push({detail:`Pool ${i} asks for ${d} vCPU, above the ${s} vCPU this host commits`,level:"error"});if(u!==fe&&(a.ceiling===fe||a.ceiling>u))l.push({detail:`Pool ${i} runs at most ${u} at once: the fleet's ${c} ceiling`,level:"warning"});let m=a.priority??dr;if(gc(o,m)<m)l.push({detail:`Pool ${i} waits at priority ${o.maxPriority}, the fleet's highest`,level:"warning"});return l})}class wc extends Error{pools;_tag="HostOffersError";constructor(e){super(`Track the host's offers for ${e.length} scale-set pools failed: the host daemon makes offers to at most ${oo} pools of one fleet`);this.pools=e;this.name="HostOffersError"}}var V1=1e4,q1=120000,K1=1000;function W1(e,t,n){let{cpus:r,diskGiB:o,memoryMiB:s}=t.resources;return{assigned:n,ceiling:t.ceiling,class:Rs(t),cpus:r,diskGiB:o,memoryMiB:s,pool:e,priority:t.priority??dr}}function WR(e){let t=e.clock??Le,n=e.intervalMs??V1,r=e.unreachableAlertMs??q1,o=Object.entries(e.pools).filter(([,h])=>h.demand==="scaleset");if(o.length>oo)throw new wc(o.map(([h])=>h));let s=new Map,i,a=!1,c,u,l,d;async function f(){try{let h=e.slots(),E=new Map(o.map(([_])=>[_,eo(h,_).length])),v=o.map(([_,C])=>W1(_,C,e.assigned(_))),S=new Map((await e.offer(v)).map((_)=>[_.pool,_.offer]));s=new Map(o.map(([_])=>[_,{live:E.get(_)??0,offer:S.get(_)??0}])),i=void 0,a=!1}catch(h){if(s=new Map,i??=t.now(),a||t.now()-i<r)return;a=!0,e.alert?.({detail:`the host daemon has offered no capacity for ${Math.round(r/K1)} s, so no new guest starts: ${J1(h)}`,reason:"host-daemon-unreachable"})}}function m(){if(!c)return c=f().finally(()=>{c=void 0}),c;return u??=c.then(()=>(u=void 0,m())),u}async function g(h){while(!h.aborted)await m(),await t.sleep(n,h)}return{capacity(h){let E=e.pools[h];if(E?.demand!=="scaleset")return 0;let v=eo(e.slots(),h).length,S=s.get(h),_=S?Math.max(0,S.offer-Math.max(0,v-S.live)):0,C=v+_;return to(E.ceiling===fe?C:Math.min(E.ceiling,C))},refresh:m,start(){if(d)return;let h=new AbortController;l=h,d=g(h.signal)},async stop(){l?.abort(),await d,l=void 0,d=void 0}}}function J1(e){return e instanceof Error?e.message:String(e)}var Y1=1e4,X1=300000;function z1(e,t){let n=[...e].sort((i,a)=>a.priority-i.priority||(i.pool<a.pool?-1:1)),r=new Map(n.map((i)=>[i.pool,i.room])),o=new Map(n.map((i)=>[i.pool,0])),s=t.map((i)=>n.filter((a)=>i.admittedBy.has(a.pool)&&ji(i.labels,a.labels))).filter((i)=>i.length>0).sort((i,a)=>i.length-a.length);for(let i of s){let a=i.find((c)=>(r.get(c.pool)??0)>0)??i[0];if(!a)continue;o.set(a.pool,(o.get(a.pool)??0)+1),r.set(a.pool,(r.get(a.pool)??0)-1)}return o}function JR(e){let{client:t,pools:n}=e,r=e.clock??Le,o=e.freshMs??Y1,s=oy(),i,a;async function c(d){let f=new Map,m=(v,S)=>{d.throwIfAborted();let _=S instanceof Error?S:Error(String(S));for(let C of v)if(!f.has(C))f.set(C,_)},g=new Map;for(let v of n)try{for(let S of await v.repositories()){let _=ry(S),C=g.get(_)??{admittedBy:new Set,repository:S};C.admittedBy.add(v.pool),g.set(_,C)}}catch(S){m([v.pool],S)}let h=[];for(let{admittedBy:v,repository:S}of g.values())try{for(let _ of await sy(t,S,s,d))h.push({admittedBy:v,labels:_})}catch(_){m(v,_)}let E=n.filter((v)=>!f.has(v.pool)).map(({labels:v,pool:S,priority:_,room:C})=>({labels:v,pool:S,priority:_,room:C()}));return{counts:z1(E,h),failures:f}}function u(d){let f=r.now();if(i&&f-i.at<o)return{round:Promise.resolve(i.round),signal:d};return a??={round:c(d).then((m)=>(i={at:f,round:m},m)).finally(()=>{a=void 0}),signal:d},a}async function l(d){for(;;){let f=u(d);try{return await f.round}catch(m){if(d.aborted||!f.signal.aborted)throw m}}}return{reader(d){if(!n.some((f)=>f.pool===d))throw Error(`Pool ${d} is not on the queued job board`);return{queued:async(f)=>{let m=await l(f),g=m.failures.get(d);if(g)throw g;return m.counts.get(d)??0}}}}}function YR(e){let{github:t,pool:n}=e,r=de(e.url);if(r.kind==="repo"){let l=[{owner:r.owner,repo:r.repo}];return async()=>l}let o=e.clock??Le,s=e.refreshMs??X1,i=Mr(),a=Mr(),c=`Read the repositories whose jobs may reach pool ${n}`,u;return async()=>{let l=o.now();if(u&&l-u.at<s)return u.repositories;let d=e.runnerGroup,f=d===void 0?void 0:await Ur(t,r.org,d,i);if(!f)throw new We(n,c,"runner-group-missing",`${r.org} has no runner group named ${d??"(none set)"}`);let{visibility:m}=f;if(!gy(m))throw new We(n,c,"runner-group-visibility",`the runner group ${f.name} admits repositories by ${m}, which Hydra does not know`);let g=await hy(t,r.org,{...f,visibility:m},a);return u={at:l,repositories:g},g}}import{closeSync as Q1,constants as Sc,fchmodSync as Z1,mkdirSync as eU,openSync as tU,writeSync as nU}from"fs";import{join as rU}from"path";var QR={pollMs:5000,retryMs:1e4,undestroyedRetryMs:900000},XR=5242880,oU=7,sU=448,zR=384,iU=/[\p{Cc}\p{Cf}]+/gu,aU="the error text was withheld because it looks like it holds a secret",cU=new Set(["busy","closed","conflict","timeout","unavailable","unreachable"]);function tp(e,t,n){let{cpus:r,diskGiB:o,memoryMiB:s}=t.resources;return{class:Rs(t),cpus:r,diskGiB:o,memoryMiB:s,pool:e,priority:t.priority??dr,slot:n}}function Ae(e){let t=(e instanceof Error?e.message:String(e)).replace(iU," ").trim();if(ir(t))return aU;return(t.length>Ya?`${t.slice(0,Ya-1)}\u2026`:t)||"an unknown error"}function ZR(e,t,n){let{clock:r,host:o,ledger:s,log:i,signal:a,timing:c}=e,u=(k)=>r.sleep(k,a),l=(k)=>s.record(t,k),d=(k)=>e.pools[k.pool];async function f(k){let D=d(k);if(n.withdraw||!D){l({kind:"drain"});return}try{let B=await o.lease(tp(k.pool,D,t));if(l({kind:"lease-granted",lease:B.grantedAt}),e.leaseChanged(),n.withdraw)l({kind:"drain"})}catch(B){if(a.aborted)return;let q=B instanceof Xe?B.code:"failed";if(q==="withdrawn"){l({kind:"drain"});return}if(k.phase==="requested")l({kind:"lease-refused"});if(cU.has(q)){await u(c.retryMs);return}l({kind:"drain"}),e.unavailable(k.pool,`the host daemon refused its guests: ${Ae(B)}`)}}async function m(k,D){if(n.withdraw){l({kind:"drain"});return}l({kind:"prepare"});try{await D.create(e.spec(k.pool,t)),await D.start(k)}catch(B){if(B instanceof Xr){i(`slot ${t} returns its lease: ${Ae(B)}`),l({kind:"budget-unavailable"});return}l({detail:Ae(B),kind:"failed"});return}l({kind:"ready"})}async function g(k,D){if(S(k)){l({kind:"timed-out"});return}let B=e.source(k.pool);if(!B){l({detail:"the pool has no demand source to mint its runner",kind:"failed"});return}let q=await _(D,k);if(!q){await u(c.pollMs);return}if(q.kind!=="running"){l({detail:`the guest was ${q.kind} before its runner was handed over`,kind:"failed"});return}let ue;try{let ze=await B.mint(t);ue=ze.jit,l({kind:"minted",runnerId:ze.runner.id,runnerName:ze.runner.name})}catch(ze){if(a.aborted)return;l({detail:Ae(ze),kind:"failed"});return}try{await D.runJit(k,ue)}catch(ze){l({detail:Ae(ze),kind:"failed"})}}async function h(k){n.retire=!1;let D=e.source(k.pool);if(!D||!k.runner)return!1;if(await D.release(k.runner).catch(()=>"busy")==="busy")return!1;return l({kind:"drain"}),!0}async function E(k,D){if(n.retire&&k.phase==="online"&&await h(k))return;let B=await _(D,k);if(B)v(k,B);let q=s.get(t);if(q&&q.phase===k.phase&&S(q)){l({kind:"timed-out"});return}if(q?.phase===k.phase)await u(c.pollMs)}function v(k,D){switch(D.kind){case"runner-alive":if(D.busy&&k.phase!=="busy")l({kind:"job-started"});else if(!D.busy&&k.phase==="registering")l({kind:"online"});return;case"exited":if(l({code:D.code,kind:"exited"}),D.code===oU)e.alert({detail:`the runner of ${t} exited asking for a newer version`,pool:k.pool,reason:"runner-update-required",slot:t});return;case"gone":l({detail:"the guest disappeared",kind:"failed"});return;case"preparing":case"running":return}}function S(k){let D=zw(k,d(k)?.maxJobMinutes??Ww);return D!==void 0&&r.now()>=D}async function _(k,D){try{return await k.state(D)}catch(B){i(`could not read the state of ${t}: ${Ae(B)}`);return}}async function C(k,D){let B=d(k);if(e.logsDir&&B&&!B.secretBearing)try{let q="";for await(let ue of D.logs(k,{bytes:XR}))q=`${q}${ue.text}`.slice(-XR);if(q)lU(e.logsDir,t,q)}catch(q){i(`could not copy the runner log of ${t}: ${Ae(q)}`)}l({kind:"collected"})}async function w(k,D){try{await rg(D,k,{fleetPrefix:e.fleetPrefix,protectedNames:e.protectedNames,recorded:async(ue)=>s.destroyable(ue)});let q=await D.verifyGone(k);if(q.leftovers.length>0)throw Error(`the guest left ${q.leftovers.join(", ")} behind`)}catch(q){let ue=Ae(q);if(e.alert({detail:ue,pool:k.pool,reason:"slot-undestroyed",slot:t}),k.phase==="destroying")e.ended(l({detail:ue,kind:"failed"}),"undestroyed");await u(c.undestroyedRetryMs);return}await x(k);let B=l({kind:"verified"});if(await y(),k.phase!=="destroying"){i(`slot ${t} is gone at last; its lease is returned`);return}if(B.phase==="quarantined")e.alert({detail:B.fault?.detail,pool:k.pool,reason:"slot-quarantined",slot:t});e.ended(B,uU(B))}async function x(k){let D=e.source(k.pool),B=k.runner;if(!B||!D)return;try{if(await D.release(B)!=="busy")return;i(`GitHub still shows the runner of ${t} as busy; reconcile removes it later`)}catch(q){i(`could not remove the runner registration of ${t}: ${Ae(q)}`)}e.runnerLeft?.(k.pool,B)}async function y(){try{await o.release(t),e.released(t,!0)}catch(k){i(`could not return the lease of ${t}: ${Ae(k)}`),e.released(t,!1)}e.leaseChanged()}async function R(k){if(k.lease!==void 0)await y();e.ended(k,"withdrawn")}async function A(k){let D=e.driver(k.pool);if(k.phase==="requested"||k.phase==="waiting")return f(k);if(!D){i(`slot ${t} of pool ${k.pool} waits: its driver is not available`),await u(c.retryMs);return}switch(k.phase){case"admitted":return m(k,D);case"preparing":l({kind:"drain"});return;case"registering":return k.runner?E(k,D):g(k,D);case"online":case"busy":return E(k,D);case"finishing":return C(k,D);default:return w(k,D)}}return(async()=>{while(!a.aborted){let k=s.get(t);if(!k||ht(k.phase)&&!qe(k)){if(k?.phase==="withdrawn")await R(k);return}await A(k)}})()}function uU(e){if(e.phase==="quarantined")return"quarantined";return e.teardown==="job-done"?"job-done":"verified"}function lU(e,t,n){eU(e,{mode:sU,recursive:!0});let r=Sc.O_WRONLY|Sc.O_CREAT|Sc.O_TRUNC|Sc.O_NOFOLLOW,o=tU(rU(e,`${t}.log`),r,zR);try{Z1(o,zR),nU(o,n.replace(/[^\P{Cc}\n\t]/gu,""))}finally{Q1(o)}}var np=60000,dU={busyRetryMs:30000,goneGapMs:3*np,refusedAlertMs:15*np,roundMs:5*np},pU=3,fU=/^[a-z0-9]{6}$/,mU=/[\p{Cc}\p{Cf}]/gu;function gU(e,t,n){let r=`hydra-${t}-${n}-`;return e.startsWith(r)&&fU.test(e.slice(r.length))}function e$(e){return ht(e.phase)&&!qe(e)}function hU(e,t){return new Set(Object.entries(t).flatMap(([n,r])=>{let o=`${e}-${n}-`;return r.name.startsWith(o)?[r.name.slice(o.length)]:[]}))}function yU(e,t,n){let r=`${t}-`;return e.startsWith(r)&&[...n].some((o)=>e.endsWith(`-${o}`)&&e.length>r.length+o.length+1)}function $s(e){return e.replace(mU,"?")}function t$(e){return(e.kind==="repo"?`repo:${e.owner}/${e.repo}`:`org:${e.org}`).toLowerCase()}function n$(e){let{fleet:t,github:n,ledger:r,log:o,registrations:s}=e,i=e.clock??Le,a={...dU,...e.timing},c=new AbortController,u=new Map,l=new Map,d=new Map,f=new Set,m=new Map,g=new Set,h=0,E=[],v=()=>{let A=new Map;for(let[k,D]of Object.entries(s)){let B=t$(D.target),q=A.get(B)??{pools:[],target:D.target};q.pools.push(k),A.set(B,q)}return[...A.values()]},S=(A,k,D)=>{let B=`${A}:${k}`;if(d.has(B))return;d.set(B,k),o(D)},_=(A,k)=>{if(!u.has(k.id))u.set(k.id,{alerted:!1,failing:!1,pool:A,runner:k,since:i.now()})};async function C(){let A={failures:[],foreign:[],removed:[],retired:[]},k=new Map(r.slots().map((z)=>[z.name,z])),D=new Map,B=new Set,q=new Set,ue=async(z,V,O)=>{try{return await O()}catch(H){B.add(z),A.failures.push(`${V}: ${Ae(H)}`);return}},ze=async(z,V)=>{let O=s[z];if(!O)return;let H=await ue("runner",`remove the runner ${V.name}`,()=>O.remove(V));if(H===void 0)return;if(H==="busy"){_(z,V),S("busy",V.id,`GitHub reports the runner ${V.name} busy; Hydra retries its removal`);return}if(u.delete(V.id),H==="gone")return;A.removed.push(V.name),o(`removed the registration of runner ${V.name} (id ${V.id}), which its ended slot left behind`)},L=async(z,V)=>{let O={id:V.id,name:V.name},H=k.get(V.name);if(H){if(!z.pools.includes(H.pool)||!e$(H))return;let ie=s[H.pool];if(H.runner?.id!==V.id&&ie?.kind==="scaleset"){if(await ue("runner",`read the runner ${V.name}`,()=>ie.locate(O))!=="here")return}await ze(H.pool,O);return}let G=z.pools.find((ie)=>gU(V.name,t,ie));if(!G){let ie=`runner ${$s(V.name)} (id ${V.id}) carries no slot name of this fleet`;S("foreign",V.id,`${ie}; Hydra leaves it alone`);return}if(r.get(V.name))return;let U=s[G],Y=`runner ${V.name} (id ${V.id}) carries a slot name of pool ${G} that the ledger does not hold`;if(U?.kind!=="scaleset"||!Fr(V)||V.busy){S("unheld",V.id,`${Y}; Hydra leaves it alone`);return}if(q.add(V.id),!g.has(V.id))return;let Se=await ue("runner",`read the runner ${V.name}`,()=>U.locate(O));if(Se==="elsewhere")S("elsewhere",V.id,`${Y} in another scale set; Hydra leaves it alone`);if(Se==="here")await ze(G,O)},j=async(z,V)=>{for(let O of r.slots()){let H=s[O.pool],G=O.runner;if(!H||!G||O.phase!=="online"||!z.pools.includes(O.pool))continue;if(V.has(G.id)){l.delete(O.name);continue}let U=await ue("runner",`read the runner of ${O.name}`,()=>H.locate(G));if(U===void 0)continue;if(U!=="gone"){l.delete(O.name);continue}let Y=l.get(O.name);if(Y===void 0){l.set(O.name,i.now());continue}if(i.now()-Y<a.goneGapMs||r.get(O.name)?.phase!=="online")continue;l.delete(O.name),A.retired.push(O.name),o(`the runner of ${O.name} is gone from GitHub while it waits for a job; retiring the slot`),e.retire(O.name)}},oe=async()=>{let z=await ue("scale-set","read the scale set records",async()=>e.records());if(!z)return;let V=new Set(Object.values(z).map((G)=>G.id)),O=hU(t,z),H=new Map;for(let[G,U]of Object.entries(z)){let Y=s[G];if(Y?.kind==="scaleset")H.set(`${t$(Y.target)}#${U.runnerGroupId}`,Y)}for(let G of H.values()){let U=De(G.target),Y=await ue("scale-set",`list the scale sets of ${U}`,()=>G.scaleSets());for(let Se of Y??[]){if(V.has(Se.id)||!yU(Se.name,t,O))continue;D.set(`scale-set:${Se.id}`,{category:"scale-set",detail:`scale set ${$s(Se.name)} (id ${Se.id}) carries this fleet's prefix and this host's id, but this home did not record it`,reason:"foreign-scale-set",subject:`scale set ${$s(Se.name)}`})}}},$e=async()=>{let z=new Map;for(let V of Object.values(e.drivers))z.set(V.capabilities().id,V);for(let[V,O]of z){let H=await ue("guest",`list the ${V} guests`,()=>O.list());for(let G of H??[]){let U=r.get(G.name),Y=k.get(G.name);if(U&&!(Y&&e$(Y)))continue;D.set(`guest:${G.name}`,{category:"guest",detail:U?`guest ${G.name} exists, though its slot ended ${U.phase}`:`guest ${G.name} carries this fleet's prefix, but the ledger holds no slot of that name`,reason:"foreign-guest",subject:`guest ${G.name}`})}}},Ie=async()=>{for(let z of e.networks??[]){let V=await ue("network","read the guest networks",()=>z.status());for(let O of V?.unplanned??[])D.set(`network:${O}`,{category:"network",detail:`network ${$s(O)} carries this fleet's prefix, but lies outside its network range`,reason:"foreign-network",subject:`network ${$s(O)}`})}},Ee=new Set,we=!0;for(let z of v()){let V=`list the runners of ${De(z.target)}`,O=await ue("runner",V,()=>Ht(n,z.target));if(!O){we=!1;continue}for(let H of O)Ee.add(H.id);for(let H of O)await L(z,H);await j(z,new Set(O.map((H)=>H.id)))}await oe(),await $e(),await Ie();for(let z of l.keys())if(r.get(z)?.phase!=="online")l.delete(z);if(g=q,we){for(let[z,V]of d)if(!Ee.has(V))d.delete(z)}return w(D,B,A),x(A.failures),A}function w(A,k,D){for(let[q,ue]of A){if(!m.has(q)||f.has(q))continue;f.add(q),D.foreign.push(ue.detail),o(`${ue.detail}; Hydra leaves it alone, and no pool takes new jobs`),e.alert({detail:ue.detail,reason:ue.reason}),e.degrade(`found ${ue.subject}, which Hydra did not create`)}let B=[...m].filter(([,q])=>k.has(q.category));m=new Map([...B,...A]);for(let q of f)if(!m.has(q))f.delete(q)}function x(A){for(let D of A)o(`reconcile could not ${D}`);if(h=A.length>0?h+1:0,h!==pU)return;let k=A.length>1?` and ${A.length-1} more`:"";e.alert({detail:`could not ${A[0]}${k}`,reason:"reconcile-failed"})}async function y(){for(let[A,k]of[...u]){let D=s[k.pool];if(!D){u.delete(A);continue}let B;try{B=await D.remove(k.runner)}catch(q){if(!k.failing)o(`could not remove the runner ${k.runner.name}: ${Ae(q)}`);k.failing=!0;continue}if(k.failing=!1,B!=="busy"){if(u.delete(A),B==="removed")o(`removed the registration of runner ${k.runner.name} (id ${A})`);continue}if(k.alerted||i.now()-k.since<a.refusedAlertMs)continue;k.alerted=!0,e.alert({detail:`GitHub still reports the runner ${k.runner.name} (id ${A}) busy after its guest was destroyed, so its registration stays`,pool:k.pool,reason:"registration-refused",slot:k.runner.name})}}let R=async(A,k)=>{while(!c.signal.aborted)await k().catch((D)=>o(`reconcile stopped on an error: ${Ae(D)}`)),await i.sleep(A,c.signal)};return{left:_,retry:y,round:C,start(){if(E.length>0||c.signal.aborted)return;E=[R(a.roundMs,C),R(a.busyRetryMs,y)]},async stop(){c.abort(),await Promise.allSettled(E)}}}var bU={busy:"busy",deleted:"removed",gone:"gone"};function wU(e,t,n){return{kind:"scaleset",async locate(r){let o=await e.getRunner(r.id);if(!o)return"gone";return o.scaleSetId===t.id&&o.name===r.name?"here":"elsewhere"},remove:(r)=>e.removeRunner(r.id),scaleSets:()=>e.listScaleSets(t.runnerGroupId),target:n}}function SU(e,t){return{kind:"poll",async locate(n){let r=await Gt(e,t,n.id);if(!r)return"gone";return r.name===n.name?"here":"elsewhere"},remove:async(n)=>bU[await zn(e,t,n.id)],scaleSets:async()=>[],target:t}}function r$(e,t,n){let r={};for(let[o,s]of Object.entries(e)){let i=de(s.url);if(s.demand==="poll"){r[o]=SU(n.github,i);continue}let a=t[o];if(a)r[o]=wU(n.scaleSetClient(s.url),a,i)}return r}import{randomBytes as RU}from"crypto";var $U={...QR,healthMs:60000,stopMs:1e4,tickMs:5000},EU=3,vU=4,o$=6,kU=36,xU=["requested","waiting"],_U=["online"],TU=["idle","connecting","conflict","retrying"];function s$(e,t){return e.slots().flatMap((n)=>{let r=t[n.pool];return r&&Xw(n)?[tp(n.pool,r,n.name)]:[]})}async function i$(e){let{host:t,ledger:n,log:r}=e,o=e.clock??Le,s={...$U,...e.timing},i=new AbortController,a=new Map,c=new Map(Object.entries(e.unavailable??{})),u=new Map,l=new Map,d=new Map,f=new Set,m=new Set(n.slots().filter((L)=>!ht(L.phase)||qe(L)).map((L)=>L.name)),g=`hydra-${e.fleet}`,h=!1,E=(L,j)=>{if(c.has(L))return;c.set(L,j),r(`pool ${L} takes no new jobs: ${j}`),e.alert({detail:j,pool:L,reason:"pool-unavailable"})},v=(L,j)=>{if(r(`slot ${L.name} of pool ${L.pool} ended ${j}`),j==="job-done")d.set(L.pool,0);if(j!=="quarantined"&&j!=="undestroyed"||m.has(L.name))return;let oe=(d.get(L.pool)??0)+1;if(d.set(L.pool,oe),oe<EU||u.has(L.pool))return;let $e=`${oe} slots in a row were quarantined, the last one ${L.name}`;u.set(L.pool,$e),r(`pool ${L.pool} is degraded: ${$e}`),e.alert({detail:$e,pool:L.pool,reason:"pool-degraded"})},S=(L)=>{let j=e.drivers[L];return j&&!l.has(j.capabilities().id)?j:void 0},_={alert:e.alert,clock:o,driver:(L)=>e.drivers[L],ended:v,fleetPrefix:g,host:t,leaseChanged:()=>{e.offers?.refresh().catch(()=>{return})},ledger:n,log:r,logsDir:e.logsDir,pools:e.pools,protectedNames:e.protectedNames??[],released:(L,j)=>{if(j)f.delete(L);else f.add(L)},runnerLeft:e.runnerLeft,signal:i.signal,source:(L)=>e.sources[L],spec:e.spec,timing:s,unavailable:E},C=(L)=>{if(a.has(L)||h)return;let j={retire:!1,withdraw:!1},oe=ZR(_,L,j).catch(($e)=>r(`slot ${L} stopped on an error: ${Ae($e)}`)).finally(()=>a.delete(L));a.set(L,{control:j,done:oe})},w=(L)=>{for(;;){let j=BigInt(`0x${RU(vU).toString("hex")}`).toString(kU).padStart(o$,"0").slice(-o$),oe=`${g}-${L}-${j}`;if(!n.get(oe))return oe}},x=(L)=>!c.has(L)&&!u.has(L)&&S(L)!==void 0&&e.held?.(L)===void 0,y=(L,j,oe)=>{let $e=(Ee)=>L.filter((we)=>Ee.includes(we.phase)&&!a.get(we.name)?.control.withdraw).sort((we,z)=>Date.parse(z.requestedAt)-Date.parse(we.requestedAt)),Ie=$e(xU).slice(0,j);for(let Ee of Ie){let we=a.get(Ee.name);if(!we)continue;we.control.withdraw=!0,t.release(Ee.name).catch(()=>{return})}if(!oe)return;for(let Ee of $e(_U).slice(0,j-Ie.length)){let we=a.get(Ee.name);if(we)we.control.retire=!0}},R=(L)=>{let j=eo(n.slots(),L),oe=e.sources[L],$e=oe!==void 0&&x(L);if($e&&TU.includes(oe.status().state))return;let Ie=$e?oe.desired():0,Ee=j.filter((z)=>a.get(z.name)?.control.withdraw).length;if(Ie<j.length){let z=$e||e.held?.(L)!==void 0;if(Ie<j.length-Ee)y(j,j.length-Ee-Ie,z);return}let we=e.drivers[L];if(!we)return;for(let z=j.length;z<Ie;z++){let V=w(L);n.request({driver:we.capabilities().id,name:V,pool:L}),r(`requested slot ${V} for pool ${L}`),C(V)}},A=()=>{if(h)return;try{for(let L of Object.keys(e.pools))R(L);for(let L of n.slots())if(!ht(L.phase)||qe(L))C(L.name)}catch(L){r(`could not balance the pools: ${Ae(L)}`)}for(let L of f)t.release(L).then(()=>f.delete(L),()=>{return})},k=(L)=>{for(let j of L.unlisted){let oe=n.get(j);if(!oe||ht(oe.phase)&&!qe(oe))f.add(j)}if(L.adopted.length>0)r(`the host daemon adopted the leases of ${L.adopted.join(", ")}`)},D=async()=>{let L=new Map(Object.values(e.drivers).map((j)=>[j.capabilities().id,j]));for(let[j,oe]of L){let $e=await oe.health().then((we)=>we.findings.filter((z)=>z.level==="error").map((z)=>z.detail)).catch((we)=>[Ae(we)]),Ie=l.get(j);if($e.length===0){if(Ie!==void 0)r(`driver ${j} is available again`);l.delete(j);continue}if(Ie!==void 0)continue;let Ee=$e.join("; ");l.set(j,Ee),r(`driver ${j} is unavailable, so its pools take no new jobs: ${Ee}`),e.alert({detail:`${j}: ${Ee}`,reason:"driver-unavailable"})}},B=async(L,j)=>{while(!i.signal.aborted)await j(),await o.sleep(L,i.signal)};for(let[L,j]of Object.entries(e.sources))try{await j.start()}catch(oe){E(L,Ae(oe))}await D(),e.offers?.start();let q=[B(s.tickMs,A),B(s.healthMs,D)];return r(`serving ${Object.keys(e.pools).length} pools of fleet ${e.fleet}`),{degrade(L){for(let j of Object.keys(e.pools)){if(u.has(j))continue;u.set(j,L),r(`pool ${j} is degraded: ${L}`)}},reported:k,retire(L){let j=a.get(L);if(j)j.control.retire=!0},async settle(){while(a.size>0)await Promise.allSettled([...a.values()].map((L)=>L.done))},status(){let L=n.slots(),j=Object.keys(e.pools).map((oe)=>{let $e=c.get(oe)??u.get(oe)??e.held?.(oe)??ze(oe),Ie=ue(oe),Ee=e.sources[oe]?.status();return{...Ee?{demand:Ee}:{},...$e?{detail:$e}:{},health:Ie,live:eo(L,oe).length,pool:oe}});return{host:t.connected()?"connected":"disconnected",pools:j,slots:a.size}},async stop(){if(h)return;h=!0,i.abort(),await Promise.all(Object.values(e.sources).map((j)=>j.stop().catch(()=>{return}))),await e.offers?.stop(),t.close();let L=Promise.allSettled([...q,...[...a.values()].map((j)=>j.done)]);await Promise.race([L,Bun.sleep(s.stopMs)])},tick:A};function ue(L){if(u.has(L))return"degraded";if(e.held?.(L)!==void 0)return"drained";return x(L)?"serving":"unavailable"}function ze(L){let j=e.drivers[L]?.capabilities().id;return j===void 0?"no driver":l.get(j)}}var CU="Check the GitHub credentials: the guard reads runner groups, their repositories and runners, and the fork pull request policy, which needs gh with the admin:org scope (admin access for a repository pool), or a GitHub App that may read the organisation's self-hosted runners and Actions settings";function Rc(e){let t=e.get("pools")??{};if(Object.keys(t).length===0)throw new b("This home has no pools to guard","Add one with hydra pool add");return t}async function $c(e,t){try{return await Ba(Mt(e).client).snapshots(t)}catch(n){if(n instanceof Re)throw new b(n.message,CU);throw n}}function io(e){try{return ec(e)}catch(t){if(t instanceof On)throw new b(t.message,"Repair or remove it, then run hydra guard record");throw t}}function Ec(e){let t=ee(e);if(!AU(Qr(t)))return ls([]);try{return ls(fS(t))}catch(n){if(n instanceof it)throw new b(n.message,"Repair the ledger, or restore it from a backup");throw n}}function vc(e){return[OU(e),PU(e)].map((t)=>` ${t}`)}function kc(e,t=p.red("\u2717")){return e.flatMap((n)=>[` ${t} ${n.detail}`,...(n.names??[]).map((r)=>p.dim(` ${Jo(r)}`))])}function OU({scope:e}){if(e.kind==="repo")return`${_t(e)}: ${e.visibility}`;let t=e.group;if(!t)return`${_t(e)}: does not exist`;let n=t.repositories?` (${t.repositories.length})`:"",r=t.restrictedToWorkflows?`${t.selectedWorkflows.length} selected workflows`:"any workflow",o=t.allowsPublicRepositories?"public repositories allowed":"public repositories refused";return`${_t(e)} (id ${t.id}): ${Va(t.visibility)}${n}, ${o}, ${r}`}function PU({forkPolicy:e}){return`fork pull requests: ${[IU(e),e.approval?`approval for ${qa(e.approval)}`:""].filter(Boolean).join("; ")}`}function IU({privateRepositories:e}){if(!e)return"";if(!e.runWorkflows)return"workflows of private repositories do not run";return`workflows of private repositories run ${[e.requireApproval?"after approval":"without approval",e.sendWriteTokens?"with write tokens":"",e.sendSecrets?"with secrets and variables":""].filter(Boolean).join(", ")}`}var a$=P({name:"check",description:"Compare each pool's runner group or repository and the fork pull request policy with the guard record",json:!0,examples:["hydra guard check","hydra guard check --json"],run:async(e)=>{let t=Rc(e.config),n=io(ee(e.config));if(!n)throw new b("This home has no guard record","Run hydra guard record once the runner groups and policies are as they should be");let r=await $c(e.config,t),o=Ec(e.config),s=Object.entries(t).flatMap(([c,u])=>{let l=r[c];if(!l)return[];let d=Ka({baseline:n.pools[c],config:u,minted:o,snapshot:l}),{runners:f,...m}=l;return[{...m,findings:d,ok:d.length===0,pool:c}]}),i=s.filter((c)=>!c.ok).length,a={ok:i===0,pools:s,recordedAt:n.recordedAt};if(!e.json)T.info(NU(a));if(e.output.result(a),a.ok)return;throw new b(`${i} pool(s) differ from the guard record`,"Put the settings back, or run hydra guard record to accept them; hydra serve gives such a pool no new jobs")}});function NU(e){let t=e.pools.flatMap((n)=>[`${n.ok?p.green("\u2713"):p.red("\u2717")} ${p.bold(n.pool)}`,...vc(n),...kc(n.findings)]);return[p.dim(`Guard recorded at ${e.recordedAt}`),...t].join(`
420
+ `)}var c$=P({name:"record",description:"Record each pool's runner group or repository, the fork pull request policy and the runners Hydra did not mint",run:async(e)=>{let t=Rc(e.config),n=ee(e.config),r=io(n),o=await $c(e.config,t),s=Object.entries(o).flatMap(([l,{scope:d}])=>d.kind==="org"&&!d.group?[`pool ${l}: ${_t(d)} does not exist`]:[]);if(s.length>0)throw new b(s.join(`
421
+ `),"Create the runner group, or name an existing one in the pool's runnerGroup");let i=Object.entries(t).flatMap(([l,d])=>{let f=o[l];return f?hd(d,f.scope).map((m)=>`pool ${l}: ${m.detail}`):[]});if(i.length>0)throw new b(i.join(`
422
+ `),"Refuse public repositories for that runner group or repository, or keep secrets out of the pool");let a=Ec(e.config),c={},u=[`Recorded the guard for ${Object.keys(o).length} pool(s)`];for(let[l,d]of Object.entries(o)){let f=wS(d,a);c[l]=f;let m=r?.pools[l],g=m?.url===f.url?yd(m,d):[];u.push(p.bold(l),...vc(f),...DU(f),...LU(g))}SS(n,{pools:c,recordedAt:new Date().toISOString()}),T.success(u.join(`
423
+ `))}});function DU(e){let t=e.acceptedRunners;if(t.length===0)return[];return[p.yellow(` accepted ${t.length} runner(s) Hydra did not mint:`),...t.map((n)=>p.dim(` ${n.id} ${Jo(n.name)}`))]}function LU(e){if(e.length===0)return[];return[p.yellow(" accepted these changes since the last record:"),...kc(e,p.yellow("!"))]}var rp=P({name:"guard",description:"Record the pools' runner groups and fork pull request policy, or compare them with the record",subcommands:[c$,a$]});import{mkdirSync as gj,statSync as hj}from"fs";import{join as yj}from"path";import{closeSync as VU,fsyncSync as qU,openSync as KU,readFileSync as WU,renameSync as JU,rmSync as f$,writeFileSync as YU}from"fs";import{join as m$}from"path";import{networkInterfaces as MU}from"os";var dn="com.apple/hydra",sp='anchor "com.apple/*"',xc=["hydra_guests","hydra_block4","hydra_self"],HU=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.168.0.0/16","198.18.0.0/15","224.0.0.0/4","240.0.0.0/4"],[ao,u$,l$]=xc,GU=/^bridge(\d+)$/,FU=/^[a-z][a-z0-9]{0,15}$/,UU=["IPv4",4],jU=/^(No ALTQ support in kernel|ALTQ related functions disabled)/;function _c(e){return Object.values(e.fleets).flatMap((t)=>t.guestRange===void 0?[]:[t.guestRange])}function Tc(e,t=MU()){let n=e.map((i)=>st(i)).filter((i)=>i!==void 0),r=new Map,o=new Map,s=[];for(let[i,a]of Object.entries(t))for(let c of a??[]){let u=UU.includes(c.family)?Cr(c.address):void 0;if(u===void 0)continue;if(r.set(u,c.address),!n.some((d)=>Or(d,u)))continue;let l=GU.exec(i);if(l)o.set(Number(l[1]),i);else s.push(`${FU.test(i)?i:"interface"} address ${c.address}`)}return{bridges:d$(o),clashes:s,guestRanges:[...e],self:d$(r)}}function Ac(e){let t=[`block drop in quick inet from <${ao}> to <${l$}>`,`block drop in quick inet from <${ao}> to <${u$}>`,...e.bridges.map((o)=>`block drop in quick on ${o} inet6 all`),`pass in quick inet proto tcp from <${ao}> to any flags S/SA keep state`,`pass in quick inet proto udp from <${ao}> to any keep state`,`pass in quick inet proto icmp from <${ao}> to any keep state`],n={hydra_block4:[...HU],hydra_guests:[...e.guestRanges],hydra_self:[...e.self]},r=[op(ao,"const",n.hydra_guests),op(u$,"const",n.hydra_block4),op(l$,"persist",n.hydra_self),...t,""].join(`
424
+ `);return{inputs:e,rules:t,tables:n,text:r}}function Es(e){return e.split(`
425
+ `).map((t)=>t.trim().replace(/\s+/g," ")).filter((t)=>t.length>0&&!jU.test(t))}function p$(e){return Es(e).sort()}function ip(e,t){let n=e.rules.join(`
426
+ `)===t.rules.join(`
427
+ `)?[]:[...co(e.rules,t.rules).map((o)=>`rule missing: ${o}`),...co(t.rules,e.rules).map((o)=>`rule not rendered: ${o}`),...BU(e.rules,t.rules)?["rules in another order"]:[]],r=xc.flatMap((o)=>{let s=e.tables[o],i=t.tables[o];if(s===null)return[];if(i===null)return[`table <${o}> is not loaded`];return[...co(s,i).map((a)=>`table <${o}> lacks ${a}`),...co(i,s).map((a)=>`table <${o}> also holds ${a}`)]});return[...n,...r]}function op(e,t,n){return n.length===0?`table <${e}> ${t}`:`table <${e}> ${t} { ${n.join(", ")} }`}function d$(e){return[...e.entries()].sort(([t],[n])=>t-n).map(([,t])=>t)}function co(e,t){let n=new Set(t);return e.filter((r)=>!n.has(r))}function BU(e,t){return co(e,t).length===0&&co(t,e).length===0}var XU="pf-reference.json",zU="pf-anchor.conf",QU=384,ZU=/^\d+$/;function y$(e){return{...b$("off"),findings:[{code:"unsupported",detail:e,fix:"Run the host daemon on macOS to load the pf anchor",level:"warning"}]}}function b$(e){return{anchor:dn,bridges:[],checkedAt:null,enforced:!1,findings:[],lastDrift:null,loadedAt:null,reference:!1,state:e}}function w$(e){let{log:t,pfctl:n,stateDir:r}=e,o=e.now??Date.now,s=e.interfaces,i=m$(r,XU),a=m$(r,zU),c,u,l=null,d=null,f=Number.NEGATIVE_INFINITY,m=b$("failing"),g,h=()=>new Date(o()).toISOString(),E=async(w,x)=>{let y=x?tj(i):void 0,R=await n.enable();if(c=R,g$(i,`${JSON.stringify({takenAt:h(),token:R})}
428
+ `),t(`took a pf enable reference${y?", replacing the one recorded before":""}`),!y||y===R)return;await n.release(y).catch((A)=>{let k=`The pf enable reference recorded before this one could not be released: ${h$(A)}`;t(k),w.push({code:"reference-release",detail:k,fix:"pfctl -s References lists the references pf holds; a stale one only keeps pf enabled",level:"warning"})})},v=async()=>{let w=await n.anchorRules(dn),x={};for(let y of xc)x[y]=await n.table(dn,y);return{rules:w,tables:x}},S=async(w,x)=>{u=void 0,g$(a,w.text),await n.load(dn,a),u={readback:await v(),rendered:w},d=h(),t(`loaded the pf anchor ${dn}: ${x}`)},_=async(w,x)=>{if(!u)await S(w,d===null?"first load since the daemon started":"the last load was not confirmed");else{let R=ip(u.readback,await v());if(R.length>0)l={at:h(),differences:R},t(`the loaded pf anchor ${dn} changed outside the daemon: ${R.join("; ")}`),await S(w,"restored after a change outside the daemon");else if(w.text!==u.rendered.text)await S(w,ej(u.rendered,w))}let y=ip(w,u.readback);if(y.length===0)return!0;return x.push({code:"anchor-readback",detail:`pfctl reads the anchor back differently from the rendered text: ${y.join("; ")}`,fix:"Compare hydra net print with pfctl -a com.apple/hydra -sr; no linux guest is admitted until they match",level:"error"}),!1},C=async()=>{let w=[],x=Ac(Tc(e.guestRanges,s?.())),y=!1;try{if(c===void 0)await E(w,!0);if(!await n.enabled()){if(w.push({code:"pf-disabled",detail:"pf was disabled; the daemon took a new enable reference",fix:"Find what ran pfctl -d; pfctl -E references keep pf enabled for every user of it",level:"warning"}),t("pf was disabled; taking a new enable reference"),await E(w,!1),!await n.enabled())throw Error("pf stays disabled after pfctl -E")}let R=(await n.mainRules()).some((k)=>k.startsWith(sp));if(!R)w.push({code:"anchor-point",detail:`The main pf ruleset has no ${sp} anchor point, so pf never evaluates ${dn}`,fix:"Reload the stock ruleset with pfctl -f /etc/pf.conf, and find what replaced it; Hydra never edits pf.conf",level:"error"});let A=x.inputs.clashes;if(A.length>0)w.push({code:"guest-range-clash",detail:`The guest ranges hold this host's own ${A.join(", ")}, so the anchor would cut the host off from that network; the daemon does not load it`,fix:"Give each fleet a guestRange that no host interface uses, then restart the host daemon",level:"error"});else y=await _(x,w)&&R}catch(R){w.push({code:"pf-failed",detail:h$(R),fix:"Run the host daemon as root, check that pfctl answers, and run hydra net verify",level:"error"})}return f=o(),m={anchor:dn,bridges:[...x.inputs.bridges],checkedAt:h(),enforced:y,findings:w,lastDrift:l,loadedAt:d,reference:c!==void 0,state:w.some((R)=>R.level==="error")?"failing":"ok"},m};return{check:(w=0)=>{if(g)return g;if(o()-f<w)return Promise.resolve(m);return g=C().finally(()=>{g=void 0}),g},status:()=>m}}function ej(e,t){let n=[e.inputs.bridges.join()===t.inputs.bridges.join()?"":"the guest bridges changed",e.inputs.self.join()===t.inputs.self.join()?"":"the host's addresses changed",e.inputs.guestRanges.join()===t.inputs.guestRanges.join()?"":"the guest ranges changed"].filter((r)=>r.length>0);return n.length===0?"re-rendered":n.join(" and ")}function tj(e){try{let t=JSON.parse(WU(e,"utf-8"));return typeof t.token==="string"&&ZU.test(t.token)?t.token:void 0}catch{return}}function g$(e,t){let n=`${e}.${process.pid}.tmp`;f$(n,{force:!0});try{let r=KU(n,"wx",QU);try{YU(r,t),qU(r)}finally{VU(r)}JU(n,e)}finally{f$(n,{force:!0})}}function h$(e){return e instanceof Error?e.message:String(e)}import{chmodSync as nj,chownSync as rj,lstatSync as oj,rmSync as S$}from"fs";import{createConnection as sj,createServer as ij}from"net";var aj=384,cj=127,uj=-1,lj=64,dj=1;async function R$(e,t,n){await fj(e);let r=new Set,o=ij((i)=>{r.add(i),pj(i,n,()=>r.delete(i))});o.maxConnections=lj;let s=process.umask(cj);try{await new Promise((i,a)=>{o.once("error",a),o.listen(e,()=>{o.off("error",a),i()})})}finally{process.umask(s)}return rj(e,t,uj),nj(e,aj),{close:async()=>{for(let i of r)i.destroy();await new Promise((i)=>o.close(()=>i())),S$(e,{force:!0})},path:e}}function pj(e,t,n){let r={close:()=>e.end(),id:dj++,send:(a)=>{if(!e.destroyed&&e.writable)e.write(Ss(a))}},o="",s=!1,i=()=>{s=!0,o="",e.end(Ss(Ye(null,"invalid",`a request line may hold at most ${bc} bytes`)),()=>e.destroy())};e.setEncoding("utf8"),e.on("data",(a)=>{if(s)return;o+=a;for(let c=o.indexOf(`
429
+ `);c>=0;c=o.indexOf(`
430
+ `)){let u=o.slice(0,c).trim();if(o=o.slice(c+1),Buffer.byteLength(u)>bc)return i();if(u)t.line(r,u)}if(Buffer.byteLength(o)>bc)i()}),e.on("error",()=>e.destroy()),e.on("close",()=>{n(),t.closed(r)})}async function fj(e){try{if(!oj(e).isSocket())throw Error(`${e} exists and is not a socket; move it aside`)}catch(t){if(t.code==="ENOENT")return;throw t}if(await mj(e))throw Error(`another host daemon answers on ${e}; stop it first`);S$(e)}function mj(e){return new Promise((t)=>{let n=sj(e);n.once("connect",()=>{n.destroy(),t(!0)}),n.once("error",()=>t(!1))})}class Ct extends Error{hint;_tag="HostDaemonError";constructor(e,t,n){super(e,n);this.hint=t;this.name="HostDaemonError"}}var bj=1e4,wj=60000,Sj=5000,ap="linux",Rj=20,$$=1024,$j=448,Ej=493,k$=1e4,vj=1000,kj=0,xj=/^\d+$/;function E$(e,t){return yj(e.socketDir,`${t}.sock`)}async function x$(e){let{budget:t,firewall:n,log:r}=e,o=e.now??Date.now;v$(t.stateDir,$j),v$(t.socketDir,Ej);let s=_R(t.stateDir),i=TR(s),a=[...new Set(i.map((O)=>O.fleet))].filter((O)=>!t.fleets[O]);if(a.length>0)throw new Ct(`${s} holds leases of fleets the host budget does not list: ${a.join(", ")}`,"Add those fleets back to the budget, or remove their leases once their guests are gone");let c=await e.live(),u,l=()=>(u??=e.live().then((O)=>(c=O,O)).finally(()=>{u=void 0}),u),d=[];for(let[O,H]of Object.entries(t.fleets))d.push([O,await e.uidOf(H.account)]);let f=[],m=GR(),g=new Set,h=new Map,E=0,v,S=!1,_=!1,C=(O)=>r(`${new Date(o()).toISOString()} ${O}`),w=(O)=>{AR(s,O),i=O},x=()=>{if(v||f.length===0)return;v=setTimeout(()=>{v=void 0,y().catch((O)=>C(`admission failed: ${at(O)}`))},Rj)},y=async()=>{if(S){_=!0;return}S=!0;try{do{if(_=!1,f.length===0)return;try{await l()}catch(U){let Y=`the host's live state cannot be read (${at(U)})`;h=new Map(f.map((Se)=>[Se.seq,{reason:Y,scope:"shared"}])),C(`granted nothing: ${Y}`);return}let O=R(),H=O?f.filter((U)=>U.request.class!==ap):f,G=ws(H,{budget:t,leases:i,live:c,now:o()});if(h=G.held,O){for(let U of f)if(U.request.class===ap)h.set(U.seq,{reason:O,scope:"own"})}if(G.granted.length===0)continue;try{w([...i,...G.granted.map((U)=>U.lease)])}catch(U){C(`granted nothing: ${at(U)}`);return}for(let U of G.granted){let[Y]=f.splice(f.findIndex((Se)=>Se.seq===U.seq),1);Y?.connection.send({id:Y.replyId,lease:U.lease,ok:!0}),C(`granted ${Cc(U.lease.fleet,U.lease)}`)}}while(_)}finally{S=!1}},R=()=>{let O=n?.status();if(!O||O.enforced)return;let H=O.findings.find((G)=>G.level==="error")?.detail;return`the pf anchor ${O.anchor} to hold${H?` (${H})`:""}`},A=async(O)=>{let H=O.status(),G=await O.check();if(G.enforced!==H.enforced||H.checkedAt===null)C(`the pf anchor ${G.anchor} ${G.enforced?"holds":"does not hold; no linux guest is admitted"}`);let U=new Set(H.findings.map((Y)=>Y.detail));for(let Y of G.findings)if(!U.has(Y.detail))C(`pf ${Y.level}: ${Y.detail}`);x()},k=(O)=>{let H=R()?(G)=>G.class!==ap:void 0;return m.offers({fleet:O,open:H,state:{budget:t,leases:i,live:c,now:o()},waiting:f})},D=async(O,H,G,U)=>{m.report(O,U,o());try{await l()}catch(Y){H.send(Ye(G,"unavailable",`the host's live state cannot be read (${at(Y)})`));return}H.send({id:G,offers:k(O),ok:!0})},B=async(O,H)=>{let G=n?await n.check(Sj):y$("this host daemon loads no pf anchor");O.send({id:H,net:G,ok:!0})},q=(O,H,G,U)=>{let Y=i.find((ie)=>ie.fleet===O&&ie.slot===U.slot);if(Y){H.send(CR(Y,U)?{id:G,lease:Y,ok:!0}:Ye(G,"conflict",`slot ${U.slot} already holds a lease with other resources`));return}if(f.some((ie)=>ie.fleet===O&&ie.request.slot===U.slot)){H.send(Ye(G,"conflict",`slot ${U.slot} already waits for a lease`));return}let Se=yc(O,U,t,c.cores);if(Se){C(`refused ${Cc(O,U)}: ${Se}`),H.send(Ye(G,"refused",Se));return}if(f.filter((ie)=>ie.fleet===O).length>=$$){H.send(Ye(G,"busy",`fleet ${O} already has ${$$} requests waiting`));return}m.claim(O,U.pool,o()),f.push({connection:H,fleet:O,replyId:G,request:U,seq:E++,since:o()}),x()},ue=(O,H,G,U)=>{let Y=f.findIndex((ie)=>ie.fleet===O&&ie.request.slot===U);if(Y>=0){let[ie]=f.splice(Y,1);ie?.connection.send(Ye(ie.replyId,"withdrawn",`the lease request for ${U} was withdrawn`)),H.send({id:G,ok:!0,released:!1,withdrawn:!0}),x();return}let Se=i.find((ie)=>ie.fleet===O&&ie.slot===U);if(!Se){H.send({id:G,ok:!0,released:!1,withdrawn:!1});return}try{w(i.filter((ie)=>ie!==Se))}catch(ie){H.send(Ye(G,"unavailable",at(ie)));return}C(`released ${Cc(O,Se)}`),H.send({id:G,ok:!0,released:!0,withdrawn:!1}),x()},ze=(O,H,G,U)=>{let Y=i.filter((xe)=>xe.fleet===O),Se=new Date(o()).toISOString(),ie=U.filter((xe)=>!Y.some((_s)=>_s.slot===xe.slot)).map((xe)=>({...xe,fleet:O,grantedAt:Se,origin:"adopted"}));if(ie.length>0)try{w([...i,...ie])}catch(xe){H.send(Ye(G,"unavailable",at(xe)));return}for(let xe of ie){C(`adopted ${Cc(O,xe)}`);let _s=f.findIndex((qp)=>qp.fleet===O&&qp.request.slot===xe.slot),[Vp]=_s>=0?f.splice(_s,1):[];Vp?.connection.send({id:Vp.replyId,lease:xe,ok:!0})}g.add(O);let Bp=new Set(U.map((xe)=>xe.slot)),ik=Y.filter((xe)=>!Bp.has(xe.slot)).map((xe)=>xe.slot);H.send({adopted:ie.map((xe)=>xe.slot),id:G,ok:!0,unlisted:ik})},L=async(O,H,G)=>{await l().catch(()=>c),H.send({id:G,ok:!0,status:j(O)})},j=(O)=>{let H=t.fleets[O];return{budget:{cpus:Ln(t,c.cores),macosVmCap:t.macosVmCap,memoryMiB:t.memoryMiB},committed:hc(i),disk:fc(c.diskFreeGiB,t.disk),fleet:{...H,id:O,reported:g.has(O)},leases:i.filter((G)=>G.fleet===O),live:c,offers:k(O),others:hc(i.filter((G)=>G.fleet!==O)),waiting:f.filter((G)=>G.fleet===O).map((G)=>({class:G.request.class,hold:h.get(G.seq)?.reason??null,pool:G.request.pool,since:new Date(G.since).toISOString(),slot:G.request.slot}))}},oe=(O,H,G)=>{let U;try{U=VR(G)}catch(Y){if(!(Y instanceof Jt))throw Y;H.send(Ye(Y.id,"invalid",Y.message));return}switch(U.op){case"lease":return q(O,H,U.id,U.request);case"net.status":return B(H,U.id).catch((Y)=>H.send(Ye(U.id,"unavailable",at(Y))));case"offer":return D(O,H,U.id,U.pools).catch((Y)=>H.send(Ye(U.id,"unavailable",at(Y))));case"release":return ue(O,H,U.id,U.slot);case"report":return ze(O,H,U.id,U.slots);case"status":return L(O,H,U.id).catch((Y)=>H.send(Ye(U.id,"unavailable",at(Y))))}},$e=(O)=>{let H=f.filter((G)=>G.connection===O);if(H.length===0)return;for(let G of H)f.splice(f.indexOf(G),1);C(`withdrew ${H.length} waiting request${H.length===1?"":"s"}: the fleet closed its connection`),x()},Ie=[],Ee=()=>Promise.all(Ie.map((O)=>O.close()));try{for(let[O,H]of d)Ie.push(await R$(E$(t,O),H,{closed:$e,line:(G,U)=>oe(O,G,U)}))}catch(O){throw await Ee(),new Ct(`Could not open the fleet sockets: ${at(O)}`,"Run hydra host serve as root",{cause:O})}let we=(O)=>A(O).catch((H)=>C(`pf check failed: ${at(H)}`));if(n)await we(n);let z=setInterval(x,e.tickMs??bj),V=n?setInterval(()=>we(n),e.firewallTickMs??wj):void 0;return C(`serving ${d.length} fleet${d.length===1?"":"s"} with ${i.length} recorded leases`),{leases:()=>i,socketPath:(O)=>E$(t,O),stop:async()=>{clearInterval(z),clearInterval(V),clearTimeout(v),f.splice(0),await Ee()}}}async function _$(e){let t=_j(e),[n,r,o]=await Promise.all([new Response(t.stdout).text(),new Response(t.stderr).text(),t.exited]),s=n.trim();if(o===0&&t.signalCode===null&&xj.test(s))return Number(s);throw new Ct(`The account ${e} has no user id (${Tj(o,t.signalCode,r)})`,"Create the fleet's account, or correct its account in the host budget")}function T$(e){let t=new Map;return async(n)=>{let r=await e(n);if(r===kj)throw new Ct(`The account ${n} is root`,"Give each fleet its own unprivileged account");let o=t.get(r);if(o!==void 0&&o!==n)throw new Ct(`The accounts ${o} and ${n} share the user id ${r}, so each could use the other's socket`,"Give each fleet an account with its own user id");return t.set(r,n),r}}function _j(e){try{return Bun.spawn(["id","-u",e],{killSignal:"SIGKILL",stderr:"pipe",stdin:"ignore",stdout:"pipe",timeout:k$})}catch(t){throw new Ct(`Could not look up the account ${e}: ${at(t)}`,"Put the id tool on the daemon's PATH",{cause:t})}}function Tj(e,t,n){if(t!==null)return`id was stopped by ${t} after at most ${k$/vj} s`;if(e===0)return"id printed no user id";return n.trim()||`id exited with code ${e}`}function v$(e,t){try{gj(e,{mode:t,recursive:!0})}catch(r){throw new Ct(`Could not create ${e}: ${at(r)}`,"Run hydra host serve as root",{cause:r})}let n=zd(hj(e),"directory");if(n)throw new Ct(`${e} ${n}`,`Fix the owner and mode of ${e}`)}function Cc(e,t){return`${e}/${t.slot} (${t.pool}, ${t.class}, ${t.cpus} vCPU, ${Ue(t.memoryMiB)}, ${t.diskGiB} GiB disk)`}function at(e){return e instanceof Error?e.message:String(e)}import{isAbsolute as Aj}from"path";class pn extends Error{args;timedOut;_tag="PfctlError";constructor(e,t,n){super(`pfctl ${e.join(" ")} ${n}`);this.args=e;this.timedOut=t;this.name="PfctlError"}}var Cj="pfctl",Oj=15000,Pj=1000,Ij=1048576,Nj=5,Dj=/Token\s*:\s*(\d+)/,Lj=/^\d+$/,Mj=/^Status:\s*Enabled\b/m,Hj=/Table does not exist/i,Gj=/^com\.apple\/hydra(-[a-z0-9]+)?$/,Fj=/^hydra_[a-z0-9_]+$/,Uj="<token>",jj=/DIOCGETRULES: (Invalid argument|No such file or directory)|Anchor does not exist/i;function A$(e={}){let t=e.binary??Cj,n=e.timeoutMs??Oj,r=(a)=>{if(Gj.test(a))return a;throw new pn(["-a",a],!1,"was refused: Hydra only touches its own anchors under com.apple/")},o=(a)=>{if(Fj.test(a))return a;throw new pn(["-t",a],!1,"was refused: Hydra only reads its own hydra_ tables")},s=(a)=>{if(Aj(a))return a;throw new pn(["-f",a],!1,"was refused: Hydra loads anchors only from absolute paths")},i=async(a,c,u=a)=>{let l=await ft([t,...a],{maxOutputChars:Ij,timeoutMs:n}).catch((d)=>{throw new pn(u,!1,`could not start (${d instanceof Error?d.message:d})`)});if(l.timedOut)throw new pn(u,!0,`did not answer within ${n/Pj} s and was stopped`);if(l.exitCode!==0&&!c?.(l.stderr))throw new pn(u,!1,`exited with code ${l.exitCode}: ${Bj(l.stderr)}`);return l};return{anchorRules:async(a)=>{let c=await i(["-a",r(a),"-s","rules"],(u)=>jj.test(u));return c.exitCode===0?Es(c.stdout):[]},enable:async()=>{let a=await i(["-E"]),c=Dj.exec(`${a.stdout}
431
+ ${a.stderr}`)?.[1];if(!c)throw new pn(["-E"],!1,"printed no enable reference token");return c},enabled:async()=>Mj.test((await i(["-s","info"])).stdout),load:async(a,c)=>{await i(["-a",r(a),"-f",s(c)])},mainRules:async()=>Es((await i(["-s","rules"])).stdout),release:async(a)=>{if(!Lj.test(a))throw new pn(["-X"],!1,"was given a token that is not a number");await i(["-X",a],void 0,["-X",Uj])},table:async(a,c)=>{let u=await i(["-a",r(a),"-t",o(c),"-T","show"],(l)=>Hj.test(l));return u.exitCode===0?p$(u.stdout):null}}}function Bj(e){let t=Es(e);return t.length===0?"(no output)":t.slice(-Nj).join("; ")}function Yt(e){return e||RR}function Mn(e){try{return $R(e)}catch(t){if(!(t instanceof cr))throw t;throw new b(t.message,"Fix the file, then run hydra host-budget check")}}var Vj=K({budget:{description:"Read the host budget from this file",displayDefault:Yt(void 0),type:"string"}}),C$=["SIGINT","SIGTERM"],O$=P({name:"serve",description:"Run the host daemon, which grants guest leases to fleets from the host budget and live state and keeps the pf anchor loaded",args:Vj,run:async(e)=>{if(process.platform!=="darwin")throw new b("hydra host serve reads the host's live state on macOS only","Run it on a macOS host");let t=Mn(Yt(e.args.budget)),n=(o)=>process.stdout.write(`${o}
432
+ `),r=await x$({budget:t,firewall:w$({guestRanges:_c(t),log:(o)=>n(`${new Date().toISOString()} ${o}`),pfctl:A$(),stateDir:t.stateDir}),live:IR(t.disk.path),log:n,uidOf:T$(_$)}).catch((o)=>{throw qj(o)});await Kj(),await r.stop()}});function qj(e){if(e instanceof Ct)return new b(e.message,e.hint);if(e instanceof Wt)return new b(e.message,"The daemon grants nothing it cannot measure");if(e instanceof no)return new b(e.message,"Restore the file, or move it aside once every fleet's guests are gone; the daemon never starts with fewer leases than it recorded");return e}function Kj(){return new Promise((e)=>{let t=()=>{for(let n of C$)process.off(n,t);e()};for(let n of C$)process.on(n,t)})}import{join as zj}from"path";function P$(e,t){let{budget:n,committed:r,fleet:o,live:s}=t,i=Dn.flatMap((a)=>{let c=o.ceilings[a];return c===void 0?[]:[`${a} ${c}`]});return[`${p.bold("Host daemon")} ${e}`,`${p.bold("Budget")} memory ${Ue(r.memoryMiB)} of ${Ue(n.memoryMiB)} \xB7 vCPU ${r.cpus} of ${n.cpus} \xB7 macOS VMs ${r.macosVms} of ${n.macosVmCap}`,`${p.bold("Live")} ${s.pressure} memory pressure \xB7 ${Ue(s.freeMemoryMiB)} free and inactive \xB7 load ${s.load1.toFixed(2)} on ${s.cores} cores \xB7 ${s.diskFreeGiB.toFixed(0)} GiB disk free (${t.disk})`,`${p.bold("Fleet")} ${o.id} \xB7 weight ${o.weight} \xB7 highest priority ${o.maxPriority} \xB7 ceilings ${i.join(", ")}${o.reported?"":p.dim(" \xB7 has not reported its slots since the daemon started")}`,"",`${p.bold(`Leases (${t.leases.length})`)}`,...t.leases.length===0?[p.dim(" none")]:t.leases.map(Wj),"",`${p.bold(`Waiting (${t.waiting.length})`)}`,...t.waiting.length===0?[p.dim(" none")]:t.waiting.map(Jj),"",`${p.bold(`Offers (${t.offers.length})`)}`,...t.offers.length===0?[p.dim(" no scale-set pool has asked")]:t.offers.map(Yj),"",`${p.bold("Other fleets")} ${Xj(t.others)}`]}function Wj(e){let t=e.origin==="adopted"?" \xB7 adopted from a report":"";return` ${e.slot} ${e.pool} \xB7 ${e.class} \xB7 ${e.cpus} vCPU \xB7 ${Ue(e.memoryMiB)} \xB7 ${e.diskGiB} GiB disk \xB7 since ${e.grantedAt}${t}`}function Jj(e){let t=e.hold?p.dim(` \xB7 waits for ${e.hold}`):"";return` ${e.slot} ${e.pool} \xB7 ${e.class} \xB7 since ${e.since}${t}`}function Yj(e){let t=e.active?"shares the headroom":p.dim("no recent demand, so one slot at most");return` ${e.pool} ${e.offer} more \xB7 ${t}`}function Xj(e){if(e.leases===0)return p.dim("no leases");return`${e.leases} lease${e.leases===1?"":"s"} \xB7 ${e.cpus} vCPU \xB7 ${Ue(e.memoryMiB)} \xB7 ${e.macosVms} macOS VMs`}var Qj=K({socket:{description:"Ask the host daemon on this socket",displayDefault:`${ln}/<fleet id>.sock`,type:"string"}}),I$=P({name:"status",description:"Show this fleet's leases and waiting requests, the host budget and the host's live state",args:Qj,json:!0,examples:["hydra host status","hydra host status --json"],run:async(e)=>{let t=e.args.socket||cp(e.config.get("fleet")?.id),n=await Zj(t).catch((r)=>{if(!(r instanceof Xe))throw r;throw new b(r.message,"Start the host daemon with hydra host serve, or pass --socket")});if(!e.json)T.info(P$(t,n).join(`
433
+ `));e.output.result(n)}});function cp(e){if(!e)throw new b("config.json names no fleet","Set fleet.id, or pass --socket <path>");return zj(ln,`${e}.sock`)}async function Zj(e){let t=await so(e);try{return await t.status()}finally{t.close()}}var up=P({name:"host",description:"Run the host daemon that admits guests, or ask it for leases and live state",subcommands:[O$,I$]});import{availableParallelism as tB}from"os";var vs=K({budget:{description:"Read the host budget from this file",displayDefault:Yt(void 0),type:"string"}}),eB=2,N$=P({name:"print",description:"Print the host budget with every default filled in",args:vs,json:!0,examples:["hydra host-budget print","hydra host-budget print --budget /etc/hydra/host.json"],run:async(e)=>{let t=Mn(Yt(e.args.budget));e.output.result(t,(n)=>JSON.stringify(n,null,eB))}});var D$=P({name:"check",description:"Check the host budget, and that this home's pools fit its fleet's share",args:vs,json:!0,examples:["hydra host-budget check","hydra host-budget check --budget /etc/hydra/host.json --json"],run:async(e)=>{let t=Yt(e.args.budget),n=Mn(t),r=tB(),o=e.config.get("fleet")?.id,s=o===void 0?{}:e.config.get("pools")??{},i=o===void 0?[]:KR(n,o,s,r),a=i.filter((u)=>u.level==="error").length,c={budget:n,cores:r,cpuLimit:Ln(n,r),findings:i,...o===void 0?{}:{fleet:o},ok:a===0,path:t,pools:Object.keys(s)};if(!e.json)T.info(nB(c));if(e.output.result(c),c.ok)return;throw new b(`${a} pool${a===1?"":"s"} cannot run within the host budget`)}});function nB(e){return[`${p.green("\u2713")} ${e.path}`,...rB(e),"",e.fleet===void 0?p.dim("config.json names no fleet, so no pools were checked"):`${p.bold("Pools")} of fleet ${e.fleet}: ${e.pools.length}`,...e.findings.map((t)=>t.level==="error"?`${p.red("\u2717")} ${t.detail}`:`${p.yellow("!")} ${t.detail}`)].join(`
434
+ `)}function rB({budget:e,cores:t,cpuLimit:n}){let{disk:r}=e;return[`${p.bold("Budget")} ${Ue(e.memoryMiB)} of memory \xB7 ${n} vCPU on this host's ${t} cores \xB7 ${e.macosVmCap} macOS VMs`,`${p.bold("Live")} ${Ue(e.freeMemoryReserveMiB)} free memory kept \xB7 load below ${e.loadFactor} per core \xB7 disk on ${r.path}: warn ${r.warnGiB}, low ${r.lowGiB}, critical ${r.criticalGiB} GiB`,...Object.entries(e.fleets).map(([o,s])=>{let i=Dn.flatMap((c)=>s.ceilings[c]===void 0?[]:[`${c} ${s.ceilings[c]}`]),a=s.guestRange?` \xB7 guests in ${s.guestRange}`:"";return`${p.bold(o)} account ${s.account} \xB7 weight ${s.weight} \xB7 highest priority ${s.maxPriority} \xB7 ${i.join(", ")}${a}`})]}var lp=P({name:"host-budget",description:"Print or check the host budget the host daemon admits guests against",subcommands:[N$,D$]});import{existsSync as oB,lstatSync as sB,readdirSync as iB,readFileSync as aB}from"fs";import{join as L$}from"path";var cB="images",uB=".json",lB=18,dB=/^[A-Za-z0-9][^\s@]*@sha256:[0-9a-f]{64}$/,pB=N({arch:J(ns),builder:J(hs),builtAt:I(),digest:I(),kind:J(["linux"]),reference:I(),runner:I(),tag:I(),variant:J(["docker","plain"])});function M$(e,t,n){return dp(e).map((r)=>r.record).filter((r)=>r.arch===t&&r.variant===n).sort((r,o)=>Date.parse(o.builtAt)-Date.parse(r.builtAt))[0]}function dp(e){let t=L$(e,cB);if(!oB(t)||!H$(t,"directory"))return[];return iB(t).filter((n)=>n.endsWith(uB)).sort().flatMap((n)=>fB(L$(t,n)))}function fB(e){if(!H$(e,"file"))return[];try{let t=pB(JSON.parse(aB(e,"utf8")));return dB.test(t.reference)&&t.reference.endsWith(`@${t.digest}`)&&!Number.isNaN(Date.parse(t.builtAt))?[{path:e,record:t}]:[]}catch{return[]}}function H$(e,t){let n=sB(e);return(t==="directory"?n.isDirectory():n.isFile())&&n.uid===process.getuid?.()&&(n.mode&lB)===0}import{mkdtempSync as NB,readFileSync as DB,rmSync as LB}from"fs";import{tmpdir as MB}from"os";import{join as X$}from"path";var G$=`#!/bin/sh
435
+ set -eu
436
+ . "\${0%/*}/layout"
437
+
438
+ fail() {
439
+ printf 'hydra-guest accept: %s\\n' "$1" >&2
440
+ exit 1
441
+ }
442
+
443
+ [ "$(id -u)" -eq 0 ] || exec sudo -n "$0"
444
+ umask 077
445
+ "\${0%/*}/ready" >/dev/null 2>&1 || fail "the guest is not waiting for a runner configuration"
446
+
447
+ line=
448
+ IFS= read -r line || [ -n "$line" ] || fail "standard input holds no runner configuration"
449
+ [ -n "$line" ] || fail "the runner configuration is empty"
450
+ case $line in
451
+ *[!A-Za-z0-9+/=]*) fail "the runner configuration is not one line of base64" ;;
452
+ esac
453
+ extra=
454
+ if IFS= read -r extra || [ -n "$extra" ]; then
455
+ fail "standard input holds more than one line"
456
+ fi
457
+
458
+ staged="$HYDRA_RUN_DIR/jit.$$"
459
+ rm -f "$staged"
460
+ (
461
+ set -C
462
+ printf '%s\\n' "$line" >"$staged"
463
+ ) || fail "could not stage the runner configuration"
464
+ line=
465
+ chmod 0600 "$staged"
466
+ chown "$HYDRA_RUNNER_UID:$HYDRA_RUNNER_GID" "$staged"
467
+ if ! ln "$staged" "$HYDRA_RUN_DIR/jit" 2>/dev/null; then
468
+ rm -f "$staged"
469
+ fail "the guest already holds a runner configuration"
470
+ fi
471
+ rm -f "$staged"
472
+
473
+ if [ "$HYDRA_OS" = macos ]; then
474
+ launchctl kickstart "gui/$HYDRA_RUNNER_UID/$HYDRA_SERVICE" >/dev/null || fail "the runner did not start"
475
+ else
476
+ systemctl start --no-block "$HYDRA_SERVICE" || fail "the runner did not start"
477
+ fi
478
+ `;var F$=`#!/bin/sh
479
+ set -eu
480
+ . "\${0%/*}/layout"
481
+
482
+ fail() {
483
+ printf '::error::Hydra stopped this job: %s\\n' "$1"
484
+ exit 1
485
+ }
486
+
487
+ [ ! -e "$HYDRA_RUN_DIR/jit" ] || fail "the runner configuration is still on the guest"
488
+ (set -C && : >"$HYDRA_RUN_DIR/job-started") 2>/dev/null || fail "this guest has already started a job"
489
+ workspace=\${GITHUB_WORKSPACE:-}
490
+ if [ -n "$workspace" ] && [ -d "$workspace" ] && [ -n "$(ls -A "$workspace")" ]; then
491
+ fail "the workspace is not empty"
492
+ fi
493
+ `;var U$=`#!/bin/sh
494
+ set -eu
495
+ . "\${0%/*}/layout"
496
+
497
+ [ "$HYDRA_SECRET_BEARING" = 1 ] || exit 0
498
+ found=$(find / -xdev \\( -name '*.p8' -o -name '*.p12' -o -name '*.keychain-db' -o -name '*.mobileprovision' -o -name '*.jks' \\) \\
499
+ -not -path "$HYDRA_RUNNER_HOME/*" -not -path "$HYDRA_RUNNER_DIR/_work/_temp/*" -not -path '/System/*' \\
500
+ -not -path '/Library/Keychains/*' -not -path '/private/var/db/*' 2>/dev/null | head -n 5)
501
+ if [ -n "$found" ]; then
502
+ printf '::error::Hydra failed this job: signing material outside the RAM disks:\\n%s\\n' "$found"
503
+ exit 1
504
+ fi
505
+ `;var j$=`#!/bin/sh
506
+ set -eu
507
+ . "\${0%/*}/layout"
508
+
509
+ fail() {
510
+ printf 'hydra-guest ramdisks: %s\\n' "$1" >&2
511
+ exit 1
512
+ }
513
+
514
+ ramdisk() {
515
+ target=$1
516
+ mib=$2
517
+ mkdir -p "$target"
518
+ if [ "$HYDRA_OS" = macos ]; then
519
+ device=$(hdiutil attach -nomount "ram://$((mib * 2048))" | awk 'NR == 1 { print $1 }')
520
+ [ -n "$device" ] || fail "hdiutil made no RAM disk for $target"
521
+ newfs_hfs -v hydra "$device" >/dev/null
522
+ mount -t hfs -o nobrowse,nodev,nosuid "$device" "$target"
523
+ else
524
+ mount -t tmpfs -o "size=\${mib}m,mode=0700,nodev,nosuid" tmpfs "$target"
525
+ fi
526
+ chown "$HYDRA_RUNNER_UID:$HYDRA_RUNNER_GID" "$target"
527
+ chmod 0700 "$target"
528
+ }
529
+
530
+ umask 077
531
+ ramdisk "$HYDRA_RUN_DIR" "$HYDRA_RAM_RUN_MIB"
532
+ if [ "$HYDRA_SECRET_BEARING" = 1 ]; then
533
+ ramdisk "$HYDRA_RUNNER_HOME" "$HYDRA_RAM_HOME_MIB"
534
+ ditto "$HYDRA_HOME_SKELETON" "$HYDRA_RUNNER_HOME" 2>/dev/null || cp -Rp "$HYDRA_HOME_SKELETON/." "$HYDRA_RUNNER_HOME"
535
+ chown -R "$HYDRA_RUNNER_UID:$HYDRA_RUNNER_GID" "$HYDRA_RUNNER_HOME"
536
+ ramdisk "$HYDRA_RUNNER_DIR/_work/_temp" "$HYDRA_RAM_TEMP_MIB"
537
+ fi
538
+ : >"$HYDRA_RUN_DIR/mounted"
539
+ `;var B$=`#!/bin/sh
540
+ set -eu
541
+ . "\${0%/*}/layout"
542
+
543
+ fail() {
544
+ printf 'hydra-guest ready: %s\\n' "$1" >&2
545
+ exit 1
546
+ }
547
+
548
+ mounted() {
549
+ [ "$(df -P "$1" 2>/dev/null | awk 'NR == 2 { print $NF }')" = "$1" ]
550
+ }
551
+
552
+ mounted "$HYDRA_RUN_DIR" || fail "the runner's RAM disk is not mounted"
553
+ [ -f "$HYDRA_RUN_DIR/mounted" ] || fail "the RAM disks are not ready"
554
+ if [ "$HYDRA_SECRET_BEARING" = 1 ]; then
555
+ mounted "$HYDRA_RUNNER_HOME" || fail "the runner's home is not on a RAM disk"
556
+ mounted "$HYDRA_RUNNER_DIR/_work/_temp" || fail "the runner's temporary directory is not on a RAM disk"
557
+ fi
558
+ for marker in jit started exit; do
559
+ [ ! -e "$HYDRA_RUN_DIR/$marker" ] || fail "the guest has already taken a runner configuration"
560
+ done
561
+ if [ "$HYDRA_OS" = macos ]; then
562
+ launchctl print "gui/$HYDRA_RUNNER_UID/$HYDRA_SERVICE" >/dev/null 2>&1 || fail "the runner's desktop session is not up"
563
+ else
564
+ systemctl cat "$HYDRA_SERVICE" >/dev/null 2>&1 || fail "the runner service is not installed"
565
+ fi
566
+ `;var V$=`#!/bin/sh
567
+ set -eu
568
+ . "\${0%/*}/layout"
569
+
570
+ fail() {
571
+ printf 'hydra-guest runner: %s\\n' "$1" >&2
572
+ printf '%s\\n' 1 >"$HYDRA_RUN_DIR/exit"
573
+ exit 1
574
+ }
575
+
576
+ umask 077
577
+ (set -C && : >"$HYDRA_RUN_DIR/started") 2>/dev/null || fail "this guest has already started a runner"
578
+ jit=
579
+ IFS= read -r jit <"$HYDRA_RUN_DIR/jit" || :
580
+ rm -f "$HYDRA_RUN_DIR/jit"
581
+ [ -n "$jit" ] || fail "the runner configuration is empty"
582
+
583
+ status=0
584
+ ACTIONS_RUNNER_INPUT_JITCONFIG=$jit HOME=$HYDRA_RUNNER_HOME "$HYDRA_RUNNER_DIR/bin/Runner.Listener" run || status=$?
585
+ printf '%s\\n' "$status" >"$HYDRA_RUN_DIR/exit.new"
586
+ mv -f "$HYDRA_RUN_DIR/exit.new" "$HYDRA_RUN_DIR/exit"
587
+ exit "$status"
588
+ `;var SB="/opt/actions-runner",fp="org.r5nlabs.hydra.runner",q$="org.r5nlabs.hydra.ramdisks",W$="hydra-runner.service",pp="hydra-ramdisks.service",RB=16,$B=2048,EB=4096,mp="hydra-golden-provisioned",uo=365,vB=292,kB=/^[A-Za-z0-9_./:-]*$/,xB={gid:20,home:"/Users/admin",uid:501,user:"admin"},_B={gid:1001,home:"/home/runner",uid:1001,user:"runner"};function J$(e,t){let n=e==="macos"?xB:_B;return{guestOs:e,homeSkeleton:`${Ge}/home.skel`,ramHomeMiB:$B,ramRunMiB:RB,ramTempMiB:EB,runDir:rd,runner:e==="macos"?$b:Ve.runner.arm64,runnerDir:SB,runnerGid:n.gid,runnerHome:n.home,runnerUid:n.uid,runnerUser:n.user,secretBearing:t,service:e==="macos"?fp:W$}}function TB(e){return[{content:G$,mode:uo,name:"accept"},{content:B$,mode:uo,name:"ready"},{content:V$,mode:uo,name:"runner"},{content:j$,mode:uo,name:"ramdisks"},{content:F$,mode:uo,name:"canary"},{content:U$,mode:uo,name:"completed"},{content:IB(e),mode:vB,name:"layout"}]}function Y$(e){let{layout:t}=e,n=t.guestOs==="macos",r=n?"root:wheel":"root:root",o=TB(t).flatMap((c)=>[`printf '%s' '${Buffer.from(c.content).toString("base64")}' | base64 -d >${Ge}/${c.name}`,`chown ${r} ${Ge}/${c.name}`,`chmod ${c.mode.toString(8)} ${Ge}/${c.name}`]),s=e.dns.map((c)=>Oc("dns",c)),i=t.runnerDir;return`${["#!/bin/sh","set -eu","umask 022",'check() { if command -v sha256sum >/dev/null 2>&1; then printf "%s %s\\n" "$1" "$2" | sha256sum -c - >/dev/null; else printf "%s %s\\n" "$1" "$2" | shasum -a 256 -c - >/dev/null; fi; }',...n?[]:AB(t),`mkdir -p ${Ge}`,`chown ${r} ${Ge}`,`chmod 0755 ${Ge}`,...o,`curl -fsSL -o /tmp/hydra-runner.tar.gz '${Oc("runner",t.runner.url)}'`,`check ${Oc("sha256",t.runner.sha256)} /tmp/hydra-runner.tar.gz`,`mkdir -p ${i}`,`tar -xzf /tmp/hydra-runner.tar.gz -C ${i}`,"rm -f /tmp/hydra-runner.tar.gz",...n?[]:[`${i}/bin/installdependencies.sh`],`mkdir -p ${i}/_work/_temp`,`printf '%s\\n' 'ACTIONS_RUNNER_HOOK_JOB_STARTED=${Ge}/canary' 'ACTIONS_RUNNER_HOOK_JOB_COMPLETED=${Ge}/completed' >${i}/.env`,`chown -R ${t.runnerUid}:${t.runnerGid} ${i}`,...n?CB(s):OB(t,s),...t.secretBearing?PB(t):[],"sync",`echo ${mp}`].join(`
589
+ `)}
590
+ `}function AB(e){return[`getent group ${e.runnerGid} >/dev/null || groupadd --gid ${e.runnerGid} ${e.runnerUser}`,`id -u ${e.runnerUser} >/dev/null 2>&1 || useradd --uid ${e.runnerUid} --gid ${e.runnerGid} --create-home --shell /bin/bash ${e.runnerUser}`]}function CB(e){let t=`/Library/LaunchAgents/${fp}.plist`,n=`/Library/LaunchDaemons/${q$}.plist`;return[`cat >${t} <<'PLIST'`,K$(fp,`${Ge}/runner`,"<key>LimitLoadToSessionType</key><string>Aqua</string>"),"PLIST",`cat >${n} <<'PLIST'`,K$(q$,`${Ge}/ramdisks`,"<key>RunAtLoad</key><true/>"),"PLIST",`chown root:wheel ${t} ${n}`,`chmod 0644 ${t} ${n}`,"networksetup -listallnetworkservices | tail -n +2 | while IFS= read -r service; do",` networksetup -setdnsservers "$service" ${e.join(" ")} || :`,' networksetup -setv6off "$service" || :',"done","systemsetup -f -setremotelogin off >/dev/null 2>&1 || :","mdutil -a -i off >/dev/null 2>&1 || :"]}function OB(e,t){return[`cat >/etc/systemd/system/${W$} <<'UNIT'`,"[Unit]",`After=${pp}`,"[Service]","Type=simple",`User=${e.runnerUser}`,`ExecStart=${Ge}/runner`,"NoNewPrivileges=yes","UNIT",`cat >/etc/systemd/system/${pp} <<'UNIT'`,"[Unit]","DefaultDependencies=no","After=local-fs.target","[Service]","Type=oneshot","RemainAfterExit=yes",`ExecStart=${Ge}/ramdisks`,"[Install]","WantedBy=multi-user.target","UNIT",`systemctl enable ${pp}`,"mkdir -p /etc/systemd/resolved.conf.d",`printf '[Resolve]\\nDNS=${t.join(" ")}\\nDomains=~.\\n' >/etc/systemd/resolved.conf.d/hydra.conf`,"printf 'net.ipv6.conf.all.disable_ipv6=1\\nnet.ipv6.conf.default.disable_ipv6=1\\n' >/etc/sysctl.d/90-hydra.conf"]}function PB(e){return[`rm -rf ${e.homeSkeleton}`,`cp -Rp ${e.runnerHome} ${e.homeSkeleton}`,`chmod 0700 ${e.homeSkeleton}`]}function K$(e,t,n){return['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0"><dict>',`<key>Label</key><string>${e}</string>`,`<key>ProgramArguments</key><array><string>${t}</string></array>`,n,"</dict></plist>"].join(`
591
+ `)}function IB(e){return`${[...[["PATH","/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],["HYDRA_OS",e.guestOs],["HYDRA_RUN_DIR",e.runDir],["HYDRA_RUNNER_DIR",e.runnerDir],["HYDRA_RUNNER_HOME",e.runnerHome],["HYDRA_RUNNER_USER",e.runnerUser],["HYDRA_RUNNER_UID",e.runnerUid],["HYDRA_RUNNER_GID",e.runnerGid],["HYDRA_SERVICE",e.service],["HYDRA_SECRET_BEARING",e.secretBearing?1:0],["HYDRA_HOME_SKELETON",e.homeSkeleton],["HYDRA_RAM_RUN_MIB",e.ramRunMiB],["HYDRA_RAM_HOME_MIB",e.ramHomeMiB],["HYDRA_RAM_TEMP_MIB",e.ramTempMiB]].map(([r,o])=>`${r}='${Oc(r,String(o))}'`),"export PATH"].join(`
592
+ `)}
593
+ `}function Oc(e,t){if(!kB.test(t))throw Error(`Refused guest value for ${e}: ${JSON.stringify(t)}`);return t}var HB={..._a,bootMs:600000,provisionMs:3600000,pullMs:7200000},GB=/^[a-z0-9][a-z0-9.-]*(?::\d+)?\/[a-z0-9._/-]+(?::[A-Za-z0-9._-]+)?@sha256:[0-9a-f]{64}$/,FB=2000;function gp(e){return GB.test(e)}function hp(e){return["exec","-i",e,"sudo","-n","/bin/sh","-s"]}function yp(e){return Y$({dns:e.dns,layout:J$(e.guestOs,e.secretBearing)})}async function z$(e){if(!gp(e.base))throw new Je("clone",e.base,"the base image must be a registry reference pinned by its sha256 digest");let t={...HB,...e.limits},n=Aa(e.binary??ka,t,Ta(e.store)),r=aw(e.guestOs,An(e.secretBearing)),o=NB(X$(MB(),"hydra-golden-")),s=X$(o,"run.log"),i,a=(u,l)=>new Je(u,r,l),c=async(u,l,d,f)=>{let m=await n.run(u,r,l,{check:!1,echo:f!==void 0,input:f,timeoutMs:d});if(m.exitCode!==0)throw a(u,`tart exited with code ${m.exitCode}
594
+ ${m.stderr.trim()}`);return m};try{if(await c("clone",Ra(e.base,r),t.pullMs),i=n.launch(r,$a({blocks:e.blocks??Ia(),name:r,rosetta:!1}),s),await UB(n,r,i,t,s),e.guestOs==="macos")await jB(n,r,e.hostVersion);if(!(await c("provision",hp(r),t.provisionMs,yp(e))).stdout.includes(mp))throw a("provision","the script did not finish");if(await n.run("stop",r,is(r),{check:!1,timeoutMs:t.stopMs}),!await La(i,r,t.exitMs))throw a("stop","the VM did not stop after provisioning");i=void 0;let l={base:e.base,builtAt:(e.now?.()??new Date).toISOString(),guestOs:e.guestOs,name:r,runner:Ve.runner.version,sha256:await sd(e.store,r),status:"candidate",variant:An(e.secretBearing)};return Oa(e.home,l),l}catch(u){if(i!==void 0&&await Bt(i,r))await n.run("stop",r,is(r),{check:!1,timeoutMs:t.stopMs}).catch(()=>{return}),await Ma(i,r,t.exitMs).catch(()=>{return});if(await n.run("delete",r,as(r),{check:!1}).catch(()=>{return}),u instanceof Je)throw u;throw a("build",u instanceof Error?u.message:String(u))}finally{LB(o,{force:!0,recursive:!0})}}async function UB(e,t,n,r,o){let s=Date.now()+r.bootMs;for(;;){if((await e.run("reach the guest agent of",t,["exec",t,"true"],{check:!1})).exitCode===0)return;if(!await Bt(n,t))throw new Je("boot",t,`the VM stopped before its guest agent answered
595
+ ${BB(o)}`);if(Date.now()>=s)throw new Je("boot",t,"the guest agent did not answer in time");await Bun.sleep(r.pollMs)}}async function jB(e,t,n){let o=(await e.run("read the macOS version of",t,["exec",t,"sw_vers","-productVersion"])).stdout.trim(),[s,i]=[Uo(o),Uo(n)];if(s===void 0||i===void 0||s>i)throw new Je("check",t,`the guest runs macOS ${o||"(unknown)"}, which must not be newer than the host's ${n??"(unknown)"}`)}function BB(e){try{let t=DB(e,"utf8").trim();return t.slice(Math.max(0,t.length-FB))}catch{return""}}var VB=K({arch:{description:"Build for this architecture",displayDefault:"this host's",type:"string"},base:{description:"Clone a Tart golden from this registry image, pinned by its sha256 digest",type:"string"},builder:{description:"Build with this tool",displayDefault:"container on macOS, podman on Linux",type:"string"},docker:{default:!1,description:"Add Docker Engine and buildx for jobs that need Docker",type:"boolean"},dryRun:{alias:"n",default:!1,description:"Print the Containerfile and the build command, build nothing",type:"boolean"},secretBearing:{default:!1,description:"Build a Tart golden for secret-bearing pools, with RAM disks for the runner's home and temporary files",type:"boolean"}}),qB=ae({kind:{description:"Image to build: linux, macos or tart-linux"}}),Q$=["linux","macos","tart-linux"],KB={arm64:"arm64",x64:"amd64"},Z$=P({name:"build",description:"Build the pinned Linux runner image, or a Tart golden VM, and record it",args:VB,positionals:qB,run:async(e)=>{let t=e.positionals.kind;if(t===void 0||!Q$.includes(t))throw new b(`Unknown image "${t??""}"`,`Choose one of: ${Q$.join(", ")}`);if(t!=="linux"){await WB(e,t==="macos"?"macos":"linux");return}let n={arch:JB(e.args.arch),docker:e.args.docker},r=YB(e.args.builder);if(e.args.dryRun){process.stdout.write(cc(n)),T.info([qd(r,n,"<context>").join(" "),p.dim("The context holds this Containerfile and the guest files; nothing was built.")].join(`
596
+ `));return}T.info(`Building ${uc(n)} with runner ${Ve.runner.version}`);let o=await cR({...n,builder:r,home:ee(e.config)}).catch((s)=>{if(s instanceof Je)throw new b(s.message,"Fix the build error above and run it again");throw s});T.success([`${p.bold(o.reference)}`,p.dim(`Recorded in ${Kd(ee(e.config),o.digest)}`)].join(`
597
+ `))}});async function WB(e,t){let n=e.args.base;if(!n||!gp(n))throw new b("A Tart golden needs --base <registry image@sha256:digest>","Pin the base image by its digest, for example ghcr.io/acme/macos-base:26@sha256:<64 hex digits>");let r={dns:e.config.get("fleet")?.dns??Jl,guestOs:t,secretBearing:e.args.secretBearing};if(e.args.dryRun){process.stdout.write(yp(r)),T.info([`tart clone ${n} <golden>`,`tart ${hp("<golden>").join(" ")} < the script above`,p.dim("Nothing was cloned or recorded.")].join(`
598
+ `));return}let o=ee(e.config),s=await En();T.info(`Building a ${e.args.secretBearing?"secret-bearing ":""}${t} golden from ${n}`);let i=await z$({...r,base:n,home:o,hostVersion:s.version,store:sr()}).catch((a)=>{if(a instanceof Je)throw new b(a.message,"Fix the build error above and run it again");throw a});T.success([`${p.bold(i.name)} is a candidate`,`disk sha256 ${i.sha256.disk}`,p.dim(i.variant==="secret"?`Promote it after review with hydra image promote ${i.name} --approve ${i.sha256.disk}`:`Promote it with hydra image promote ${i.name}`)].join(`
599
+ `))}function JB(e){let t=e??KB[process.arch];if(t!==void 0&&Eb(t))return t;throw new b(`Unknown architecture "${e??process.arch}"`,`Choose one of: ${ns.join(", ")}`)}function YB(e){let t=e??(process.platform==="linux"?"podman":"container");if(XB(t))return t;throw new b(`Unknown image builder "${t}"`,`Choose one of: ${hs.join(", ")}`)}function XB(e){return hs.includes(e)}var eE=P({name:"list",description:"List the Tart goldens this home recorded, with their state and disk hash",json:!0,examples:["hydra image list","hydra image list --json"],run:async(e)=>{let t={goldens:us(ee(e.config))};if(!e.json)T.info(zB(t));e.output.result(t)}});function zB({goldens:e}){if(e.length===0)return"No Tart goldens are recorded; build one with hydra image build macos --base <image@sha256:digest>";return e.map((t)=>[`${p.bold(t.name)} ${t.status}`,p.dim(` ${t.guestOs} \xB7 ${t.variant==="secret"?"secret-bearing":"general"} \xB7 built ${t.builtAt}`),p.dim(` base ${t.base}`),p.dim(` disk sha256 ${t.sha256.disk}`)].join(`
600
+ `)).join(`
601
+
602
+ `)}var QB=K({approve:{description:"The SHA-256 of the golden's disk, which a golden for secret-bearing pools needs",type:"string"}}),ZB=ae({golden:{description:"The candidate golden to promote"}}),tE=P({name:"promote",description:"Promote a candidate Tart golden, so new guests of its pools start from it",args:QB,positionals:ZB,run:async(e)=>{let t=e.positionals.golden;if(!t)throw new b("Name the golden to promote","hydra image list shows the candidates");T.info(`Checking the disk and configuration of ${t} against its recorded hashes`);let n=await dw({approve:e.args.approve,home:ee(e.config),name:t,store:sr()}).catch((r)=>{if(!(r instanceof rr))throw r;let o=r.reason==="approval"?"Review the candidate, then pass --approve with the disk SHA-256 that hydra image list shows":"hydra image list shows the recorded goldens";throw new b(r.message,o)});T.success(`${p.bold(n.name)} is the promoted ${n.variant==="secret"?"secret-bearing ":""}${n.guestOs} golden`)}});var bp=P({name:"image",description:"Build, list and promote the images and goldens that slot drivers start guests from",subcommands:[Z$,eE,tE]});var bt=K({dryRun:{alias:"n",default:!1,description:"List what would change, change nothing",type:"boolean"},yes:{alias:"y",default:!1,description:"Go ahead without a confirmation prompt",type:"boolean"}}),e2="Pass --yes to go ahead, or --dry-run to only list what it would do";function wt(e){if(e.dryRun&&e.yes)throw new W("Pass either --dry-run or --yes, not both")}function pr(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Xt({args:e,json:t},n,r="This step requires confirmation"){if(e.yes)return!0;if(t||!pr())throw new W(r,e2);return Rt({initialValue:!1,message:n})}var t2="https://github.com/r5n-labs/clis/blob/develop/packages/hydra/docs/migrating.md",n2="Profiles are deprecated: pools run each job in a fresh guest that Hydra destroys afterwards",nE=`Move this fleet to pools: ${t2}`,r2=new Map([["cleanup","legacy cleanup"],["create","legacy create"],["init","legacy init"],["logs","legacy logs"],["profile","legacy profile"],["reconcile","legacy reconcile"],["remove","legacy remove"],["start","legacy start"],["status","legacy status"],["stop","legacy halt"],["update","legacy update"]]);function ge(){T.warn(p.yellow(n2)),T.info(p.dim(nE))}function rE(e){let t=e===void 0?void 0:r2.get(e);if(t===void 0)return;return new b(`hydra ${e} is now hydra ${t}: profiles are deprecated in favour of pools`,`Run hydra ${t} --help for its options. ${nE}`)}var oE=0,o2={logs:"file(s)",shared:"version(s)",work:"item(s)"},s2="Delete _work contents (checkouts and caches) of stopped runners?",sE=P({name:"cleanup",description:"Remove logs, workspaces, and old runner versions",args:K({days:{alias:"d",default:oE,description:"Override log retention",displayDefault:`config or ${li} days`,type:"number"},dryRun:{alias:"n",default:!1,description:"Preview cleanup without deleting",type:"boolean"},logs:{alias:"l",default:!1,description:"Remove old diagnostic logs",type:"boolean"},shared:{alias:"s",default:!1,description:"Remove unused runner versions",type:"boolean"},work:{alias:"w",default:!1,description:"Clear stopped runners' workspaces",type:"boolean"},yes:{alias:"y",default:!1,description:"Clear workspaces without a confirmation prompt",type:"boolean"}}),json:!0,examples:["hydra legacy cleanup --dry-run","hydra legacy cleanup --work --yes","hydra legacy cleanup --json"],run:async(e)=>{ge();let t=e.config.get("profiles");if(Object.keys(t).length===0)throw new b("No profiles configured","Run hydra legacy init to set up a profile");let n=sa(e.config.get("cleanup")),r=["logs","work","shared"].filter((d)=>e.args[d]),o=r.length>0?[...r]:n.targets,s=e.args.days>oE?e.args.days:n.olderThanDays,i=o.includes("work")&&!e.args.dryRun&&!e.args.yes;if(i&&(e.json||!pr()))throw new W("Clearing workspaces requires confirmation","Pass --yes to clear them, or --dry-run to preview what would be removed");let c=i&&!await Rt({initialValue:!1,message:s2})?o.filter((d)=>d!=="work"):o,u=await iE(e.config,c,s,e.args.dryRun);if(!e.args.dryRun)e.config.set("cleanup",{...e.config.get("cleanup"),lastRun:new Date().toISOString()});let l={dryRun:e.args.dryRun,freedBytes:ia(u),olderThanDays:s,report:u,targets:c};if(e.output.result(l,i2),u.shared?.error)throw new b(`Kept every runner version: ${u.shared.error}`,"Fix the access problem and run hydra legacy cleanup --shared again",void 0,{tag:"SharedCleanupSkipped"})}});async function Pc(e){try{let t=sa(e.get("cleanup"));if(!t.auto)return;if(!Nl(t,Date.now()))return;let n=await iE(e,t.targets,t.olderThanDays,!1);e.set("cleanup",{...e.get("cleanup"),lastRun:new Date().toISOString()});let r=ia(n);if(r>0)T.info(p.dim(`Auto cleanup freed ${kt(r)}`));if(n.shared?.error)T.warn(p.yellow(`Auto cleanup kept every runner version: ${n.shared.error}`))}catch(t){let n=t instanceof Error?t.message:String(t);T.warn(p.yellow(`Auto cleanup failed: ${n}`))}}async function iE(e,t,n,r){return Ll({dryRun:r,entries:e.get("runners")??[],now:Date.now(),olderThanDays:n,profileDirectories:Object.values(e.get("profiles")).map((o)=>o.directory),sharedDir:wn(ee(e)).shared,targets:t})}function i2({dryRun:e,freedBytes:t,report:n}){let r=[];for(let[o,s]of Object.entries(n)){if(!s)continue;if(s.error){r.push(`${p.bold(o)}: ${p.yellow(`skipped, ${s.error}`)}`);continue}let i=o2[o],a=kt(s.freedBytes),c=e?`would remove ${s.removed} ${i}, ${a}`:`removed ${s.removed} ${i}, freed ${a}`;if(r.push(`${p.bold(o)}: ${s.removed>0?c:p.dim("nothing to do")}`),s.skipped.length>0)r.push(p.dim(` skipped running runner(s): ${s.skipped.join(", ")}`))}if(r.length===0)return p.dim("Nothing to clean.");return r.push(p.dim(`${e?"Would free":"Freed"} ${kt(t)} total`)),r.join(`
603
+ `)}import{existsSync as dE}from"fs";import{join as pE}from"path";import{mkdirSync as a2,rmSync as cE,statSync as c2}from"fs";import{join as u2,resolve as aE}from"path";var l2=".config.lock",d2=1e4,p2=50,f2=60000;async function uE(e,t){let n=u2(ee(e),l2);await g2(n);try{let r=Oi(ee(e));if(r.failure)throw r.failure;let o=t(r.get("runners")??[]);return e.set("runners",o),o}finally{cE(n,{force:!0,recursive:!0})}}async function lE(e,t){await uE(e,(n)=>[...n.filter((r)=>!m2(r,t)),t])}async function lo(e,t,n){await uE(e,(r)=>r.filter((o)=>o.profile!==t||!n.includes(o.id)))}function zt(e,t){let n=aE(e.directory,t.id);if(aE(t.directory)===n)return;throw new b(`Runner ${t.id} is recorded in ${t.directory}, but profile "${t.profile}" keeps its runners in ${e.directory}`,`Restore the profile's directory in config.json, or move the runner directory to ${n}`,void 0,{tag:"RunnerDirectoryMoved"})}function m2(e,t){return e.profile===t.profile&&e.id===t.id}async function g2(e){let t=Date.now()+d2;while(!0){try{a2(e);return}catch(n){if(n.code!=="EEXIST")throw n}if(h2(e)>f2){cE(e,{force:!0,recursive:!0});continue}if(Date.now()>=t)throw new b(`Another Hydra command holds the config lock ${e}`,"Retry once it finishes; delete the lock only when no Hydra command is running",void 0,{tag:"ConfigLocked"});await Bun.sleep(p2)}}function h2(e){try{return Date.now()-c2(e).mtimeMs}catch{return 0}}var fE=P({name:"create",description:"Download and register runners up to the profile's count",positionals:ae({profile:{description:"Profile to use"},count:{description:"Runner count override"}}),json:!0,examples:["hydra legacy create","hydra legacy create default 3"],run:async(e)=>{ge();let{name:t,profile:n}=pt(e.config,e.positionals.profile),r=Tr(e.positionals.count??n.numberOfMachines),o=e.config.get("runners")??[],s=o.filter((h)=>h.profile===t),i=r-s.length;if(i<=0){T.warn(`Already have ${s.length} runner(s) for profile "${t}". Nothing to create.`),e.output.result({created:[],profile:t});return}let a=ve(n,e.config),c=ot();c.start("Downloading runner binary...");let{version:u}=await a.download();c.stop(`Runner v${u} ready`);let l=new Set(o.map((h)=>h.id)),d=[],f=1;while(d.length<i){let h=`${n.name}-${f++}`;if(l.has(h))continue;let E={createdAt:new Date().toISOString(),directory:pE(n.directory,h),id:h,name:h,profile:t,provider:n.provider,url:n.url},v=dE(E.directory);c.start(`Registering ${h}...`);try{await a.create([h])}catch(S){throw c.stop(`${p.red("\u2717")} ${h}`),S}finally{if(!v&&dE(pE(E.directory,ke))){let{agentId:S}=await Qn(E.directory);await lE(e.config,S===void 0?E:{...E,agentId:S})}}d.push(h),c.stop(`${p.green("+")} ${h}`)}let g=t===e.config.get("defaultProfile")?"":` ${t}`;T.info(`${p.green("Created")} ${d.length} runner(s) for "${t}". Run ${p.green(`hydra legacy start${g}`)} to start them.`),e.output.result({created:d,profile:t,version:u})}});function ct(e){let t="worker"in e&&e.worker?", running a job":"";switch(e.kind){case"stopped":return"stopped";case"running":return`running, pid ${e.pid}${t}`;case"stale":return`stale .pid: pid ${e.pid} runs no runner from its directory`;case"unproven":return`running outside Hydra's record, pid ${e.pids.join(", ")}${t}`}}function po(e){switch(e.kind){case"stale":return`delete its .pid file once you have checked that pid ${e.pid} is not this runner`;case"unproven":return"Hydra signals only a process group it can prove, so stop those processes by hand";case"running":case"stopped":return"run hydra legacy stop first"}}function y2(e){let t=e.registration&&!e.registration.disableUpdate?", updates itself":"";return`${w2(e.layout)}${t}`}function b2(e,t){if(!e.scope)return"no GitHub profile";if(!e.github)return e.registration?.agentId===void 0?"no runner id":"not on GitHub";let{busy:n,id:r,status:o}=e.github;return`${o}, ${n?"busy":"idle"} \xB7 id ${r}${t?" \xB7 drained":""}`}function mE(e,t){let n=` ${e.name} ${[ct(e.process),b2(e,t),y2(e)].join(" \xB7 ")}`;return e.refusal?`${n} \xB7 ${p.dim(`left alone: ${e.refusal}`)}`:n}function nt(e,t){return` ${p.dim("leave")} ${e.name} \xB7 ${t}`}function Ot(e,t,n=""){return` ${e} ${t.name}${n?` \xB7 ${n}`:""}`}function w2(e){switch(e.kind){case"shared":return`shared ${e.version}`;case"self-updated":return`self-updated ${e.version}`;case"copied":return"own copy of the runner";case"missing":return"no runner binaries";case"unknown":return"unrecognised externals link"}}import{lstat as j2,readdir as B2}from"fs/promises";import{basename as V2,dirname as q2,join as K2,resolve as Lc}from"path";import{existsSync as E2}from"fs";import{dirname as v2,join as k2,resolve as Ic}from"path";var S2=/[.*+?^${}()|[\]\\]/g,R2="-[1-9][0-9]*",$2=["unrecorded","online","busy","foreign","local","elsewhere"];function wE({elsewhere:e,elsewhereUnreadable:t,github:n,local:r,prefixes:o,protectedNames:s=new Set}){let i=o.map((h)=>new RegExp(`^${h.replace(S2,"\\$&")}${R2}$`)),a=r.filter((h)=>!h.orphaned),c=r.filter((h)=>h.orphaned),u=[...s].map(fo),l=new Set([...bE(a),...u]),d=new Set([...bE(r),...u]),f=new Set([...e].map(fo)),m=new Set,g=[];for(let h of n){let E=fo(h.name),v=yE(h,a,m);if(v){m.add(v),g.push({github:h,local:v,placement:"both"});continue}let S={elsewhere:f.has(E),foreign:!i.some((w)=>w.test(h.name))},_=yE(h,c,m);if(!_){let w=hE({...S,local:d.has(E),unrecorded:!0});g.push({github:h,keep:w,placement:"github"});continue}m.add(_);let C=hE({...S,busy:h.busy,local:l.has(E),online:!Fr(h)});g.push({github:h,keep:C.length===0&&t?["unreadable"]:C,local:_,placement:"recorded"})}for(let h of r)if(!m.has(h))g.push({local:h,placement:"local"});return g.sort((h,E)=>gE(h).localeCompare(gE(E),void 0,{numeric:!0}))}function fn(e){return e.placement==="recorded"&&e.keep.length===0}function SE(e){return e.placement==="recorded"&&e.keep.includes("unreadable")}function gE(e){return e.placement==="github"?e.github.name:e.local.name}function hE(e){return $2.filter((t)=>e[t])}function yE(e,t,n){let r=t.filter((o)=>!n.has(o));return r.find((o)=>o.agentId===e.id)??r.find((o)=>o.agentId===void 0&&o.names.some((s)=>fo(s)===fo(e.name)))}function bE(e){return new Set(e.flatMap((t)=>t.names.map(fo)))}function fo(e){return e.toLowerCase()}var x2=new Set([401,403,404]),_2="Nothing was changed; retry once GitHub answers",T2="Registrations reported as deleted stay deleted; run hydra legacy reconcile again to finish";function mo(e){return Mt(e)}async function Nc(e,t){let{homeNames:n,scopes:r}=await A2(e),o=P2(e),s=[];for(let i of r){let a=await ut(t,i.target,_2,()=>Ht(t.client,i.target)),c=wE({elsewhere:o.names,elsewhereUnreadable:o.unreadable.length>0,github:a,local:i.local,prefixes:i.prefixes,protectedNames:n});s.push({...i,rows:c})}return{scopes:s,unreadableHomes:o.unreadable}}async function Dc(e,t,n,r=T2){return ut(e,t,r,async()=>{let o=await Gt(e.client,t,n.id);if(!o)return"gone";if(o.name!==n.name)return"renamed";if(!Fr(o)||o.busy)return"changed";return zn(e.client,t,n.id)})}function $E(e){return E2(k2(e.directory,ke))}async function A2(e){let t=Object.entries(e.get("profiles")).filter(([,u])=>u.provider==="github"),n=new Map,r=new Map,o=new Map,s=new Map;for(let[u,l]of t){let d=wp(u,l.url),f=fr(d),m=n.get(f)??{key:f,local:[],prefixes:[],target:d};n.set(f,m),m.prefixes.push(l.name),r.set(u,m);let g=Ic(l.directory);if(o.set(g,(o.get(g)??new Set).add(m)),!s.has(g))s.set(g,l)}let i=new Map;for(let u of s.values())for(let l of await ve(u,e).list())i.set(Ic(l.directory),l);let a=new Set;for(let u of e.get("runners")??[]){let l=Object.hasOwn(e.get("profiles"),u.profile)?r.get(u.profile):void 0,d=Ic(u.directory);if(!l||a.has(d))continue;a.add(d),l.local.push(RE(u.id,u.directory,i.get(d),u))}let c=new Set;for(let[u,l]of i){if(a.has(u))continue;let d=RE(l.id,l.directory,l,void 0);for(let g of d.names)c.add(g);let f=n.get(await C2(l.directory)??""),m=f?[f]:[...o.get(Ic(v2(l.directory)))??[]];for(let g of m)g.local.push(d)}return{homeNames:c,scopes:[...n.values()]}}async function C2(e){let{gitHubUrl:t}=await Qn(e);if(!t)return;try{return fr(de(t))}catch{return}}function RE(e,t,n,r){let o=n?O2(n):void 0,s=n?.status??"unknown",i=[...new Set([o,r?.name,e].filter((a)=>Boolean(a)))];return{agentId:n?.agentId??r?.agentId,directory:t,id:e,name:o??r?.name??e,names:i,orphaned:r!==void 0&&s==="unknown",status:s}}function O2(e){return e.name===Br?void 0:e.name}function P2(e){let t=new Set,n=[];for(let r of fi(ee(e),process.cwd(),process.env)){let o=Vm(r.path);if(!o)n.push(r.path);for(let s of o??[])t.add(s)}return{names:t,unreadable:n}}function wp(e,t){try{return de(t)}catch(n){throw new b(`profiles.${e}.url: ${n.message}`,"Use a github.com repository or organisation URL")}}function fr(e){return(e.kind==="repo"?`repo:${e.owner}/${e.repo}`:`org:${e.org}`).toLowerCase()}async function ut(e,t,n,r){try{return await r()}catch(o){if(!(o instanceof Re))throw o;let s=o.status!==void 0&&x2.has(o.status);throw new b(o.message,s?Xo(e.credentials.kind,t):n)}}import{readdir as I2,readFile as N2,readlink as D2}from"fs/promises";import{join as EE}from"path";var L2="externals",M2=/(?:^|\/)externals\.(\d+\.\d+\.\d+)$/,H2=/^(?:bin|externals)\.\d+\.\d+\.\d+$/,G2=/^[\w.-]+\.sh(?:\.template)?$/,F2=/^\uFEFF/,U2=new Set([".DS_Store",".credentials",".credentials_migrated",".credentials_rsaparams",".env",".path",".pid",".runner",".runner_migrated","_diag","_update","_work","bin","externals","hydra-hooks"]);async function vE(e){try{let t=await D2(EE(e,L2)),n=Vr(t);if(n)return{kind:"shared",version:n};let r=t.match(M2)?.[1];return r?{kind:"self-updated",version:r}:{kind:"unknown"}}catch(t){return t.code==="EINVAL"?{kind:"copied"}:{kind:"missing"}}}async function kE(e){let t;try{t=JSON.parse((await N2(EE(e,".runner"),"utf-8")).replace(F2,""))}catch{return}if(typeof t!=="object"||t===null)return;let{agentId:n,agentName:r,disableUpdate:o,gitHubUrl:s}=t;return{agentId:Number.isSafeInteger(n)&&n>0?n:void 0,agentName:typeof r==="string"&&r?r:void 0,disableUpdate:o===!0,gitHubUrl:typeof s==="string"?s:void 0}}async function Sp(e){return(await I2(e)).filter((n)=>!_E(n)).sort()}function xE(e){return e.filter(_E)}function _E(e){return U2.has(e)||H2.test(e)||G2.test(e)}var W2="Nothing was changed; retry once GitHub answers",TE="config.json does not record it",AE="its directory is missing";async function J2(e,t){let n=e.get("profiles"),r=new Map;for(let[c,u]of Object.entries(n)){if(u.provider!=="github")continue;let l=wp(c,u.url);r.set(fr(l),{key:fr(l),registered:new Map,target:l})}for(let c of r.values()){let u=await ut(t,c.target,W2,()=>Ht(t.client,c.target));for(let l of u)c.registered.set(l.id,l)}let o=await Ut(),s=[],i=new Set;for(let c of e.get("runners")??[]){i.add(Lc(c.directory));let u=Object.hasOwn(n,c.profile)?n[c.profile]:void 0;s.push(await Y2(c,u,r,o))}let a=new Set(Object.values(n).filter((c)=>c.provider==="github").map((c)=>Lc(c.directory)));for(let c of a)for(let u of await Z2(c)){if(i.has(u))continue;i.add(u),s.push(await X2(u,r,o))}return{runners:s,scopes:[...r.values()]}}function Pt(e){return e.refusal===void 0&&e.entry!==void 0&&e.scope!==void 0}function CE(e){return e.refusal===AE&&e.entry!==void 0&&e.scope!==void 0&&e.process.kind==="stopped"}function OE(e){let{agentId:t,id:n,name:r}=e.entry;return[...e.scope.registered.values()].find((o)=>t===void 0?[n,r].some((s)=>typeof s==="string"&&Rp(s,o.name)):o.id===t)}async function mr(e){return Zi(e.directory,await zi(e.directory),await Ut())}async function Y2(e,t,n,r){let o=await PE(Lc(e.directory),r),s=t?.provider==="github"?n.get(fr(de(t.url))):void 0,i=o.registration?.agentId===void 0?void 0:s?.registered.get(o.registration.agentId),a={...o,entry:e,github:i,name:e.id,profile:e.profile,scope:s};return{...a,refusal:await z2(a,t)}}async function X2(e,t,n){let r=await PE(e,n),o=Q2(r.registration,t),s=r.registration?.agentId,i=s===void 0?void 0:o?.registered.get(s),a=r.registration?.agentName??V2(e);return{...r,github:i,name:a,refusal:TE,scope:o}}async function PE(e,t){let n=await zi(e);return{directory:e,layout:await vE(e),pid:n,process:Zi(e,n,t),registration:await kE(e)}}async function z2(e,t){let{directory:n,entry:r,github:o,registration:s,scope:i}=e;if(!r)return TE;if(!t)return`its profile ${r.profile} is not in config.json`;if(t.provider!=="github"||!i)return"its profile does not use GitHub";if(q2(n)!==Lc(t.directory))return"its directory is not in its profile's directory";let a=await $p(n);if(a==="missing")return AE;if(a!=="directory")return"its directory is a symbolic link or not a directory";if(!s)return"it has no readable .runner file";if(s.agentId===void 0||s.agentName===void 0)return"its .runner file records no runner id or name";if(![r.id,r.name].filter((u)=>typeof u==="string").some((u)=>Rp(u,s.agentName)))return`it is registered as ${s.agentName}, not as ${r.id}`;if(IE(s)!==i.key)return"its .runner file names another organisation or repository";if(o&&!Rp(o.name,s.agentName))return`GitHub lists runner ${o.id} as ${o.name}`;return}function Q2(e,t){let n=IE(e);return n===void 0?void 0:t.get(n)}function IE(e){if(!e?.gitHubUrl)return;try{return fr(de(e.gitHubUrl))}catch{return}}async function Z2(e){try{return(await B2(e,{withFileTypes:!0})).filter((n)=>n.isDirectory()).map((n)=>K2(e,n.name))}catch{return[]}}async function $p(e){try{return(await j2(e)).isDirectory()?"directory":"other"}catch(t){return t.code==="ENOENT"?"missing":"other"}}function Rp(e,t){return e.toLowerCase()===t.toLowerCase()}async function Qt(e){if(Object.keys(e.get("profiles")).length===0)throw new b("No profiles configured",`Select the 0.x fleet's home with ${ye} <path> or ${et}`);let t=mo(e);return{github:t,inventory:await J2(e,t)}}var eV={busy:"busy",elsewhere:"recorded in another Hydra home",foreign:"name not managed here",local:"name used by a runner in this home",unreadable:"another Hydra home cannot be read",unrecorded:"not recorded in this home"},DE="recorded, no runner here";function Ep(e){return`${p.bold(De(e.target))} ${p.dim("on GitHub")}`}function Mc(e){return`${e.status}, ${e.busy?"busy":"idle"}`}function vp(e){return e.keep.map((t)=>t==="online"?e.github.status:eV[t]).join(", ")}function LE(e){let t=[Ep(e)];if(e.rows.length===0)return[...t,p.dim(" No runners here or on GitHub.")];for(let n of e.rows)t.push(` ${tV(n)}`);return t.push(p.dim(` ${nV(e.rows)}`)),t}function tV(e){switch(e.placement){case"both":return`${e.local.name} ${e.local.status} \xB7 ${Mc(e.github)} \xB7 id ${e.github.id}`;case"local":return`${e.local.name} ${ME(e.local)} \xB7 ${p.yellow("not on GitHub")}`;case"recorded":return`${e.local.name} ${DE} \xB7 ${NE(e)}`;case"github":return`${e.github.name} not in this home \xB7 ${NE(e)}`}}function ME(e){return e.orphaned?DE:e.status}function NE(e){let t=fn(e)?p.yellow("stale"):p.dim(`left alone: ${vp(e)}`);return`${Mc(e.github)} \xB7 id ${e.github.id} \xB7 ${t}`}function nV(e){let t=(a)=>e.filter((c)=>c.placement===a).length,n=t("both"),r=t("local"),o=t("recorded"),s=t("github"),i=e.filter(fn).length;return[`${n+o+s} on GitHub, ${n+o+r} in this home:`,`${n} in both, ${o} recorded without a runner, ${r} only here, ${s} only on GitHub, ${i} stale`].join(" ")}function Hc(e){return{rows:e.rows.map(rV),scope:De(e.target)}}function rV(e){let t=e.placement==="github"?void 0:{directory:e.local.directory,id:e.local.id,status:ME(e.local)};return{...e.placement==="local"?{}:{github:e.github},..."keep"in e?{keep:e.keep}:{},...t?{local:t}:{},name:e.placement==="github"?e.github.name:e.local.name,placement:e.placement,stale:fn(e)}}var oV="Registrations reported as deleted stay deleted; run hydra legacy deregister again to finish",sV={busy:"kept: GitHub reports it busy",changed:"kept: GitHub no longer reports it offline and idle",deleted:"deregistered",gone:"already gone",renamed:"kept: GitHub lists it under another name now"},HE=P({name:"deregister",description:"Delete the GitHub registrations of stopped 0.x runners by id",args:bt,json:!0,examples:["hydra legacy deregister --dry-run","hydra legacy deregister --yes"],run:async(e)=>{wt(e.args);let{github:t,inventory:n}=await Qt(e.config),r=[],o=[];for(let i of n.runners)if(!Pt(i))o.push(nt(i,i.refusal??"config.json does not record it"));else if(!i.github)o.push(Ot(p.dim("done"),i,"not registered on GitHub"));else if(i.process.kind!=="stopped")o.push(nt(i,`${ct(i.process)}; ${po(i.process)}`));else{r.push(i);let a=p.red(e.args.dryRun?"would deregister":"deregister");o.push(Ot(a,i,`id ${i.github.id} \xB7 ${i.github.status}`))}T.info(o.join(`
604
+ `));let s={deregistered:[],dryRun:e.args.dryRun,planned:r.map((i)=>i.name)};if(r.length===0){T.info(p.dim("Nothing to deregister.")),e.output.result(s);return}if(e.args.dryRun){T.info(`Would deregister ${r.length} runner(s). Run ${p.green("hydra legacy deregister --yes")} to do it.`),e.output.result(s);return}if(!await Xt(e,`Delete ${r.length} registration(s) from GitHub?`))return;for(let i of r){let a=await mr(i);if(a.kind!=="stopped"||!i.github){T.info(`${i.name} \xB7 ${p.yellow(`kept: ${ct(a)}`)}`);continue}let c=await Dc(t,i.scope.target,i.github,oV);if(c==="deleted")s.deregistered.push(i.name);let u=sV[c];T.info(`${i.name} \xB7 id ${i.github.id} \xB7 ${c==="deleted"?p.green(u):u}`)}T.info(`${p.green("Deregistered")} ${s.deregistered.length} of ${r.length} runner(s).`),e.output.result(s)}});var GE="hydra-drain",FE="Nothing was changed; retry once GitHub answers",iV="Drained runners move only into a group no repository can use; name another one with --group";async function Gc(e,t,n){return ut(e,t,FE,async()=>{let r=await Ur(e.client,t.org,n);if(!r)return;await jE(e,t,r);let o=await Vi(e.client,t.org,r);return{group:r,members:new Map(o.map((s)=>[s.id,s]))}})}async function UE(e,t,n){let r=await Gc(e,t,n);if(r)return r;return ut(e,t,FE,async()=>{let o=await uy(e.client,t.org,n);return await jE(e,t,o),{group:o,members:new Map}})}async function jE(e,t,n){let r=py(n,await ly(e.client,t.org,n));if(r)throw new b(`The runner group ${n.name} of ${t.org} is not closed: ${r}`,iV)}function gr(e){return e.kind==="org"?e:void 0}async function go(e,t,n){let r=new Map;for(let o of t){let s=gr(o.target),i=s?await Gc(e,s,n):void 0;if(i)r.set(o.key,i)}return r}function ho(e,t){return t.github!==void 0&&t.scope!==void 0?e.get(t.scope.key)?.members.has(t.github.id)??!1:!1}var yo=K({group:{default:GE,description:"Runner group that drained runners move into; no repository may use it",type:"string"}});var aV="Runners reported as moved stay drained; run hydra legacy drain again to finish",BE=P({name:"drain",description:"Move a 0.x fleet's runners into a runner group no repository can use",args:K({...bt,...yo}),json:!0,examples:["hydra legacy drain --dry-run","hydra legacy drain --yes"],run:async(e)=>{wt(e.args);let{group:t,dryRun:n}=e.args,{github:r,inventory:o}=await Qt(e.config),s=await go(r,o.scopes,t),i=new Map,a=[];for(let l of o.runners){if(!Pt(l)){a.push(nt(l,l.refusal??"config.json does not record it"));continue}if(!l.github){a.push(nt(l,"not registered on GitHub"));continue}if(!gr(l.scope.target)){a.push(nt(l,"repository runners have no runner groups; stop it with hydra legacy halt once idle"));continue}if(s.get(l.scope.key)?.members.has(l.github.id)){a.push(Ot(p.dim("drained"),l,`already in ${t}`));continue}i.set(l.scope,[...i.get(l.scope)??[],{id:l.github.id,runner:l}]);let d=l.github.busy?"busy, its job keeps running":"idle";a.push(Ot(p.yellow(n?"would move":"move"),l,`id ${l.github.id} \xB7 ${d}`))}for(let l of i.keys())if(!s.has(l.key))a.push(p.dim(` ${n?"would create":"create"} ${t}`));T.info(a.join(`
605
+ `));let c=[...i.values()].reduce((l,d)=>l+d.length,0),u={dryRun:n,group:t,moved:[],planned:[...i.values()].flatMap((l)=>l.map(({runner:d})=>d.name))};if(c===0){T.info(p.dim("Nothing to drain.")),e.output.result(u);return}if(n){T.info(`Would move ${c} runner(s) into ${t}. Run ${p.green("hydra legacy drain --yes")} to move them.`),e.output.result(u);return}if(!await Xt(e,`Move ${c} runner(s) into ${t}?`))return;for(let[l,d]of i){let f=gr(l.target);if(!f)continue;let m=s.get(l.key)??await UE(r,f,t);for(let{id:g,runner:h}of d)await ut(r,f,aV,()=>dy(r.client,f.org,m.group,g)),u.moved.push(h.name),T.info(`${h.name} \xB7 id ${g} \xB7 ${p.green(`moved into ${m.group.name}`)}`)}T.info(`${p.green("Drained")} ${u.moved.length} runner(s). They take no new jobs; run ${p.green("hydra legacy stop --wait")} to stop them once their jobs finish.`),e.output.result(u)}});function bo(e,t){if(!(t instanceof b))throw t;return{_tag:t._tag,id:e,message:t.message,...t.hint?{hint:t.hint}:{}}}function wo({id:e,message:t}){return`${p.red("\u2717")} ${e} ${p.dim(t)}`}function So(e,t,n){let r=[...new Set(t.flatMap((o)=>o.hint?[o.hint]:[]))];return new b(`${e}: ${t.map((o)=>o.id).join(", ")}`,[...t.map((o)=>o.message),...r].join(`
606
+ `),void 0,{tag:n})}var cV={"not-running":(e)=>`${p.dim("\u25CF")} ${e} ${p.dim("not running")}`,"stale-pid":(e)=>`${p.dim("\u25CF")} ${e} ${p.dim("not running; removed a .pid file naming another process")}`,stopped:(e)=>`${p.red("\u25A0")} ${e}`},VE=P({name:"halt",description:"Stop runners at once, without waiting for a running job, and wait for their processes to exit",positionals:ae({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}}),json:!0,examples:["hydra legacy halt","hydra legacy halt default runner-1"],run:async(e)=>{ge();let{name:t,profile:n}=pt(e.config,e.positionals.profile),r=(e.config.get("runners")??[]).filter((c)=>c.profile===t);if(r.length===0)throw new b(`No runners found for profile "${t}"`,"Run hydra legacy create to provision runners");let o=Ar(e.positionals.ids??[],r.map((c)=>c.id)),s=ve(n,e.config),i={failed:[],notRunning:[],profile:t,stalePidFiles:[],stopped:[]},a=ot();for(let c of o){a.start(`Stopping ${c}...`);try{zt(n,r.find((d)=>d.id===c));let[u="not-running"]=await s.stop([c]);(u==="stopped"?i.stopped:u==="stale-pid"?i.stalePidFiles:i.notRunning).push(c),a.stop(cV[u](c))}catch(u){let l=bo(c,u);i.failed.push(l),a.stop(wo(l))}}if(T.info(`${p.green("Stopped")} ${i.stopped.length} runner(s).`),e.output.result(i),i.failed.length>0)throw So("Some runners did not stop",i.failed,"RunnersNotStopped")}});import{mkdir as kp}from"fs/promises";var qE=1,Fc="runner",uV=448,KE="https://github.com/<owner>/<repo> or https://github.com/<org>",WE=P({name:"init",description:"Set up a runner profile",args:K({force:{alias:"f",default:!1,description:"Overwrite an existing profile",type:"boolean"},labels:{alias:"l",description:"Set comma-separated runner labels",type:"string"},name:{alias:"n",description:"Set the runner name prefix",displayDefault:Fc,type:"string"},profile:{alias:"p",description:"Set the profile name",displayDefault:_r,type:"string"},runners:{alias:"c",description:"Set the runner count",displayDefault:"1",type:"number"}}),positionals:ae({url:{description:"GitHub repository or organisation URL"}}),prompts:!0,json:!0,examples:["hydra legacy init https://github.com/owner/repo -c 2","hydra legacy init https://github.com/org --profile org"],run:async(e)=>{ge();let t=e.interactive?await Fn({initialValue:e.args.profile??_r,message:"Profile name",validate:JE}):dV(e.args.profile??_r),n=!e.config.exists(),r=n?void 0:lV(e.config.get("profiles"),t);if(r&&!e.args.force){if(!e.interactive)throw new b(`Profile "${t}" already exists. Use --force to overwrite.`);if(!await Rt({initialValue:!1,message:`Profile "${t}" already exists. Overwrite?`}))return}let o=wn(ee(e.config)),s=r?.directory??o.runners,i=e.interactive?await fV(s):mV(e.positionals.url,e.args,s);await pV(o);let a={...n?{}:e.config.get("profiles"),[t]:i};if(e.config.set("profiles",a),!e.config.get("defaultProfile"))e.config.set("defaultProfile",t);Do([`${p.dim("Profile:")} ${t}`,`${p.dim("URL:")} ${i.url}`,`${p.dim("Runners:")} ${i.numberOfMachines}`,`${p.dim("Name:")} ${i.name}`,i.labels?`${p.dim("Labels:")} ${i.labels}`:"","",`Run ${p.green(`${ui} legacy create${t!==e.config.get("defaultProfile")?` ${t}`:""}`)} to provision runners.`].filter(Boolean).join(`
607
+ `),p.green(n?"Hydra initialized":`Profile "${t}" added`)),e.output.result({created:n,profile:t,settings:i})}});function lV(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function JE(e){return e?.trim()?void 0:"Profile name is required"}function dV(e){let t=JE(e);if(t)throw new W(t,"Pass --profile <name>");return e}async function pV(e){await kp(e.home,{mode:uV,recursive:!0}),await kp(e.shared,{recursive:!0}),await kp(e.runners,{recursive:!0})}async function fV(e){let t=await Ys({url:()=>Fn({message:"GitHub repository or organisation URL",placeholder:"https://github.com/owner/repo",validate:(n)=>{if(!n)return"URL is required";try{de(n)}catch{return`Must be a GitHub repository or organisation URL (${KE})`}return}}),name:()=>Fn({initialValue:Fc,message:"Base name for runners",placeholder:Fc,validate:qu}),runners:()=>Fn({initialValue:String(qE),message:"Number of runners",placeholder:"1",validate:Jm}),labels:()=>Fn({message:"Additional labels (comma-separated, optional)",placeholder:"self-hosted,macOS,ARM64"})},{onCancel:()=>{throw new rt}});return YE(e,{labels:t.labels||void 0,name:t.name,numberOfMachines:Tr(t.runners),url:t.url})}function mV(e,t,n){if(!e)throw new W("URL is required","Usage: hydra legacy init <url>");return gV(e),YE(n,{labels:t.labels,name:Wm(t.name??Fc),numberOfMachines:Tr(t.runners??qE),url:e})}function YE(e,t){return{directory:e,jobHooks:wl(),labels:t.labels,name:t.name,numberOfMachines:t.numberOfMachines,os:hV(),overwrite:!1,provider:"github",run:!1,url:t.url}}function gV(e){try{de(e)}catch(t){throw new W(t instanceof Error?t.message:`Invalid GitHub URL: ${e}`,`Expected ${KE}`)}}function hV(){if(process.platform==="darwin")return"osx";if(process.platform==="win32")return"windows";return"linux"}var XE=P({name:"inventory",description:"List a 0.x fleet's runners, here and on GitHub",args:yo,json:!0,examples:["hydra legacy inventory","hydra legacy inventory --json"],run:async(e)=>{let{github:t,inventory:n}=await Qt(e.config),r=await go(t,n.scopes,e.args.group),o=e.config.get("profiles"),s=new Map;for(let u of n.runners){let l=u.entry?u.entry.profile:"";s.set(l,[...s.get(l)??[],u])}let i=[];for(let[u,l]of s){if(i.length>0)i.push("");let d=Object.hasOwn(o,u)?o[u]?.url:void 0;i.push(u?`${p.bold(u)} ${p.dim(d??"no such profile")}`:p.bold("Not recorded"));let f=l.sort((m,g)=>m.name.localeCompare(g.name,void 0,{numeric:!0}));for(let m of f)i.push(mE(m,ho(r,m)))}if(i.length===0)i.push(p.dim("No runners in this home."));let a=n.runners,c=(u)=>a.filter(u).length;i.push("",p.dim([`${a.length} runner(s)`,`${c(Pt)} provably this home's`,`${c((u)=>u.process.kind==="running"||u.process.kind==="unproven")} running`,`${c((u)=>u.github?.busy===!0)} busy`,`${c((u)=>ho(r,u))} drained into ${e.args.group}`,`${c((u)=>u.layout.kind==="self-updated")} self-updated`,`${c((u)=>u.refusal!==void 0)} left alone`].join(", "))),T.info(i.join(`
608
+ `)),e.output.result({runners:a.map((u)=>({directory:u.directory,drained:ho(r,u),github:u.github,layout:u.layout.kind,name:u.name,own:Pt(u),process:u.process,profile:u.entry?.profile,refusal:u.refusal}))})}});import{existsSync as yV}from"fs";import{readFile as bV}from"fs/promises";var wV=100,SV={runner:"runner daemon log",worker:"job log"},zE=P({name:"logs",description:"Show recent runner logs",args:K({lines:{alias:"n",default:wV,description:"Number of lines to show",type:"number"},list:{alias:"l",default:!1,description:"List log files instead of showing one",type:"boolean"},open:{alias:"o",default:!1,description:"Open the log file",type:"boolean"},runner:{alias:"r",default:!1,description:"Show the runner log instead of a job log",type:"boolean"}}),positionals:ae({id:{description:"Runner ID"}}),json:!0,examples:["hydra legacy logs runner-1","hydra legacy logs runner-1 --list","hydra legacy logs runner-1 --runner -n 50"],run:async(e)=>{if(ge(),e.json&&e.args.open)throw new W("--open cannot be combined with --json");let t=e.config.get("runners")??[];if(t.length===0)throw new b("No runners found","Run hydra legacy create to provision runners");let n=RV(e.positionals.id,t),r=e.config.get("profiles"),o=Object.hasOwn(r,n.profile)?r[n.profile]:void 0;if(!o)throw new b(`Profile "${n.profile}" not found for runner "${n.id}"`,"Run hydra legacy init to set it up");if(!yV(n.directory))throw new b(`Runner directory not found: ${n.directory}`,"Run hydra legacy create to provision this runner");let s=await ve(o,e.config).logFiles(n.id);if(s.length===0)QE(n.id);if(e.args.list){e.output.result({directory:n.directory,files:s,runner:n.id},()=>EV(n,s));return}let i=$V(e.args.runner,n,s);if(e.args.open){await vV(i),e.output.result({opened:i.path,runner:n.id});return}let a=El(await bV(i.path,"utf-8"),e.args.lines);T.info([`${p.bold(n.name)} ${p.dim(SV[i.type])}`,p.dim(i.path),p.dim(`Last modified: ${i.mtime.toISOString()}`)].join(`
609
+ `)),e.output.result({content:a,file:i,runner:n.id},()=>a)}});function RV(e,t){if(e){let r=t.find((o)=>o.id===e);if(!r)throw new b(`Runner "${e}" not found`,`Known runners: ${t.map((o)=>o.id).join(", ")}`);return r}let n=t[0];if(t.length===1&&n)return n;throw new W("Multiple runners found",`Pass a runner id: hydra legacy logs <id> (${t.map((r)=>r.id).join(", ")})`)}function $V(e,t,n){if(e){let o=n.find((s)=>s.type==="runner");if(!o)throw new b(`No runner daemon logs found for "${t.id}"`,"Start the runner first: hydra legacy start");return o}let r=$l(n,"worker");if(!r)QE(t.id);if(r.fallback)T.warn(p.yellow("No job (Worker) logs yet; showing the runner daemon log instead"));return r.file}function QE(e){throw new b(`No logs found for runner "${e}"`,"Logs appear once the runner has started; run hydra legacy start")}function EV(e,t){let n=[`${p.bold(e.name)} ${p.dim(e.directory)}`];for(let r of t){let o=r.type==="worker"?p.green("worker"):p.blue("runner");n.push(` ${o} ${r.name} ${p.dim(`${r.mtime.toISOString()} \xB7 ${kt(r.size)}`)}`)}return n.join(`
610
+ `)}async function vV(e){let[t,...n]=(process.env.EDITOR??"").split(" ").filter(Boolean);if(t){await Bun.spawn([t,...n,e.path],{stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited;return}if(process.platform==="darwin"){await Bun.$`open ${e.path}`.quiet();return}throw new b("No editor configured","Set $EDITOR to open log files")}var ZE=P({name:"default",description:"Set the default profile",positionals:ae({name:{description:"Profile name to set as default",required:!0}}),json:!0,examples:["hydra legacy profile default org"],run:async(e)=>{ge();let{name:t}=pt(e.config,e.positionals.name),n=e.config.get("defaultProfile")!==t;if(n)e.config.set("defaultProfile",t);T.info(n?`${p.green("Default profile set to")} "${t}".`:`"${t}" is already the default profile.`),e.output.result({changed:n,defaultProfile:t})}});var ev=P({name:"list",description:"List profiles",json:!0,examples:["hydra legacy profile list --json"],run:async(e)=>{ge();let t=Object.entries(e.config.get("profiles"));if(t.length===0)throw new b("No profiles configured","Run hydra legacy init to set up a profile");let n=e.config.get("runners")??[],r=e.config.get("defaultProfile"),o=[];for(let[s,i]of t){let a=await ve(i,e.config).list(),c=n.filter((f)=>f.profile===s),u=new Set(a.filter((f)=>f.status==="running").map((f)=>f.id)),l={default:s===r,name:s,namePrefix:i.name,numberOfMachines:i.numberOfMachines,os:i.os,provider:i.provider,runners:c.length,running:c.filter((f)=>u.has(f.id)).length,url:i.url,...i.labels?{labels:i.labels}:{}};o.push(l);let d=[`${p.dim("URL:")} ${l.url}`,`${p.dim("Provider:")} ${l.provider}`,`${p.dim("OS:")} ${l.os}`,`${p.dim("Name:")} ${l.namePrefix}`,`${p.dim("Runners:")} ${l.runners}/${l.numberOfMachines} created, ${p.green(`${l.running} running`)}`,...l.labels?[`${p.dim("Labels:")} ${l.labels}`]:[]];Do(d.join(`
611
+ `),l.default?`${s} ${p.dim("(default)")}`:s)}T.info(p.dim(`${t.length} profile(s)`)),e.output.result({defaultProfile:r,profiles:o})}});import{rm as kV}from"fs/promises";var tv=P({name:"remove",description:"Delete a profile and its runners",args:K({yes:{alias:"y",default:!1,description:"Remove its runners without a confirmation prompt",type:"boolean"}}),positionals:ae({name:{description:"Profile name to remove",required:!0}}),json:!0,examples:["hydra legacy profile remove org --yes"],run:async(e)=>{ge();let t=e.positionals.name,{profile:n}=pt(e.config,t),r=(e.config.get("runners")??[]).filter((c)=>c.profile===t);for(let c of r)zt(n,c);if(r.length>0&&!e.args.yes){if(e.json||!pr())throw new W("Runner removal requires confirmation","Pass --yes to remove the profile and its runners without a prompt");if(!await Rt({initialValue:!1,message:`This will stop and remove ${r.length} runner(s). Continue?`})){e.output.result({profile:t,removed:!1,runners:[]});return}}let o=ve(n,e.config),s=ot();for(let c of r){s.start(`Stopping and removing ${c.id}...`);try{await o.remove([c])}catch(u){throw s.stop(`${p.red("\u2717")} ${c.id}`),u}await kV(c.directory,{force:!0,recursive:!0}),await lo(e.config,t,[c.id]),s.stop(`${p.red("-")} ${c.id}`)}let{[t]:i,...a}=e.config.get("profiles");if(e.config.set("profiles",a),e.config.get("defaultProfile")===t)e.config.set("defaultProfile",Object.keys(a)[0]);T.info(`${p.green("Removed")} profile "${t}".`),e.output.result({profile:t,removed:!0,runners:r.map((c)=>c.id)})}});var nv=P({name:"profile",description:"Manage profiles",subcommands:[ev,tv,ZE]});var xV={busy:"kept: GitHub reports it busy",changed:"kept: it is no longer offline and idle",deleted:"deleted",gone:"already gone",renamed:"kept: GitHub lists it under another name now",returned:"kept: its directory in this home holds a runner again"},rv=P({name:"reconcile",description:"Delete stale GitHub registrations of this home's runners",args:bt,json:!0,examples:["hydra legacy reconcile --dry-run","hydra legacy reconcile --yes --json"],run:async(e)=>{if(ge(),wt(e.args),Object.keys(e.config.get("profiles")).length===0)throw new b("No profiles configured","Run hydra legacy init to set up a profile");let t=mo(e.config),{scopes:n,unreadableHomes:r}=await Nc(e.config,t),o={deleted:[],dryRun:e.args.dryRun,scopes:n.map(Hc),stale:0};if(n.length===0){T.info(p.dim("No GitHub profiles to reconcile.")),e.output.result(o);return}let s=n.flatMap((a)=>a.rows.filter(fn).map((c)=>({row:c,scope:a})));o.stale=s.length,T.info(_V(n,e.args.dryRun).join(`
612
+ `));for(let a of r)T.warn(p.yellow(`Cannot read the runner records of ${a}`));if(n.some((a)=>a.rows.some(SE)))throw new b("Not deleting: another Hydra home may record these runners","Repair or move the home named above, then run hydra legacy reconcile again");if(s.length===0){T.info(p.dim("Nothing to delete.")),e.output.result(o);return}if(e.args.dryRun){T.info(`Would delete ${s.length} registration(s). Run ${p.green("hydra legacy reconcile --yes")} to delete them.`),e.output.result(o);return}let i=`Delete ${s.length} registration(s) from GitHub?`;if(!await Xt(e,i,"Deleting registrations requires confirmation"))return;o.deleted=await TV(t,s),e.output.result(o)}});function _V(e,t){let n=[];for(let r of e){if(n.length>0)n.push("");n.push(Ep(r));let o=r.rows.filter((s)=>s.placement!=="both");if(o.length===0)n.push(p.dim(" Every runner here matches a registration on GitHub."));for(let s of o){if(s.placement==="local"){n.push(` ${s.local.name} ${p.dim("is in this home but not registered on GitHub")}`);continue}let i=`${s.github.name} \xB7 id ${s.github.id}`;n.push(fn(s)?` ${p.red(t?"would delete":"delete")} ${i} \xB7 ${Mc(s.github)}`:` ${p.dim("keep")} ${i} \xB7 ${vp(s)}`)}}return n}async function TV(e,t){let n=[];for(let{row:o,scope:s}of t){let i=$E(o.local)?"returned":await Dc(e,s.target,o.github);n.push({id:o.github.id,name:o.github.name,outcome:i});let a=xV[i];T.info(`${o.github.name} \xB7 id ${o.github.id} \xB7 ${i==="deleted"?p.green(a):a}`)}let r=n.filter(({outcome:o})=>o==="deleted").length;return T.info(`${p.green("Deleted")} ${r} of ${t.length} registration(s).`),n}import{existsSync as AV}from"fs";import{rm as CV}from"fs/promises";import{join as OV}from"path";var ov=P({name:"remove",description:"Stop, deregister and delete runners; removing every runner of a profile needs --yes or a prompt",args:bt,positionals:ae({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}}),json:!0,examples:["hydra legacy remove default runner-2","hydra legacy remove default --dry-run","hydra legacy remove default --yes"],run:async(e)=>{ge(),wt(e.args);let{name:t,profile:n}=pt(e.config,e.positionals.profile),r=(e.config.get("runners")??[]).filter((d)=>d.profile===t);if(r.length===0)throw new b(`No runners found for profile "${t}"`,"Run hydra legacy create to provision runners");let o=e.positionals.ids??[],i=Ar(o,r.map((d)=>d.id)).map((d)=>r.find((f)=>f.id===d));for(let d of i)zt(n,d);let a=i.map((d)=>({directory:d.directory,id:d.id,registered:AV(OV(d.directory,ke))})),c={dryRun:e.args.dryRun,plan:a,profile:t,removed:[]};if(T.info(IV(a,e.args.dryRun)),e.args.dryRun){e.output.result(c);return}if(o.length===0&&!e.args.yes&&!await PV(t,a.length,e.json)){e.output.result(c);return}let u=ve(n,e.config),l=ot();for(let d of i){l.start(`Stopping and removing ${d.id}...`);try{await u.remove([d])}catch(f){throw l.stop(`${p.red("\u2717")} ${d.id}`),f}await CV(d.directory,{force:!0,recursive:!0}),await lo(e.config,t,[d.id]),c.removed.push(d.id),l.stop(`${p.red("-")} ${d.id}`)}T.info(`${p.green("Removed")} ${c.removed.length} runner(s).`),e.output.result(c)}});async function PV(e,t,n){if(n||!pr())throw new W(`Removing every runner of profile "${e}" requires confirmation`,`Pass --yes to remove all ${t}, --dry-run to list them, or name the runner ids`);return Rt({initialValue:!1,message:`Stop, deregister and delete all ${t} runner(s) of "${e}"?`})}function IV(e,t){let n=t?"would remove":"remove";return e.map(({directory:r,id:o,registered:s})=>{let i=s?"stop, deregister from GitHub and delete":"stop and delete";return`${p.red(n)} ${o} \xB7 ${i} ${p.dim(r)}`}).join(`
613
+ `)}var sv=P({name:"start",description:"Start runners in the background; exits 1 when any runner could not start",positionals:ae({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}}),json:!0,examples:["hydra legacy start","hydra legacy start default runner-1"],run:async(e)=>{ge();let{name:t,profile:n}=pt(e.config,e.positionals.profile),r=(e.config.get("runners")??[]).filter((c)=>c.profile===t);if(r.length===0)throw new b(`No runners found for profile "${t}"`,"Run hydra legacy create to provision runners");let o=Ar(e.positionals.ids??[],r.map((c)=>c.id)),s=ve(n,e.config),i={failed:[],profile:t,running:[],started:[]},a=ot();for(let c of o){a.start(`Starting ${c}...`);try{zt(n,r.find((l)=>l.id===c));let[u]=await s.start([c]);if(u==="running"){i.running.push(c),a.stop(`${p.dim("\u25CF")} ${c} ${p.dim("already running")}`);continue}i.started.push(c),a.stop(`${p.green("\u25B6")} ${c}`)}catch(u){let l=bo(c,u);i.failed.push(l),a.stop(wo(l))}}if(T.info(`${p.green("Started")} ${i.started.length} runner(s).`),await Pc(e.config),e.output.result(i),i.failed.length>0)throw So("Some runners did not start",i.failed,"RunnersNotStarted")}});var NV={registered:p.yellow,running:p.green,stopped:p.red,unknown:p.dim},iv=P({name:"status",description:"Show status across profiles",args:K({github:{alias:"g",default:!1,description:"Compare with the runners registered on GitHub",type:"boolean"}}),json:!0,examples:["hydra legacy status","hydra legacy status --github --json"],run:async(e)=>{ge();let t=Object.entries(e.config.get("profiles"));if(t.length===0)throw new b("No profiles configured","Run hydra legacy init to set up a profile");let n=e.config.get("runners")??[],r={profiles:[],running:0,total:0},o=[];for(let[s,i]of t){let a=await ve(i,e.config).list(),c=new Set(n.filter((l)=>l.profile===s).map((l)=>l.id)),u=a.filter((l)=>c.has(l.id)).sort((l,d)=>l.name.localeCompare(d.name,void 0,{numeric:!0}));if(o.length>0)o.push("");o.push(`${p.bold(s)} ${p.dim(i.url)}`,...LV(u)),r.profiles.push({name:s,runners:u.map(({id:l,name:d,pid:f,status:m})=>({id:l,name:d,status:m,...f?{pid:f}:{}})),url:i.url}),r.total+=u.length,r.running+=u.filter((l)=>l.status==="running").length}if(o.push("",p.dim(`${r.total} runner(s) total, ${r.running} running`)),T.info(o.join(`
614
+ `)),e.args.github)r.github=await DV(e.config);e.output.result(r)}});async function DV(e){let{scopes:t,unreadableHomes:n}=await Nc(e,mo(e));if(t.length===0)return T.info(p.dim("No GitHub profiles to compare.")),{scopes:[],stale:0,unreadableHomes:n};let r=t.flatMap((s,i)=>[...i>0?[""]:[],...LE(s)]),o=t.flatMap((s)=>s.rows.filter(fn)).length;if(o>0)r.push("",p.yellow(`Run ${p.green("hydra legacy reconcile --dry-run")} to review ${o} stale registration(s).`));T.info(r.join(`
615
+ `));for(let s of n)T.warn(p.yellow(`Cannot read the runner records of ${s}`));return{scopes:t.map(Hc),stale:o,unreadableHomes:n}}function LV(e){if(e.length===0)return[p.dim(" No runners.")];return e.map((t)=>{let n=NV[t.status]??p.dim,r=t.pid?p.dim(` (pid: ${t.pid})`):"";return` ${n("\u25CF")} ${t.name} ${n(t.status)}${r}`})}var MV=K({...bt,...yo,interval:{default:15,description:"Seconds between checks while waiting",type:"number"},timeout:{default:60,description:"Minutes to wait for busy runners",type:"number"},wait:{alias:"w",default:!1,description:"Wait for busy runners to finish their jobs",type:"boolean"}}),xp=1000,HV=60,GV="Nothing more was stopped; run hydra legacy stop again",cv=P({name:"stop",description:"Stop drained 0.x runners once GitHub and the host show them idle",args:MV,json:!0,examples:["hydra legacy stop --dry-run","hydra legacy stop --yes --wait"],run:async(e)=>{wt(e.args);let{dryRun:t,group:n,interval:r,timeout:o,wait:s}=e.args;if(!(r>0)||!(o>=0))throw new W("--interval must be above 0 and --timeout at least 0");let{github:i,inventory:a}=await Qt(e.config),c=await go(i,a.scopes,n),u=[],l=[],d={busy:[],dryRun:t,left:[],planned:[],stopped:[]};for(let g of a.runners.filter((h)=>h.process.kind!=="stopped")){let h=jV(g,ho(c,g),n);if(h||!Pt(g)){if(g.process.kind!=="stale")d.left.push(g.name);l.push(nt(g,h??"config.json does not record it"));continue}u.push(g),d.planned.push(g.name);let E=g.github?.busy||"worker"in g.process&&g.process.worker?"busy":"idle";l.push(Ot(p.yellow(t?"would stop":"stop"),g,`${ct(g.process)} \xB7 ${E}`))}if(l.length===0)l.push(p.dim(" No runner of this home is running."));if(T.info(l.join(`
616
+ `)),u.length===0)return e.output.result(d),av(d,s);if(t){T.info(`Would stop ${u.length} runner(s), each only once it is idle.`),e.output.result(d);return}if(!await Xt(e,`Stop ${u.length} runner(s) once each is idle?`))return;let f=Date.now()+o*HV*xp,m=u;while(!0){let g=[],h=await FV(i,m,n);for(let E of m){let v=await UV(i,E,h.get(E.scope.key));if(v==="busy")g.push(E);else d[v].push(E.name)}if(m=g,m.length===0||!s||Date.now()+r*xp>f)break;T.info(p.dim(`Waiting for ${m.length} busy runner(s)...`)),await Bun.sleep(r*xp)}for(let g of m)d.busy.push(g.name),T.info(`${g.name} \xB7 ${p.yellow("still busy, left running")}`);e.output.result(d),av(d,s)}});async function FV(e,t,n){let r=new Map;for(let o of t){let s=gr(o.scope.target);if(!s||r.has(o.scope.key))continue;r.set(o.scope.key,await Gc(e,s,n))}return r}async function UV(e,t,n){let r=t.github?.id;if(r===void 0||!n?.members.has(r))return T.info(`${t.name} \xB7 ${p.yellow("left running: it is no longer in the drain group")}`),"left";if(n.members.get(r)?.busy)return"busy";let o=await ut(e,t.scope.target,GV,()=>Gt(e.client,t.scope.target,r));if(!o||o.name.toLowerCase()!==t.github?.name.toLowerCase())return T.info(`${t.name} \xB7 ${p.yellow("left running: GitHub no longer lists it under this id and name")}`),"left";if(o.busy)return"busy";let s=await mr(t);if(s.kind==="stopped")return T.info(`${t.name} \xB7 already stopped`),"stopped";if(s.kind==="unproven"||s.kind==="stale")return T.info(`${t.name} \xB7 ${p.yellow(`left running: ${ct(s)}`)}`),"left";if(s.worker)return"busy";if(await Oy(t.directory,s.pid)==="timeout")return T.info(`${t.name} \xB7 ${p.yellow("did not stop in time; check it with hydra legacy inventory")}`),"left";return T.info(`${t.name} \xB7 ${p.green("stopped")}`),"stopped"}function av({busy:e,left:t},n){if(t.length+e.length===0)return;let r=e.length===0?"Check why they were left alone with hydra legacy inventory":n?"Their jobs outlasted --timeout; run hydra legacy stop --wait again":"Pass --wait to stop busy runners once their jobs finish";throw new b(`${t.length+e.length} runner(s) are still running`,r)}function jV(e,t,n){if(e.refusal)return e.refusal;if(e.process.kind==="stale")return`${ct(e.process)}; ${po(e.process)}`;if(e.process.kind==="unproven")return ct(e.process);if(!e.github)return"not registered on GitHub, so Hydra cannot prove it takes no jobs";if(e.scope&&!gr(e.scope.target))return"repository runners have no runner groups; stop it with hydra legacy halt once idle";if(!t)return`not in ${n}; run hydra legacy drain first`;return}var _p={busy:"running a job; left on its current version until it is idle","not-registered":"no registered runner in its directory; drop the record with hydra legacy remove"},lv=P({name:"update",description:"Update runner binaries and job hooks; restarts idle running runners, skips busy ones",json:!0,examples:["hydra legacy update","hydra legacy update --json"],run:async(e)=>{ge();let t=e.config.get("profiles"),n=e.config.get("runners")??[];if(n.length===0)throw new b("No runners found","Run hydra legacy create to provision runners");let r=Map.groupBy(n,(i)=>i.profile);for(let i of r.keys()){let a=uv(t,i);if(a)an(a.jobHooks)}let o={failed:[],refreshed:[],restartNeeded:[],skipped:[],updated:[]},s=ot();for(let[i,a]of r){let c=uv(t,i);if(!c)continue;let u=ve(c,e.config);s.start(`Checking for updates for "${i}"...`);let{version:l}=await u.download();s.stop(`Latest: v${l}`);let d=new Set((await u.list()).filter((m)=>m.status==="running").map((m)=>m.id)),f={ids:[],profile:i,total:a.length};for(let m of a){let g={entry:m,latestVersion:l,profile:c,profileName:i,provider:u,wasRunning:d.has(m.id)};s.start(`Updating ${m.id}...`);try{s.stop(await BV(g,o,f))}catch(h){let E={...bo(m.id,h),profile:i};o.failed.push(E),s.stop(wo(E))}}if(f.ids.length>0)o.restartNeeded.push(f)}if(VV(o),await Pc(e.config),e.output.result(o),o.failed.length>0)throw So("Some runners were not updated",o.failed,"RunnersNotUpdated");if(o.skipped.length>0)throw new b(`${o.skipped.length} runner(s) were not updated: ${o.skipped.map((i)=>i.id).join(", ")}`,o.skipped.map((i)=>`${i.id}: ${_p[i.reason]}`).join(`
617
+ `),void 0,{tag:"RunnersNotUpdated"})}});async function BV({entry:e,latestVersion:t,profile:n,profileName:r,provider:o,wasRunning:s},i,a){if(zt(n,e),!o.registered(e.id))return i.skipped.push({id:e.id,profile:r,reason:"not-registered"}),`${p.yellow("!")} ${e.id} ${p.dim(_p["not-registered"])}`;if(await o.currentVersion(e.id)===t){let c=await o.configureJobHooks(e.id);if(!c.envChanged&&!c.scriptsChanged)return`${p.dim("\u25CF")} ${e.id} ${p.dim("up to date")}`;if(i.refreshed.push(e.id),c.envChanged&&s)a.ids.push(e.id);return`${p.green("\u2713")} ${e.id} ${p.dim("(job hooks)")}`}if(s&&await o.busy(e.id))return i.skipped.push({id:e.id,profile:r,reason:"busy"}),`${p.yellow("!")} ${e.id} ${p.dim(_p.busy)}`;if(s)await o.stop([e.id]);if(await o.update([e.id]),s)await o.start([e.id]);return i.updated.push({id:e.id,profile:r,restarted:s,version:t}),`${p.green("\u2713")} ${e.id}${s?` ${p.dim("(restarted)")}`:""}`}function VV(e){if(T.info(e.updated.length+e.skipped.length+e.failed.length>0?`${p.green("Updated")} ${e.updated.length} runner(s).`:"All runners are already on the latest version."),e.refreshed.length>0)T.info(`${p.green("Refreshed")} job hooks on ${e.refreshed.length} runner(s).`);if(e.restartNeeded.length===0)return;let t=["Running runners load job hook settings only when they start. Restart them once they are idle:"];for(let{ids:n,profile:r,total:o}of e.restartNeeded){let s=n.length===o?r:`${r} ${n.join(" ")}`;t.push(` ${p.green(`hydra legacy halt ${s} && hydra legacy start ${s}`)}`)}T.warn(t.join(`
618
+ `))}function uv(e,t){return Object.hasOwn(e,t)?e[t]:void 0}import{readdir as qV,rm as dv,rmdir as KV}from"fs/promises";import{join as pv}from"path";var WV="Nothing more was wiped; run hydra legacy wipe again",ks="Its .runner file is kept; fix the cause, then run hydra legacy wipe again",JV="Delete what is left of the directory, then run hydra legacy wipe again to drop its record",YV=2,mv=P({name:"wipe",description:"Delete the directories and records of stopped, deregistered 0.x runners",args:bt,json:!0,examples:["hydra legacy wipe --dry-run","hydra legacy wipe --yes"],run:async(e)=>{wt(e.args);let{github:t,inventory:n}=await Qt(e.config),r=(l)=>p.red(e.args.dryRun?`would ${l}`:l),o=[],s=[],i=[],a=[];for(let l of n.runners)if(CE(l)){let d=OE(l);if(d){a.push(nt(l,`its directory is missing but GitHub lists id ${d.id}; run hydra legacy reconcile`));continue}s.push(l),a.push(Ot(r("drop"),l,"its directory is missing, so only its record is left"))}else if(!Pt(l))a.push(nt(l,l.refusal??"config.json does not record it"));else if(l.github)a.push(nt(l,`registered on GitHub as id ${l.github.id}; run hydra legacy deregister first`));else if(l.process.kind!=="stopped")a.push(nt(l,`${ct(l.process)}; ${po(l.process)}`));else{let d=await Ro(l,ks,()=>Sp(l.directory));if(d.length>0)i.push(` ${l.name}: ${d.join(", ")}`);o.push(l),a.push(Ot(r("wipe"),l,l.directory))}if(T.info(a.join(`
619
+ `)),i.length>0)throw T.warn(p.yellow(["Unexpected entries in runner directories:",...i].join(`
620
+ `))),new b("Not wiping: a runner directory holds entries a 0.x runner does not create","Move those entries out of the runner directory, then run hydra legacy wipe again");let c=o.length+s.length,u={dryRun:e.args.dryRun,planned:[...o,...s].map((l)=>l.name),wiped:[]};if(c===0){T.info(p.dim("Nothing to wipe.")),e.output.result(u);return}if(e.args.dryRun){T.info(`Would wipe ${c} runner(s). Run ${p.green("hydra legacy wipe --yes")} to do it.`),e.output.result(u);return}if(!await Xt(e,`Delete ${o.length} runner directory(ies) and ${c} record(s)?`))return;for(let l of o){let d=await XV(t,l);if(d){T.info(`${l.name} \xB7 ${p.yellow(`kept: ${d}`)}`);continue}await QV(l),await fv(e.config,l.entry),u.wiped.push(l.name),T.info(`${l.name} \xB7 ${p.green("wiped")}`)}for(let l of s){let d=await zV(l);if(d){T.info(`${l.name} \xB7 ${p.yellow(`kept: ${d}`)}`);continue}await fv(e.config,l.entry),u.wiped.push(l.name),T.info(`${l.name} \xB7 ${p.green("record dropped")}`)}T.info(`${p.green("Wiped")} ${u.wiped.length} of ${c} runner(s).`),e.output.result(u)}});async function XV(e,t){let n=await mr(t);if(n.kind!=="stopped")return ct(n);let r=t.registration?.agentId;if(r===void 0)return"its .runner file records no runner id";if(await ut(e,t.scope.target,WV,()=>Gt(e.client,t.scope.target,r)))return`GitHub lists it again as id ${r}`;let s=await Ro(t,ks,()=>Sp(t.directory));return s.length>0?`unexpected entries: ${s.join(", ")}`:void 0}async function zV(e){let t=await mr(e);if(t.kind!=="stopped")return ct(t);return await $p(e.directory)==="missing"?void 0:"its directory exists again"}async function QV(e){let{directory:t}=e;for(let n=0;n<YV;n++){let r=await Ro(e,ks,()=>qV(t));for(let o of xE(r).filter((s)=>s!==ke))await Ro(e,ks,()=>dv(pv(t,o),{force:!0,recursive:!0}))}await Ro(e,ks,()=>dv(pv(t,ke),{force:!0})),await Ro(e,JV,()=>KV(t))}async function Ro(e,t,n){try{return await n()}catch(r){throw new b(`Cannot wipe ${e.name} in ${e.directory}: ${r.message}`,t)}}async function fv(e,t){await lo(e,t.profile,[t.id])}var Tp=P({name:"legacy",description:"Run a 0.x fleet of profiles, or drain, stop, deregister and wipe it",subcommands:[WE,fE,sv,VE,iv,rv,zE,sE,lv,ov,nv,XE,BE,cv,HE,mv]});var gv="Default",ZV="self-hosted",eq=",",tq="pool",nq=2,rq=1,oq=/[^a-z0-9]+/g,hv=/^-+|-+$/g,sq={linux:"linux",osx:"macos"},iq={linux:"Linux",macos:"macOS"},yv={arm:"ARM",arm64:"ARM64",ia32:"X86",x64:"X64"},aq={linux:"scaleset",macos:"poll"},cq={linux:{cpus:2,diskGiB:30,memoryMiB:4096},macos:{cpus:4,diskGiB:60,memoryMiB:8192}};function wv(e,t){let n=new Set(t.taken),r={pools:[],skipped:[]};for(let[o,s]of Object.entries(e)){let i=uq(o,s,t.arch,n);if("reason"in i){r.skipped.push(i);continue}n.add(i.name),r.pools.push(i)}return r}function uq(e,t,n,r){if(t.provider!=="github")return{profile:e,reason:`pools serve GitHub only, and this profile uses ${t.provider}`};if(t.os==="windows")return{profile:e,reason:"no slot driver runs Windows guests"};let o=pq(t.url);if(!o)return{profile:e,reason:"its url is not a GitHub organisation or repository URL"};let s=sq[t.os],i=Zu(o),a=dq(e,r),c=Object.hasOwn(yv,n)?yv[n]:void 0,u=t.numberOfMachines??rq,l=Nr(mt,s),d=Math.min(u,l?.guests??u),f=t.runnerGroup?.trim(),m=[a===e?"":`named ${a}: pool names are unique lowercase words joined by hyphens`,i===t.url?"":`url written as ${i}`,c?"":`no architecture label: GitHub's label for ${n} is not known`,l&&d<u?`ceiling ${d}, not ${u}: ${l.driver} runs at most ${d} macOS guests per host`:"",o.kind==="org"&&!f?`runner group ${gv}, which 0.x runners joined without one`:"",o.kind==="repo"&&f?"runnerGroup dropped: repository runners belong to no group":""].filter(Boolean),g={ceiling:d,demand:aq[s],driver:mt,guestOs:s,labels:lq(t.labels,s,c),resources:{...cq[s]},...o.kind==="org"?{runnerGroup:f||gv}:{},secretBearing:!0,url:i};try{return{name:a,notes:m,pool:Bo(a,g),profile:e}}catch(h){return{profile:e,reason:`its pool would be refused: ${h instanceof Error?h.message:String(h)}`}}}function lq(e,t,n){let r=(e??"").split(eq).map((s)=>s.trim()),o=[];for(let s of[ZV,iq[t],n??"",...r])if(s&&!o.some((i)=>i.toLowerCase()===s.toLowerCase()))o.push(s);return o}function dq(e,t){let n=bv(e,Kn)||tq;if(!t.has(n))return n;for(let r=nq;;r++){let o=`-${r}`,s=`${bv(n,Kn-o.length)}${o}`;if(!t.has(s))return s}}function bv(e,t){return e.toLowerCase().replace(oq,"-").replace(hv,"").slice(0,t).replace(hv,"")}function pq(e){try{return de(e)}catch{return}}var fq=K({dryRun:{alias:"n",default:!1,description:"Print the v2 pools for this home's 0.x profiles, write nothing",type:"boolean"}}),mq=2,Ap=P({name:"migrate",description:"Print v2 pools for this home's 0.x profiles",args:fq,json:!0,examples:["hydra migrate --dry-run","hydra migrate --dry-run --json"],run:async(e)=>{if(!e.args.dryRun)throw new b("hydra migrate needs --dry-run","It prints the v2 pools for this home's profiles and writes nothing");let t=e.config.get("profiles");if(Object.keys(t).length===0)throw new b("No profiles to migrate",`Select the home that holds them with ${ye}`);let n=e.config.get("pools")??{},r=wv(t,{arch:process.arch,taken:Object.keys(n)}),o=[...r.pools.flatMap(gq),...r.skipped.map(({profile:c,reason:u})=>`${p.bold(c)} ${p.yellow("skipped")}: ${u}`)];T.info(o.join(`
621
+ `));let i={pools:Object.fromEntries(r.pools.map(({name:c,pool:u})=>[c,u])),skipped:r.skipped};if(r.pools.length===0){T.info(p.dim("No profile maps to a pool. Nothing was written.")),e.output.result(i);return}e.output.result(i,(c)=>JSON.stringify({pools:c.pools},null,mq));let a=e.config.get("fleet")?"":', with a fleet id in "fleet": { "id": "<name>" }';T.info(p.dim([`Nothing was written. To use these pools, add them to the pools in ${e.config.path}${a}.`,"They are secret-bearing because 0.x runners shared one host user; set secretBearing to false only for pools whose jobs hold no secrets.","auto picks a driver per host (hydra driver list names it), and the resources are starting values to size to the jobs."].join(`
622
+ `)))}});function gq({name:e,notes:t,pool:n,profile:r}){let o=n.runnerGroup?`${n.url} \xB7 runner group ${n.runnerGroup}`:n.url,{cpus:s,diskGiB:i,memoryMiB:a}=n.resources;return[`${p.bold(r)} \u2192 pool ${p.bold(e)}`,` ${o}`,` labels ${n.labels.join(", ")}`,` ${on[n.guestOs]} guests \xB7 driver ${n.driver} \xB7 demand ${n.demand} \xB7 ceiling ${n.ceiling} \xB7 ${s} CPUs, ${a} MiB, ${i} GiB each`,...t.map((c)=>p.dim(` ${c}`))]}var Sv=P({name:"print",description:"Print the pf anchor rendered from the host budget and this host's interfaces",args:vs,run:async(e)=>{let t=Mn(Yt(e.args.budget));process.stdout.write(Ac(Tc(_c(t))).text)}});var hq=K({socket:{description:"Ask the host daemon on this socket",displayDefault:`${ln}/<fleet id>.sock`,type:"string"}}),yq=120000,Rv=P({name:"verify",description:"Ask the host daemon to compare the loaded pf anchor with the rendered one, and report the pf reference",args:hq,json:!0,examples:["hydra net verify","hydra net verify --json"],run:async(e)=>{let t=e.args.socket||cp(e.config.get("fleet")?.id),n=await wq(t).catch((r)=>{if(!(r instanceof Xe))throw r;throw new b(r.message,"Start the host daemon with hydra host serve, or pass --socket")});if(!e.json)T.info(bq(t,n).join(`
623
+ `));if(e.output.result(n),n.state==="ok"&&n.enforced)return;throw new b(n.state==="off"?"The host daemon loads no pf anchor":`The pf anchor ${n.anchor} ${n.enforced?"holds, with problems":"does not hold"}`,n.findings[0]?.fix??"Read the host daemon's log")}});function bq(e,t){let n=t.enforced?p.green("holds"):p.red("does not hold"),r=t.reference?"enable reference held":"no enable reference",o=t.lastDrift;return[`${p.bold("Host daemon")} ${e}`,`${p.bold("pf anchor")} ${t.anchor} \xB7 ${n} \xB7 ${r} \xB7 loaded ${t.loadedAt??"never"} \xB7 checked ${t.checkedAt??"never"}`,`${p.bold("Guest bridges")} ${t.bridges.length===0?p.dim("none"):t.bridges.join(", ")}`,...o?[`${p.bold("Last change outside the daemon")} ${o.at}: ${o.differences.join("; ")}`]:[],...t.findings.map((s)=>`${s.level==="error"?p.red("\u2717"):p.yellow("!")} ${s.detail}
624
+ ${p.dim(s.fix)}`)]}async function wq(e){let t=await so(e,yq);try{return await t.netStatus()}finally{t.close()}}var Cp=P({name:"net",description:"Print the pf anchor that keeps guests off the host, or verify the one the host daemon loaded",subcommands:[Sv,Rv]});import{existsSync as Mq}from"fs";import{existsSync as $v,lstatSync as Sq,mkdirSync as Rq,readFileSync as $q,renameSync as Eq,rmSync as vq,writeFileSync as kq}from"fs";import{hostname as xq}from"os";import{dirname as Op,join as _q}from"path";var Tq="scalesets.json",jc=16,Aq="Default",Ev=1,Cq=448,Oq=384,Pq=18,Iq=/^[a-z0-9]+$/,Nq=/[^a-z0-9]/g,Dq=N({id:X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),labels:Z(I()),name:I(),runnerGroupId:X().map((e)=>Number.isSafeInteger(e)&&e>0?e:F())}),Lq=N({scaleSets:kr(Dq),v:J([Ev])});class xs extends Error{path;_tag="ScaleSetRecordsError";constructor(e,t){super(`Scale set records ${e} ${t}`);this.path=e;this.name="ScaleSetRecordsError"}}class Bc extends Error{scaleSet;id;_tag="ScaleSetLabelsError";constructor(e,t){super(`The scale set ${e} (id ${t}) already exists with other labels; Hydra never changes a scale set's labels`);this.scaleSet=e;this.id=t;this.name="ScaleSetLabelsError"}}function vv(e){return _q(e,ps,Tq)}function kv(e){return e.length<=jc&&Iq.test(e)}function xv(e=xq()){let t=(e.split(".")[0]??"").toLowerCase().replace(Nq,"").slice(0,jc);return t===""?void 0:t}function _v(e,t,n){return`${e}-${t}-${n}`}function hr(e){let t=vv(e);if(!$v(t))return{};Uc(Op(t),"directory"),Uc(t,"file");try{return Lq(JSON.parse($q(t,"utf8"))).scaleSets}catch{throw new xs(t,"is not a valid scale set record file")}}function Vc(e,t){let n=vv(e);if(Rq(Op(n),{mode:Cq,recursive:!0}),Uc(Op(n),"directory"),$v(n))Uc(n,"file");let r=`${n}.${process.pid}.tmp`;vq(r,{force:!0}),kq(r,`${JSON.stringify({scaleSets:t,v:Ev},null,2)}
625
+ `,{flag:"wx",mode:Oq}),Eq(r,n)}function Uc(e,t){let n=Sq(e);if(!(t==="directory"?n.isDirectory():n.isFile()))throw new xs(e,t==="file"?"is not a regular file":"is not a directory");if(n.uid!==process.getuid?.())throw new xs(e,"is not owned by the user running Hydra");if((n.mode&Pq)!==0)throw new xs(e,"can be written by other users")}async function Tv(e,t,n){let r=await e.getRunnerGroup(t.runnerGroup??Aq),{created:o,labelsMatch:s,scaleSet:i}=await e.ensureScaleSet({labels:t.labels,name:n,runnerGroupId:r.id});if(!s)throw new Bc(n,i.id);return{adopted:!o,record:{id:i.id,labels:[...t.labels],name:i.name,runnerGroupId:r.id}}}var qc="Check the GitHub credentials: scale sets need the Self-hosted runners organisation permission (read and write)",Hq="Delete that scale set first, or give this host another id with --host";function Pp(e,t){return ic({apiUrl:kn(process.env),github:Mt(e).client,url:t})}function Kc(e,t,n){try{return Bo(e,t)}catch(r){throw new b(r.message,n)}}function Wc(e){let t=e??xv();if(t!==void 0&&kv(t))return t;throw new b(`The host id "${t??""}" is not lowercase letters and digits, at most ${jc} characters`,"Name this host with --host, for example --host build1")}async function Jc(e,t,n,r,o){let s=ee(e),i=hr(s),a=i[n];if(a)return`Pool ${n} keeps scale set ${a.name} (id ${a.id})`;let c,u;try{({adopted:u,record:c}=await Tv(Pp(e,r.url),r,_v(t,n,o)))}catch(l){throw new b(l.message,l instanceof Bc?Hq:qc)}return Vc(s,{...i,[n]:c}),`${u?"Adopted":"Created"} scale set ${c.name} (id ${c.id}) in runner group ${c.runnerGroupId}`}function Av(e,t){let n=ee(e);if(!Mq(Qr(n)))return 0;return Qa(n).slots().filter((r)=>r.pool===t&&(!ht(r.phase)||qe(r))).length}var Gq=K({allowWeakerIsolation:{description:"Let a secret-bearing pool use a user-space kernel driver",type:"boolean"},ceiling:{description:`Most jobs the pool runs at once, or ${fe}`,type:"string"},cpus:{description:"Virtual CPUs per guest",type:"number"},demand:{description:"Where demand comes from: scaleset or poll",type:"string"},diskGib:{description:"Disk per guest in GiB",type:"number"},docker:{description:"Docker the jobs need: none, limited or full",type:"string"},driver:{description:"Slot driver, or auto (default)",type:"string"},fleet:{description:"Fleet id to set when config.json has none",type:"string"},foreignArch:{description:"The jobs run binaries built for another architecture",type:"boolean"},guestOs:{description:"Guest operating system: linux or macos",type:"string"},guiSession:{description:"The runner needs a desktop session",type:"boolean"},host:{description:"This host's id in the scale set name (default: from the host name)",type:"string"},labels:{description:"The pool's full label set, comma-separated",type:"string"},maxJobMinutes:{description:"Longest a job may run, in minutes",type:"number"},memoryMib:{description:"Memory per guest in MiB",type:"number"},priority:{description:"Priority from 0 to 100",type:"number"},runnerGroup:{description:"The organisation runner group the pool's runners join",type:"string"},secretBearing:{description:"The jobs may hold secrets",type:"boolean"},url:{description:"https://github.com/<org> or https://github.com/<owner>/<repo>",type:"string"}}),Fq=ae({pool:{description:"Name of the new pool",required:!0}}),Uq="Run 'hydra pool add --help' for the settings a pool takes",jq=["allowWeakerIsolation","foreignArch","guiSession","secretBearing"],Cv=P({name:"add",description:"Add a pool; a scale-set pool gets its scale set in its runner group",args:Gq,positionals:Fq,run:async(e)=>{let t=e.positionals.pool;if(!jo(t))throw new b(`"${t}" is not a valid pool name`,"Use lowercase words joined by hyphens");let n=e.config.get("pools")??{};if(Object.hasOwn(n,t))throw new b(`Pool ${t} already exists`,"hydra pool set changes it; hydra pool remove deletes it");let r=Bq(e),o=Kc(t,Vq(e.args),Uq),s=o.demand==="scaleset"?Wc(e.args.host):void 0,i=[`Added pool ${p.bold(t)} (${o.demand} demand)`];if(s!==void 0)i.push(await Jc(e.config,r,t,o,s));if(!e.config.get("fleet"))e.config.set("fleet",{id:r});e.config.set("pools",{...n,[t]:o}),T.success(i.join(`
626
+ `))}});function Bq(e){let t=e.config.get("fleet")?.id,n=e.args.fleet;if(t!==void 0&&n!==void 0&&n!==t)throw new b(`This home belongs to fleet ${t}`,"Leave out --fleet, or use another Hydra home");let r=t??n;if(r!==void 0&&Wn(r))return r;throw new b(r===void 0?"This home has no fleet yet":`"${r}" is not a valid fleet id`,"Name it with --fleet: lowercase letters and digits, at most 16 characters")}function Vq(e){let t=e.labels?.split(",").map((o)=>o.trim()),r={ceiling:e.ceiling===void 0||e.ceiling===fe?e.ceiling:Number(e.ceiling),demand:e.demand,docker:e.docker,driver:e.driver??"auto",guestOs:e.guestOs,labels:t,maxJobMinutes:e.maxJobMinutes,priority:e.priority,resources:{cpus:e.cpus,diskGiB:e.diskGib,memoryMiB:e.memoryMib},runnerGroup:e.runnerGroup,url:e.url};for(let o of jq)if(e[o])r[o]=!0;return Object.fromEntries(Object.entries(r).filter(([,o])=>o!==void 0))}var qq=ae({pool:{description:"Pool to remove",required:!0}}),Ov=P({name:"remove",description:"Remove a pool and delete its scale set",positionals:qq,run:async(e)=>{let t=e.positionals.pool,n=ee(e.config),r=e.config.get("pools")??{},o=r[t],s=hr(n),i=s[t];if(!o&&!i)throw new b(`No pool is named ${t}`);let a=Av(e.config,t);if(a>0)throw new b(`Pool ${t} still has ${a} slot(s) in the ledger that have not ended`,"Drain the pool and let its jobs finish and its guests be destroyed");let c=[];if(i){let d=o?.url;if(d===void 0)throw new b(`Pool ${t} has a scale set but no settings`,"Add the pool again, then remove it");let f=await Kq(Pp(e.config,d),i),{[t]:m,...g}=s;Vc(n,g),c.push(f==="gone"?`Scale set ${i.name} (id ${i.id}) was already gone`:`Deleted scale set ${i.name} (id ${i.id})`)}let{[t]:u,...l}=r;e.config.set("pools",l),T.success([`Removed pool ${p.bold(t)}`,...c].join(`
627
+ `))}});async function Kq(e,t){let n;try{n=await e.getScaleSetById(t.id)}catch(r){throw new b(r.message,qc)}if(!n)return"gone";if(n.name!==t.name||n.runnerGroupId!==t.runnerGroupId)throw new b(`Scale set ${t.id} is ${n.name} in runner group ${n.runnerGroupId}, not the recorded ${t.name} in runner group ${t.runnerGroupId}`,"Hydra deletes only the scale set it recorded; check ledger/scalesets.json");try{return await e.deleteScaleSet(t.id)}catch(r){throw new b(r.message,qc)}}var Wq=K({ceiling:{description:`Most jobs the pool runs at once, or ${fe}`,type:"string"},demand:{description:"Where demand comes from: scaleset or poll",type:"string"},host:{description:"This host's id in a new scale set's name (default: from the host name)",type:"string"}}),Jq=ae({pool:{description:"Pool to change",required:!0}}),Yq="Run 'hydra pool set --help' for the settings it changes",Pv=P({name:"set",description:"Change a pool's demand source or ceiling",args:Wq,positionals:Jq,run:async(e)=>{let t=e.positionals.pool,n=e.config.get("pools")??{},r=n[t],o=e.config.get("fleet")?.id;if(!r||o===void 0)throw new b(`No pool is named ${t}`,"hydra pool add creates one");let{ceiling:s,demand:i}=e.args;if(s===void 0&&i===void 0)throw new b("Name a change","Use --demand or --ceiling");let a=Kc(t,{...r,...i===void 0?{}:{demand:i},...s===void 0?{}:{ceiling:s===fe?s:Number(s)}},Yq),c=[`Pool ${p.bold(t)} takes ${a.demand} demand with a ceiling of ${a.ceiling}`];if(a.demand==="scaleset")c.push(await Jc(e.config,o,t,a,Wc(e.args.host)));if(a.demand==="poll"&&r.demand==="scaleset")c.push(p.dim("Its scale set stays registered; hydra pool remove deletes it"));e.config.set("pools",{...n,[t]:a}),T.success(c.join(`
628
+ `))}});var Ip=P({name:"pool",description:"Add, change and remove pools and their scale sets",subcommands:[Cv,Pv,Ov]});import{existsSync as Xq,lstatSync as zq,readdirSync as Qq}from"fs";import{join as Iv}from"path";var Np="slot-logs",Dp=14,Zq=86400000,Nv=".log",eK=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,tK=18,nK=["current","previous"];function Yc(e){let t={images:[],kept:[],logs:[],notes:[]};return rK(e,t),iK(e,t),t}function rK(e,t){let n=new Map;for(let r of dp(e.home)){if(!aR(r.record))continue;let o=sK(r.record);n.set(o,[...n.get(o)??[],r])}if(e.serving===void 0&&n.size>0)t.notes.push("The images hydra serve uses could not be read, so every image is kept");for(let r of n.values()){let o=r.sort((s,i)=>Date.parse(i.record.builtAt)-Date.parse(s.record.builtAt));for(let[s,i]of o.entries()){let a=oK(s,i.record,e.serving);if(a)t.kept.push({reason:a,record:i.record});else t.images.push(i)}}}function oK(e,t,n){let r=nK[e];if(r)return r;if(n===void 0)return"serving-unknown";return n.includes(t.reference)?"serving":void 0}function sK(e){return[e.kind,e.builder,e.arch,e.variant].join("/")}function iK(e,t){if(e.fleet===void 0)return;let n=Iv(e.home,Np);if(!Xq(n))return;if(!Dv(n,"directory")){t.notes.push(`${n} is not a directory that only this user can write, so no slot log is pruned`);return}let r=`hydra-${e.fleet}-`,o=e.now-Dp*Zq;for(let s of Qq(n).sort()){if(!aK(s,r))continue;let i=Iv(n,s),a=Lv(i);if(!a?.isFile()||!Dv(i,"file")||a.mtimeMs>o)continue;t.logs.push({bytes:a.size,modifiedAt:a.mtimeMs,name:s,path:i})}}function aK(e,t){if(!e.startsWith(t)||!e.endsWith(Nv))return!1;return eK.test(e.slice(t.length,-Nv.length))}function Dv(e,t){let n=Lv(e);if(!n)return!1;return(t==="directory"?n.isDirectory():n.isFile())&&n.uid===process.getuid?.()&&(n.mode&tK)===0}function Lv(e){try{return zq(e)}catch{return}}import{lstatSync as Mv,readFileSync as cK,renameSync as uK,rmSync as Hv,writeFileSync as lK}from"fs";import{join as dK}from"path";var pK="serving.json",fK=384,mK=18,gK=N({images:Z(I()),startedAt:I()});function Lp(e){return dK(e,pK)}function hK(e,t,n=new Date){let r=Lp(e),o=`${r}.${process.pid}.tmp`;try{let s={images:[...new Set(t)].sort(),startedAt:n.toISOString()};lK(o,`${JSON.stringify(s,null,2)}
629
+ `,{flag:"wx",mode:fK}),uK(o,r)}finally{Hv(o,{force:!0})}}function Gv(e,t,n,r=new Date){let o=n?Mp(e):[];if(o===void 0)return;let s=[...new Set([...t,...o])].sort();return hK(e,s,r),s}function Fv(e,t){if(!t)yK(e)}function yK(e){let t=Lp(e);if(Mv(t,{throwIfNoEntry:!1})?.isFile())Hv(t,{force:!0})}function Mp(e){let t=Lp(e),n=Mv(t,{throwIfNoEntry:!1});if(!n)return[];if(!n.isFile()||n.uid!==process.getuid?.()||(n.mode&mK)!==0)return;try{return gK(JSON.parse(cK(t,"utf8"))).images}catch{return}}var bK=K({yes:{alias:"y",default:!1,description:"Remove what the dry run lists",type:"boolean"}}),wK={current:"the newest of its kind",previous:"the one before the newest",serving:"hydra serve starts guests from it","serving-unknown":"the images hydra serve uses could not be read"},SK=86400000,RK="Nothing was removed. Run hydra prune --yes to remove what is listed.",Hp=P({name:"prune",description:"List, or with --yes remove, the runner images and slot logs Hydra recorded and no longer needs",args:bK,json:!0,examples:["hydra prune","hydra prune --json","hydra prune --yes"],run:async(e)=>{let t=ee(e.config),n=Date.now(),r=Yc({fleet:e.config.get("fleet")?.id,home:t,now:n,serving:Mp(t)}),o=r.images.length+r.logs.length;if(!e.json)T.info($K(r,n));if(!e.args.yes){if(!e.json&&o>0)T.info(p.dim(RK));e.output.result(Uv(r));return}let s=await dc(r,lc());if(!e.json&&o>0)T.info(EK(s));if(e.output.result(Uv(r,s)),s.failed.length===0)return;throw new b(`Could not prune ${s.failed.length} of ${o} items`,"Each item above that could not be removed stays listed; fix its problem and run hydra prune --yes again")}});function Uv(e,t){let n=e.logs.map((r)=>({...r,modifiedAt:new Date(r.modifiedAt).toISOString()}));return{images:e.images,kept:e.kept,logs:n,notes:e.notes,...t?{removed:t}:{}}}function $K(e,t){let n=[...e.images.map(({record:o})=>`${p.bold("image")} ${o.reference} ${p.dim(`(${o.variant}, ${o.arch}, built ${o.builtAt})`)}`),...e.logs.map((o)=>`${p.bold("slot log")} ${o.name} ${p.dim(`(${kt(o.bytes)}, ${Math.floor((t-o.modifiedAt)/SK)} days old)`)}`)];if(n.length===0)n.push(`Nothing to prune: no image beyond the two newest, no slot log older than ${Dp} days`);let r=e.kept.map(({reason:o,record:s})=>p.dim(`keeps ${s.reference}: ${wK[o]}`));return[...n,...r,...e.notes.map((o)=>p.yellow(o))].join(`
630
+ `)}function EK(e){return[`Removed ${pc(e)}`,...e.failed.map((n)=>p.yellow(`${n.item}: ${n.detail}`))].join(`
631
+ `)}import{join as Kv}from"path";import{join as vK}from"path";var kK={arm64:"arm64",x86_64:"amd64"},xK="tart";function jv(e,t,n,r){let o={drivers:{},images:{},networks:[],unavailable:{}},s=new Map;for(let[i,a]of Object.entries(t)){let c=xi(a.driver,Ti(a),n);if(c.kind==="refused"){o.unavailable[i]=c.refusals.map((f)=>f.detail).join("; ");continue}let u=c.driver;if(!s.has(u))s.set(u,TK(u,e,o,r));let l=s.get(u);if(typeof l==="string"){o.unavailable[i]=l;continue}if(l)o.drivers[i]=l;let d=u==="tart"?AK(r,a):CK(r,n,a);if(typeof d==="object")o.images[i]="reference"in d?d.reference:d.name;else o.unavailable[i]=d}return o}function Bv(e,t,n){let r=n.scaleSetClient??Gp(n.apiUrl,n.github),o=JR({client:n.github,pools:_K(e,t,n)}),s={};for(let[i,a]of Object.entries(e)){if(t.unavailable[i]!==void 0)continue;let c={alert:n.alert,onDemand:n.onDemand};if(a.demand==="scaleset"){let u=n.records[i];if(!u){t.unavailable[i]=`no scale set is recorded for it; hydra pool set ${i} --demand scaleset creates one`;continue}s[i]=XS({...c,capacity:()=>n.capacity(i),client:r(a.url),labels:a.labels,ownerName:u.name,pool:i,runnerGroupId:u.runnerGroupId,scaleSetId:u.id});continue}s[i]=KS({...c,capacity:()=>Vv(a),github:n.github,labels:a.labels,pool:i,reader:o.reader(i),runnerGroup:a.runnerGroup,slots:()=>n.ledger.slots(),url:a.url})}return s}function _K(e,t,n){return Object.entries(e).filter(([r,o])=>o.demand==="poll"&&t.unavailable[r]===void 0).map(([r,o])=>({labels:o.labels,pool:r,priority:o.priority??dr,repositories:YR({github:n.github,pool:r,runnerGroup:o.runnerGroup,url:o.url}),room:()=>n.serving?.(r)??!0?Vv(o)-sc(n.ledger.slots(),r):0}))}function Vv(e){return e.ceiling===fe?Zr:e.ceiling}function Gp(e,t){let n=new Map;return(r)=>{let o=n.get(r);if(o)return o;let s=ic({apiUrl:e,github:t,url:r});return n.set(r,s),s}}function qv(e,t){return(n,r)=>{let o=e[n],s=t[n];if(!o||s===void 0)throw Error(`Pool ${n} has no image to start ${r} from`);return{...o.resources,docker:(o.docker??"none")!=="none",foreignArch:o.foreignArch??!1,guestOs:o.guestOs,image:s,name:r,pool:n,secretBearing:o.secretBearing??!1}}}function TK(e,t,n,r){if(e==="tart"){let s=lw(r,sr());return Ga({checkImage:s,fleet:{id:t.id,stateDir:vK(r,xK)}})}if(e!=="apple-container")return`This version of Hydra does not include the ${e} driver`;if(!t.networks)return"fleet.networks is not set, and the apple-container driver takes its guests' networks from it";let o=ma({fleet:{dns:t.dns,id:t.id,networks:t.networks}});return n.networks.push(o.networks()),o}function AK(e,t){let n=An(t.secretBearing??!1),r=cw(e,t.guestOs,n);if(r)return r;let o=`${n==="secret"?"secret-bearing ":""}${t.guestOs} golden`,s=`hydra image build ${t.guestOs==="macos"?"macos":"tart-linux"}${n==="secret"?" --secret-bearing":""}`;return`no ${o} is promoted; run ${s} --base <image@sha256:digest>, then hydra image promote`}function CK(e,t,n){let r=kK[t.arch];if(!r)return`Hydra builds no Linux image for ${t.arch} hosts`;let o=(n.docker??"none")!=="none";return M$(e,r,o?"docker":"plain")??`no ${o?"Docker ":""}Linux image is recorded; run hydra image build linux${o?" --docker":""}`}var OK=K({socket:{description:"Ask the host daemon on this socket for leases",displayDefault:`${ln}/<fleet id>.sock`,type:"string"}}),Wv=["SIGINT","SIGTERM"],PK=30000,Fp=P({name:"serve",description:"Run this fleet's pools: start a fresh guest for each job their demand sources bring, until stopped",args:OK,run:async(e)=>{let t=e.config.get("fleet"),n=e.config.get("pools")??{};if(!t||Object.keys(n).length===0)throw new b("This home has no pools to serve","Add one with hydra pool add");let r=e.config.get("alerts");if(Et(r).length===0)throw new b("Pools need an alert sink",Yn);let o=ee(e.config);if(!io(o))throw new b("Pools need a guard record","Run hydra guard record once the runner groups and policies are as they should be");let s=IK(o),i=(R)=>process.stdout.write(`${new Date().toISOString()} ${R}
632
+ `),a=Li({fleet:t.id,sinks:Mi(r,{env:process.env,version:vn}),store:Gi(o)}),c=()=>{a.deliver().catch((R)=>i(`alert delivery failed: ${String(R)}`))},u=(R)=>{a.raise(R),i(`alert ${R.reason}${R.pool?` for pool ${R.pool}`:""}${R.detail?`: ${R.detail}`:""}`),c()},l=Mt(e.config).client,d=qS({alert:u,log:i,minted:()=>ls(s.slots()),pools:n,reader:Ba(l),record:()=>ec(o)}),f=jv(t,n,await En(),o),m,g=qR({connect:()=>so(e.args.socket||Kv(ln,`${t.id}.sock`)),reported:(R)=>m?.reported(R),slots:()=>s$(s,n)}),h=kn(process.env),E=Gp(h,l),v=hr(o),S=Bv(n,f,{alert:u,apiUrl:h,capacity:(R)=>d.held(R)===void 0?_.capacity(R):0,github:l,ledger:s,onDemand:async()=>m?.tick(),records:v,scaleSetClient:E,serving:(R)=>(m?.status().pools.find((A)=>A.pool===R)?.health??"serving")==="serving"}),_=NK(()=>WR({alert:u,assigned:(R)=>S[R]?.status().demand??0,offer:(R)=>g.offer(R),pools:Object.fromEntries(Object.entries(n).filter(([R])=>S[R]!==void 0)),slots:()=>s.slots()}));for(let[R,A]of Object.entries(f.unavailable))i(`pool ${R} takes no new jobs: ${A}`);let C=Gv(o,Object.values(f.images),Jv(s));if(!C)i("could not read the images an earlier hydra serve started guests from; every image is kept");let w=mR({alert:u,log:i,prune:(R)=>dc(Yc({fleet:t.id,home:o,now:Date.now(),serving:C}),lc(),R),read:async()=>{let R=await g.status();return{freeGiB:R.live.diskFreeGiB,state:R.disk}}});await DK(f.networks,i);let x=n$({alert:u,degrade:(R)=>m?.degrade(R),drivers:f.drivers,fleet:t.id,github:l,ledger:s,log:i,networks:f.networks,records:()=>hr(o),registrations:r$(n,v,{github:l,scaleSetClient:E}),retire:(R)=>m?.retire(R)});await d.round(),m=await i$({alert:u,drivers:f.drivers,fleet:t.id,held:d.held,host:g,ledger:s,log:i,logsDir:Kv(o,Np),offers:_,pools:n,runnerLeft:x.left,sources:S,spec:qv(n,f.images),unavailable:f.unavailable}),x.start(),d.start(),w.start();let y=setInterval(c,PK);await LK(),clearInterval(y),i("stopping; running guests keep their jobs"),await x.stop(),await d.stop(),await w.stop(),await m.stop(),Fv(o,Jv(s)),await a.deliver({flush:!0}).catch(()=>{return})}});function Jv(e){return e.slots().some((t)=>!ht(t.phase)||qe(t))}function IK(e){try{return Qa(e)}catch(t){if(t instanceof it)throw new b(t.message,"Repair the ledger, or restore it from a backup");throw t}}function NK(e){try{return e()}catch(t){if(t instanceof wc)throw new b(t.message,"Split the pools between fleets");throw t}}async function DK(e,t){for(let n of e)try{let r=await n.prepare();if(r.created.length>0)t(`created the guest networks ${r.created.join(", ")}`);for(let o of r.findings)t(`network ${o.level}: ${o.detail}`)}catch(r){t(`could not prepare the guest networks: ${r instanceof Error?r.message:String(r)}`)}}function LK(){return new Promise((e)=>{let t=()=>{for(let n of Wv)process.off(n,t);e()};for(let n of Wv)process.on(n,t)})}var MK=K({budget:{description:"With --host: the host budget file the daemon reads",type:"string"},host:{default:!1,description:"Print the root host daemon's LaunchDaemon instead of this fleet's",type:"boolean"},script:{default:!1,description:"Print the root script that installs the staged property list and loads it",type:"boolean"},socket:{description:"For a fleet: the host daemon socket hydra serve asks for leases",type:"string"},stage:{description:"With --script: the directory holding the reviewed property list",type:"string"}}),HK=0,Yv=P({name:"print",description:"Print this fleet's LaunchDaemon, or with --host the host daemon's, with an explicit environment",args:MK,run:async(e)=>{if(e.args.host&&e.args.socket!==void 0)throw new b("--socket is for a fleet's service, not --host");if(!e.args.host&&e.args.budget!==void 0)throw new b("--budget goes with --host");if(e.args.script!==(e.args.stage!==void 0))throw new b("--script and --stage go together","Pass the directory the reviewed property list is staged in");try{let t=e.args.host?Hb({budget:e.args.budget}):GK(e.config,e.args.socket);process.stdout.write(e.args.stage===void 0?t.plist:Fb({service:t,stage:e.args.stage}))}catch(t){if(t instanceof ya||t instanceof rs||t instanceof qr)throw new b(t.message);throw t}}});function GK(e,t){let n=e.get("fleet");if(!n)throw new b("config.json names no fleet","Run hydra service print as the fleet's account, with its home");if(process.getuid?.()===HK)throw new b("A fleet's service never runs as root","Run hydra service print as the fleet's account, or pass --host");let r=rb();return Gb({account:r.name,accountHome:r.home,fleet:n.id,home:ee(e),socket:t})}var Up=P({name:"service",description:"Print the LaunchDaemons that run the host daemon and this fleet, or the root script that installs them",subcommands:[Yv]});var FK=K({group:{description:"With --script: the group that may run softnet, the fleet account's own group",type:"string"},integrity:{description:`The npm registry's sha512 integrity of ${Kr}@${tr}`,type:"string"},script:{default:!1,description:"Print the install script for root instead of the artefact list",type:"boolean"},stage:{description:"With --script: the directory holding the downloaded artefacts",type:"string"}}),Xv=P({name:"print",description:"Print the pinned artefacts to download, or with --script the install script for root",args:FK,run:async(e)=>{let t=UK(e.args.integrity);if(!e.args.script){if(e.args.stage!==void 0||e.args.group!==void 0)throw new b("--stage and --group go with --script","Add --script to print the install script");process.stdout.write(Ab(t));return}if(e.args.stage===void 0||e.args.group===void 0)throw new b("--script needs --stage and --group","Pass the directory the artefacts were downloaded to and the fleet account's group");process.stdout.write(jK(t,e.args.stage,e.args.group))}});function UK(e){let t=`Read it with npm view ${Kr}@${tr} dist.integrity`;if(e===void 0)throw new b("hydra toolchain print needs --integrity",t);try{return Tb(e)}catch(n){if(n instanceof ga)throw new b(`--integrity ${n.message}`,t);throw n}}function jK(e,t,n){try{return Cb({group:n,pins:e,stage:t})}catch(r){if(r instanceof Jr)throw new b(r.message);throw r}}var zv=P({name:"verify",description:"Check that every file and directory Hydra runs from is owned and writable only by root and matches its recorded checksum",json:!0,examples:["hydra toolchain verify","hydra toolchain verify --json"],run:async(e)=>{let{findings:t,lines:n,report:r}=await wa(),o={...r,findings:t,ok:r.installed&&t.length===0,prefix:er};if(!e.json&&r.installed)T.info(n.join(`
633
+ `));if(e.output.result(o),!r.installed)throw new b(`No toolchain is installed in ${er}`,"Install it with the script from hydra toolchain print --script");if(t.length>0)throw new b(Sa(t),"Fix each path above, then verify again")}});var jp=P({name:"toolchain",description:"Print the pinned host toolchain and its root install script, or verify the installed one",subcommands:[Xv,zv]});var BK=`Run each GitHub Actions job in a fresh guest on this machine. ${ye} <absolute path> (or ${et}) selects the state directory, ~/.hydra by default.`;function Qv(e,t){return Cu({name:"HYDRA",bin:ui,version:vn,description:BK,config:e,commands:[Ip,Fp,ld,bp,rp,ul,up,lp,Cp,jp,Up,Hp,td,Ap,Tp],interactive:{clearOnStart:t,exitLabel:"Exit",goodbyeMessage:"Heads down.",promptMessage:"What do you need?"}})}var VK="--",Zv="help",qK=new Set(["doctor","driver","host serve","host-budget print","toolchain"]),KK=new Set(["alerts test","guard check","host status","host-budget check","image list","legacy logs","legacy profile list","legacy status","migrate","service print"]),WK=3,JK={...He,home:Uu},YK={help:He.help,home:Uu,json:He.json},XK=/^(?:--json(?:=true)?|-[^-=]*j[^-=]*(?:=true)?)$/;function ek(e){let t=ok(e);return t?.command===Zv?t.restArgs[0]:t?.command}function tk(e){let t=ok(e);if(!t)return"write";let{command:n,flags:r,restArgs:o}=t;if(!n)return r.version||!r.interactive?"help":"write";if(n===Zv)return"help";let s=zK(n,o);if(s.some((i)=>qK.has(i)))return"diagnose";if(r.help)return"help";return s.some((i)=>KK.has(i))?"read":"write"}function nk({home:e,source:t},n,r){if(n==="help"||n==="diagnose")return;let o=Um(e,r);if(!o||t!=="default"||n!=="write")return o;throw new b(`This directory holds the Hydra home ${o}, but no home was selected, so this command would act on ${e}`,`Pass ${ye} <path> or set ${et} to choose ${o} or ${e}`)}function rk(e){let t=e.indexOf(VK);return(t<0?e:e.slice(0,t)).some((n)=>XK.test(n))}function ok(e){try{return _o([...e],JK,YK)}catch{return}}function zK(e,t){let n=[e,...t.slice(0,WK-1)];return n.map((r,o)=>n.slice(0,o+1).join(" "))}function QK(e,t){T.warn(p.yellow(`Ignoring ${t}: Hydra keeps its state in ${e}`),{output:process.stderr}),T.info(p.dim(`To manage that fleet, pass ${ye} ${t} or set ${et}=${t}`),{output:process.stderr})}async function ZK(e){let t=Fm(e,process.env),n=rE(ek(t.argv));if(n)throw n;let r=tk(t.argv),o=nk(t,r,process.cwd()),s=Oi(t.home);if(o)QK(t.home,o);let i=r==="read"||r==="write"?Pi(s):void 0;if(i)throw i;await Qv(s,o===void 0).main(t.argv)}var sk=process.argv.slice(2);ZK(sk).catch((e)=>{process.exit(It(e,{json:rk(sk)}))});