@r5n/hydra 0.13.0 → 1.0.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/README.md +54 -27
- package/THIRD_PARTY_NOTICES.md +30 -0
- package/dist/cli.js +493 -114
- package/package.json +5 -5
- package/schema.json +200 -10
package/dist/cli.js
CHANGED
|
@@ -1,106 +1,114 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
`),
|
|
5
|
-
`){if(
|
|
6
|
-
`){if(o&&
|
|
7
|
-
`)}var
|
|
3
|
+
var Y$=Object.create;var{getPrototypeOf:z$,defineProperty:fp,getOwnPropertyNames:X$}=Object;var mp=Object.prototype.hasOwnProperty;function Q$(e){return this[e]}var Z$,ev,gp=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var o=t?Z$??=new WeakMap:ev??=new WeakMap,s=o.get(e);if(s)return s}n=e!=null?Y$(z$(e)):{};let i=t||!e||!e.__esModule||!mp.call(e,"default")?fp(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let a of X$(e))if(!mp.call(i,a))fp(i,a,{get:Q$.bind(e,a),enumerable:!0})}if(r)o.set(e,i);return i};var tv=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Sc=tv(function(ej,Tp){var bc={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"},gv={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},hv={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?bc.up():"");if(e)t+=bc.left;return t}};Tp.exports={cursor:bc,scroll:gv,erase:hv,beep:"\x07"}});class mt extends Error{constructor(e="Operation cancelled"){super(e)}}class w extends Error{hint;exitCode;constructor(e,t,n=1){super(e);this.hint=t;this.exitCode=n}}import{styleText as yv}from"util";import{stdout as $c,stdin as Op}from"process";import*as en from"readline";import wv from"readline";var hp=(()=>{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}})(),yp=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,wp=(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 nv=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,rv=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,bp=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,ov=/\t{1,1000}/y,Sp=/[\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,sv=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,iv=/\p{M}+/gu,av={limit:1/0,ellipsis:""},Rp=(e,t={},n={})=>{let r=t.limit??1/0,o=t.ellipsis??"",s=t?.ellipsisWidth??(o?Rp(o,av,n).width:0),i=0,a=n.controlWidth??0,c=n.tabWidth??8,l=n.emojiWidth??2,u=2,d=n.regularWidth??1,p=n.wideWidth??2,m=[[sv,d],[nv,0],[rv,a],[ov,c],[Sp,l],[bp,p]],g=0,h=0,E=e.length,v=0,R=!1,_=E,T=Math.max(0,r-s),b=0,A=0,y=0,S=0;e:while(!0){if(A>b||h>=E&&h>g){let C=e.slice(b,A)||e.slice(g,h);v=0;for(let x of C.replaceAll(iv,"")){let L=x.codePointAt(0)||0;if(yp(L))S=2;else if(wp(L))S=p;else S=d;if(y+S>T)_=Math.min(_,Math.max(b,g)+v);if(y+S>r){R=!0;break e}v+=x.length,y+=S}b=A=0}if(h>=E)break e;for(let C=0,x=m.length;C<x;C++){let[L,V]=m[C];if(L.lastIndex=h,L.test(e)){if(v=L===bp?hp(e.slice(h,L.lastIndex)):L===Sp?1:L.lastIndex-h,S=v*V,y+S>T)_=Math.min(_,h+Math.floor((T-y)/V));if(y+S>r){R=!0;break e}y+=S,b=g,A=h,h=g=L.lastIndex;continue e}}h+=1}return{width:R?T:y,index:R?_:E,truncated:R,ellipsed:R&&r>=s}},$p=Rp;var cv={limit:1/0,ellipsis:"",ellipsisWidth:0},lv=(e,t={})=>$p(e,cv,t).width,Be=lv;var ts="\x1B",_p="\x9B",uv=39,yc="\x07",Ap="[",dv="]",Cp="m",wc=`${dv}8;;`,vp=new RegExp(`(?:\\${Ap}(?<code>\\d+)m|\\${wc}(?<uri>.*)${yc})`,"y"),Ep=(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},xp=(e)=>`${ts}${Ap}${e}${Cp}`,kp=(e)=>`${ts}${wc}${e}${yc}`,hc=(e,t,n)=>{let r=t[Symbol.iterator](),o=!1,s=!1,i=e.at(-1),a=i===void 0?0:Be(i),c=r.next(),l=r.next(),u=0;while(!c.done){let d=c.value,p=Be(d);if(a+p<=n)e[e.length-1]+=d;else e.push(d),a=0;if(d===ts||d===_p)o=!0,s=t.startsWith(wc,u+1);if(o){if(s){if(d===yc)o=!1,s=!1}else if(d===Cp)o=!1}else if(a+=p,a===n&&!l.done)e.push(""),a=0;c=l,l=r.next(),u+=d.length}if(i=e.at(-1),!a&&i!==void 0&&i.length&&e.length>1)e[e.length-2]+=e.pop()},pv=(e)=>{let t=e.split(" "),n=t.length;while(n){if(Be(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},fv=(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 p=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=Be(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=Be(p);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("");hc(a,p,t),c=Be(a.at(-1)??"");continue}if(c+m>t&&c&&m){if(n.wordWrap===!1&&c<t){hc(a,p,t),c=Be(a.at(-1)??"");continue}a.push(""),c=0}if(c+m>t&&n.wordWrap===!1){hc(a,p,t),c=Be(a.at(-1)??"");continue}a[a.length-1]+=p,c+=m}if(n.trim!==!1)a=a.map((d)=>pv(d));let l=a.join(`
|
|
4
|
+
`),u=!1;for(let d=0;d<l.length;d++){let p=l[d];if(r+=p,!u){if(u=p>="\uD800"&&p<="\uDBFF",u)continue}else u=!1;if(p===ts||p===_p){vp.lastIndex=d+1;let g=vp.exec(l)?.groups;if(g?.code!==void 0){let h=Number.parseFloat(g.code);o=h===uv?void 0:h}else if(g?.uri!==void 0)s=g.uri.length===0?void 0:g.uri}if(l[d+1]===`
|
|
5
|
+
`){if(s)r+=kp("");let m=o?Ep(o):void 0;if(o&&m)r+=xp(m)}else if(p===`
|
|
6
|
+
`){if(o&&Ep(o))r+=xp(o);if(s)r+=kp(s)}}return r},mv=/\r?\n/;function kt(e,t,n){return String(e).normalize().split(mv).map((r)=>fv(r,t,n)).join(`
|
|
7
|
+
`)}var De=gp(Sc(),1);import{ReadStream as Pp}from"tty";function Tn(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?Tn(s,t<0?-1:1,n):s}var bv=["up","down","left","right","space","enter","cancel"],Sv=["January","February","March","April","May","June","July","August","September","October","November","December"],Oe={actions:new Set(bv),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:[...Sv],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 vc(e,t){if(typeof e=="string")return Oe.aliases.get(e)===t;for(let n of e)if(n!==void 0&&vc(n,t))return!0;return!1}function Rv(e,t){if(e===t)return;let n=e.split(`
|
|
8
8
|
`),r=t.split(`
|
|
9
|
-
`),o=Math.max(n.length,r.length),
|
|
10
|
-
`).map((c,
|
|
11
|
-
`)}function
|
|
12
|
-
`),
|
|
13
|
-
`).length-1;this.output.write(
|
|
14
|
-
`);this.output.write(s
|
|
15
|
-
`).slice(
|
|
16
|
-
`)),this._prevFrame=e;return}}this.output.write(
|
|
17
|
-
`);
|
|
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"&<(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",_)}
|
|
9
|
+
`),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 $v=globalThis.process.platform.startsWith("win"),Rc=Symbol("clack:cancel");function eo(e){return e===Rc}function ns(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Ip({input:e=Op,output:t=$c,overwrite:n=!0,hideCursor:r=!0}={}){let o=en.createInterface({input:e,output:t,prompt:"",tabSize:1});en.emitKeypressEvents(e,o),e instanceof Pp&&e.isTTY&&e.setRawMode(!0);let s=(i,{name:a,sequence:c})=>{let l=String(i);if(vc([l,a,c],"cancel")){r&&t.write(De.cursor.show),process.exit(0);return}if(!n)return;en.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{en.clearLine(t,1,()=>{e.once("keypress",s)})})};return r&&t.write(De.cursor.hide),e.once("keypress",s),()=>{e.off("keypress",s),r&&t.write(De.cursor.show),e instanceof Pp&&e.isTTY&&!$v&&e.setRawMode(!1),o.terminal=!1,o.close()}}var to=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Ec=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function tn(e,t,n,r=n,o=n,s){let i=to(e??$c);return kt(t,i-n.length,{hard:!0,trim:!1}).split(`
|
|
10
|
+
`).map((a,c,l)=>{let u=s?s(a,c):a;return c===0?`${r}${u}`:c===l.length-1?`${o}${u}`:`${n}${u}`}).join(`
|
|
11
|
+
`)}function Np(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 no{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=Op,output:r=$c,render:o,signal:s,...i}=e;this.opts=i,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=s,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(Rc);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=wv.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),ns(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(De.cursor.show),this.output.off("resize",this.render),ns(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(De.cursor.show),this.output.off("resize",this.render),ns(this.input,!1),e(Rc)})})}_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&&Oe.aliases.has(t.name)&&this.emit("cursor",Oe.aliases.get(t.name)),Oe.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=Np(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")}vc([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
|
+
`),ns(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=kt(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
13
|
+
`).length-1;this.output.write(De.cursor.move(-999,e*-1))}render(){let e=kt(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(De.cursor.hide);else{let t=Rv(this._prevFrame,e),n=Ec(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),o=Math.max(0,t.numLinesBefore-n),s=t.lines.find((i)=>i>=r);if(s===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(De.cursor.move(0,s-o)),this.output.write(De.erase.lines(1));let i=e.split(`
|
|
14
|
+
`);this.output.write(i[s]),this._prevFrame=e,this.output.write(De.cursor.move(0,i.length-s-1));return}else if(t.lines.length>1){if(r<o)s=r;else{let a=s-o;a>0&&this.output.write(De.cursor.move(0,a))}this.output.write(De.erase.down());let i=e.split(`
|
|
15
|
+
`).slice(s);this.output.write(i.join(`
|
|
16
|
+
`)),this._prevFrame=e;return}}this.output.write(De.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}class xc extends no{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(De.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class kc extends no{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?Tn(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=Tn(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Tn(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Dp=class extends no{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?Tn(r,1,this.options):r,this.changeValue(),this.on("cursor",(o)=>{switch(o){case"left":case"up":this.cursor=Tn(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Tn(this.cursor,1,this.options);break}this.changeValue()})}};class _c extends no{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}${yv("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 O,stripVTControlCharacters as hj}from"util";import st from"process";var oo=gp(Sc(),1);function vv(){if(st.platform!=="win32")return st.env.TERM!=="linux";return Boolean(st.env.CI)||Boolean(st.env.WT_SESSION)||Boolean(st.env.TERMINUS_SUBLIME)||st.env.ConEmuTask==="{cmd::Cmder}"||st.env.TERM_PROGRAM==="Terminus-Sublime"||st.env.TERM_PROGRAM==="vscode"||st.env.TERM==="xterm-256color"||st.env.TERM==="alacritty"||st.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Ac=vv(),Ev=()=>process.env.CI==="true";var de=(e,t)=>Ac?e:t,xv=de("\u25C6","*"),Fp=de("\u25A0","x"),Up=de("\u25B2","x"),ss=de("\u25C7","o"),kv=de("\u250C","T"),re=de("\u2502","|"),nn=de("\u2514","\u2014"),Sj=de("\u2510","T"),Rj=de("\u2518","\u2014"),Cc=de("\u25CF",">"),os=de("\u25CB"," "),_v=de("\u25FB","[\u2022]"),Lp=de("\u25FC","[+]"),Hp=de("\u25FB","[ ]"),$j=de("\u25AA","\u2022"),Mp=de("\u2500","-"),Av=de("\u256E","+"),Cv=de("\u251C","+"),Tv=de("\u256F","+"),Pv=de("\u2570","+"),vj=de("\u256D","+"),Ov=de("\u25CF","\u2022"),Iv=de("\u25C6","*"),Nv=de("\u25B2","!"),Dv=de("\u25A0","x"),is=(e)=>{switch(e){case"initial":case"active":return O("cyan",xv);case"cancel":return O("red",Fp);case"error":return O("yellow",Up);case"submit":return O("green",ss)}},Bp=(e)=>{switch(e){case"initial":case"active":return O("cyan",re);case"cancel":return O("red",re);case"error":return O("yellow",re);case"submit":return O("green",re)}};function jp(e,t){let n=[`${t?`${O("cyan",re)} `:""}${e.join(" \u2022 ")}`];return t&&n.push(O("cyan",nn)),n}var Gp=(e,t,n,r,o,s=!1)=>{let i=t,a=0;if(s)for(let c=r-1;c>=n;c--){let l=e[c];if(l&&(i-=l.length),a++,i<=o)break}else for(let c=n;c<r;c++){let l=e[c];if(l&&(i-=l.length),a++,i<=o)break}return{lineCount:i,removals:a}},Tc=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:o=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:i=4})=>{let a=to(r)-s,c=Ec(r),l=O("dim","..."),u=Math.max(c-i,0),d=Math.max(Math.min(o,u),5),p=0;e>=d-3&&(p=Math.max(Math.min(e-d+3,t.length-d),0));let m=d<t.length&&p>0,g=d<t.length&&p+d<t.length,h=Math.min(p+d,t.length),E=[],v=0;m&&v++,g&&v++;let R=p+(m?1:0),_=h-(g?1:0);for(let b=R;b<_;b++){let A=t[b],y=A?n(A,b===e):"",S=kt(y,a,{hard:!0,trim:!1}).split(`
|
|
17
|
+
`);E.push(S),v+=S.length}if(v>u){let b=0,A=0,y=v,S=e-R,C=u,x=()=>Gp(E,y,0,S,C),L=()=>Gp(E,y,S+1,E.length,C,!0);m?({lineCount:y,removals:b}=x(),y>C&&(g||(C-=1),{lineCount:y,removals:A}=L())):(g||(C-=1),{lineCount:y,removals:A}=L(),y>C&&(C-=1,{lineCount:y,removals:b}=x())),b>0&&(m=!0,E.splice(0,b)),A>0&&(g=!0,E.splice(E.length-A,A))}let T=[];m&&T.push(l);for(let b of E)for(let A of b)T.push(A);return g&&T.push(l),T};var Vp=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new xc({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??Oe.withGuide,o=`${is(this.state)} `,s=r?`${O("gray",re)} `:"",i=tn(e.output,e.message,s,o),a=`${r?`${O("gray",re)}
|
|
28
18
|
`:""}${i}
|
|
29
|
-
`,c=this.value
|
|
30
|
-
${
|
|
31
|
-
|
|
32
|
-
`),
|
|
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(`
|
|
44
|
-
`)}
|
|
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)}
|
|
19
|
+
`,c=this.value?t:n;switch(this.state){case"submit":{let l=r?`${O("gray",re)} `:"";return`${a}${l}${O("dim",c)}`}case"cancel":{let l=r?`${O("gray",re)} `:"";return`${a}${l}${O(["strikethrough","dim"],c)}${r?`
|
|
20
|
+
${O("gray",re)}`:""}`}default:{let l=r?`${O("cyan",re)} `:"",u=r?O("cyan",nn):"";return`${a}${l}${this.value?`${O("green",Cc)} ${t}`:`${O("dim",os)} ${O("dim",t)}`}${e.vertical?r?`
|
|
21
|
+
${O("cyan",re)} `:`
|
|
22
|
+
`:` ${O("dim","/")} `}${this.value?`${O("dim",os)} ${O("dim",n)}`:`${O("green",Cc)} ${n}`}
|
|
54
23
|
${u}
|
|
55
|
-
|
|
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(`
|
|
62
|
-
`)?e.split(`
|
|
24
|
+
`}}}}).prompt()};var as=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"&&eo(i)){n[o]="canceled",t.onCancel({results:n});continue}n[o]=i}return n},Lv=[`${O("dim","\u2191/\u2193")} to navigate`,`${O("dim","Space:")} select`,`${O("dim","Enter:")} confirm`],ro=(e,t)=>e.split(`
|
|
63
25
|
`).map((n)=>t(n)).join(`
|
|
64
|
-
`)
|
|
26
|
+
`),Kp=(e)=>{let t=(o,s)=>{let i=o.label??String(o.value);return s==="disabled"?`${O("gray",Hp)} ${ro(i,(a)=>O(["strikethrough","gray"],a))}${o.hint?` ${O("dim",`(${o.hint??"disabled"})`)}`:""}`:s==="active"?`${O("cyan",_v)} ${i}${o.hint?` ${O("dim",`(${o.hint})`)}`:""}`:s==="selected"?`${O("green",Lp)} ${ro(i,(a)=>O("dim",a))}${o.hint?` ${O("dim",`(${o.hint})`)}`:""}`:s==="cancelled"?`${ro(i,(a)=>O(["strikethrough","dim"],a))}`:s==="active-selected"?`${O("green",Lp)} ${i}${o.hint?` ${O("dim",`(${o.hint})`)}`:""}`:s==="submitted"?`${ro(i,(a)=>O("dim",a))}`:`${O("dim",Hp)} ${ro(i,(a)=>O("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new kc({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
|
+
${O("reset",O("dim",`Press ${O(["gray","bgWhite","inverse"]," space ")} to select, ${O("gray",O("bgWhite",O("inverse"," enter ")))} to submit`))}`},render(){let o=e.withGuide??Oe.withGuide,s=tn(e.output,e.message,o?`${Bp(this.state)} `:"",`${is(this.state)} `),i=`${o?`${O("gray",re)}
|
|
65
28
|
`:""}${s}
|
|
66
|
-
|
|
67
|
-
${
|
|
68
|
-
`).
|
|
69
|
-
`),
|
|
70
|
-
|
|
29
|
+
`,a=this.value??[],c=(l,u)=>{if(l.disabled)return t(l,"disabled");let d=a.includes(l.value);return u&&d?t(l,"active-selected"):d?t(l,"selected"):t(l,u?"active":"inactive")};switch(this.state){case"submit":{let l=this.options.filter(({value:d})=>a.includes(d)).map((d)=>t(d,"submitted")).join(O("dim",", "))||O("dim","none"),u=tn(e.output,l,o?`${O("gray",re)} `:"");return`${i}${u}`}case"cancel":{let l=this.options.filter(({value:d})=>a.includes(d)).map((d)=>t(d,"cancelled")).join(O("dim",", "));if(l.trim()==="")return`${i}${O("gray",re)}`;let u=tn(e.output,l,o?`${O("gray",re)} `:"");return`${i}${u}${o?`
|
|
30
|
+
${O("gray",re)}`:""}`}case"error":{let l=o?`${O("yellow",re)} `:"",u=this.error.split(`
|
|
31
|
+
`).map((m,g)=>g===0?`${o?`${O("yellow",nn)} `:""}${O("yellow",m)}`:` ${m}`).join(`
|
|
32
|
+
`),d=i.split(`
|
|
33
|
+
`).length,p=u.split(`
|
|
34
|
+
`).length+1;return`${i}${l}${Tc({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:l.length,rowPadding:d+p,style:c}).join(`
|
|
35
|
+
${l}`)}
|
|
36
|
+
${u}
|
|
37
|
+
`}default:{let l=o?`${O("cyan",re)} `:"",u=i.split(`
|
|
38
|
+
`).length,d=r?jp(Lv,o):o?[O("cyan",nn)]:[],p=d.join(`
|
|
39
|
+
`),m=d.length+1;return`${i}${l}${Tc({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:l.length,rowPadding:u+m,style:c}).join(`
|
|
40
|
+
${l}`)}
|
|
71
41
|
${p}
|
|
72
|
-
`}}}}).prompt()};var
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
`
|
|
81
|
-
`).
|
|
82
|
-
`)
|
|
83
|
-
|
|
84
|
-
|
|
42
|
+
`}}}}).prompt()};var k={message:(e=[],{symbol:t=O("gray",re),secondarySymbol:n=O("gray",re),output:r=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??Oe.withGuide,c=a?n:"",l=a?`${t} `:"",u=a?`${n} `:"";for(let p=0;p<o;p++)i.push(c);let d=Array.isArray(e)?e:e.split(`
|
|
43
|
+
`);if(d.length>0){let[p,...m]=d;p.length>0?i.push(`${l}${p}`):i.push(a?t:"");for(let g of m)g.length>0?i.push(`${u}${g}`):i.push(a?n:"")}r.write(`${i.join(`
|
|
44
|
+
`)}
|
|
45
|
+
`)},info:(e,t)=>{k.message(e,{...t,symbol:O("blue",Ov)})},success:(e,t)=>{k.message(e,{...t,symbol:O("green",Iv)})},step:(e,t)=>{k.message(e,{...t,symbol:O("green",ss)})},warn:(e,t)=>{k.message(e,{...t,symbol:O("yellow",Nv)})},warning:(e,t)=>{k.warn(e,t)},error:(e,t)=>{k.message(e,{...t,symbol:O("red",Dv)})}};var cs=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??Oe.withGuide?`${O("gray",kv)} `:"";n.write(`${r}${e}
|
|
46
|
+
`)},ls=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??Oe.withGuide?`${O("gray",re)}
|
|
47
|
+
${O("gray",nn)} `:"";n.write(`${r}${e}
|
|
48
|
+
|
|
49
|
+
`)};var Hv=(e)=>e,Mv=(e,t,n)=>{let r={hard:!0,trim:!1},o=kt(e,t,r).split(`
|
|
50
|
+
`),s=o.reduce((c,l)=>Math.max(Be(l),c),0),i=o.map(n).reduce((c,l)=>Math.max(Be(l),c),0),a=t-(i-s);return kt(e,a,r)},ir=(e="",t="",n)=>{let r=n?.output??st.stdout,o=n?.withGuide??Oe.withGuide,s=n?.format??Hv,i=["",...Mv(e,to(r)-6,s).split(`
|
|
51
|
+
`).map(s),""],a=Be(t),c=Math.max(i.reduce((p,m)=>{let g=Be(m);return g>p?g:p},0),a)+2,l=i.map((p)=>`${O("gray",re)} ${p}${" ".repeat(c-Be(p))}${O("gray",re)}`).join(`
|
|
52
|
+
`),u=o?`${O("gray",re)}
|
|
53
|
+
`:"",d=o?Cv:Pv;r.write(`${u}${O("green",ss)} ${O("reset",t)} ${O("gray",Mp.repeat(Math.max(c-a-1,1))+Av)}
|
|
54
|
+
${l}
|
|
55
|
+
${O("gray",d+Mp.repeat(c+2)+Tv)}
|
|
56
|
+
`)};var Gv=(e)=>O("magenta",e),ze=({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:o,frames:s=Ac?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=Ac?80:120,signal:a,...c}={})=>{let l=Ev(),u,d,p=!1,m=!1,g="",h,E=performance.now(),v=to(n),R=c?.styleFrame??Gv,_=(W)=>{let pe=W>1?o??Oe.messages.error:r??Oe.messages.cancel;m=W===1,p&&(K(pe,W),m&&typeof t=="function"&&t())},T=()=>_(2),b=()=>_(1),A=()=>{process.on("uncaughtExceptionMonitor",T),process.on("unhandledRejection",T),process.on("SIGINT",b),process.on("SIGTERM",b),process.on("exit",_),a&&a.addEventListener("abort",b)},y=()=>{process.removeListener("uncaughtExceptionMonitor",T),process.removeListener("unhandledRejection",T),process.removeListener("SIGINT",b),process.removeListener("SIGTERM",b),process.removeListener("exit",_),a&&a.removeEventListener("abort",b)},S=()=>{if(h===void 0)return;l&&n.write(`
|
|
57
|
+
`);let W=kt(h,v,{hard:!0,trim:!1}).split(`
|
|
58
|
+
`);W.length>1&&n.write(oo.cursor.up(W.length-1)),n.write(oo.cursor.to(0)),n.write(oo.erase.down())},C=(W)=>W.replace(/\.+$/,""),x=(W)=>{let pe=(performance.now()-W)/1000,D=Math.floor(pe/60),U=Math.floor(pe%60);return D>0?`[${D}m ${U}s]`:`[${U}s]`},L=c.withGuide??Oe.withGuide,V=(W="")=>{p=!0,u=Ip({output:n}),g=C(W),E=performance.now(),L&&n.write(`${O("gray",re)}
|
|
59
|
+
`);let pe=0,D=0;A(),d=setInterval(()=>{if(l&&g===h)return;S(),h=g;let U=R(s[pe]),te;if(l)te=`${U} ${g}...`;else if(e==="timer")te=`${U} ${g} ${x(E)}`;else{let xe=".".repeat(Math.floor(D)).slice(0,3);te=`${U} ${g}${xe}`}let ye=kt(te,v,{hard:!0,trim:!1});n.write(ye),pe=pe+1<s.length?pe+1:0,D=D<4?D+0.125:0},i)},K=(W="",pe=0,D=!1)=>{if(!p)return;p=!1,clearInterval(d),S();let U=pe===0?O("green",ss):pe===1?O("red",Fp):O("red",Up);g=W??g,D||(e==="timer"?n.write(`${U} ${g} ${x(E)}
|
|
60
|
+
`):n.write(`${U} ${g}
|
|
61
|
+
`)),y(),u()};return{start:V,stop:(W="")=>K(W,0),message:(W="")=>{g=C(W??g)},cancel:(W="")=>K(W,1),error:(W="")=>K(W,2),clear:()=>K("",0,!0),get isCancelled(){return m}}},Ej={light:de("\u2500","-"),heavy:de("\u2501","="),block:de("\u2588","#")};var Fv=[`${O("dim","\u2191/\u2193")} to navigate`,`${O("dim","Enter:")} confirm`],rs=(e,t)=>e.includes(`
|
|
62
|
+
`)?e.split(`
|
|
63
|
+
`).map((n)=>t(n)).join(`
|
|
64
|
+
`):t(e),qp=(e)=>{let t=(r,o)=>{if(r===void 0)return"";let s=r.label??String(r.value);switch(o){case"disabled":return`${O("gray",os)} ${rs(s,(i)=>O("gray",i))}${r.hint?` ${O("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${rs(s,(i)=>O("dim",i))}`;case"active":return`${O("green",Cc)} ${s}${r.hint?` ${O("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${rs(s,(i)=>O(["strikethrough","dim"],i))}`;default:return`${O("dim",os)} ${rs(s,(i)=>O("dim",i))}`}},n=e.showInstructions??!0;return new Dp({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??Oe.withGuide,o=`${is(this.state)} `,s=`${Bp(this.state)} `,i=tn(e.output,e.message,s,o),a=`${r?`${O("gray",re)}
|
|
65
|
+
`:""}${i}
|
|
66
|
+
`;switch(this.state){case"submit":{let c=r?`${O("gray",re)} `:"",l=tn(e.output,t(this.options[this.cursor],"selected"),c);return`${a}${l}`}case"cancel":{let c=r?`${O("gray",re)} `:"",l=tn(e.output,t(this.options[this.cursor],"cancelled"),c);return`${a}${l}${r?`
|
|
67
|
+
${O("gray",re)}`:""}`}default:{let c=r?`${O("cyan",re)} `:"",l=a.split(`
|
|
68
|
+
`).length,u=n?jp(Fv,r):r?[O("cyan",nn)]:[],d=u.join(`
|
|
69
|
+
`),p=u.length+1;return`${a}${c}${Tc({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:c.length,rowPadding:l+p,style:(m,g)=>t(m,m.disabled?"disabled":g?"active":"inactive")}).join(`
|
|
70
|
+
${c}`)}
|
|
71
|
+
${d}
|
|
72
|
+
`}}}}).prompt()};var xj=`${O("gray",re)} `;var Wp=(e)=>new _c({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??Oe.withGuide,n=`${`${t?`${O("gray",re)}
|
|
73
|
+
`:""}${is(this.state)} `}${e.message}
|
|
74
|
+
`,r=e.placeholder&&e.placeholder.length>0?O("inverse",e.placeholder[0])+O("dim",e.placeholder.slice(1)):O(["inverse","hidden"],"_"),o=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"error":{let i=this.error?` ${O("yellow",this.error)}`:"",a=t?`${O("yellow",re)} `:"",c=t?O("yellow",nn):"";return`${n.trim()}
|
|
75
|
+
${a}${o}
|
|
76
|
+
${c}${i}
|
|
77
|
+
`}case"submit":{let i=s?` ${O("dim",s)}`:"",a=t?O("gray",re):"";return`${n}${a}${i}`}case"cancel":{let i=s?` ${O(["strikethrough","dim"],s)}`:"",a=t?O("gray",re):"";return`${n}${a}${i}${s.trim()?`
|
|
78
|
+
${a}`:""}`}default:{let i=t?`${O("cyan",re)} `:"",a=t?O("cyan",nn):"";return`${n}${i}${o}
|
|
79
|
+
${a}
|
|
80
|
+
`}}}}).prompt();var Bv=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),zp=["black","blue","cyan","gray","green","magenta","red","white","yellow"],jv=["bold","dim","italic","underline","reset"],Xp={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Vv={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"},Kv={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"},Jp={"\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 us(e){return(t)=>Bv?`${e}${t}${Xp.reset}`:t}function qv(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32&&n!==27)return!1}return!0}function Yp({bright:e=!1,color:t}){let n=Bun.color(t,"ansi"),r=typeof n==="string"&&n.length>0&&qv(n)?n:Vv[t];if(!r)return"";return e&&r in Jp?Jp[r]:r}var Wv=zp.reduce((e,t)=>{let n=Yp({color:t});if(n)e[t]=us(n);let r=Yp({bright:!0,color:t});if(r)e[`${t}Bright`]=us(r);return e},{}),Jv=jv.reduce((e,t)=>(e[t]=us(Xp[t]),e),{}),Yv=zp.reduce((e,t)=>{let n=Kv[t];if(n){let r=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;e[r]=us(n)}return e},{}),f={...Wv,...Jv,...Yv};function ds(e){if(eo(e))throw new mt;return e}function Xv(e){return e.map((t)=>t.key?`${f.bold(t.key)} ${f.dim(t.text)}`:f.dim(t.text)).join(f.dim(" \xB7 "))}function ps(e){k.info(Xv(e))}var fs={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 gt(e){return ps(fs.confirm),ds(await Vp(e))}async function Ft(e){return ps(fs.text),ds(await Wp(e))}async function Pn(e){return ps(fs.select),ds(await qp({showInstructions:!1,...e}))}async function On(e){return ps(fs.multiselect),ds(await Kp({showInstructions:!1,...e}))}var Qv=4;function ar(e,t=0){if(t>=Qv)return;let n=[...e instanceof AggregateError?e.errors:[],...e.cause!==void 0?[e.cause]:[]];for(let r of n){if(k.info(f.dim(`caused by: ${r instanceof Error?r.message:String(r)}`)),r instanceof w&&r.hint)k.info(f.dim(` ${r.hint}`));if(r instanceof Error)ar(r,t+1)}}function Pc(e){return e==null?[]:Array.isArray(e)?e:[e]}function Zv(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 so(e,t){e=e||[],t=t||{};var n,r,o,s,i,a={_:[]},c=0,l=0,u=0,d=e.length;let p=t.alias!==void 0,m=t.unknown!==void 0,g=t.default!==void 0;if(t.alias=t.alias||{},t.string=Pc(t.string),t.boolean=Pc(t.boolean),p)for(n in t.alias){r=t.alias[n]=Pc(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(l=r.length;l-- >0;)t.boolean.push(r[l])}for(c=t.string.length;c-- >0;){r=t.alias[t.string[c]]||[];for(l=r.length;l-- >0;)t.string.push(r[l])}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(l=0;l<o.length;l++)if(o.charCodeAt(l)!==45)break;if(l===0)a._.push(o);else if(o.substring(l,l+3)==="no-"){if(s=o.substring(l+3),m&&!~h.indexOf(s))return t.unknown(o);a[s]=!1}else{for(u=l+1;u<o.length;u++)if(o.charCodeAt(u)===61)break;s=o.substring(l,u),i=o.substring(++u)||(c+1===d||(""+e[c+1]).charCodeAt(0)===45||e[++c]),r=l===2?[s]:s;for(u=0;u<r.length;u++){if(s=r[u],m&&!~h.indexOf(s))return t.unknown("-".repeat(l)+s);Zv(a,s,u+1<r.length||i,t)}}}if(g){for(n in t.default)if(a[n]===void 0)a[n]=t.default[n]}if(p)for(n in a){r=t.alias[n]||[];while(r.length>0)a[r.shift()]=a[n]}return a}var Qp=1,eE=2;function cr(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Oc(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=cr(n);if(o!==n)t.alias[o]=n;if(r.default!==void 0)t.default[n]=r.default}return t}function ms(e,t){if(e in t)return`--${cr(e)}`;let n=Object.entries(t).find(([,r])=>r.alias===e)?.[0];if(n)return`--${cr(n)}`;return e.length===Qp?`-${e}`:`--${cr(e)}`}function M(e,t,n){let{alias:r}=Oc(t),o=Object.keys(e).find((s)=>!Object.hasOwn(t,s)&&!Object.hasOwn(r,s));if(o!==void 0)throw new w(`Unknown option: ${ms(o,t)}`,n)}function Zp(e,t){for(let[r,o]of Object.entries(e))if(Array.isArray(o))throw new w(`${ms(r,t)} can only be provided once`);let n={...e};for(let[r,o]of Object.entries(t)){if(o.type!=="number")continue;let s=e[r];if(s===void 0)continue;let i=Number(s);if(typeof s==="boolean"||typeof s==="string"&&s.trim().length===0||!Number.isFinite(i)){let a=ms(r,t);throw new w(`Invalid number for ${a}: "${s}"`,`Use ${a}=<number> with a finite numeric value`)}n[r]=i}return n}function io(e,t){let n=Oc(t);ef(e,n,t,!0);let r=so(e,n),o=r._[0],s=o?e.indexOf(o):-1,i=so(s>=0?e.slice(0,s):e,n),{_:a,...c}=i;M(c,t,"Place command options after the command name");let{_:l,...u}=r,d=Object.fromEntries(Object.entries(u).filter(([m])=>(m in t)||(m in n.alias))),p=Zp(d,t);return{command:o,flags:p,restArgs:s>=0?e.slice(s+1):[]}}function Ic(e,t={}){let n=Oc(t),r=tE(e,n);ef(r,n,t);let o=so(r,n),{_:s,...i}=o;return{args:Zp(i,t),rawPositionals:s}}function ef(e,t,n,r=!1){let o=new Set;for(let s of e){if(s==="--")break;let i=s.match(/^-+/)?.[0];if(!i)continue;let a=s.slice(i.length),c=a.split("=",Qp)[0]??"",l=a.startsWith("no-")?[a.slice(3)]:i.length===eE?[c]:[...c];for(let u of l){let d=Object.hasOwn(t.alias,u)?t.alias[u]??u:u;if(r&&!Object.hasOwn(n,d))continue;if(o.has(d))throw new w(`${ms(d,n)} can only be provided once`);o.add(d)}}}function tE(e,t){let n=!0;return e.map((r)=>{if(r==="--")n=!1;if(!n)return r;return r.replace(/^--(no-[^=]+)(=.*)?$/,(o,s,i)=>{let a=t.alias[s];return a&&t.boolean.includes(a)?`--${a}${i??""}`:o})})}function Nc(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 tf(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 nE=(e)=>e,ne={arg:f.magenta,cmd:f.cyan,default:f.bold,desc:nE,flag:f.green,header:(e)=>f.bold(f.yellow(e)),hint:f.dim,name:(e)=>f.bold(f.cyan(e)),placeholder:f.magenta};class Dc{metadata;commands;globalArgs;constructor(e,t,n){this.metadata=e;this.commands=t;this.globalArgs=n}version(){return`${ne.name(this.metadata.name)} ${ne.hint(this.metadata.version??"0.0.0")}`}global(){let e=[],{name:t,bin:n,version:r,description:o}=this.metadata;if(e.push(`${ne.name(t)}${r?` ${ne.hint(`v${r}`)}`:""}`),o)e.push(ne.desc(o));e.push(""),e.push(ne.header("Usage:")),e.push(` ${ne.cmd(n)} ${ne.placeholder("[command]")} ${ne.placeholder("[options]")}`),e.push(""),e.push(ne.header("Commands:"));let s=Array.from(this.commands.values()).map((i)=>[` ${ne.cmd(i.name)}`,ne.desc(i.description)]);return e.push(...this.formatColumns(s)),e.push(""),e.push(ne.header("Options:")),e.push(...this.formatArgDefs(this.globalArgs)),e.push(""),e.push(`${ne.hint("Run")} ${ne.cmd(`${n} <command> --help`)} ${ne.hint("for command details.")}`),e.join(`
|
|
81
|
+
`).trimEnd()}command(e,t){let n=[],r=t??this.metadata.bin,o=`${r} ${e.name}`,s=`${ne.cmd(r)} ${ne.cmd(e.name)}`;n.push(ne.name(o)),n.push(ne.desc(e.description)),n.push(""),n.push(ne.header("Usage:"));let i=this.formatPositionalUsage(e.positionals);if(e.hasSubcommands())n.push(` ${s} ${ne.placeholder("<subcommand>")} ${ne.placeholder("[options]")}`);else{let l=[s];if(i)l.push(i);l.push(ne.placeholder("[options]")),n.push(` ${l.join(" ")}`)}if(e.prompts&&Object.keys(e.positionals).length>0)n.push(` ${ne.hint("Omit positional arguments to run interactively.")}`);if(n.push(""),e.hasSubcommands()){n.push(ne.header("Subcommands:"));let l=e.getSubcommands().map((u)=>[` ${ne.cmd(u.name)}`,ne.desc(u.description)]);n.push(...this.formatColumns(l)),n.push("")}if(Object.entries(e.positionals).length>0)n.push(ne.header("Arguments:")),n.push(...this.formatPositionalDefs(e.positionals)),n.push("");if(Object.entries(e.args).length>0)n.push(ne.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?ne.arg(`<${r}>`):ne.arg(`[${r}]`)}).join(" ")}formatPositionalDefs(e){let t=Object.entries(e).map(([n,r])=>{let o=r.variadic?`${n}...`:n,s=ne.desc(r.description??""),i=r.required?"":ne.hint(" (optional)");return[` ${ne.arg(o)}`,`${s}${i}`]});return this.formatColumns(t)}formatArgDefs(e){let t=[];for(let[n,r]of Object.entries(e)){let o=r.alias?`${ne.flag(`-${r.alias}`)}, `:" ",s=r.type==="boolean"?"":` ${ne.placeholder(`<${r.type==="number"?"number":"value"}>`)}`,i=`${o}${ne.flag(`--${cr(n)}`)}${s}`,a=ne.desc(r.description??""),c=this.formatDefault(r),l=c===void 0?"":` (default: ${ne.default(c)})`;t.push([` ${i}`,`${a}${l}`])}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 s=t-this.stripAnsi(r).length+n;return`${r}${" ".repeat(s)}${o}`})}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}}var Ut=new Uint32Array(65536),rE=(e,t)=>{let n=e.length,r=t.length,o=1<<n-1,s=-1,i=0,a=n,c=n;while(c--)Ut[e.charCodeAt(c)]|=1<<c;for(c=0;c<r;c++){let l=Ut[t.charCodeAt(c)],u=l|i;if(l|=(l&s)+s^s,i|=~(l|s),s&=l,i&o)a++;if(s&o)a--;i=i<<1|1,s=s<<1|~(u|i),i&=u}c=n;while(c--)Ut[e.charCodeAt(c)]=0;return a},oE=(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 R=E;R<v;R++)Ut[e.charCodeAt(R)]|=1<<R;for(let R=0;R<n;R++){let _=Ut[t.charCodeAt(R)],T=s[R/32|0]>>>R&1,b=o[R/32|0]>>>R&1,A=_|g,y=((_|b)&h)+h^h|_|b,S=g|~(y|h),C=h&y;if(S>>>31^T)s[R/32|0]^=1<<R;if(C>>>31^b)o[R/32|0]^=1<<R;S=S<<1|T,C=C<<1|b,h=C|~(A|S),g=S&A}for(let R=E;R<v;R++)Ut[e.charCodeAt(R)]=0}let l=0,u=-1,d=c*32,p=Math.min(32,r-d)+d;for(let g=d;g<p;g++)Ut[e.charCodeAt(g)]|=1<<g;let m=r;for(let g=0;g<n;g++){let h=Ut[t.charCodeAt(g)],E=s[g/32|0]>>>g&1,v=o[g/32|0]>>>g&1,R=h|l,_=((h|v)&u)+u^u|h|v,T=l|~(_|u),b=u&_;if(m+=T>>>r-1&1,m-=b>>>r-1&1,T>>>31^E)s[g/32|0]^=1<<g;if(b>>>31^v)o[g/32|0]^=1<<g;T=T<<1|E,b=b<<1|v,u=b|~(R|T),l=T&R}for(let g=d;g<p;g++)Ut[e.charCodeAt(g)]=0;return m},sE=(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 rE(e,t);return oE(e,t)},nf=(e,t)=>{let n=1/0,r=0;for(let o=0;o<t.length;o++){let s=sE(e,t[o]);if(s<n)n=s,r=o}return t[r]};function gs(e,t,n,r){let o=nf(t,n);if(console.error(f.red(`Unknown ${e}: ${t}`)),o)console.error(f.yellow(`Did you mean "${o}"?`));console.error(`
|
|
83
|
+
Run "${r} --help" for usage.`),process.exit(1)}function hs(e,t){if(Array.isArray(t))return[...t];if(!rf(e)||!rf(t))return t;return Object.fromEntries([...Object.entries(e),...Object.entries(t).map(([n,r])=>[n,hs(Object.hasOwn(e,n)?e[n]:void 0,r)])])}function rf(e){if(e===null||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var Lc="__exit__";class lr{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 w("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);gs("subcommand",e,t,this.commandPath)}async handleSubcommandRoute(e,t){await new lr(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}=Ic(e,this.command.args),o=Nc(r,this.command.positionals),s=tf(o,this.command.positionals);if(s)k.error(s),console.error(`
|
|
84
|
+
Run "${this.commandPath} --help" for usage.`),process.exit(1);let i=this.command.prompts&&r.length===0&&process.stdout.isTTY===!0,a=this.buildContext(o,n,i);await this.command.execute(a)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:e}=Ic([],this.command.args),t=Nc([],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===Lc){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 mt){if(this.options.isRoot)this.options.onExit?.();return null}throw e}}async executeSubcommand(e){try{await new lr(e,this.env,this.commandPath,{selections:this.selections}).route([],!0)}catch(t){if(t instanceof mt)return;if(t instanceof w){if(k.warn(f.yellow(t.message)),t.hint)k.info(f.dim(t.hint));ar(t);return}throw t}}promptSubcommandSelection(){let{isRoot:e}=this.options,t=e?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:Lc}:{hint:"Return to previous menu",label:"Back",value:Lc};return Pn({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 iE="--",of="--help",aE=new Set([of,"-h"]),cE={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"},Hc={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 Mc{commands=new Map;metadata;configManager;help;bin;globalArgs={...Hc};constructor(e,t){this.configManager=e,this.metadata={...cE,...t},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Dc({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}=io(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 lr(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(){ls(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 s={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new lr(r,s,this.bin).route(n?lE(t):t,!1)}catch(s){this.handleError(s)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let e=this.metadata.version?` v${this.metadata.version}`:"";cs(`${f.bgCyan(f.black(` ${this.metadata.name}${e} `))}`)}handleUnknownCommand(e){let t=Array.from(this.commands.keys());gs("command",e,t,this.bin)}handleError(e){if(this.metadata.onError?.(e))return;if(e instanceof mt)process.exit(0);if(e instanceof w){if(k.warn(f.yellow(e.message)),e.hint)k.info(f.dim(e.hint));ar(e),process.exit(e.exitCode)}if(e instanceof Error)k.error(f.red(e.message)),ar(e),process.exit(1);console.error(f.red("Error:"),e),process.exit(1)}}function lE(e){let t=e.indexOf(iE),n=t<0?e:e.slice(0,t);if(n.some((r)=>aE.has(r)))return e;return[...n,of,...t<0?[]:e.slice(t)]}class ao{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 q(e){return e}function le(e){return e}import it from"fs";import sf from"path";var Xe=(e)=>(e.map=(t)=>Xe((n)=>t(e(n))),e.or=(t)=>Xe((n)=>{try{return e(n)}catch(r){return t(n)}}),e),B=()=>"bad banditype"();var ur=()=>Xe((e)=>e),Y=(e)=>Xe((t)=>e.includes(t)?t:B()),ys=(e)=>Xe((t)=>typeof t===typeof e?t:B()),N=()=>ys(""),X=()=>ys(0),Z=()=>ys(!0);var oe=()=>ys(),ht=()=>Xe((e)=>e===null?e:B()),co=(e)=>Xe((t)=>t instanceof e?t:B()),dr=(e)=>co(Object).map((t)=>{let n={};for(let r in t){let o=e(t[r]);o!==void 0&&(n[r]=o)}return n}),H=(e)=>co(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 ee=(e)=>co(Array).map((t)=>t.map(e));function Fc(e,t){JSON.parse(e);let n=JSON.parse(JSON.stringify(t)),r=uE(e),o=e.match(/^[\t ]+(?=\S)/m)?.[0]??" ",s=e.includes(`\r
|
|
85
85
|
`)?`\r
|
|
86
86
|
`:`
|
|
87
|
-
`,
|
|
88
|
-
`));let
|
|
89
|
-
`));let
|
|
90
|
-
`)?
|
|
91
|
-
`))});return`${
|
|
92
|
-
`,
|
|
93
|
-
`,
|
|
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
|
-
${
|
|
87
|
+
`,i=/\s/.test(e[r.start+1]??"")||r.entries.some((l)=>/:\s+$/.test(e.slice(l.start,l.node.start)))?" ":"";function a(l,u){let d=e.slice(l.start,l.end);if(JSON.stringify(l.value)===JSON.stringify(u))return d;let p=Array.isArray(u);if(u===null||typeof u!=="object"||l.value===null||typeof l.value!=="object"||Array.isArray(l.value)!==p)return c(u,l.start,d.includes(`
|
|
88
|
+
`));let m=p?u.map((S,C)=>String(C)):[...new Set([...l.entries.map((S)=>S.key).filter((S)=>Object.hasOwn(u,S)),...Object.keys(u)])];if(m.length===0)return p?"[]":"{}";let g=l.entries[0],h=l.entries.at(-1);if(!g||!h)return c(u,l.start,d.includes(`
|
|
89
|
+
`));let E=(S)=>p?u[Number(S)]:u[S];if(m.length===l.entries.length&&m.every((S,C)=>S===l.entries[C]?.key)){let S=l.start,C="";for(let x of l.entries)C+=e.slice(S,x.node.start)+a(x.node,E(x.key)),S=x.node.end;return C+e.slice(S,l.end)}let v=e.slice(l.start+1,g.start),R=e.slice(h.node.end,l.end-1),_=l.entries[1],T=_?e.slice(g.node.end,_.start):`,${v.includes(`
|
|
90
|
+
`)?v:i}`,b=p?"":e.slice(g.start,g.node.start).match(/:\s*$/)?.[0]??": ",A=new Map(l.entries.map((S)=>[S.key,S])),y=m.map((S)=>{let C=A.get(S);if(C)return e.slice(C.start,C.node.start)+a(C.node,E(S));return(p?"":JSON.stringify(S)+b)+c(E(S),g.start,v.includes(`
|
|
91
|
+
`))});return`${p?"[":"{"}${v}${y.join(T)}${R}${p?"]":"}"}`}function c(l,u,d){if(!d)return Gc(l,i);let p=e.lastIndexOf(`
|
|
92
|
+
`,u-1)+1,m=e.slice(p,u).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(l,null,o).replaceAll(`
|
|
93
|
+
`,s+m)}return e.slice(0,r.start)+a(r,n)+e.slice(r.end)}function Gc(e,t){if(Array.isArray(e))return`[${e.map((o)=>Gc(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}${Gc(s,t)}`);return`{${t}${r.join(`,${t}`)}${t}}`}function uE(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 u=n.index,d=a?JSON.parse(r()[0]):String(i.length);if(a)r();if(i.push({key:d,node:o(),start:u}),n?.[0]===",")r()}let l=r().index+1;return{end:l,entries:i,start:s.index,value:JSON.parse(e.slice(s.index,l))}}return o()}var dE=2,pE=co(Object);class Uc{config;configPath;defaultConfig;loadError;loadFailure;constructor(e,t,n={}){this.configPath=sf.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 it.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()?it.realpathSync(this.configPath):this.configPath,n=`${t}.${crypto.randomUUID()}.tmp`;try{let r=this.exists()?it.statSync(this.configPath).mode:void 0,o=this.exists()?Fc(it.readFileSync(this.configPath,"utf-8"),this.config):`${JSON.stringify(this.config,null,dE)}
|
|
94
|
+
`;if(it.writeFileSync(n,o,{flag:"wx",mode:r}),r!==void 0)it.chmodSync(n,r);it.renameSync(n,t)}catch(r){throw Error(`Failed to save config to ${this.configPath}`,{cause:r})}finally{it.rmSync(n,{force:!0})}}assertLoaded(){if(this.loadFailure)throw this.loadFailure}ensureDirectoryExists(){let e=sf.dirname(this.configPath);if(!it.existsSync(e))try{it.mkdirSync(e,{recursive:!0})}catch(t){throw Error(`Failed to create config directory at ${e}`,{cause:t})}}loadConfig({parse:e,strict:t}){if(!t&&!it.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=hs(structuredClone(this.defaultConfig),pE(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 it.readFileSync(this.configPath,"utf-8")}catch(e){if(e.code==="ENOENT")return;throw e}}}var cf="@r5n/hydra";var rn="1.0.0";class I extends ao{}import{accessSync as Cx,constants as Tx,statSync as Px}from"fs";var fE=/[\p{Cc}\p{Cf}]+/gu,mE=/\s+/g;function lo(e){let t=e.argv.length-1;return`command ${e.argv[0]}${t>0?` with ${t} ${t===1?"argument":"arguments"}`:""}`}function lf(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:lo(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(p){let m=p.code??"unknown error";return{detail:`Cannot start ${r} (${m})`,outcome:"failed"}}let a=i.stderr.getReader(),c=gE(a),l=await i.exited,u=await Promise.race([c,Bun.sleep(1000).then(()=>{return})]);if(u===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(l===0)return{exitCode:l,outcome:"delivered"};let d=(u??"").replace(fE," ").replace(mE," ").trim().slice(0,200);return{detail:`${r} exited with ${l}${d?`: ${d}`:""}`,outcome:"failed"}},signature(){return JSON.stringify(e)}}}async function gE(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()}var on=["discord","command"];function ws(e){return on.includes(e)}function yt(e){return on.filter((t)=>e?.[t]!==void 0)}function In(e){return"webhookFile"in e}import{constants as Bc,lstatSync as uf}from"fs";import{open as hE}from"fs/promises";var yE=384,wE=511,bE=8,SE=4,jc=4096,RE=Bc.O_RDONLY|Bc.O_NOFOLLOW|Bc.O_NONBLOCK,$E=/\r?\n$/,vE=/[\r\n]/,df="Keep it as a regular file owned by the user running Hydra, with mode 0600";class Nn extends Error{_tag="SecretFileError";constructor(e,t,n){super(`The ${e} ${t} ${n}`);this.name="SecretFileError"}}function pf(e){try{return mf(uf(e))}catch(t){return`cannot be read (${t.code??"unknown error"})`}}function ff(e){try{let t=uf(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}catch{return"missing"}}async function Vc(e,t){let n;try{n=await hE(e,RE)}catch(r){let o=r.code;throw new Nn(t,e,o==="ELOOP"?"is a symbolic link":`cannot be opened (${o})`)}try{let r=mf(await n.stat());if(r)throw new Nn(t,e,r);let o=Buffer.alloc(jc+1),{bytesRead:s}=await n.read(o,0,o.length,0);if(s>jc)throw new Nn(t,e,`is longer than ${jc} bytes`);let i=o.subarray(0,s).toString("utf8").replace($E,"");if(i.trim().length===0||vE.test(i)||i!==i.trim())throw new Nn(t,e,"must hold one line with no surrounding spaces");return i}finally{await n.close()}}function mf(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&wE;if(n!==yE)return`has mode ${n.toString(bE).padStart(SE,"0")}, not 0600`;return}var Kc={"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"},bs={now:()=>Date.now(),sleep:(e)=>Bun.sleep(e)};function gf(e){return Object.hasOwn(Kc,e)}var EE="https://discord.com/api/v10",pr="HYDRA_DISCORD_API_URL",xE=new Set(["discord.com","discordapp.com","canary.discord.com","ptb.discord.com"]),kE=/^\/api(?:\/v\d+)?\/webhooks\/(\d{16,20})\/([A-Za-z0-9_-]{1,128})$/,_E=/^[A-Za-z0-9._-]{1,256}$/,AE=new Set(["127.0.0.1","[::1]"]),CE=/\/+$/,TE=15000,PE=3,OE=30000,IE=1,NE=1000,hf=429,DE=new Set([401,403,404]),LE={parse:[]},yf="```",HE=H({id:N()}),ME=H({retry_after:X().or(oe())});function Ss(e){let t=e[pr];if(!t)return EE;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 w(`${pr} is not a URL`,n)}if(!(r.protocol==="https:"||r.protocol==="http:"&&AE.has(r.hostname))||r.username||r.password||r.search||r.hash)throw new w(`${pr} is not an API root Hydra may send its Discord secrets to`,n);return r.href.replace(CE,"")}function GE(e){let t;try{t=new URL(e)}catch{return}if(t.protocol!=="https:"||!xE.has(t.hostname))return;if(t.port||t.username||t.password||t.search||t.hash)return;let n=t.pathname.match(kE);return n?{id:n[1],token:n[2]}:void 0}async function qc(e){if(In(e)){let n=GE(await Vc(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 Vc(e.botTokenFile,"Discord bot token file");if(!_E.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 uo(e){return In(e)?`Discord webhook from ${e.webhookFile}`:`Discord channel ${e.channelId} as the bot in ${e.botTokenFile}`}function bf(e,t){let n=t.clock??bs,r=0;function o(a){let c=a!==void 0&&Number.isFinite(a)&&a>=0?a:IE;r=Math.max(r,n.now()+c*NE)}function s(a){if(a.headers.get("x-ratelimit-remaining")!=="0")return;o(wf(a,"x-ratelimit-reset-after"))}async function i(a,c){try{return await fetch(`${t.apiUrl}${a.path}`,{body:JSON.stringify({allowed_mentions:LE,content:`${yf}
|
|
95
|
+
${c}
|
|
96
|
+
${yf}`}),headers:{...a.authorization?{Authorization:a.authorization}:{},"Content-Type":"application/json","User-Agent":t.userAgent},method:"POST",redirect:"manual",signal:AbortSignal.timeout(TE)})}catch(l){return{detail:`Discord did not answer (${l.code??l.name??"unknown error"})`,outcome:"failed"}}}return{describe:uo(e),name:"discord",async send(a){let c;try{c=await qc(e)}catch(l){return{detail:l.message,outcome:"failed"}}for(let l=1;l<=PE;l++){let u=r-n.now();if(u>OE)return{detail:"Discord asked Hydra to wait",outcome:"failed",retryAfterMs:u};if(u>0)await n.sleep(u);let d=await i(c,a);if(!(d instanceof Response))return d;if(s(d),d.ok)return{messageId:await UE(d),outcome:"delivered",status:d.status};if(d.status===hf){o(await BE(d)??wf(d,"retry-after"));continue}if(await d.body?.cancel(),DE.has(d.status))return{detail:`Discord refused the ${FE(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:hf}},signature(){return JSON.stringify([e,ff(In(e)?e.webhookFile:e.botTokenFile)])}}}function FE(e){return In(e)?"webhook":`bot token for channel ${e.channelId}`}function wf(e,t){let n=e.headers.get(t);return n===null||n.trim()===""?void 0:Number(n)}async function UE(e){try{return HE(await e.json()).id}catch{return}}async function BE(e){try{return ME(await e.json()).retry_after}catch{return}}function jE(e){return[e.pool??"",e.reason].join("/")}function Sf(e,t,n){let r=jE(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 Rf(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 $f(e,t){return e!==void 0&&t>=e.start+600000}function vf(e){return e!==void 0&&e.sent>=10}import{randomUUID as Tf}from"crypto";var Ef=1500,VE=64,KE=300,qE=/[^A-Za-z0-9._-]/g,WE=/^([A-Za-z0-9_.-]{1,100})\/([A-Za-z0-9_.-]{1,100})$/,JE=/[\p{Cc}\p{Cf}`]+/gu,YE=/\s+/g,xf="\u2026",zE=/\.\d{3}Z$/,XE="\x00",kf=" \xB7 ";function Rs(e,t){let n=[t.fleet?`fleet ${po(t.fleet)}`:"",e.pool?`pool ${po(e.pool)}`:"",e.slot?`slot ${po(e.slot)}`:""].filter(Boolean),r=[`[hydra] ${e.reason}: ${Kc[e.reason]}`,n.join(kf),e.repository?`repository ${QE(e.repository)}`:"",e.detail?`detail ${fo(e.detail)}`:"",t.count>1?`count ${t.count}${t.since?` since ${_t(t.since)}`:""}`:"",`time ${_t(t.at)}`];return Cf(r.filter(Boolean))}function _f(e,t){let n=e.reduce((s,i)=>s+i.count,0),r=[`[hydra] digest: ${n} ${n===1?"alert":"alerts"} held back from ${_t(t.from)} to ${_t(t.at)}`,t.fleet?`fleet ${po(t.fleet)}`:""].filter(Boolean),o=Wc(e).map((s)=>`${s.count} \xD7 ${s.reason}${s.pool?`${kf}pool ${po(s.pool)}`:""}`);return Cf([...r,...o,`time ${_t(t.at)}`])}function Wc(e){let t=new Map;for(let n of e){let r=`${n.reason}${XE}${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 _t(e){return new Date(e).toISOString().replace(zE,"Z")}function fo(e){return Af(e.replace(JE," ").replace(YE," ").trim(),KE)}function po(e){return Af(e.replace(qE,"_"),VE)}function QE(e){let t=e.match(WE);return t?`${t[1]}/${t[2]}`:"(not a repository name)"}function Af(e,t){return e.length<=t?e:`${e.slice(0,t-1)}${xf}`}function Cf(e){let t=[],n=0;for(let[r,o]of e.entries()){let s=e.length-r-1,i=`${xf} ${s+1} more ${s===0?"line":"lines"}`;if(n+o.length+1+(s>0?i.length+1:0)>Ef){t.push(i);break}t.push(o),n+=o.length+1}return t.join(`
|
|
97
|
+
`).slice(0,Ef)}var ZE=3600000,ex=100,tx=30000,nx=1800000;function rx(e){return Math.min(tx*2**Math.max(0,e-1),nx)}function Jc(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>=ZE)}function $s(e){let t=e.clock??bs,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)),R=Wc(h.flatMap((y)=>y.items)),_=h.findLast((y)=>y.error!==void 0)?.error,T={attempts:Math.max(...h.map((y)=>y.attempts)),createdAt:v,..._===void 0?{}:{error:_},id:Tf(),items:R,kind:"digest",nextAttemptAt:Math.max(E,...h.map((y)=>y.nextAttemptAt)),sink:g,text:_f(R,{at:E,fleet:e.fleet,from:v})},b=n.messages.indexOf(h[0]),A=n.messages.filter((y)=>!h.includes(y));return A.splice(Math.min(b,A.length),0,T),n.messages=A,T}function i({alert:g,count:h,since:E},v){let R=t.now(),_=Rs(g,{at:R,count:h,fleet:e.fleet,since:E}),T=g.pool?{count:h,pool:g.pool,reason:g.reason}:{count:h,reason:g.reason};for(let b of e.sinks){if(b.name===v)continue;let A=o(b.name);if(A.length>=ex)s(b.name,A);n.messages.push({attempts:0,createdAt:R,id:Tf(),items:[T],kind:"alert",nextAttemptAt:R,sink:b.name,text:_})}}function a(g,h){let E=Sf(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 l(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 R=n.windows[g.name]??{sent:0,start:v};return n.windows[g.name]={...R,sent:R.sent+1},r(),!0}case"failed":return h.attempts++,h.error=E.detail,h.nextAttemptAt=v+Math.max(rx(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 u(g,h){if(c(g))return;let E=()=>o(g.name).filter((b)=>b.held);if($f(n.windows[g.name],t.now()))s(g.name,E()),delete n.windows[g.name];let v=t.now(),R=o(g.name);if(R.some((b)=>b.attempts>0&&b.nextAttemptAt>v))return;let _=R.filter((b)=>!b.held&&b.nextAttemptAt<=v);for(let b of _){if(vf(n.windows[g.name])){b.held=!0;continue}if(!await l(g,b))return r()}r();let T=h?s(g.name,E()):void 0;if(T)await l(g,T)}function d(){let g=t.now(),h=e.sinks.map((E)=>E.name);for(let E of Jc(n,g,h)){let v=E.count===1?"1 alert":`${E.count} alerts`;a({detail:`${v} for the ${E.sink} sink, the oldest from ${_t(E.oldest)}`,reason:"alert-undelivered"},E.sink)}}async function p(g){for(let h of Rf(n.reasons,t.now()))i(h);r();for(let h of e.sinks)await u(h,g);d(),r()}let m;return{deliver({flush:g=!1}={}){return m??=p(g).finally(()=>{m=void 0}),m},raise(g){a(g),r()},snapshot:()=>structuredClone(n)}}var ox="https://www.npmjs.com/package/@r5n/hydra";function vs(e,t){let n=(o)=>t.only===void 0||t.only===o,r=[];if(e?.discord&&n("discord"))r.push(bf(e.discord,{apiUrl:Ss(t.env),clock:t.clock,userAgent:`DiscordBot (${ox}, ${t.version})`}));if(e?.command&&n("command"))r.push(lf(e.command,{home:t.env.HOME}));return r}import{mkdirSync as sx,readFileSync as ix,renameSync as ax,rmSync as cx,writeFileSync as lx}from"fs";import{join as If}from"path";var Nf="alerts",Df=1,ux="queue.json",dx=448,px=384,fr=()=>N().or(oe()),Es=()=>X().map((e)=>Number.isSafeInteger(e)&&e>=0?e:B()),Lf=N().map((e)=>gf(e)?e:B()),fx=Y(on),mx=H({count:Es(),pool:fr(),reason:Lf}),gx=H({detail:fr(),pool:fr(),reason:Lf,repository:fr(),slot:fr()}),hx=H({attempts:Es(),createdAt:X(),error:fr(),held:Z().or(oe()),id:N(),items:ee(mx),kind:Y(["alert","digest"]),nextAttemptAt:X(),sink:fx,text:N()}),yx=H({alert:gx,firstRepeatAt:X().or(oe()),repeats:Es(),sentAt:X()}),Pf=H({at:X(),detail:N(),signature:N(),status:X()}),Of=H({sent:Es(),start:X()}),wx=H({messages:ee(hx),reasons:dr(yx),stopped:H({command:Pf.or(oe()),discord:Pf.or(oe())}),version:Y([Df]),windows:H({command:Of.or(oe()),discord:Of.or(oe())})});function Hf(){return{messages:[],reasons:{},stopped:{},version:Df,windows:{}}}function bx(e){return If(e,Nf,ux)}function Mf(e=Hf()){let t=structuredClone(e);return{load:()=>structuredClone(t),save(n){t=structuredClone(n)}}}function xs(e){let t=bx(e);return{load(){let n;try{n=ix(t,"utf-8")}catch(r){if(r.code==="ENOENT")return Hf();throw Error(`Cannot read the alert queue ${t}`,{cause:r})}try{return wx(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){sx(If(e,Nf),{mode:dx,recursive:!0});let r=`${t}.${process.pid}.tmp`;try{lx(r,`${JSON.stringify(n)}
|
|
98
|
+
`,{flag:"wx",mode:px}),ax(r,t)}finally{cx(r,{force:!0})}}}}import{isAbsolute as Ff}from"path";function fe(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 se(e,t,n,r){if(e===void 0)throw Error(`${n} is missing; expected ${r}`);ae(e,t,n,r)}function ae(e,t,n,r){if(e===void 0)return;try{t(e)}catch{throw Error(`${n} must be ${r}`)}}var Sx=["command","discord"],Rx=["webhookFile"],$x=["botTokenFile","channelId"],vx=["argv"],Uf=32,Ex=1024,Bf=/[\p{Cc}\p{Cf}]/u,xx=/^[1-9]\d{15,19}$/,Gf=N().map((e)=>Ff(e)&&!Bf.test(e)?e:B()),kx=N().map((e)=>xx.test(e)?e:B()),_x=N().map((e)=>e.length<=Ex&&!Bf.test(e)?e:B()),Ax=ee(_x).map((e)=>e.length>0&&e.length<=Uf&&Ff(e[0])?e:B()),Yc=`a list of 1 to ${Uf} arguments without control characters, the first an absolute path to the program`;function jf(e){if(e===void 0)return;let t=fe(e,"alerts");if(_e(t,Sx,"alerts","alerts"),t.discord!==void 0)zc(t.discord);if(t.command!==void 0)Xc(t.command);let n=t;if(yt(n).length===0)throw Error("alerts must name at least one sink: discord or command");return n}function zc(e){let n=fe(e,"alerts.discord");if(n.webhookFile!==void 0)return _e(n,Rx,"alerts.discord","a Discord webhook sink, which takes no bot token or channel"),se(n.webhookFile,Gf,"alerts.discord.webhookFile","an absolute path"),n;if(_e(n,$x,"alerts.discord","a Discord sink"),n.botTokenFile===void 0)throw Error("alerts.discord needs webhookFile, or botTokenFile with channelId");return se(n.botTokenFile,Gf,"alerts.discord.botTokenFile","an absolute path"),se(n.channelId,kx,"alerts.discord.channelId","a Discord channel id, as a string of digits"),n}function Xc(e){let n=fe(e,"alerts.command");return _e(n,vx,"alerts.command","a command sink"),se(n.argv,Ax,"alerts.command.argv",Yc),n}var Vf=q({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"}}),Ox=le({sink:{description:"Sink to set: discord or command"}}),mo="Use --webhook-file <path>, or --bot-token-file <path> with --channel-id <id>",Qc=`Use --argv '["/usr/local/bin/notify", "--from", "hydra"]'`;class Zc extends I{name="set";description="Send alerts to Discord or to a fixed command";args=Vf;positionals=Ox;async execute(e){M(e.args,Vf,"Run 'hydra alerts set --help' for supported options");let t=e.positionals.sink;if(t===void 0||!ws(t))throw new w(`Unknown alert sink "${t??""}"`,`Choose one of: ${on.join(", ")}`);let n=e.config.get("alerts");if(t==="discord"){let o=await Ix(e.args);e.config.set("alerts",{...n,discord:o}),Kf(uo(o),t);return}let r=Nx(e.args);e.config.set("alerts",{...n,command:r}),Kf(lo(r),t)}}async function Ix(e){if(e.argv!==void 0)throw new w("--argv applies to the command sink",mo);let{botTokenFile:t,channelId:n,webhookFile:r}=e;if(r!==void 0&&(t!==void 0||n!==void 0))throw new w("Choose a webhook or a bot, not both",mo);if(r===void 0&&t===void 0)throw new w("Name a webhook or a bot",mo);let o;try{o=zc(r!==void 0?{webhookFile:r}:{botTokenFile:t,channelId:n})}catch(s){throw new w(s.message,mo)}try{await qc(o)}catch(s){throw new w(s.message,s instanceof Nn?df:mo)}return o}function Nx(e){let{argv:t,botTokenFile:n,channelId:r,webhookFile:o}=e;if(o!==void 0||n!==void 0||r!==void 0)throw new w("--webhook-file, --bot-token-file and --channel-id apply to the discord sink",Qc);if(t===void 0)throw new w("Name the command with --argv",Qc);let s;try{s=Xc({argv:JSON.parse(t)})}catch{throw new w(`--argv must be a JSON array: ${Yc}`,Qc)}let i=s.argv[0];try{if(Cx(i,Tx.X_OK),!Px(i).isFile())throw Error("not a file")}catch{throw new w(`${i} is not an executable file`,"Hydra runs the command directly, without a shell")}return s}function Kf(e,t){k.success([`Alerts go to the ${e}`,f.dim(`Run hydra alerts test --sink ${t} to send a test message`)].join(`
|
|
99
|
+
`))}var Dn="Run hydra alerts set discord --webhook-file <path>, or hydra alerts set command --argv <json>";function qf(e,{env:t,home:n,now:r,pools:o}){if(yt(e).length===0)return o?[`${f.bold("Alerts")} ${f.yellow("no sink")}`]:[];let s=[f.bold("Alerts")];if(e?.discord){let i=In(e.discord)?e.discord.webhookFile:e.discord.botTokenFile,a=pf(i);if(s.push(` discord: ${uo(e.discord)}`),a)s.push(f.yellow(` The file ${a}`));s.push(...Dx(t))}if(e?.command)s.push(` command: ${lo(e.command)}`);return[...s,...Lx(n,r,yt(e))]}function Dx(e){if(!e[pr])return[];try{let t=f.dim(`(from ${pr}; Hydra sends the webhook or bot token there)`);return[` API ${Ss(e)} ${t}`]}catch(t){if(!(t instanceof w))throw t;return[f.yellow(` ${t.message}`),...t.hint?[f.dim(` ${t.hint}`)]:[]]}}function Lx(e,t,n){let r;try{r=xs(e).load()}catch(i){return[f.yellow(` ${i.message}`)]}let o=n.flatMap((i)=>{let a=r.stopped[i];return a?[f.yellow(` ${i} stopped at ${_t(a.at)} after HTTP ${a.status}: ${a.detail}; change its settings or its file to resume`)]:[]}),s=Jc(r,t,n).map(({count:i,error:a,oldest:c,sink:l})=>f.yellow(` ${i} ${i===1?"alert":"alerts"} for ${l} undelivered since ${_t(c)}${a?`: ${a}`:""}`));return[...o,...s]}var Wf=q({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"}}),Jf=50;class el extends I{name="test";description="Send a test alert to each sink and print what each sink answered";args=Wf;async execute(e){M(e.args,Wf,"Run 'hydra alerts test --help' for supported options");let t=e.config.get("alerts"),n=yt(t);if(n.length===0)throw new w("No alert sink is configured",Dn);let r=Hx(e.args.sink,n),o=Mx(e.args.burst),s=vs(t,{env:process.env,only:r,version:rn}),i=e.config.get("fleet")?.id,a=o===void 0?await Gx(s,i):await Fx(s,i,o);if(a===0)return;throw new w(`${a} test ${a===1?"delivery":"deliveries"} failed`,"Each line above names what the sink answered")}}function Hx(e,t){if(e===void 0)return;if(!ws(e))throw new w(`Unknown alert sink "${e}"`,`Choose one of: ${on.join(", ")}`);if(!t.includes(e))throw new w(`The ${e} sink is not configured`,Dn);return e}function Mx(e){if(e===void 0)return;if(Number.isSafeInteger(e)&&e>=1&&e<=Jf)return e;throw new w(`--burst must be a whole number from 1 to ${Jf}`)}async function Gx(e,t){let n=Rs({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++;k.info(Yf(o.name,"test alert",s))}return r}async function Fx(e,t,n){let r=[],o=$s({fleet:t,onDelivery(s){r.push(s),k.info(Yf(s.sink,s.kind,s.delivery))},sinks:e,store:Mf()});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;k.info(f.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 Yf(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"?f.green("\u2713"):f.red("\u2717")} ${e} ${t} ${r}`}class ks extends I{name="alerts";description="Choose where Hydra sends alerts and test it";init(){this.registerSubcommands([new Zc,new el])}}import{isAbsolute as w_}from"path";var _s="hydra",go="default",zf={profiles:{}},Xf=!1,Qf=24,As=7,Zf=["logs","shared"],em=!1,tm=!0,nm=!0,rm=!0,om=120,sm=["github.com","api.github.com","objects.githubusercontent.com","pipelines.actions.githubusercontent.com"];import{readFileSync as Ux,statSync as tl}from"fs";import{homedir as Bx}from"os";import{basename as jx,dirname as rl,isAbsolute as am,join as sn,resolve as Cs}from"path";var Ts=".hydra",at="HYDRA_HOME",Ee="--home",Ps={description:"Use this state directory (absolute path)",displayDefault:`${at} or ~/.hydra`,type:"string"},ol="config.json",Vx="runners",Kx="shared",qx="--",Wx=`Pass ${Ee} <absolute path> or set ${at}`;function cm(e){return sn(e.HOME||Bx(),Ts)}function lm(e,t){let{flag:n,rest:r}=Jx(e);if(n!==void 0)return{argv:r,home:im(n,Ee),source:"flag"};let o=t[at];if(o)return{argv:r,home:im(o,at),source:"environment"};return{argv:r,home:cm(t),source:"default"}}function Bt(e){return{config:sn(e,ol),home:e,runners:sn(e,Vx),shared:sn(e,Kx)}}function ie(e){return rl(e.path)}function sl(e,t){if(am(t))return t;return Cs(jx(e)===Ts?rl(e):e,t)}function um(e,t){let n=sn(t,Ts);return pm(n)&&!nl(n,e)?n:void 0}function Os(e,t,n){let r=[...dm(t).map((s)=>sn(s,Ts)),cm(n)],o=[];for(let s of r){if(!pm(s)||nl(s,e))continue;if(o.some((i)=>nl(i,s)))continue;o.push(s)}return o.map((s)=>({counts:Yx(s),path:s}))}function Jx(e){let t=[],n;for(let r=0;r<e.length;r++){let o=e[r];if(o===qx){t.push(...e.slice(r));break}let s=o.startsWith(`${Ee}=`);if(o!==Ee&&!s){t.push(o);continue}if(n!==void 0)throw new w(`${Ee} can only be provided once`);let i=s?o.slice(Ee.length+1):e[r+1];if(!i||!s&&i.startsWith("-"))throw new w(`${Ee} needs a directory`,`Use ${Ee} <absolute path>`);if(n=i,!s)r++}return{flag:n,rest:t}}function im(e,t){if(!am(e))throw new w(`${t} must be an absolute path: ${e}`,Wx);return Cs(e)}function dm(e){let t=rl(e);return t===e?[e]:[e,...dm(t)]}function pm(e){try{return tl(sn(e,ol)).isFile()}catch{return!1}}function nl(e,t){if(Cs(e)===Cs(t))return!0;try{let n=tl(e),r=tl(t);return n.dev===r.dev&&n.ino===r.ino}catch{return!1}}function fm(e){let t=mm(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 Yx(e){let t=mm(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 mm(e){try{let t=JSON.parse(Ux(sn(e,ol),"utf-8"));return typeof t==="object"&&t!==null?t:void 0}catch{return}}var gm="Runner count must be a positive safe integer",il=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B());function Ln(e){try{return il(typeof e==="string"?Number(e):e)}catch{throw new w(gm)}}function Is(e){try{Ln(e);return}catch{return gm}}function mr(e,t){if(e.length===0)return t;for(let n of e)if(!t.includes(n))throw new w(`Runner "${n}" not found`);return e}function Le(e,t){let n=e.get("profiles");if(Object.keys(n).length===0)throw new w("No profiles configured","Run hydra legacy init to set up a profile");let r=t??e.get("defaultProfile")??go,o=Object.hasOwn(n,r)?n[r]:void 0;if(!o)throw new w(`Profile "${r}" not found`);return{name:r,profile:o}}async function ct(e){let t=e.get("profiles"),n=Object.keys(t);if(n.length===0)throw new w("No profiles configured","Run hydra legacy init to set up a profile");if(n.length===1)return n[0];return Pn({message:"Select profile",options:n.map((r)=>({label:r,value:r,hint:t[r]?.url}))})}var hm=32,zx=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"];var Xx=/^(0|[1-9]\d{0,2})$/,Qx=/^(0|[1-9]\d?)$/,Zx=zx.map((e)=>et(e)),ek=["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)=>et(e));function gr(e){let t=e.split(".");if(t.length!==4||!t.every((n)=>Xx.test(n)&&Number(n)<=255))return;return t.reduce((n,r)=>n*256+Number(r),0)}function et(e){let[t,n,r]=e.split("/"),o=t===void 0?void 0:gr(t),s=Number(n);if(o===void 0||r!==void 0||!Qx.test(n??""))return;if(s<0||s>32||(o&~Ns(s))>>>0!==0)return;return{base:o,prefix:s}}function Ds(e){let t=gr(e);return t!==void 0&&!ek.some((n)=>hr(n,t))}function Ls(e){return Zx.some((t)=>t.prefix<=e.prefix&&hr(t,e.base))}function hr(e,t){return(t&Ns(e.prefix))>>>0===e.base}function Hs(e,t){let n=Math.min(e.prefix,t.prefix);return(e.base&Ns(n))>>>0===(t.base&Ns(n))>>>0}function ym(e){return Array.from({length:4},(t,n)=>e>>>8*(3-n)&255).join(".")}function Ns(e){return e===0?0:4294967295<<32-e>>>0}var jt=[];var wm=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,tk={"apple-container":["-v","--volume","--mount","--ssh","-p","--publish","--publish-socket"],firecracker:jt,native:jt,"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"]},nk={"apple-container":jt,firecracker:jt,native:jt,"podman-gvisor":jt,tart:["--suspendable"]},rk={"apple-container":jt,firecracker:jt,native:jt,"podman-gvisor":["checkpoint"],tart:["suspend"]},ok={"apple-container":["--virtualization"],firecracker:["--virtualization"],native:["--virtualization"],"podman-gvisor":["--virtualization"],tart:["--virtualization","--nested"]},sk={"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"},ik={"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 Ms extends Error{driver;reason;index;option;_tag="ArgvRefusedError";constructor(e,t,n,r){super(`Refused argument ${n} of a ${e} command${r?` (${r})`:""}: ${sk[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}: ${ik[t]}`);this.slot=e;this.reason=t;this.name="DestroyRefusedError"}}function Vt(e,t,n){let r=[["host-share",tk[e]],["suspend",nk[e]],["virtualization",ok[e]]];for(let[o,s]of t.entries()){if(n?.contains(s))throw new Ms(e,"jit-config",o,void 0);if(rk[e].includes(s))throw new Ms(e,"suspend",o,s);for(let[i,a]of r){let c=a.find((l)=>ak(s,l));if(c)throw new Ms(e,i,o,c)}}return t}function Hn(e,t){if(!wm.test(t))throw Error(`Invalid fleet prefix "${t}"`);let n=e.startsWith(`${t}-`)?e.slice(t.length+1):"";return wm.test(n)}async function bm(e,t,n){if(t.driver!==e.capabilities().id)throw new ho(t,"foreign-driver");if(!Hn(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 ak(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 lt(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=Sm(n.stdout,t.echo?process.stdout:void 0,a),l=Sm(n.stderr,t.echo?process.stderr:void 0,a);try{let u=await Promise.race([n.exited,s.promise]);if(!await ck([c,l],2000))await Promise.all([c.stop(),l.stop()]);return{exitCode:u===void 0||n.signalCode!==null?u||1:u,stderr:l.text(),stdout:c.text(),timedOut:r}}finally{clearTimeout(o),clearTimeout(i)}}async function ck(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 Sm(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=Rm(s,n)})().catch(()=>{return}).then(()=>{s+=o.decode()}),stop:()=>r.cancel().catch(()=>{return}),text:()=>Rm(s,n)}}function Rm(e,t){return e.length>t?e.slice(e.length-t):e}class Te 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 vm="container",Gs=3,Mn=1000,lk=10,uk="[redacted]",dk=4194304,Em={callMs:60*Mn,createMs:600*Mn,pollMs:Mn,readyMs:300*Mn,runnerMs:60*Mn,stopMs:120*Mn};function xm(e,t){let n=0,r=!1;return{binary:e,limits:t,recover:()=>{n=0,r=!1},run:async(i,a,c,l={})=>{Vt("apple-container",c,l.stdin);let u=l.timeoutMs??t.callMs,d=l.stdin?new TextEncoder().encode(l.stdin.line()):void 0;try{let p=l.maxOutputChars??dk,m=await pk(i,a,[e,...c],{input:d,maxOutputChars:p,timeoutMs:u});if(m.timedOut){n+=1,r||=n>=Gs;let h=u/Mn;throw new Te("timeout",i,a,`${e} did not finish within ${h} s`)}n=0;let g={exitCode:m.exitCode,stderr:$m(m.stderr,l.stdin),stdout:$m(m.stdout,l.stdin)};if(g.exitCode===0||l.check===!1)return g;throw new Te("failed",i,a,fk(e,g))}finally{d?.fill(0)}},unavailable:()=>r}}async function pk(e,t,n,r){try{return await lt(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 $m(e,t){return t?.contains(e)?uk:e}function fk(e,t){let n=t.stderr.trim().split(`
|
|
100
|
+
`).slice(-lk).join(`
|
|
101
|
+
`);return`${e} exited with code ${t.exitCode}${n?`
|
|
102
|
+
${n}`:""}`}var mk=["running","stopped","stopping","unknown"],gk="container",hk="container-apiserver",yk=/(?:^|\s)version\s+(\S+)/,wk=["mounts","networks","publishedPorts","publishedSockets","ssh","virtualization"],Kt=Xe((e)=>typeof e==="string"?e:void 0),km=Xe((e)=>typeof e==="boolean"?e:void 0),yr=Xe((e)=>Array.isArray(e)?e:void 0),Am=Xe((e)=>{if(typeof e!=="object"||e===null||Array.isArray(e))return{};return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]==="string"))}),bk=H({network:Kt}),Sk=H({destination:Kt,type:Xe((e)=>typeof e==="object"&&e!==null&&Object.hasOwn(e,"tmpfs"))}),Rk=H({id:N(),labels:Am,mounts:yr,networks:yr,publishedPorts:yr,publishedSockets:yr,ssh:km,virtualization:km}),$k=H({networks:yr,startedDate:ur(),state:Kt}),vk=H({configuration:Rk,networks:yr,status:ur()}),Ek=Xe((e)=>Fs(()=>H({ipv4Subnet:Kt})(e))?.ipv4Subnet),xk=H({configuration:H({ipv4Subnet:Kt,labels:Am,name:Kt}),id:Kt,status:Ek}),kk=ee(H({appName:Kt,version:Kt}));async function wr(e){let t=await e.run("list","containers",["list","--all","--format","json"]);return al(t.stdout,"list","containers",(n)=>ee(vk)(n).map(_k))}async function Cm(e){let t=await e.run("list","networks",["network","list","--format","json"]);return al(t.stdout,"list","networks",(n)=>ee(xk)(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 Tm(e){let t=await e.run("read the version of","Apple container",["system","version","--format","json"]);return al(t.stdout,"read the version of","Apple container",(n)=>{let r=kk(n),o=r.find((i)=>i.appName===gk)?.version,s=r.find((i)=>i.appName===hk)?.version;return{cli:o,services:s===void 0?void 0:yk.exec(s)?.[1]??s}})}function _k(e){let{configuration:t}=e,n=Ak(e.status,e.networks??[]),r=[...t.networks??[],...n.networks].flatMap((o)=>{let s=Fs(()=>bk(o).network);return s?[s]:[]});return{id:t.id,labels:t.labels,mounts:(t.mounts??[]).map((o)=>{let s=Fs(()=>Sk(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:wk.filter((o)=>t[o]===void 0),virtualization:t.virtualization??!1}}function Ak(e,t){if(typeof e==="string")return{networks:t,started:!1,state:_m(e)};let n=Fs(()=>$k(e));return{networks:n?.networks??[],started:n?.startedDate!==void 0&&n?.startedDate!==null,state:_m(n?.state)}}function _m(e){return mk.find((t)=>t===e)??"unknown"}function Fs(e){try{return e()}catch{return}}function al(e,t,n,r){try{return r(JSON.parse(e))}catch(o){throw new Te("failed",t,n,"container printed JSON in an unexpected shape",{cause:o})}}var yo="org.r5nlabs.hydra.fleet",Pm=16,Om=28,Im=256,Lm="network-unknown";function cl(e,t){let n=et(t.range);if(!n)throw Error(`The network range "${t.range}" is not an IPv4 CIDR block without host bits`);if(!Ls(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<Pm||r>Om)throw Error(`The subnet prefix must be a whole number from ${Pm} to ${Om}`);if(r<n.prefix)throw Error(`A /${r} subnet does not fit in ${t.range}`);let o=2**(r-n.prefix);if(o>Im)throw Error(`${t.range} holds ${o} /${r} subnets; a fleet has at most ${Im}`);let s=2**(hm-r);return Array.from({length:o},(i,a)=>({name:`hydra-${e}-net-${a+1}`,subnet:`${ym(n.base+a*s)}/${r}`}))}function Hm(e,t,n){let r=cl(t,n),o=new Map,s=Promise.resolve(),i=async()=>{let[d,p]=await Promise.all([Cm(e),wr(e)]);return{containers:p,networks:new Map(d.map((m)=>[m.name,m]))}},a=(d)=>{let p=new Set(d.containers.flatMap((R)=>R.networks)),m=new Set(o.values()),g=d.containers.filter((R)=>R.unread.includes("networks")),h=[...Nm(r,d.networks),...Dm(t,r,d.networks),...Ck(g)],E=r.filter((R)=>d.networks.get(R.name)?.subnet===R.subnet),v=g.length>0?[]:E.filter((R)=>!p.has(R.name));return{findings:h,free:v.filter((R)=>!m.has(R.name)).map(Us),inUse:E.filter((R)=>p.has(R.name)||m.has(R.name)).map(Us),missing:r.filter((R)=>!d.networks.has(R.name)).map(Us),unplanned:Mm(t,r,d.networks)}},c=async(d)=>{let p=a(await i()),m=p.free[0];if(!m){let g=p.findings.find((h)=>h.code===Lm)?.detail;throw new Te("no-network","find a free network for",d,g??`all ${p.inUse.length} usable networks of the fleet are in use${p.missing.length>0?`, and ${p.missing.length} are not created yet`:""}`)}return o.set(d,m),m},l=async()=>{let d=await i(),p=[],m=[...Nm(r,d.networks),...Dm(t,r,d.networks)];for(let g of r){if(d.networks.has(g.name))continue;let h=Tk(g,d.networks);if(h){m.push(Pk(g,h));continue}await e.run("create",`network ${g.name}`,["network","create","--subnet",g.subnet,"--label",`${yo}=${t}`,g.name]),p.push(g.name)}return{created:p,findings:m}},u=(d)=>{let p=s.then(d);return s=p.catch(()=>{return}),p};return{networkOf:(d)=>o.get(d),plan:r,prepare:()=>u(l),release:(d)=>{o.delete(d)},status:async()=>a(await i()),take:(d)=>u(()=>c(d))}}function Nm(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 Mm(e,t,n){let r=new Set(t.map(Us)),o=`hydra-${e}-net-`;return[...n.keys()].filter((s)=>s.startsWith(o)&&!r.has(s))}function Dm(e,t,n){return Mm(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 Ck(e){if(e.length===0)return[];return[{code:Lm,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 Tk(e,t){let n=et(e.subnet);return[...t.values()].find((r)=>{let o=r.subnet===void 0?void 0:et(r.subnet);return o!==void 0&&Hs(n,o)})}function Pk(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 Us(e){return e.name}var ll=["arm64"],Gm=["arm64","x86_64"];var an=2,He={"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:ll,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:Gm,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:ll,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:Gm,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:ll,minMacos:13}}},Bs={darwin:{linux:["apple-container","tart"],macos:["tart"]},linux:{linux:["firecracker","podman-gvisor"],macos:[]}},cn={darwin:"macOS",linux:"Linux"},qt={linux:"Linux",macos:"macOS"};import{constants as Fm,existsSync as Ok}from"fs";import{access as Ik}from"fs/promises";var Nk=1e4,wo="/dev/kvm",Dk="/sys/fs/cgroup/cgroup.controllers",Um="unknown",Lk=10,Bm={Darwin:"darwin",Linux:"linux"},jm={aarch64:"arm64",amd64:"x86_64",arm64:"arm64",x86_64:"x86_64"};async function ln(){let[e,t]=await Promise.all([ul(["uname","-s"]),ul(["uname","-m"])]),n=e&&Object.hasOwn(Bm,e)?Bm[e]:void 0,r=await ul(n==="darwin"?["sw_vers","-productVersion"]:["uname","-r"]);return{arch:(t&&Object.hasOwn(jm,t)?jm[t]:t)??Um,cgroupV2:Ok(Dk),kvm:await Hk(),os:n,osName:n?cn[n]:e??Um,version:r}}function js(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 bo(e){let t=Number.parseInt(e??"",Lk);return Number.isSafeInteger(t)?t:void 0}async function Hk(){try{return await Ik(wo,Fm.R_OK|Fm.W_OK),"usable"}catch(e){return e.code==="ENOENT"?"missing":"denied"}}async function ul(e){try{let t=Bun.spawn(e,{stderr:"ignore",stdin:"ignore",stdout:"pipe",timeout:Nk}),[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 wt=["apple-container","tart","firecracker","podman-gvisor","native"],ut="auto";function Vm(e){return wt.includes(e)}var Mk=60000,Gk=1000,Km=["none","limited","full"],Wm="pick another driver from hydra driver list",Fk=Object.keys(Bs);function Jm(e){return wt.filter((t)=>He[t].capabilities.hostOs===e)}function Ks(e,t,n){return e===ut?Bk(t,n):Uk(e,t,n)}function Ym(e,t){if(e!==ut)return Vs(He[e].capabilities,t);let n=Xm(t.guestOs).map((r)=>Vs(He[r].capabilities,t));return n.some((r)=>r.length===0)?[]:n.flat()}function br(e,t){if(t!=="macos")return;return(e===ut?Xm(t):[e]).flatMap((o)=>{let s=He[o].capabilities.maxMacosGuests;return s===void 0?[]:[{driver:o,guests:s}]}).sort((o,s)=>o.guests-s.guests)[0]}function qs(e,t){let{capabilities:n,requires:r}=He[e];if(t.os!==n.hostOs){let s=cn[n.hostOs];return[Wt("host-os",Qm(e,t),`Run ${e} on a ${s} host, or ${Wm}`)]}let o=[];if(!r.arch.includes(t.arch)){let s=r.arch.join(" or ");o.push(Wt("host-arch",`${e} supports ${s} hosts; this host is ${t.arch}`,`Use an ${s} host`))}if(r.minMacos!==void 0)o.push(...qk(e,r.minMacos,t.version));if(r.kvm&&t.kvm!=="usable")o.push(Wk(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 zm(e,t,n,r=Mk){let o=qs(e,t),s=qm(o)?[]:await Kk(e,n[e],r),i=[...o,...s];return{driver:e,findings:i,status:qm(i)?"unavailable":"available"}}function qm(e){return e.some((t)=>t.level==="error")}function Uk(e,t,n){let r=He[e].capabilities.hostOs,s=[...n.os===r?[]:[{code:"host-os",detail:Qm(e,n),driver:e}],...Vs(He[e].capabilities,t)];return s.length>0?{kind:"refused",refusals:s}:{driver:e,kind:"resolved",passedOver:[]}}function Bk(e,t){if(!t.os)return{kind:"refused",refusals:[{code:"host-os",detail:`Hydra has no slot driver for ${t.osName} hosts`}]};let n=Bs[t.os][e.guestOs];if(n.length===0)return{kind:"refused",refusals:[{code:"guest-os",detail:`No driver runs ${qt[e.guestOs]} guests on ${cn[t.os]} hosts`}]};let r=[];for(let o of n){let s=[...Vs(He[o].capabilities,e),...Vk(o,t)];if(s.length===0)return{driver:o,kind:"resolved",passedOver:r};r.push(...s)}return{kind:"refused",refusals:r}}function Xm(e){return[...new Set(Fk.flatMap((t)=>Bs[t][e]))]}function Vs(e,t){let n=e.id;return[[!e.guestOs.includes(t.guestOs),"guest-os",`${n} runs no ${qt[t.guestOs]} guests`],[Km.indexOf(e.docker)<Km.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&&!jk(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 jk(e,t){return e.secretBearing||e.isolation==="user-space-kernel"&&t.allowWeakerIsolation}function Vk(e,t){return qs(e,t).filter((n)=>n.level==="error").map((n)=>({code:"host",detail:n.detail,driver:e}))}async function Kk(e,t,n){if(!t)return[Wt("not-included",`This version of Hydra does not include the ${e} driver`,`Update Hydra, or ${Wm}`)];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[Wt("check-timeout",`The ${e} host check did not finish within ${n/Gk} 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[Wt("check-failed",`The ${e} host check failed: ${i}`,"Fix the cause and run hydra driver check again")]}finally{clearTimeout(o)}}function qk(e,t,n){let r=bo(n);if(r===void 0)return[Wt("os-version","Could not read the macOS version","Check that sw_vers -productVersion prints it")];if(r>=t)return[];return[Wt("os-version",`${e} needs macOS ${t} or later; this host runs ${n}`,`Upgrade macOS to ${t} or later`)]}function Wk(e,t){return t==="missing"?Wt("kvm",`${e} needs ${wo}, which this host does not have`,"Run on bare metal or on a VM with nested virtualisation, with the kvm module loaded"):Wt("kvm",`${wo} is not readable and writable by this user`,`Give this user read and write access to ${wo}, for example through the kvm group`)}function Qm(e,t){return`${e} runs on ${cn[He[e].capabilities.hostOs]} hosts; this host runs ${t.osName}`}function Wt(e,t,n){return{code:e,detail:t,fix:n,level:"error"}}var Jk=new Set(["github.com","www.github.com"]);var Zm=/\.git$/;function me(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(!Jk.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(Zm,"");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(Zm,"");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 Me(e){return e.kind==="repo"?`${e.owner}/${e.repo}`:e.org}var eg=["scaleset","poll"],ge="none";function Ws(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 Ys=16,Fn=24,Yk=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,zk=/^[a-z0-9]+$/,tg=7200,ng=100,Xk=["linux","macos"],rg=[ut,...wt],Qk=["none","limited","full"],Zk=["dns","id","networks"],e_=["range","subnetPrefix"],t_=["cpus","diskGiB","memoryMiB"],n_=["allowWeakerIsolation","ceiling","demand","docker","driver","foreignArch","guestOs","guiSession","labels","maxJobMinutes","priority","resources","runnerGroup","secretBearing","url"],r_=",",sg=/[\p{Cc}\p{Cf}]/u,Js="https://github.com",og=/^[A-Za-z0-9_-]+$/,o_=/^[A-Za-z0-9._-]+$/,s_=`${Js}/<org> or ${Js}/<owner>/<repo>, with nothing else`,Gn=(e,t=Number.MAX_SAFE_INTEGER)=>X().map((n)=>Number.isSafeInteger(n)&&n>=e&&n<=t?n:B()),i_=N().map((e)=>e.trim().length>0&&!sg.test(e)?e:B()),a_=N().map((e)=>e.length>0&&e===e.trim()&&!e.includes(r_)&&!sg.test(e)?e:B()),c_=Gn(1).or(Y([ge])),l_=N().map((e)=>Ds(e)?e:B()),u_=N().map((e)=>cg(e)?e:B());function So(e){return e.length<=Fn&&Yk.test(e)}function Un(e){return e.length<=Ys&&zk.test(e)}function ig(e){if(e===void 0)return;let t=fe(e,"fleet");_e(t,Zk,"fleet","the fleet");let n=N().map((r)=>Un(r)?r:B());if(se(t.id,n,"fleet.id",`lowercase letters and digits without hyphens, at most ${Ys} characters, so no fleet's name prefix starts another's`),ae(t.dns,ee(l_),"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 d_(t.networks,t.id),t}function d_(e,t){if(e===void 0)return;let n=fe(e,"fleet.networks");_e(n,e_,"fleet.networks","the fleet's networks"),se(n.range,N(),"fleet.networks.range","a private IPv4 CIDR block"),se(n.subnetPrefix,Gn(0),"fleet.networks.subnetPrefix","a whole number");try{cl(t,n)}catch(r){throw Error(`fleet.networks: ${r.message}`)}}function ag(e,t){if(e===void 0)return;let n=fe(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)Ro(o,n[o])}function Ro(e,t){if(!So(e))throw Error(`Pool name "${e}" must be lowercase letters and digits in hyphen-separated words, at most ${Fn} characters`);let n=`pools.${e}`,r=fe(t,n);_e(r,n_,n,"a pool"),se(r.url,u_,`${n}.url`,s_),se(r.guestOs,Y(Xk),`${n}.guestOs`,"linux or macos"),se(r.driver,Y(rg),`${n}.driver`,`one of ${rg.join(", ")}`),se(r.demand,Y(eg),`${n}.demand`,"scaleset or poll"),se(r.ceiling,c_,`${n}.ceiling`,`a positive whole number or "${ge}"`),m_(r.labels,`${n}.labels`),g_(r.runnerGroup,cg(r.url),`${n}.runnerGroup`),h_(r.resources,`${n}.resources`),ae(r.docker,Y(Qk),`${n}.docker`,"none, limited or full");for(let s of["foreignArch","guiSession","secretBearing","allowWeakerIsolation"])ae(r[s],Z(),`${n}.${s}`,"a boolean");ae(r.maxJobMinutes,Gn(1,tg),`${n}.maxJobMinutes`,`whole minutes from 1 to ${tg}`),ae(r.priority,Gn(0,ng),`${n}.priority`,`a whole number from 0 to ${ng}`);let o=r;return f_(o,n),o}function p_(e,t,n){let r=br(e,t);if(r===void 0||n!==ge&&n<=r.guests)return;let o=e===ut?`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 f_(e,t){let n=Ws(e);if(n.allowWeakerIsolation&&!n.secretBearing)throw Error(`${t}.allowWeakerIsolation applies only to a secret-bearing pool`);let r=Ym(e.driver,n);if(r.length>0)throw Error(`${t}: ${r.map((s)=>s.detail).join("; ")}`);let o=p_(e.driver,e.guestOs,e.ceiling);if(o)throw Error(`${t}.ceiling ${o}`)}function m_(e,t){se(e,ee(a_),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 g_(e,t,n){if(t.kind==="org"){se(e,i_,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 h_(e,t){if(e===void 0)throw Error(`${t} is missing; expected cpus, memoryMiB and diskGiB per guest`);let n=fe(e,t);_e(n,t_,t,"pool resources"),se(n.cpus,Gn(1),`${t}.cpus`,"a positive whole number of virtual CPUs"),se(n.memoryMiB,Gn(1),`${t}.memoryMiB`,"a positive whole number of MiB"),se(n.diskGiB,Gn(1),`${t}.diskGiB`,"a positive whole number of GiB")}function dl(e){return e.kind==="org"?`${Js}/${e.org}`:`${Js}/${e.owner}/${e.repo}`}function cg(e){try{let t=me(e);return dl(t)===e&&y_(t)?t:void 0}catch{return}}function y_(e){return e.kind==="org"?og.test(e.org):og.test(e.owner)&&o_.test(e.repo)}var Sr=N().map((e)=>e.trim().length>0?e:B()),b_=Y(["osx","linux","windows"]),lg=Y(["github","gitlab"]),S_=ee(Y(["logs","work","shared"])),R_=Y(["app","gh"]),pl=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B()),$_=N().map((e)=>w_(e)?e:B()),v_={app:["mode","appId","installationId","privateKeyPath"],gh:["mode"]};function ug(e){return new Uc(Bt(e).config,zf,{parse:(t)=>E_(t,e),strict:!0})}function zs(e){if(!e.failure)return;return new w(e.failure.message,`Repair ${e.path} or select another home with ${Ee}; hydra doctor lists the homes it finds`)}function E_(e,t){let n=fe(e,"the config");ae(n.defaultProfile,N(),"defaultProfile","a string"),__(n.cleanup),A_(n.credentials),jf(n.alerts);let r=ig(n.fleet);ag(n.pools,r);let o=Object.fromEntries(Object.entries(fe(n.profiles,"profiles")).map(([i,a])=>[i,x_(a,`profiles.${i}`,t)])),s=n.runners===void 0?void 0:k_(n.runners,t);return{...e,profiles:o,...s?{runners:s}:{}}}function x_(e,t,n){let r=fe(e,t);if(se(r.url,Sr,`${t}.url`,"a URL"),se(r.name,Sr,`${t}.name`,"a runner name prefix"),se(r.directory,Sr,`${t}.directory`,"a directory"),se(r.os,b_,`${t}.os`,"osx, linux or windows"),se(r.provider,lg,`${t}.provider`,"github or gitlab"),ae(r.labels,N(),`${t}.labels`,"a comma-separated string"),ae(r.runnerGroup,N(),`${t}.runnerGroup`,"a string"),ae(r.numberOfMachines,il,`${t}.numberOfMachines`,"a positive safe integer"),ae(r.overwrite,Z(),`${t}.overwrite`,"a boolean"),ae(r.run,Z(),`${t}.run`,"a boolean"),r.jobHooks!==void 0)fe(r.jobHooks,`${t}.jobHooks`);let o=e;return{...o,directory:sl(n,o.directory)}}function k_(e,t){if(!Array.isArray(e))throw Error("runners must be a list");return e.map((n,r)=>{let o=`runners[${r}]`,s=fe(n,o);se(s.id,Sr,`${o}.id`,"a runner id"),se(s.profile,Sr,`${o}.profile`,"a profile name"),se(s.directory,Sr,`${o}.directory`,"a directory");for(let a of["name","url","createdAt"])ae(s[a],N(),`${o}.${a}`,"a string");ae(s.provider,lg,`${o}.provider`,"github or gitlab"),ae(s.agentId,pl,`${o}.agentId`,"a positive GitHub runner id");let i=n;return{...i,directory:sl(t,i.directory)}})}function __(e){if(e===void 0)return;let t=fe(e,"cleanup");ae(t.auto,Z(),"cleanup.auto","a boolean"),ae(t.intervalHours,X(),"cleanup.intervalHours","a number of hours"),ae(t.olderThanDays,X(),"cleanup.olderThanDays","a number of days"),ae(t.targets,S_,"cleanup.targets","a list of logs, work and shared"),ae(t.lastRun,N(),"cleanup.lastRun","a timestamp")}function A_(e){if(e===void 0)return;let t=fe(e,"credentials");se(t.mode,R_,"credentials.mode","app or gh");let n=t.mode;if(_e(t,v_[n],"credentials",`the ${n} mode`),n==="gh")return;se(t.appId,pl,"credentials.appId","a GitHub App id"),se(t.installationId,pl,"credentials.installationId","an installation id"),se(t.privateKeyPath,$_,"credentials.privateKeyPath","an absolute path")}var C_=/^(?:W\/)?"[\x21\x23-\x7e]*"$/;function dg(e){return C_.test(e)}function Rr(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 fl="https://api.github.com",$r="HYDRA_GITHUB_API_URL",T_="2022-11-28",P_="r5n-hydra",O_=3,bg=500,I_=60000,Sg=30000,Xs=1000,N_=100,pg=100,D_=200,L_=403,fg=429,H_=204,mg=304,M_=500,gg="[redacted]",G_=new Set(["DELETE","GET","PUT"]),F_=new Set(["127.0.0.1","[::1]"]),U_=[/\bgh[opsur]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_\w{20,}\b/g,/\beyJ[\w-]+\.[\w-]+\.[\w-]+/g],B_=/[\p{Cc}\p{Cf}]+/gu,j_=/<([^>]+)>;\s*rel="next"/,V_=/\/+$/,K_=/^\/+/,q_=/\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 un(e){let t=e[$r];if(!t)return fl;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 w(`${$r} is not a URL`,n)}if(!(r.protocol==="https:"||r.protocol==="http:"&&F_.has(r.hostname))||r.username||r.password||r.search||r.hash)throw new w(`${$r} is not an API root Hydra may send tokens to`,n);return r.href.replace(V_,"")}function ml({apiUrl:e,auth:t}){let n=new URL(`${e}/`);async function r(c,l,u,d,p,m){let g=s(l);for(let h=1;;h++){let E=await t.token(),v=h<O_,R;try{R=await fetch(l,{body:d===void 0?void 0:JSON.stringify(d),headers:J_(E,d!==void 0,m),method:c,redirect:"manual",signal:AbortSignal.timeout(Sg)})}catch(b){if(p&&v){await Bun.sleep(hg(h));continue}throw new Re(u,c,g,void 0,wg(yg(b),E))}if(R.ok||m!==void 0&&R.status===mg)return R;let _=Y_(R);if(_!==void 0&&v&&_<=I_){await R.body?.cancel(),await Bun.sleep(_);continue}if(_===void 0&&R.status>=M_&&p&&v){await R.body?.cancel(),await Bun.sleep(hg(h));continue}let T=[_===void 0?"":z_(R),await X_(R)].filter(Boolean).join("; ");throw new Re(u,c,g,R.status,wg(T,E))}}async function o(c,l,u,d,p){let m=s(p),g;try{g=c.status===H_?"":await c.text()}catch(E){throw new Re(u,d,m,c.status,yg(E))}let h;try{h=g===""?void 0:JSON.parse(g)}catch{throw new Re(u,d,m,c.status,"the response is not JSON")}try{return l(h)}catch{throw new Re(u,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(K_,""),n)}function a(c){return c.origin===n.origin&&c.pathname.startsWith(n.pathname)}return{async paginate({cache:c,item:l,key:u,operation:d,path:p}){let m=[],g=i(p);if(!g.searchParams.has("per_page"))g.searchParams.set("per_page",String(N_));let h=g;for(let E=1;h;E++){if(E>pg)throw new Re(d,"GET",p,void 0,`stopped after ${pg} pages`);let v=h,R=c?.get(v.href),_=await r("GET",v,d,void 0,!0,R?.etag);if(R&&_.status===mg){await _.body?.cancel(),m.push(...R.items),h=R.next===void 0?void 0:new URL(R.next);continue}let T=_.headers.get("link"),b=await o(_,W_(l,u),d,"GET",v);m.push(...b);let A=T?.match(j_)?.[1];if(h=A?new URL(A):void 0,h&&!a(h))throw new Re(d,"GET",p,_.status,"refused a next page outside the API root");let y=_.headers.get("etag");if(c&&y!==null&&dg(y))c.set(v.href,{etag:y,items:b,next:h?.href})}return m},async request({body:c,idempotent:l,method:u="GET",operation:d,path:p,schema:m}){let g=i(p),h=await r(u,g,d,c,l??G_.has(u));return o(h,m,d,u,g)}}}function Rg(e){let t,n=()=>(t??=e(),t);return{async paginate(r){return n().paginate(r)},async request(r){return n().request(r)}}}function W_(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 J_(e,t,n){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"User-Agent":P_,"X-GitHub-Api-Version":T_,...t?{"Content-Type":"application/json"}:{},...n===void 0?{}:{"If-None-Match":n}}}function hg(e){return bg*2**(e-1)}function Y_(e){if(e.status!==L_&&e.status!==fg)return;let t=e.headers.get("retry-after");if(t!==null&&t.trim()!==""&&Number.isFinite(Number(t)))return Math.max(0,Number(t)*Xs);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*Xs-Date.now()):Number.POSITIVE_INFINITY}return e.status===fg?bg:void 0}function z_(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*Xs).toISOString()}`;return"rate limited"}async function X_(e){try{let n=JSON.parse(await e.text())?.message;return typeof n==="string"?n:""}catch{return""}}function yg(e){if(e instanceof Error&&e.name==="TimeoutError")return`timed out after ${Sg/Xs} s`;return e instanceof Error?e.message:String(e)}function wg(e,t){let n=t?e.replaceAll(t,gg):e;return U_.reduce((r,o)=>r.replace(o,gg),n).replace(B_," ").replace(q_," ").trim().slice(0,D_)}import{createPrivateKey as Q_,sign as Z_}from"crypto";import{constants as $g}from"fs";import{open as eA,stat as tA}from"fs/promises";var vg="github.com",nA=60,rA=540,oA=300000,sA=1000,iA=63,aA=511,cA=8,lA=4,uA=$g.O_RDONLY|$g.O_NONBLOCK,gl="Check the GitHub App's id, installation id and private key in credentials",hl=N().map((e)=>e.trim()===""?B():e),dA=H({expires_at:N(),token:hl}),Eg=new WeakMap;class Bn extends w{_tag="GitHubCredentialsError"}function pA(e,t){let n,r=()=>{if(n)return n;let o=un(t),s=e?.mode==="app"?mA(e,o):fA();return n={client:ml({apiUrl:o,auth:s}),credentials:s},n};return{client:Rg(()=>r().client),credentials:{kind:e?.mode??"gh",async token(){return r().credentials.token()}}}}function At(e){let t=Eg.get(e);if(t)return t;let n=pA(e.get("credentials"),process.env);return Eg.set(e,n),n}function kg(e){return e?.mode==="app"?`GitHub App ${e.appId}, installation ${e.installationId}, key ${e.privateKeyPath}`:"the gh login (gh auth token)"}async function _g(e){try{return Ag(await tA(e))}catch(t){return`cannot be read (${t.code??"unknown error"})`}}function fA(){let e;return{kind:"gh",token(){return e??=gA().catch((t)=>{throw e=void 0,t}),e}}}function mA(e,t){let n=ml({apiUrl:t,auth:{token:async()=>yA(e.appId,await hA(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:dA});return{expiresAt:Date.parse(i),token:a}}catch(i){throw i instanceof Re?new Bn(i.message,gl):i}}return{kind:"app",async token(){if(r&&r.expiresAt-oA>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 gA(){let e=await Bun.$`gh auth token --hostname ${vg}`.quiet().nothrow(),t=e.stdout.toString().trim();if(e.exitCode===0&&t)return t;let n=e.stderr.toString().trim();throw new Bn(`gh auth token failed for ${vg}${n?`: ${n}`:""}`,"Run gh auth login, or configure a GitHub App in credentials")}async function hA(e){let n;try{n=await eA(e,uA)}catch(r){throw new Bn(`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=Ag(await n.stat());if(r)throw new Bn(`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=Q_(await n.readFile("utf8"))}catch{throw new Bn(`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 Bn(`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 Ag(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&iA)!==0)return`is open to its group or others (mode ${(e.mode&aA).toString(cA).padStart(lA,"0")})`;return}function yA(e,t){let n=Math.floor(Date.now()/sA)-nA,r=xg(JSON.stringify({alg:"RS256",typ:"JWT"})),o=xg(JSON.stringify({exp:n+rA,iat:n,iss:e})),s=Z_("sha256",Buffer.from(`${r}.${o}`),t).toString("base64url");return`${r}.${o}.${s}`}function xg(e){return Buffer.from(e).toString("base64url")}var Cg=404,wA=422,bA="offline",SA=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B()),Qs=H({busy:Z(),id:SA,name:N(),status:N()}),RA=()=>{return};function vr(e){return`/${e.kind==="repo"?`repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`:`orgs/${encodeURIComponent(e.org)}`}/actions/runners`}function Er(e){return e.status===bA}async function dn(e,t){return e.paginate({item:Qs,key:"runners",operation:`List the runners of ${Me(t)}`,path:vr(t)})}async function pn(e,t,n){try{return await e.request({operation:`Read runner ${n} of ${Me(t)}`,path:`${vr(t)}/${n}`,schema:Qs})}catch(r){if(r instanceof Re&&r.status===Cg)return;throw r}}async function jn(e,t,n){try{return await e.request({method:"DELETE",operation:`Delete runner ${n} of ${Me(t)}`,path:`${vr(t)}/${n}`,schema:RA}),"deleted"}catch(r){if(!(r instanceof Re))throw r;if(r.status===Cg)return"gone";if(r.status===wA)return"busy";throw r}}function Zs(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 Tg=1,$A="_work",vA=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B()),Pg=H({busy:Z(),id:vA,labels:ee(H({name:N()})),name:N(),status:N()}).map((e)=>({busy:e.busy,id:e.id,labels:e.labels.map((t)=>t.name),name:e.name,status:e.status})),EA=H({encoded_jit_config:N().map((e)=>e.trim()===""?B():e),runner:Pg}).map((e)=>({encodedJitConfig:e.encoded_jit_config,runner:e.runner}));function xA(e){return`${vr(e)}/generate-jitconfig`}async function Og(e,t,{labels:n,name:r,runnerGroupId:o,workFolder:s=$A}){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 ${Me(t)}`,path:xA(t),schema:EA})}async function Ig(e,t,n){return(await e.paginate({item:Pg,key:"runners",operation:`Find the runner ${n} of ${Me(t)}`,path:`${vr(t)}?name=${encodeURIComponent(n)}`})).find((o)=>o.name===n)}var kA=["queued","in_progress"],Ng=4096,_A="queued",AA=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B()),CA=H({id:AA}),TA=H({labels:ee(N()),status:N()});function ei(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 ti({owner:e,repo:t}){return`/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function Dg({owner:e,repo:t}){return`${e}/${t}`.toLowerCase()}function Lg(){return{jobs:Rr(Ng),runs:Rr(Ng)}}async function Hg(e,t,n,r){let o=`${t.owner}/${t.repo}`,s=ti(t),i=new Set;for(let c of kA){r.throwIfAborted();let l=await e.paginate({cache:n.runs,item:CA,key:"workflow_runs",operation:`List the ${c} workflow runs of ${o}`,path:`${s}/actions/runs?status=${c}`});for(let u of l)i.add(u.id)}let a=[];for(let c of i){r.throwIfAborted();let l=await e.paginate({cache:n.jobs,item:TA,key:"jobs",operation:`List the jobs of workflow run ${c} of ${o}`,path:`${s}/actions/runs/${c}/jobs?filter=latest`});for(let u of l)if(u.status===_A)a.push(u.labels)}return a}var Mg="selected",Gg=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B()),Fg=H({allows_public_repositories:Z().or(oe()),default:Z(),id:Gg,name:N(),visibility:N()}).map((e)=>({allowsPublicRepositories:e.allows_public_repositories,default:e.default,id:e.id,name:e.name,visibility:e.visibility})),PA=H({id:Gg}),OA=()=>{return};function Ct(e){return`/orgs/${encodeURIComponent(e)}/actions/runner-groups`}async function IA(e,t,n){return e.paginate({cache:n,item:Fg,key:"runner_groups",operation:`List the runner groups of ${t}`,path:Ct(t)})}async function xr(e,t,n,r){return(await IA(e,t,r)).find((s)=>s.name.toLowerCase()===n.toLowerCase())}async function Ug(e,t,n){return e.request({body:{allows_public_repositories:!1,name:n,selected_repository_ids:[],visibility:Mg},method:"POST",operation:`Create the runner group ${n} in ${t}`,path:Ct(t),schema:Fg})}async function Bg(e,t,n){return(await e.paginate({item:PA,key:"repositories",operation:`List the repositories that may use the runner group ${n.name} of ${t}`,path:`${Ct(t)}/${n.id}/repositories`})).length}async function ni(e,t,n){return e.paginate({item:Qs,key:"runners",operation:`List the runners in the runner group ${n.name} of ${t}`,path:`${Ct(t)}/${n.id}/runners`})}async function jg(e,t,n,r){await e.request({method:"PUT",operation:`Move runner ${r} of ${t} into the runner group ${n.name}`,path:`${Ct(t)}/${n.id}/runners/${r}`,schema:OA})}function Vg(e,t){if(e.default)return"it is the default group, which every repository may use";if(e.visibility!==Mg)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 NA=["all","private","selected"],DA=/^[A-Za-z0-9._-]+$/,Kg=N().map((e)=>DA.test(e)?e:B()),qg=H({archived:Z().or(oe()),name:Kg,owner:H({login:Kg}),private:Z()}).map((e)=>({archived:e.archived??!1,owner:e.owner.login,private:e.private,repo:e.name}));function Wg(e){return NA.includes(e)}async function LA(e,t,n){return e.paginate({cache:n,item:qg,operation:`List the repositories of ${t}`,path:`/orgs/${encodeURIComponent(t)}/repos?type=all`})}async function HA(e,t,n,r){return e.paginate({cache:r,item:qg,key:"repositories",operation:`List the repositories that may use the runner group ${n.name} of ${t}`,path:`${Ct(t)}/${n.id}/repositories`})}async function Jg(e,t,n,r){return(n.visibility==="selected"?await HA(e,t,n,r):await LA(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{spawn as gC}from"child_process";import{once as hC}from"events";import{existsSync as Vn}from"fs";import{cp as yC,link as wC,mkdir as ui,mkdtemp as bC,readdir as ah,readFile as ch,readlink as SC,rename as RC,rm as Kn,stat as lh,symlink as $C,unlink as uh,writeFile as vC}from"fs/promises";import{join as ue,resolve as kl}from"path";import{chmod as GA,mkdir as FA,readFile as UA,rename as BA,rm as jA,stat as VA,writeFile as Zg}from"fs/promises";import{dirname as KA,join as Rl,resolve as oi}from"path";import{isAbsolute as MA}from"path";var yl="# Generated by Hydra; hydra update rewrites this file.";function Yg(e){return`'${e.replaceAll("'","'\\''")}'`}function zg(){return`#!/usr/bin/env bash
|
|
103
|
+
${yl}
|
|
96
104
|
# Disabled in the Hydra profile; kept so runners started before the change still find it.
|
|
97
105
|
exit 0
|
|
98
|
-
`}function
|
|
99
|
-
${
|
|
106
|
+
`}function Xg(e){return`#!/usr/bin/env bash
|
|
107
|
+
${yl}
|
|
100
108
|
# Waits until every host resolves, then lets the job start; fails the job on timeout.
|
|
101
109
|
set +e
|
|
102
110
|
|
|
103
|
-
hosts=(${e.hosts.map(
|
|
111
|
+
hosts=(${e.hosts.map(Yg).join(" ")})
|
|
104
112
|
timeout_seconds=${e.timeoutSeconds}
|
|
105
113
|
|
|
106
114
|
if command -v dscacheutil >/dev/null 2>&1; then
|
|
@@ -138,15 +146,15 @@ while :; do
|
|
|
138
146
|
pending=("\${unresolved[@]}")
|
|
139
147
|
sleep 1
|
|
140
148
|
done
|
|
141
|
-
`}function
|
|
142
|
-
${
|
|
149
|
+
`}function Qg(e,t){if(!MA(e)||e==="/")throw Error(`Refusing to generate a workspace cleanup hook for runner directory "${e}"`);return`#!/usr/bin/env bash
|
|
150
|
+
${yl}
|
|
143
151
|
# Removes this job's workspace and temporary files from this runner's _work directory.
|
|
144
152
|
# Always exits 0 so a cleanup problem never fails a finished job; problems become warnings.
|
|
145
153
|
set +e
|
|
146
154
|
trap 'exit 0' EXIT
|
|
147
155
|
shopt -s dotglob nullglob
|
|
148
156
|
|
|
149
|
-
runner_root=${
|
|
157
|
+
runner_root=${Yg(e)}
|
|
150
158
|
keep_tool_cache=${t.keepToolCache}
|
|
151
159
|
|
|
152
160
|
note() { echo "Hydra cleanup: $*"; }
|
|
@@ -234,29 +242,400 @@ cd -- "$work_root" || exit 0
|
|
|
234
242
|
clean_job_workspace "\${RUNNER_WORKSPACE:-\${GITHUB_WORKSPACE:-}}"
|
|
235
243
|
clear_dir "$work_root/_temp" _runner_file_commands _github_workflow
|
|
236
244
|
[ "$keep_tool_cache" = true ] || clear_dir "$work_root/_tool"
|
|
237
|
-
`}var
|
|
238
|
-
`);if(o.at(-1)==="")o.pop();let
|
|
245
|
+
`}var qA="hydra-hooks",eh=".env",si={started:{envKey:"ACTIONS_RUNNER_HOOK_JOB_STARTED",file:"job-started.sh"},completed:{envKey:"ACTIONS_RUNNER_HOOK_JOB_COMPLETED",file:"job-completed.sh"}},WA=Object.keys(si),JA=493,YA=253,zA=/^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/,Sl="Fix the profile's jobHooks in config.json in the Hydra home; see the Hydra reference for the allowed values",wl={dns:["enabled","hosts","timeoutSeconds"],workspaceCleanup:["enabled","keepToolCache"]},XA=N().map((e)=>e.length<=YA&&zA.test(e)?e:B()),QA=ee(XA).map((e)=>e.length>0?e:B()),ZA=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B());function th(){return{dns:{enabled:rm,hosts:[...sm],timeoutSeconds:om},workspaceCleanup:{enabled:em,keepToolCache:nm}}}function ii(){let e=th();return{...e,workspaceCleanup:{...e.workspaceCleanup,enabled:tm}}}function Jt(e){let t=th(),n=bl(e,"jobHooks",Object.keys(wl)),r=bl(n.dns,"jobHooks.dns",wl.dns),o=bl(n.workspaceCleanup,"jobHooks.workspaceCleanup",wl.workspaceCleanup);return{dns:{enabled:$o(Z(),r.enabled,t.dns.enabled,"jobHooks.dns.enabled","a boolean"),hosts:$o(QA,r.hosts,t.dns.hosts,"jobHooks.dns.hosts","a non-empty list of hostnames"),timeoutSeconds:$o(ZA,r.timeoutSeconds,t.dns.timeoutSeconds,"jobHooks.dns.timeoutSeconds","a positive whole number of seconds")},workspaceCleanup:{enabled:$o(Z(),o.enabled,t.workspaceCleanup.enabled,"jobHooks.workspaceCleanup.enabled","a boolean"),keepToolCache:$o(Z(),o.keepToolCache,t.workspaceCleanup.keepToolCache,"jobHooks.workspaceCleanup.keepToolCache","a boolean")}}}function nh(e,t){return Rl(oi(e),qA,si[t].file)}function rh(e,t,n){switch(e){case"started":return n.dns.enabled?Xg(n.dns):null;case"completed":return n.workspaceCleanup.enabled?Qg(oi(t),n.workspaceCleanup):null}}function eC(e,t){let n=new Map(t.map((i)=>[i.key,i])),r=new Set,o=e.split(`
|
|
246
|
+
`);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
247
|
`)}
|
|
240
|
-
`:""}async function
|
|
241
|
-
`).filter((r)=>r.startsWith(n)).map((r)=>r.slice(n.length)).at(-1)}async function
|
|
248
|
+
`:""}async function ai(e,t){let n=[],r=!1;for(let a of WA){let c=nh(e,a),l=rh(a,e,t),u=await ri(c),d=l??(u===null?null:zg());if(d!==null&&d!==u)await oC(c,d),r=!0;n.push({key:si[a].envKey,managedPath:c,value:l===null?null:c})}let o=Rl(oi(e),eh),s=await ri(o)??"",i=eC(s,n);if(i===s)return{envChanged:!1,scriptsChanged:r};return await Zg(o,i),{envChanged:!0,scriptsChanged:r}}async function $l(e,t){let n=Rl(oi(e),eh),r=await ri(n)??"",o=(s)=>tC(nh(e,s),nC(r,si[s].envKey),rh(s,e,t));return{envModifiedAt:await rC(n),states:{completed:await o("completed"),started:await o("started")}}}async function tC(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 ri(e)===n?"configured":"outdated"}function nC(e,t){let n=`${t}=`;return e.split(`
|
|
249
|
+
`).filter((r)=>r.startsWith(n)).map((r)=>r.slice(n.length)).at(-1)}async function rC(e){try{return(await VA(e)).mtime}catch(t){if(t.code==="ENOENT")return null;throw t}}function bl(e,t,n){if(e===void 0)return{};if(typeof e!=="object"||e===null||Array.isArray(e))throw new w(`Invalid ${t}: expected an object`,Sl);let r=Object.keys(e).find((o)=>!n.includes(o));if(r!==void 0)throw new w(`Unknown ${t} setting: ${r}`,Sl);return e}function $o(e,t,n,r,o){if(t===void 0)return n;try{return e(t)}catch{throw new w(`Invalid ${r}: expected ${o}`,Sl)}}async function ri(e){try{return await UA(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function oC(e,t){let n=`${e}.${process.pid}.tmp`;await FA(KA(e),{recursive:!0});try{await Zg(n,t),await GA(n,JA),await BA(n,e)}finally{await jA(n,{force:!0})}}import{existsSync as sC}from"fs";import{readdir as iC,stat as aC}from"fs/promises";import{join as cC}from"path";var ci="_diag",oh={runner:/^Runner_.+\.log$/,worker:/^Worker_.+\.log$/},sh=1024,ih=["B","KB","MB","GB"],lC=1;function uC(e){if(oh.worker.test(e))return"worker";if(oh.runner.test(e))return"runner";return null}function vl(e){return[...e].sort((t,n)=>n.mtime.getTime()-t.mtime.getTime())}async function li(e){if(!sC(e))return[];let t=await iC(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile())continue;let o=uC(r.name);if(!o)continue;let s=cC(e,r.name),i=await aC(s);n.push({mtime:i.mtime,name:r.name,path:s,size:i.size,type:o})}return vl(n)}function El(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 xl(e,t){if(t<=0)return"";let n=e.endsWith(`
|
|
242
250
|
`)?e.slice(0,-1):e;if(n==="")return"";return n.split(`
|
|
243
251
|
`).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
|
-
|
|
246
|
-
|
|
247
|
-
|
|
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
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
252
|
+
`)}function bt(e){let t=e,n=0;while(t>=sh&&n<ih.length-1)t/=sh,n++;return`${n===0?String(t):t.toFixed(lC)} ${ih[n]??"B"}`}import{readFile as dC}from"fs/promises";import{join as pC}from"path";var kr="unknown";var Yt=".runner",fC=/^\uFEFF/;async function vo(e){try{let t=await dC(pC(e,Yt),"utf-8"),n=JSON.parse(t.replace(fC,""));return{agentId:Number.isSafeInteger(n.agentId)?n.agentId:void 0,name:typeof n.agentName==="string"?n.agentName:kr}}catch{return{name:kr}}}var mC=/(?:^|\/)github\/([^/]+)\/externals$/;function _r(e){return e.match(mC)?.[1]??null}var dh="actions/runner",EC={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},_l=["bin"],Al=["externals"],xC=1,kC=5000,_C=50,AC=5000,CC=50,TC="ACTIONS_RUNNER_INPUT_TOKEN",PC=/^\d+\.\d+\.\d+$/,OC=/^v/,IC=H({token:hl}),NC=H({tag_name:N()}),DC={app:gl,gh:"Check the gh login with gh auth status"},LC={"registration-token":"Mint a runner registration token","remove-token":"Mint a runner removal token"};class Cl{profile;sharedDir;github;sharedPath=null;constructor(e,t,n){this.profile=e;this.sharedDir=t;this.github=n}async download(){let e=EC[this.profile.os],t=await this.getLatestVersion(),n=ue(this.sharedDir,"github",t);if(await this.isCompleteDownload(n))return this.sharedPath=n,{path:n,version:t};let r=ue(this.sharedDir,"github");await ui(r,{recursive:!0});let o=await bC(ue(this.sharedDir,`.github-${t}-`)),s=`actions-runner-${e}-${t}.tar.gz`,i=ue(o,s),a=`https://github.com/${dh}/releases/download/v${t}/${s}`;try{if(await Bun.$`curl --fail --silent --show-error --location -o ${i} ${a}`,await Bun.$`tar xzf ${i} -C ${o}`,await uh(i),!await this.isCompleteDownload(o))throw new w(`Runner v${t} archive is incomplete`);await this.publishDownload(o,n,t)}finally{await Kn(o,{force:!0,recursive:!0})}return this.sharedPath=n,{path:n,version:t}}async create(e){let t=Jt(this.profile.jobHooks),n=await this.ensureDownloaded(),r=[];for(let o of e){let s=ue(this.profile.directory,o);if(Vn(s))throw new w(`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(!Vn(ue(s,".runner")))await Kn(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=ue(this.profile.directory,t);if(!Vn(ue(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(ph(r)).quiet().nothrow();if(o.exitCode!==0)throw new w(`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=ue(this.profile.directory,t),r=await this.readPidFile(n);if(r&&this.isProcessRunning(r))continue;let o=gC("bash",["./run.sh"],{cwd:kl(n),detached:!0,stdio:"ignore"});if(await hC(o,"spawn"),o.pid===void 0)throw new w(`Failed to start runner ${t}`);o.unref(),await this.writePidFile(n,o.pid)}}async stop(e){for(let t of e){let n=ue(this.profile.directory,t),r=await this.readPidFile(n);if(r&&this.isProcessRunning(r)){try{process.kill(-r,"SIGTERM")}catch(s){if(s.code!=="ESRCH")throw s;try{process.kill(r,"SIGTERM")}catch(i){if(i.code!=="ESRCH")throw i}}let o=Date.now()+kC;while(this.isProcessRunning(r)){if(Date.now()>=o)throw new w(`Runner ${t} did not stop`,"Wait for its current job to finish and retry");await Bun.sleep(_C)}}await this.removePidFile(n)}}async list(){let e=this.profile.directory;if(!Vn(e))return[];let t=await ah(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let o=ue(e,r.name);n.push(await this.getRunnerStatus(o,r.name))}return n}async currentVersion(e){let t=ue(this.profile.directory,e);return this.detectVersion(t)}async logFiles(e){return li(ue(this.profile.directory,e,ci))}async update(e){let t=Jt(this.profile.jobHooks),n=await this.ensureDownloaded();for(let r of e){let o=ue(this.profile.directory,r);await this.removeRunnerBinaries(o),await this.setupRunnerDir(n,o),await ai(o,t)}}async configureJobHooks(e){let t=Jt(this.profile.jobHooks),n=ue(this.profile.directory,e);if(!Vn(ue(n,".runner")))return{envChanged:!1,scriptsChanged:!1};return ai(n,t)}async getRunnerStatus(e,t){let{agentId:n,name:r}=await vo(e),o=await this.readPidFile(e),s=o!==null&&this.isProcessRunning(o),i="unknown";if(s)i="running";else if(Vn(ue(e,".runner")))i="registered";let a=s?await this.readStartTime(e):void 0;return{agentId:n,directory:e,id:t,name:r,pid:s?o:void 0,startedAt:a,status:i}}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)=>lh(ue(e,n))))).every((n,r)=>r<_l.length+Al.length?n.isDirectory():n.isFile())}catch(t){if(t.code==="ENOENT")return!1;throw t}}async publishDownload(e,t,n){let r=ue(this.sharedDir,`.github-${n}.lock`),o=Date.now()+AC;while(!0)try{await ui(r);break}catch(s){if(s.code!=="EEXIST")throw s;if(Date.now()>=o)throw new w(`Runner download is locked: ${r}`,"Retry after other Hydra downloads finish; remove a stale lock only when no download is running");await Bun.sleep(CC)}try{if(await this.isCompleteDownload(t))return;await Kn(t,{force:!0,recursive:!0}),await RC(e,t)}finally{await Kn(r,{force:!0,recursive:!0})}}async setupRunnerDir(e,t){await ui(t,{recursive:!0});for(let n of _l)await this.hardLinkDir(ue(e,n),ue(t,n));for(let n of Al){let r=kl(e,n),o=ue(t,n);if(!Vn(o))await $C(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 yC(ue(e,o),ue(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(ph(r)).quiet(),await ai(e,n)}async fetchRegistrationToken(){return this.fetchRunnerToken(me(this.profile.url),"registration-token")}async fetchRemovalToken(e){let t=await ch(ue(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(me(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:`${LC[t]} for ${Me(e)}`,path:`/${n}/actions/runners/${t}`,schema:IC},Zs(this.github.credentials.kind,e));return r}async getLatestVersion(){let{tag_name:e}=await this.callGitHub({operation:"Read the latest runner release",path:`/repos/${dh}/releases/latest`,schema:NC},DC[this.github.credentials.kind]),t=e.replace(OC,"");if(!PC.test(t))throw new w(`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 Re?new w(n.message,t):n}}pidFilePath(e){return kl(e,".pid")}async writePidFile(e,t){await vC(this.pidFilePath(e),String(t))}async readPidFile(e){try{let t=await ch(this.pidFilePath(e),"utf-8"),n=Number(t.trim());return Number.isSafeInteger(n)&&n>xC?n:null}catch{return null}}async readStartTime(e){try{return(await lh(this.pidFilePath(e))).mtime}catch{return}}async removePidFile(e){try{await uh(this.pidFilePath(e))}catch{}}async hardLinkDir(e,t){await ui(t,{recursive:!0});let n=await ah(e,{withFileTypes:!0});for(let r of n){let o=ue(e,r.name),s=ue(t,r.name);if(r.isDirectory())await this.hardLinkDir(o,s);else await wC(o,s)}}async detectVersion(e){try{let t=await SC(ue(e,"externals"));return _r(t)}catch{return null}}async removeRunnerBinaries(e){for(let t of _l)await Kn(ue(e,t),{force:!0,recursive:!0});for(let t of Al)await Kn(ue(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 Kn(ue(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 ph(e){return{...process.env,[TC]:e}}import{existsSync as Tl}from"fs";import{readdir as Pl,readFile as HC,readlink as MC,rm as Ol,stat as GC}from"fs/promises";import{join as fn}from"path";var FC="_work",UC="externals",BC=".pid",jC="github",VC=["runner","worker"],KC=24,mh=3600000,fh=10,qC=1,WC=X().map((e)=>Number.isSafeInteger(e)&&e>qC?e:B());function di(e){return{auto:e?.auto??Xf,intervalHours:e?.intervalHours??Qf,lastRun:e?.lastRun,olderThanDays:e?.olderThanDays??As,targets:e?.targets??Zf}}function JC(e,t){return e-t*KC*mh}function Il(e,t){if(!e.lastRun)return!0;let n=Date.parse(e.lastRun);if(Number.isNaN(n))return!0;return t-n>=e.intervalHours*mh}function YC(e,t){let n=vl(e),r=new Set;for(let o of VC){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 zC(e){return[...e].sort(rT)[0]??null}function XC(e,t){let n=zC(e),r=new Set(t);return e.filter((o)=>o!==n&&!r.has(o))}function pi(e){return Object.values(e).reduce((t,n)=>t+n.freedBytes,0)}async function QC(e){let t;try{t=await HC(fn(e,BC),"utf-8")}catch(r){if(r.code==="ENOENT")return!1;throw r}let n;try{n=WC(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 Nl(e){if(!Tl(e))return 0;let t=await Pl(e,{withFileTypes:!0}),n=0;for(let r of t){if(r.isSymbolicLink())continue;let o=fn(e,r.name);if(r.isDirectory()){n+=await Nl(o);continue}if(r.isFile()){let s=await GC(o);n+=s.size}}return n}async function fi(e){let t=JC(e.now,e.olderThanDays),n={};for(let r of e.targets)switch(r){case"logs":n.logs=await ZC(e.entries,t,e.dryRun);break;case"work":n.work=await eT(e.entries,e.dryRun);break;case"shared":n.shared=await tT(e.entries,e.dryRun,e.sharedDir);break}return n}async function ZC(e,t,n){let r={freedBytes:0,removed:0,skipped:[]};for(let o of e){let s=await li(fn(o.directory,ci));for(let i of YC(s,t)){if(!n)await Ol(i.path,{force:!0});r.removed++,r.freedBytes+=i.size}}return r}async function eT(e,t){let n={freedBytes:0,removed:0,skipped:[]};for(let r of e){if(await QC(r.directory)){n.skipped.push(r.id);continue}let o=fn(r.directory,FC);if(!Tl(o))continue;let s=await Pl(o);if(s.length===0)continue;if(n.freedBytes+=await Nl(o),n.removed+=s.length,t)continue;for(let i of s)await Ol(fn(o,i),{force:!0,recursive:!0})}return n}async function tT(e,t,n){let r={freedBytes:0,removed:0,skipped:[]},o=fn(n,jC);if(!Tl(o))return r;let i=(await Pl(o,{withFileTypes:!0})).filter((c)=>c.isDirectory()).map((c)=>c.name),a=await nT(e);for(let c of XC(i,a)){let l=fn(o,c);if(r.freedBytes+=await Nl(l),r.removed++,!t)await Ol(l,{force:!0,recursive:!0})}return r}async function nT(e){let t=[];for(let n of e)try{let r=await MC(fn(n.directory,UC)),o=_r(r);if(o)t.push(o)}catch{}return t}function rT(e,t){let n=e.split(".").map((s)=>Number.parseInt(s,fh)),r=t.split(".").map((s)=>Number.parseInt(s,fh)),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,l=Number.isNaN(a)?0:a;if(c!==l)return l-c}return 0}import{readFile as oT}from"fs/promises";var sT=1e4,iT="/etc/resolv.conf",aT=/^\s*nameserver\[\d+\]\s*:\s*(\S+)/gm,cT=/^\s*nameserver\s+(\S+)/gm,lT=/^(?:ip|ipv6)_address:\s*(\S+)/gm,uT=/^(\S+)\s/gm;async function Dl(){let[e,t]=Bun.which("scutil")?[await gh(["scutil","--dns"]),aT]:[await dT(),cT];return yh(hh(e,t))}function Ll(){return Bun.which("dscacheutil")!==null||Bun.which("getent")!==null}async function Hl(e){let[t,n]=Bun.which("dscacheutil")?[["dscacheutil","-q","host","-a","name",e],lT]:[["getent","hosts",e],uT],r=performance.now(),o=await gh(t);return{addresses:yh(hh(o,n)),durationMs:Math.round(performance.now()-r),host:e}}async function gh(e){let t=Bun.spawn(e,{stderr:"ignore",stdin:"ignore",stdout:"pipe",timeout:sT}),[n]=await Promise.all([new Response(t.stdout).text(),t.exited]);return n}async function dT(){try{return await oT(iT,"utf-8")}catch(e){if(e.code==="ENOENT")return"";throw e}}function hh(e,t){return[...e.matchAll(t)].flatMap((n)=>n[1]?[n[1]]:[])}function yh(e){return[...new Set(e)]}function ve(e,t){switch(e.provider){case"github":return new Cl(e,Bt(ie(t)).shared,At(t));default:throw Error(`Runner provider "${e.provider}" is not yet implemented`)}}import{isAbsolute as pT}from"path";class Ar extends Error{_tag="AccountLookupError";constructor(e){super(`Could not read this account's directory entry: ${e}`);this.name="AccountLookupError"}}var fT=1e4,mT={darwin:{argv:()=>["/usr/bin/id","-P"],home:8},linux:{argv:()=>["getent","passwd",String(process.getuid?.())],home:5}};function wh(){let e=mT[process.platform];if(!e)throw new Ar(`no lookup for ${process.platform}`);let t=Bun.spawnSync(e.argv(),{stderr:"pipe",stdin:"ignore",timeout:fT});if(t.exitCode!==0)throw new Ar(t.stderr.toString().trim()||"the lookup failed");let n=t.stdout.toString().trim().split(":"),r=n[0],o=n[e.home];if(!r||!o||!pT(o))throw new Ar("it names no user or no absolute home");return{home:o,name:r}}import{lstatSync as p0,readdirSync as f0}from"fs";import{isAbsolute as m0,join as vi}from"path";var Cr="/opt/hydra",gT=`${Cr}/bin`,bh="/usr/local",Eo=[gT,`${bh}/bin`,"/usr/bin","/bin","/usr/sbin","/sbin"],Ml=["--no-env-file","--no-install"],Tr=cf,qn=rn;function Pr(e=Cr,t=bh){return{bun:`${e}/bin/bun`,cli:`${e}/lib/hydra/${qn}/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 Gl(e=Pr()){return[e.bun,...Ml,e.cli]}import{isAbsolute as e0}from"path";import{statfsSync as PT}from"fs";import{availableParallelism as OT,freemem as IT,homedir as NT}from"os";var Sh=`#!/bin/sh
|
|
253
|
+
set -eu
|
|
254
|
+
. "\${0%/*}/layout"
|
|
255
|
+
|
|
256
|
+
fail() {
|
|
257
|
+
printf 'hydra-guest accept: %s\\n' "$1" >&2
|
|
258
|
+
exit 1
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
umask 077
|
|
262
|
+
"\${0%/*}/ready" >/dev/null 2>&1 || fail "the guest is not waiting for a runner configuration"
|
|
263
|
+
[ ! -e "$HYDRA_RUN_DIR/jit" ] || fail "the guest already holds a runner configuration"
|
|
264
|
+
|
|
265
|
+
line=
|
|
266
|
+
IFS= read -r line || [ -n "$line" ] || fail "standard input holds no runner configuration"
|
|
267
|
+
[ -n "$line" ] || fail "the runner configuration is empty"
|
|
268
|
+
case $line in
|
|
269
|
+
*[!A-Za-z0-9+/=]*) fail "the runner configuration is not one line of base64" ;;
|
|
270
|
+
esac
|
|
271
|
+
extra=
|
|
272
|
+
if IFS= read -r extra || [ -n "$extra" ]; then
|
|
273
|
+
fail "standard input holds more than one line"
|
|
274
|
+
fi
|
|
275
|
+
|
|
276
|
+
staged="$HYDRA_RUN_DIR/jit.$$"
|
|
277
|
+
rm -f "$staged"
|
|
278
|
+
(
|
|
279
|
+
set -C
|
|
280
|
+
printf '%s\\n' "$line" >"$staged"
|
|
281
|
+
) || fail "could not stage the runner configuration"
|
|
282
|
+
line=
|
|
283
|
+
chmod 0600 "$staged"
|
|
284
|
+
if ! ln "$staged" "$HYDRA_RUN_DIR/jit" 2>/dev/null; then
|
|
285
|
+
rm -f "$staged"
|
|
286
|
+
fail "the guest already holds a runner configuration"
|
|
287
|
+
fi
|
|
288
|
+
rm -f "$staged"
|
|
289
|
+
`;var Rh=`#!/bin/bash
|
|
290
|
+
set -euo pipefail
|
|
291
|
+
. "\${0%/*}/layout"
|
|
292
|
+
|
|
293
|
+
fail() {
|
|
294
|
+
printf '::error::Hydra stopped this job: %s\\n' "$1"
|
|
295
|
+
exit 1
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
[ ! -e "$HYDRA_RUN_DIR/jit" ] || fail "the runner configuration is still on the guest"
|
|
299
|
+
(set -C && : >"$HYDRA_STATE_DIR/job-started") 2>/dev/null || fail "this guest has already started a job"
|
|
300
|
+
|
|
301
|
+
workspace=\${GITHUB_WORKSPACE:-}
|
|
302
|
+
if [ -n "$workspace" ] && [ -d "$workspace" ] && [ -n "$(ls -A "$workspace")" ]; then
|
|
303
|
+
fail "the workspace is not empty"
|
|
304
|
+
fi
|
|
305
|
+
|
|
306
|
+
current=$(cd "$HYDRA_RUNNER_HOME" && find . -mindepth 1 | LC_ALL=C sort)
|
|
307
|
+
expected=$(cat "$HYDRA_HOME_MANIFEST")
|
|
308
|
+
[ "$current" = "$expected" ] || fail "the home holds files the image does not"
|
|
309
|
+
`;var $h=`#!/bin/sh
|
|
310
|
+
set -eu
|
|
311
|
+
. "\${0%/*}/layout"
|
|
312
|
+
|
|
313
|
+
fail() {
|
|
314
|
+
printf 'hydra-guest init: %s\\n' "$1" >&2
|
|
315
|
+
exit 1
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
wait_for() {
|
|
319
|
+
limit=$1
|
|
320
|
+
shift
|
|
321
|
+
waited=0
|
|
322
|
+
until "$@"; do
|
|
323
|
+
waited=$((waited + 1))
|
|
324
|
+
[ "$waited" -le "$limit" ] || return 1
|
|
325
|
+
sleep 1
|
|
326
|
+
done
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
has_config() {
|
|
330
|
+
[ -f "$HYDRA_RUN_DIR/jit" ]
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
docker_answers() {
|
|
334
|
+
docker info >/dev/null 2>&1
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
umask 077
|
|
338
|
+
mkdir -p "$HYDRA_RUN_DIR"
|
|
339
|
+
chmod 0711 "$HYDRA_RUN_DIR"
|
|
340
|
+
[ ! -e "$HYDRA_RUN_DIR/jit" ] || fail "a runner configuration arrived before the guest was ready"
|
|
341
|
+
|
|
342
|
+
if [ "$HYDRA_DOCKER" = 1 ]; then
|
|
343
|
+
dockerd --group docker >"$HYDRA_RUN_DIR/dockerd.log" 2>&1 &
|
|
344
|
+
wait_for "$HYDRA_DOCKER_WAIT_SECONDS" docker_answers || fail "dockerd did not answer within $HYDRA_DOCKER_WAIT_SECONDS s"
|
|
345
|
+
fi
|
|
346
|
+
|
|
347
|
+
printf '%s\\n' "$$" >"$HYDRA_RUN_DIR/ready.new"
|
|
348
|
+
mv -f "$HYDRA_RUN_DIR/ready.new" "$HYDRA_RUN_DIR/ready"
|
|
349
|
+
|
|
350
|
+
wait_for "$HYDRA_JIT_WAIT_SECONDS" has_config || fail "no runner configuration arrived within $HYDRA_JIT_WAIT_SECONDS s"
|
|
351
|
+
rm -f "$HYDRA_RUN_DIR/ready"
|
|
352
|
+
jit=
|
|
353
|
+
IFS= read -r jit <"$HYDRA_RUN_DIR/jit" || :
|
|
354
|
+
rm -f "$HYDRA_RUN_DIR/jit"
|
|
355
|
+
[ -n "$jit" ] || fail "the runner configuration is empty"
|
|
356
|
+
|
|
357
|
+
ACTIONS_RUNNER_INPUT_JITCONFIG=$jit HOME=$HYDRA_RUNNER_HOME USER=$HYDRA_RUNNER_USER LOGNAME=$HYDRA_RUNNER_USER \\
|
|
358
|
+
setpriv --reuid="$HYDRA_RUNNER_UID" --regid="$HYDRA_RUNNER_GID" --init-groups --inh-caps=-all --no-new-privs -- \\
|
|
359
|
+
"$HYDRA_RUNNER_DIR/bin/Runner.Listener" run &
|
|
360
|
+
runner=$!
|
|
361
|
+
jit=
|
|
362
|
+
trap 'kill -TERM "$runner" 2>/dev/null || :' TERM INT HUP
|
|
363
|
+
|
|
364
|
+
while :; do
|
|
365
|
+
status=0
|
|
366
|
+
wait "$runner" || status=$?
|
|
367
|
+
kill -0 "$runner" 2>/dev/null || break
|
|
368
|
+
done
|
|
369
|
+
exit "$status"
|
|
370
|
+
`;var vh=`#!/bin/sh
|
|
371
|
+
set -eu
|
|
372
|
+
. "\${0%/*}/layout"
|
|
373
|
+
|
|
374
|
+
fail() {
|
|
375
|
+
printf 'hydra-guest ready: %s\\n' "$1" >&2
|
|
376
|
+
exit 1
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
[ -f "$HYDRA_RUN_DIR/ready" ] || fail "the guest is not waiting for a runner configuration"
|
|
380
|
+
pid=
|
|
381
|
+
IFS= read -r pid <"$HYDRA_RUN_DIR/ready" || :
|
|
382
|
+
case $pid in
|
|
383
|
+
'' | *[!0-9]*) fail "the guest init left no process id" ;;
|
|
384
|
+
esac
|
|
385
|
+
kill -0 "$pid" 2>/dev/null || fail "the guest init is not running"
|
|
386
|
+
`;var Tt="/opt/hydra-guest",xo=`${Tt}/init`,gi=`${Tt}/accept`,hi=`${Tt}/ready`,Fl=`${Tt}/canary.sh`,Eh=`${Tt}/layout`,yi=`${Tt}/home.manifest`,ko="/run/hydra",Ul="/var/lib/hydra-guest",mn="runner",Qe=1001,Bl=`/home/${mn}`,gn="/opt/actions-runner",_o="/opt/hostedtoolcache",ST="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",RT=900,$T=120,vT=/^[A-Za-z0-9_./:-]*$/,mi=365,ET=292;function xh(e){return{docker:e,dockerWaitSeconds:$T,homeManifest:yi,jitWaitSeconds:RT,path:ST,runDir:ko,runnerDir:gn,runnerGid:Qe,runnerHome:Bl,runnerUid:Qe,runnerUser:mn,stateDir:Ul}}function xT(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}='${kT(r,String(o))}'`),"export PATH"].join(`
|
|
387
|
+
`)}
|
|
388
|
+
`}function kh(e){return[{content:$h,mode:mi,name:"init"},{content:Sh,mode:mi,name:"accept"},{content:vh,mode:mi,name:"ready"},{content:Rh,mode:mi,name:"canary.sh"},{content:xT(e),mode:ET,name:"layout"}]}function kT(e,t){if(!vT.test(t))throw Error(`Refused guest layout value for ${e}: ${JSON.stringify(t)}`);return t}var jl="org.r5nlabs.hydra.pool",Vl="org.r5nlabs.hydra.secret-bearing",_T=["SETGID","SETUID"],AT=["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"],wi="Runner.Listener",bi="Runner.Worker",CT=30,TT='for f in /proc/[0-9]*/comm; do IFS= read -r n <"$f" && printf "%s\\n" "$n"; done 2>/dev/null; exit 0';function _h(e){let{spec:t}=e,n=t.docker?AT:_T;return["create","--name",t.name,"--network",e.network,"--cpus",String(t.cpus),"--memory",`${t.memoryMiB}M`,...e.dns.flatMap((r)=>["--dns",r]),"--label",`${yo}=${e.fleet}`,"--label",`${jl}=${t.pool}`,"--label",`${Vl}=${t.secretBearing}`,"--cap-drop","ALL",...n.flatMap((r)=>["--cap-add",r]),"--tmpfs",ko,...t.foreignArch?["--rosetta"]:[],t.image,xo]}function Ah(e){return["start",e]}function Ch(e){return["exec",e,hi]}function Th(e){return["exec","--interactive",e,gi]}function Ph(e){return["exec",e,"/bin/sh","-c",TT]}function Oh(e){return["stop","--time",String(CT),e]}function Ih(e){return["delete","--force",e]}function Nh(e){return["logs",e]}var Wn="1.7.1",Kl=["1.1.1.1"],ql=-1,Si="apple-container",DT=/^[a-z0-9]+$/,LT=/^[A-Za-z0-9][^\s@]*@sha256:[0-9a-f]{64}$/,Lh=1048576,HT=1024*Lh,MT=1000,GT="console.log",FT=/[^\P{Cc}\n\t]/gu;function Ri(e={}){let t={...Em,...e.limits},n=xm(e.binary??vm,t),r=e.fleet?UT(n,e.fleet):void 0,o=new Set,s=(b)=>{if(r)return r;throw Error(`The apple-container driver needs a fleet to ${b}`)},i=(b,A)=>{let y=s(A);if(b.driver!==Si||!Hn(b.name,y.prefix))throw new Te("invalid-name",A,b.name,`it is not a guest of fleet ${y.id}`);return y},a=async(b)=>(await wr(n)).find((A)=>A.id===b),c=async(b,A,y,S)=>{let C=Date.now()+b;while(!await S()){if(Date.now()>=C)throw new Te("not-ready",A,y,`no answer within ${b/MT} s`);await Bun.sleep(t.pollMs)}},l=async(b)=>{i(b,"read the state of a guest");let A=await a(b.name);if(!A)return{kind:"gone"};if(A.state==="stopped")return A.started||o.has(b.name)?{code:ql,kind:"exited"}:{kind:"preparing"};if(A.state!=="running")return{kind:"running"};let y=await n.run("list the processes of",b.name,Ph(b.name),{check:!1}),S=y.exitCode===0?y.stdout.split(`
|
|
389
|
+
`).map((C)=>C.trim()):[];return S.includes(wi)?{busy:S.includes(bi),kind:"runner-alive"}:{kind:"running"}},u=async(b)=>{let A=await a(b);if(!A)return;if(A.state!=="stopped")await n.run("stop",b,Oh(b),{check:!1,timeoutMs:t.stopMs});await n.run("delete",b,Ih(b))},d=async(b)=>{let A=s("create a guest"),y={driver:Si,name:b.name,pool:b.pool};if(i(y,"create"),b.guestOs!=="linux")throw new Te("wrong-guest","create",b.name,"Apple container runs only Linux guests");if(!LT.test(b.image))throw new Te("refused-config","create",b.name,"the image must be pinned by its sha256 digest");if(n.unavailable())throw new Te("unavailable","create",b.name,`${Gs} container calls in a row timed out; a host check that finds the tool answering lifts this`);let S=await A.pool.take(b.name);try{await n.run("create",b.name,_h({dns:A.dns,fleet:A.id,network:S,spec:b}),{timeoutMs:t.createMs});let C=BT(await a(b.name),S);if(C.length===0)return y;throw await u(b.name),new Te("refused-config","create",b.name,C.join("; "))}catch(C){throw A.pool.release(b.name),C}},p=async(b)=>{i(b,"start"),await n.run("start",b.name,Ah(b.name)),o.add(b.name),await c(t.readyMs,"wait for the guest init of",b.name,async()=>{if((await n.run("check the guest init of",b.name,Ch(b.name),{check:!1})).exitCode===0)return!0;if((await a(b.name))?.state==="running")return!1;throw new Te("not-ready","start",b.name,"the guest stopped before its init was ready")})},m=async(b,A)=>{i(b,"hand the runner configuration to"),await n.run("hand the runner configuration to",b.name,Th(b.name),{stdin:A}),await c(t.runnerMs,"wait for the runner of",b.name,async()=>{let y=await l(b);if(y.kind==="runner-alive")return!0;if(y.kind==="running")return!1;throw new Te("not-ready","start the runner of",b.name,"the guest stopped first")})},g=async(b)=>{let A=i(b,"destroy");await u(b.name),A.pool.release(b.name),o.delete(b.name)},h=async(b)=>{i(b,"verify the removal of");let y=(await wr(n)).filter((S)=>S.id===b.name).map((S)=>`container ${S.id} (${S.state})`);return{checked:["container"],leftovers:y}},E=async()=>{let b=s("list its guests");return(await wr(n)).filter((A)=>A.labels[yo]===b.id&&Hn(A.id,b.prefix)).map((A)=>({driver:Si,name:A.id,pool:A.labels[jl]??""}))};async function*v(b,A){if(i(b,"read the logs of"),(await a(b.name))?.labels[Vl]!=="false")return;let C=(await n.run("read the logs of",b.name,Nh(b.name),{maxOutputChars:A.bytes})).stdout.replace(FT,"");yield{file:GT,text:C.slice(Math.max(0,C.length-A.bytes))}}return{capabilities:()=>He[Si].capabilities,capacity:async()=>{let b=s("report its capacity"),A=PT(NT());return{cpus:OT(),diskGiB:Math.floor(A.bavail*A.bsize/HT),guests:(await b.pool.status()).free.length,memoryMiB:Math.floor(IT()/Lh)}},checkHost:async()=>{let b=await Dh(n,Wn);if(b.answered)n.recover();return{findings:b.findings}},create:d,destroy:g,health:async()=>{let b=[...(await Dh(n,Wn)).findings];if(n.unavailable())b.push(KT());if(r)b.push(...await jT(r.pool));return{findings:b}},list:E,logs:v,networks:()=>s("manage its networks").pool,runJit:m,start:p,state:l,verifyGone:h}}function UT(e,t){if(!DT.test(t.id))throw Error(`Invalid fleet id "${t.id}"`);let n=t.dns??Kl;if(n.length===0)throw Error("A fleet needs at least one DNS server for its guests");for(let r of n)if(!Ds(r))throw Error(`The guest DNS server "${r}" must be a public IPv4 address`);return{dns:n,id:t.id,pool:Hm(e,t.id,t.networks),prefix:`hydra-${t.id}`}}function BT(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!==ko)?"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 Dh(e,t){let n;try{n=await Tm(e)}catch(o){return{answered:!1,findings:[VT(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 jT(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 VT(e,t){let n=e instanceof Te?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 KT(){return{code:"unresponsive",detail:`${Gs} 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 Ao=["arm64","amd64"];function Wl(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 je={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:[Wl("22.23.5","2babb9eb5264860d540849f4b064a6fbdebcdc323657d9d382ce23d313fd5e09","cdeb8670a0c81f51b4dc4ac61919f9b1ad917b304bf8221eb939570663d240f8"),Wl("24.22.3","6e51a2ada00f0011cc266f65d98922b403d7ad88f809ca2aa615a5fe1ce6e86c","4f2b175a6d53a5c617a80dba2676238a0688cef28c6da4eba35c7d844e66fcfb"),Wl("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"}},Hh={sha256:"25a065af409ffa317ab4d5a3b614dd15fc9c40f2172bc1b35a1b1258e919a388",url:"https://github.com/actions/runner/releases/download/v2.338.2/actions-runner-osx-arm64-2.338.2.tar.gz"};function Mh(e){return Ao.includes(e)}class $i extends Error{integrity;_tag="IntegrityError";constructor(e){super(`"${e}" is not an npm sha512 integrity value`);this.integrity=e;this.name="IntegrityError"}}var Bh="Developer ID Installer: Apple Inc. - Containerization (UPBK2H6LZM)",Gh=je.bun.version,Fh="2.42.0",Uh="0.26.0",qT="https://registry.npmjs.org",WT=64,JT=/^sha512-([A-Za-z0-9+/]{86}==)$/,YT={algorithm:"sha256",digest:"b5d6bc2e13caf14e57c89661e89efd073ff16165b41bfe43882616410609cd10",file:"bun-darwin-aarch64.zip",url:`https://github.com/oven-sh/bun/releases/download/bun-v${Gh}/bun-darwin-aarch64.zip`,version:Gh},zT={algorithm:"sha256",digest:"b6739caf3d47ca53a78f1a7edf32521420a75c7941838c3cefa75f30b80f5a97",file:`container-${Wn}-installer-signed.pkg`,url:`https://github.com/apple/container/releases/download/${Wn}/container-${Wn}-installer-signed.pkg`,version:Wn},XT={algorithm:"sha256",digest:"a95dda214b5f676298430d665a8174992e6b300dd20c653385b60481ae819ddf",file:"tart.tar.gz",url:`https://github.com/openai/tart/releases/download/${Fh}/tart.tar.gz`,version:Fh},QT={algorithm:"sha256",digest:"8469759f9cdfaaba52a150b629877985129308461702bc074c3ad7727837db82",file:"softnet.tar.gz",url:`https://github.com/openai/softnet/releases/download/${Uh}/softnet.tar.gz`,version:Uh};function jh(e){let n=`${Tr.split("/").pop()}-${qn}.tgz`;return{bun:YT,container:zT,hydra:{algorithm:"sha512",digest:ZT(e),file:n,url:`${qT}/${Tr}/-/${n}`,version:qn},softnet:QT,tart:XT}}function ZT(e){let t=JT.exec(e.trim()),n=t?Buffer.from(t[1],"base64"):void 0;if(!n||n.length!==WT)throw new $i(e);return n.toString("hex")}function Vh(e){return Object.values(e).map((t)=>`${t.file} ${t.algorithm} ${t.digest} ${t.url}
|
|
390
|
+
`).join("")}class Or extends Error{option;_tag="InstallScriptError";constructor(e,t){super(`${e} ${t}`);this.option=e;this.name="InstallScriptError"}}var St="com.apple.quarantine",t0=/^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/,n0=/\p{Cc}/u,r0=new Set(["wheel","admin","staff","everyone"]),o0="/usr/bin:/bin:/usr/sbin:/sbin",Jl="tar --no-same-owner --no-same-permissions -xzf",s0={sha256:256,sha512:512};function dt(e){return`'${e.replaceAll("'","'\\''")}'`}function i0(e){if(!e0(e.stage)||n0.test(e.stage))throw new Or("--stage","must be an absolute path without control characters");if(!t0.test(e.group))throw new Or("--group","must be a group name");if(r0.has(e.group))throw new Or("--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 a0(e=Pr()){let t=[e.bun,...Ml,e.cli].map(dt).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=${dt(Eo.join(":"))} HOME="$home" HYDRA_HOME="$home/.hydra" TART_NO_AUTO_PRUNE=1 TERM="\${TERM:-dumb}" ${t} "$@"`,""].join(`
|
|
391
|
+
`)}function Kh(e,t=Pr()){i0(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=${o0}`,"export PATH","cd /","",`prefix=${dt(a)}`,`stage=${dt(e.stage)}`,`group=${dt(e.group)}`,`container_root=${dt(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 ${St} "$file" >/dev/null 2>&1; then`,` fail "$file carries ${St}; 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((l)=>`take ${dt(l.file)} ${l.digest} ${s0[l.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 ${dt(Bh)} "$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"',`${Jl} "$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'`,a0(t).trimEnd(),"HYDRA_WRAPPER",'install -o root -g wheel -m 0755 "$work/wrapper" "$prefix/bin/hydra"',"",`echo "Installing Tart ${i.version}"`,'mkdir "$work/tart"',`${Jl} "$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"',`${Jl} "$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 ${St} | grep -q .; then fail "a file under $prefix carries ${St}"; 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(`
|
|
392
|
+
`)}class Co 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 c0=['<?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">'],qh=" ",l0=/\p{Cc}/u,u0={'"':""","&":"&","'":"'","<":"<",">":">"};function zl(e){return[...c0,...Wh(e,"",""),"</plist>",""].join(`
|
|
393
|
+
`)}function Wh(e,t,n){let r=`${t}${qh}`,o=[`${t}<dict>`];for(let[s,i]of Object.entries(e)){let a=n?`${n}.${s}`:s;o.push(`${r}<key>${Yl(s,a)}</key>`,...d0(i,r,a))}return o.push(`${t}</dict>`),o}function d0(e,t,n){if(typeof e==="boolean")return[`${t}<${e}/>`];if(typeof e==="number"){if(!Number.isSafeInteger(e))throw new Co(n);return[`${t}<integer>${e}</integer>`]}if(typeof e==="string")return[`${t}<string>${Yl(e,n)}</string>`];if(Array.isArray(e))return[`${t}<array>`,...e.map((r)=>`${t}${qh}<string>${Yl(r,n)}</string>`),`${t}</array>`];return Wh(e,t,n)}function Yl(e,t){if(l0.test(e))throw new Co(t);return e.replace(/["&'<>]/g,(n)=>u0[n])}class Ei extends Error{option;_tag="ServiceOptionError";constructor(e,t){super(`${e} ${t}`);this.option=e;this.name="ServiceOptionError"}}var Xl="org.r5nlabs.hydra",Jh=`${Xl}.host`,Xh="/Library/LaunchDaemons",Yh="/var/log/hydra-host.log",g0="serve.log",h0="/var/root",y0=0,Qh=30,w0=30,b0=60,zh=90,S0=18,R0=63,$0=18,v0="/usr/bin/xattr",E0=1e4,x0="/usr/bin:/bin:/usr/sbin:/sbin",k0=/\p{Cc}/u;function _0(e){return`${Xl}.fleet.${e}`}function Zh(e={}){let t=e.budget===void 0?[]:["--budget",To("--budget",e.budget)],n={Label:Jh,ProgramArguments:[...Gl(),"host","serve",...t],EnvironmentVariables:{HOME:h0,PATH:Eo.join(":")},WorkingDirectory:"/",Umask:S0,RunAtLoad:!0,KeepAlive:!0,ThrottleInterval:Qh,ExitTimeOut:w0,AbandonProcessGroup:!1,StandardOutPath:Yh,StandardErrorPath:Yh};return{label:Jh,plist:zl(n)}}function ey(e){let t=To("the Hydra home",e.home),n=e.socket===void 0?[]:["--socket",To("--socket",e.socket)],r=_0(e.fleet),o=vi(t,g0),s={Label:r,UserName:e.account,ProgramArguments:[...Gl(),"serve",...n],EnvironmentVariables:{HOME:To("the account's home directory",e.accountHome),HYDRA_HOME:t,PATH:Eo.join(":"),TART_NO_AUTO_PRUNE:"1"},WorkingDirectory:"/",Umask:R0,RunAtLoad:!0,KeepAlive:!0,ThrottleInterval:Qh,ExitTimeOut:b0,AbandonProcessGroup:!0,StandardOutPath:o,StandardErrorPath:o};return{label:r,plist:zl(s)}}function ty(e){let t=To("--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=${x0}`,"export PATH","cd /","",`label=${dt(n)}`,`staged=${dt(vi(t,o))}`,`target=${dt(vi(Xh,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 ${St} "$staged" >/dev/null 2>&1; then`,` fail "$staged carries ${St}, 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 ${zh} ] || fail "$label did not stop within ${zh} s"`," sleep 1"," waited=$((waited + 1))"," done","fi",'install -o root -g wheel -m 0644 "$work/plist" "$target"',`if xattr -p ${St} "$target" >/dev/null 2>&1; then fail "$target carries ${St}"; fi`,'launchctl bootstrap system "$target"','echo "Loaded $label from $target"',""].join(`
|
|
394
|
+
`)}async function ny(e={}){let t=e.directory??Xh,n=e.owners??[y0],r=e.quarantined??A0,o;try{o=f0(t).filter((i)=>i.startsWith(`${Xl}.`)&&i.endsWith(".plist"))}catch{return[]}let s=[];for(let i of o.sort()){let a=vi(t,i),c=p0(a),l="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&$0)!==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 ${St}, so launchd will not load it`,fix:"Install it again with the script from hydra service print --script",path:a})}return s}async function A0(e){if(process.platform!=="darwin")return!1;return await Bun.spawn([v0,"-p",St,e],{stderr:"ignore",stdin:"ignore",stdout:"ignore",timeout:E0}).exited===0}function To(e,t){if(m0(t)&&!k0.test(t))return t;throw new Ei(e,"must be an absolute path without control characters")}import{lstatSync as C0,readdirSync as T0,readFileSync as P0,readlinkSync as O0,realpathSync as I0}from"fs";import{dirname as ry,isAbsolute as N0,join as Po}from"path";var D0=0,L0=18,H0=4095,M0=2536,G0=/^([0-9a-f]{64}) [ *](\/.*)$/,F0=8,U0=32,Ir="Run the install script from hydra toolchain print --script again";async function oy(e={}){let t=e.layout??Pr(),n=W0(e.owners??[D0]),r=Z0(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 j0(t))if(!r.entries.has(i))n.findings.push({detail:"is not in the recorded checksums",fix:Ir,path:i});let{files:o,unreadable:s}=await V0(r.entries,n);K0(t.softnet,n);for(let i of e.pathDirs??B0(t))q0(i,n);return{files:o,findings:tP(n.findings),installed:!0,manifest:t.manifest,unreadable:s}}function B0(e){return[Po(e.prefix,"bin"),Po(e.containerRoot,"bin")]}function j0(e){return[e.hydra,e.bun,e.softnet,X0(e.tart)??e.tart,e.cli,Po(e.containerRoot,"bin","container")]}async function V0(e,t){let n=0,r=[];for(let[o,s]of e){if(t.check(o),!xi(o)?.isFile()){t.findings.push({detail:"is missing or no longer a regular file",fix:Ir,path:o});continue}let a=await eP(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:Ir,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 ${Ir.toLowerCase()}`,path:o})}return{files:n,unreadable:r}}function K0(e,t){let n=xi(e);if(!n?.isFile())return;let r=n.mode&H0;if(t.owners.includes(n.uid)&&r===M0)return;t.findings.push({detail:`is owned by uid ${n.uid} with mode ${r.toString(F0).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 q0(e,t){t.check(e);let n;try{n=T0(e)}catch{return}for(let r of n)t.check(Po(e,r))}function W0(e){let t=[],n=new Map,r=(s,i)=>{let a=n.get(s);if(a!==void 0)return a;let c=xi(s),l=c?Y0(c,e):void 0;if(l)t.push({detail:i?`${l} (reached from ${i})`:l,fix:z0(s),path:s});return n.set(s,l===void 0),l===void 0};return{check:(s)=>{let i=[],{end:a,links:c}=J0(s,i),l=new Set(sy(s)),u=i.some((d)=>!l.has(d))?s:void 0;for(let d of i)r(d,l.has(d)?void 0:u);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 J0(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===".."?ry(r):r;continue}let i=Po(r,s),a=xi(i);if(!a)return{end:"missing",links:o};if(t.push(i),!a.isSymbolicLink()){r=i;continue}if(o+=1,o>U0)return{end:"loop",links:o};let c=Q0(i);if(c===void 0)return{end:"missing",links:o};r=N0(c)?"/":r,n.unshift(...c.split("/").filter(Boolean))}return{end:"found",links:o}}function Y0(e,t){if(!t.includes(e.uid))return`is owned by uid ${e.uid}, not root`;if(e.isSymbolicLink())return;return(e.mode&L0)===0?void 0:"is writable by its group or by other users"}function z0(e){return`Make ${e} owned by root and writable only by root, or move it out of the path Hydra runs from`}function sy(e){let t=ry(e);return t===e?[e]:[...sy(t),e]}function X0(e){try{return I0(e)}catch{return}}function Q0(e){try{return O0(e)}catch{return}}function xi(e){try{return C0(e)}catch{return}}function Z0(e){let t;try{t=P0(e,"utf-8")}catch(o){if(o.code==="ENOENT")return;return{entries:new Map,problems:[{detail:`cannot be read (${o.message})`,fix:Ir,path:e}]}}let n=new Map,r=[];for(let[o,s]of t.split(`
|
|
395
|
+
`).entries()){if(s==="")continue;let i=G0.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:Ir,path:e})}return{entries:n,problems:r}}async function eP(e){let t=new Bun.CryptoHasher("sha256");return t.update(await Bun.file(e).bytes()),t.digest("hex")}function tP(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 ki(){let e=await oy(),t=e.installed?[...e.findings,...await ny()]:[];return{findings:t,lines:nP(e,t),report:e}}function nP(e,t){if(!e.installed)return[`${f.bold("Toolchain")} ${f.dim(`not installed: ${e.manifest} is missing`)}`,f.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[`${f.bold("Toolchain")} ${f.green("\u2713")} ${r}; every path Hydra runs from is writable only by root`];return[`${f.bold("Toolchain")} ${f.red(`${t.length} problem${t.length===1?"":"s"}`)} ${f.dim(`(${r})`)}`,...t.flatMap((o)=>[` ${f.red("\u2717")} ${o.path} ${o.detail}`,f.dim(` ${o.fix}`)])]}function _i(e){return`The toolchain in ${Cr} has ${e.length} problem${e.length===1?"":"s"}`}var rP={configured:{paint:f.green,text:"configured"},foreign:{paint:f.yellow,text:"set to another script"},missing:{paint:f.yellow,text:"missing"},off:{paint:f.dim,text:"off"},outdated:{paint:f.yellow,text:"outdated"}},iy=new Set(["missing","outdated"]);class Ai extends I{name="doctor";description="Check the home, credentials, alert sinks and host toolchain, and each 0.x runner's DNS and job hooks";async execute(e){M(e.args,this.args,"Run 'hydra doctor --help' for supported options");let t=ie(e.config),n=Os(t,process.cwd(),process.env),r=zs(e.config),o=r?[]:await this.credentialLines(e.config.get("credentials")),s=r?!1:Object.keys(e.config.get("pools")??{}).length>0,i=r?[]:qf(e.config.get("alerts"),{env:process.env,home:t,now:Date.now(),pools:s}),a=await ki();if(k.info([...this.homeLines(t,n),...o,...i,...a.lines].join(`
|
|
396
|
+
`)),r)throw r;if(s&&yt(e.config.get("alerts")).length===0)throw new w("Pools need an alert sink",Dn);if(a.findings.length>0)throw new w(_i(a.findings),"Fix each path above, then run hydra toolchain verify");let c=e.config.get("profiles");if(Object.keys(c).length===0){if(s)return;throw new w("No pools configured",n.length>0?`Run hydra pool add, or pass ${Ee} with one of the homes above`:"Run hydra pool add to add a pool")}let l=e.config.get("runners")??[],u=await Dl(),d=[`${f.bold("DNS servers")} ${u.length>0?u.join(", "):f.dim("unknown")}`],p=!1,m=!1;for(let[g,h]of Object.entries(c)){let E=Jt(h.jobHooks);d.push("",`${f.bold(g)} ${f.dim(h.url)}`),d.push(...await this.dnsLines(E.dns)),d.push(this.cleanupLine(E));let v=await this.runnerLines(e.config,h,E,l.filter((R)=>R.profile===g));d.push(...v.lines),p||=v.needsUpdate,m||=v.needsRestart}if(p)d.push("",f.yellow(`Run ${f.green("hydra legacy update")} to write the missing hooks.`));if(m)d.push("",f.yellow('Restart runners marked "restart" once they are idle: hydra legacy halt <profile> && hydra legacy start <profile>'));k.info(d.join(`
|
|
397
|
+
`))}homeLines(e,t){let n=[`${f.bold("Home")} ${e}`];if(t.length===0)return n;n.push(f.yellow("Other Hydra homes, not used by this run:"));for(let r of t){let o=r.counts?`${ay(r.counts.profiles,"profile")}, ${ay(r.counts.runners,"runner")}`:"unreadable config";n.push(` ${r.path} ${f.dim(o)}`)}return n.push(f.dim(` Manage one with ${Ee} <path> or ${at}=<path>`)),n}async dnsLines(e){let t=[` DNS wait: ${e.enabled?`on, up to ${e.timeoutSeconds} s`:f.dim("off")}`];if(!Ll())return[...t,f.yellow(" No dscacheutil or getent to look hosts up with")];for(let n of e.hosts){let r=await Hl(n);t.push(r.addresses.length>0?` ${f.green("\u2713")} ${n} ${f.dim(`${r.durationMs} ms \xB7 ${r.addresses.join(", ")}`)}`:` ${f.red("\u2717")} ${n} ${f.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"}`:f.dim("off")}`}async credentialLines(e){let t=[`${f.bold("GitHub credentials")} ${kg(e)}`,...this.apiRootLines()];if(e?.mode!=="app")return t;let n=await _g(e.privateKeyPath);return n?[...t,f.yellow(` The private key ${n}`)]:t}apiRootLines(){if(!process.env[$r])return[];try{let e=f.dim(`(from ${$r}; Hydra sends its tokens there)`);return[`${f.bold("GitHub API")} ${un(process.env)} ${e}`]}catch(e){if(!(e instanceof w))throw e;return[f.yellow(` ${e.message}`),...e.hint?[f.dim(` ${e.hint}`)]:[]]}}async runnerLines(e,t,n,r){if(r.length===0)return{lines:[f.dim(" No runners.")],needsRestart:!1,needsUpdate:!1};let o=new Map((await ve(t,e).list()).map((l)=>[l.id,l])),s=[...r].sort((l,u)=>l.id.localeCompare(u.id,void 0,{numeric:!0})),i=[],a=!1,c=!1;for(let l of s){let u=o.get(l.id),{envModifiedAt:d,states:p}=await $l(l.directory,n),m=this.loadedBefore(u,d);a||=m,c||=iy.has(p.started)||iy.has(p.completed),i.push([` ${l.id}`,f.dim(u?.status??"unknown"),`DNS wait ${this.stateLabel(p.started)}`,`cleanup ${this.stateLabel(p.completed)}`,m?f.yellow("restart"):""].filter(Boolean).join(" "))}return{lines:i,needsRestart:a,needsUpdate:c}}stateLabel(e){let{paint:t,text:n}=rP[e];return t(n)}loadedBefore(e,t){if(e?.status!=="running"||!e.startedAt||!t)return!1;return t>e.startedAt}}function ay(e,t){return`${e} ${t}${e===1?"":"s"}`}class Nr 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",oP=`${Ge}/accept`,sP=`${Ge}/ready`,Zl="/var/run/hydra",cy=`${Zl}/exit`,iP="rosetta",aP=30,Ql="exit=",cP=`ps -axo comm= 2>/dev/null; if [ -f ${cy} ]; then printf '${Ql}%s\\n' "$(cat ${cy})"; fi; exit 0`,lP=`f=$(ls -t ${gn}/_diag/Runner_*.log 2>/dev/null | head -n 1); if [ -n "$f" ]; then cat "$f"; fi; exit 0`;function Ci(e,t){return["clone",e,t]}function ly(e,t,n,r){return["set",e,"--cpu",String(t),"--memory",String(n),"--disk-size",String(r)]}function Ti(e){return["run","--no-graphics","--no-audio","--net-softnet",`--net-softnet-block=${e.blocks.join(",")}`,...e.rosetta?[`--rosetta=${iP}`]:[],e.name]}function uy(e){return["exec",e,sP]}function dy(e){return["exec","-i",e,oP]}function py(e){return["exec",e,"/bin/sh","-c",cP]}function fy(e){return["exec",e,"/bin/sh","-c",lP]}function Oo(e){return["stop","--timeout",String(aP),e]}function Io(e){return["delete",e]}function my(){return["--version"]}function gy(e){let t,n=[];for(let r of e.split(`
|
|
398
|
+
`).map((o)=>o.trim())){if(r.startsWith(Ql)){let o=Number(r.slice(Ql.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 gO,readFileSync as hO,statfsSync as yO}from"fs";import{availableParallelism as wO,freemem as bO,homedir as Fy}from"os";import{join as SO}from"path";import{randomBytes as bP}from"crypto";import{existsSync as SP,lstatSync as RP,mkdirSync as $P,readdirSync as vP,readFileSync as EP,renameSync as xP,rmSync as kP,writeFileSync as _P}from"fs";import{join as Yn}from"path";import{spawn as uP}from"child_process";import{closeSync as dP,constants as Pi,fchmodSync as pP,openSync as fP}from"fs";class Ae 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 Ii="tart",Ni=3,Oi=1000,No=60*Oi,mP=10,gP="[redacted]",hP=4194304,hy=384,Di={callMs:No,cloneMs:10*No,exitMs:10*Oi,pollMs:2*Oi,readyMs:5*No,runnerMs:No,stopMs:2*No};function Li(e){return{...process.env,TART_HOME:e,TART_NO_AUTO_PRUNE:"1"}}function Hi(e,t,n){let r=0,o=!1;return{binary:e,env:n,launch:(c,l,u)=>{Vt("tart",l);let d=Pi.O_WRONLY|Pi.O_CREAT|Pi.O_TRUNC|Pi.O_NOFOLLOW,p=fP(u,d,hy);try{pP(p,hy);let m=uP(e,[...l],{detached:!0,env:n,stdio:["ignore",p,p]});if(m.pid===void 0)throw new Ae("missing","start",c,`${e} could not start`);return m.on("error",()=>{return}),m.unref(),m.pid}finally{dP(p)}},limits:t,recover:()=>{r=0,o=!1},run:async(c,l,u,d={})=>{Vt("tart",u,d.stdin);let p=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??hP,E=await yP(c,l,[e,...u],{echo:d.echo,env:n,input:g,maxOutputChars:h,timeoutMs:p});if(E.timedOut)throw r+=1,o||=r>=Ni,new Ae("timeout",c,l,`${e} did not finish within ${p/Oi} s`);r=0;let v={exitCode:E.exitCode,stderr:yy(E.stderr,d.stdin),stdout:yy(E.stdout,d.stdin)};if(v.exitCode===0||d.check===!1)return v;throw new Ae("failed",c,l,wP(e,v))}finally{g?.fill(0)}},unavailable:()=>o}}async function yP(e,t,n,r){try{return await lt(n,r)}catch(o){let s=o instanceof Error?o.message:String(o);throw new Ae("missing",e,t,`${n[0]} could not start (${s})`,{cause:o})}}function yy(e,t){return t?.contains(e)?gP:e}function wP(e,t){let n=t.stderr.trim().split(`
|
|
399
|
+
`).slice(-mP).join(`
|
|
400
|
+
`);return`${e} exited with code ${t.exitCode}${n?`
|
|
401
|
+
${n}`:""}`}var AP=["general","secret"],CP=["candidate","promoted","previous"];class Jn 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 Ry="goldens",wy={config:"config.json",disk:"disk.img"},TP={general:86400000,secret:3600000},PP=/^golden-(macos|linux)-(general|secret)-[0-9a-f]{12}$/,OP=6,eu=".json",IP=448,NP=384,DP=18,LP=/^[0-9a-f]{64}$/,HP="vms",by=N().map((e)=>LP.test(e)?e:B()),MP=H({base:N(),builtAt:N(),guestOs:Y(["linux","macos"]),name:N(),promotedAt:N().or(oe()),runner:N(),sha256:H({config:by,disk:by}),status:Y(CP),variant:Y(AP)});function $y(e,t){return`golden-${e}-${t}-${bP(OP).toString("hex")}`}function Mi(e){let t=PP.exec(e);return t?{guestOs:t[1],variant:t[2]}:void 0}function hn(e){return e?"secret":"general"}function Do(e){let t=Yn(e,Ry);if(!SP(t)||!_y(t,"directory"))return[];return vP(t).filter((n)=>n.endsWith(eu)).flatMap((n)=>GP(Yn(t,n),n.slice(0,-eu.length))).sort((n,r)=>Date.parse(r.builtAt)-Date.parse(n.builtAt))}function vy(e,t,n){return Do(e).find((r)=>r.status==="promoted"&&r.guestOs===t&&r.variant===n)}function Gi(e,t){let n=Yn(e,Ry);$P(n,{mode:IP,recursive:!0});let r=Yn(n,`${t.name}${eu}`),o=`${r}.${process.pid}.tmp`;try{_P(o,`${JSON.stringify(t,null,2)}
|
|
402
|
+
`,{flag:"wx",mode:NP}),xP(o,r)}finally{kP(o,{force:!0})}}async function tu(e,t){let n=Yn(e,HP,t),[r,o]=await Promise.all([Sy(Yn(n,wy.config)),Sy(Yn(n,wy.disk))]);return{config:r,disk:o}}async function Ey(e,t){try{let n=await tu(e,t.name);return n.config===t.sha256.config&&n.disk===t.sha256.disk}catch{return!1}}function xy(e,t,n=Date.now){let r=new Map,o=new Map,s=new Set,i=(a,c)=>{let l=o.get(a);if(l)return l;let u=(async()=>{let d=Do(e).find((m)=>m.name===a);return d!==void 0&&(!c||d.status==="promoted")&&await Ey(t,d)})().finally(()=>o.delete(a));return o.set(a,u),u};return async(a,c)=>{let l=r.get(a),u=l!==void 0&&n()-l<TP[hn(c)];if(!s.has(a)&&u)return;if(s.has(a)||!await i(a,c))throw s.add(a),new Ae("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 ky(e){let{home:t,name:n}=e,r=Do(t),o=r.find((a)=>a.name===n);if(!o)throw new Jn("missing",n,"no golden of that name is recorded in this home");if(o.status==="promoted")throw new Jn("state",n,"it is already promoted");if(o.variant==="secret"&&e.approve!==o.sha256.disk)throw new Jn("approval",n,"a golden for secret-bearing pools is promoted only with --approve and the SHA-256 of its disk");if(!await Ey(e.store,o))throw new Jn("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")Gi(t,{...a,status:"previous"});let i={...o,promotedAt:s,status:"promoted"};return Gi(t,i),i}async function Sy(e){let t=new Bun.CryptoHasher("sha256");for await(let n of Bun.file(e).stream())t.update(n);return t.digest("hex")}function GP(e,t){if(!_y(e,"file"))return[];try{let n=MP(JSON.parse(EP(e,"utf8")));return n.name===t&&Mi(t)?.guestOs===n.guestOs&&Mi(t)?.variant===n.variant&&!Number.isNaN(Date.parse(n.builtAt))?[n]:[]}catch{return[]}}function _y(e,t){let n=RP(e);return(t==="directory"?n.isDirectory():n.isFile())&&n.uid===process.getuid?.()&&(n.mode&DP)===0}import{existsSync as Cy,lstatSync as FP,statSync as UP}from"fs";import{delimiter as BP,join as jP}from"path";var Fi="2.42.0",VP="0.26.0",Ay="softnet",KP=2048,Ty=18,qP=1,WP=0,JP=/\d+\.\d+\.\d+/;async function Py(e){try{let n=(await e.run("read the version of",e.binary,my())).stdout.match(JP)?.[0];if(n===Fi)return{answered:!0,findings:[]};return{answered:!0,findings:[{code:"tool-version",detail:`${e.binary} is version ${n??"(unknown)"}; Hydra is pinned to ${Fi}`,fix:`Install Tart ${Fi} 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 Ae?t.reason:"failed",o=r==="missing"?`Install Tart ${Fi} 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 Oy(e){let t=(e??"").split(BP).filter(Boolean).map((o)=>jP(o,Ay)).find((o)=>Cy(o));if(!t)return[{code:"softnet-missing",detail:`${Ay} is not on PATH, so Tart cannot isolate its guests' network`,fix:`Install softnet ${VP} beside Tart, owned by root with mode 4750 and the fleet's group`,level:"error"}];let n=UP(t),r=[];if(n.uid!==WP||(n.mode&KP)===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&Ty)!==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&qP)!==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 Iy(e){if(!Cy(e))return[];let t=FP(e),n=[t.isDirectory()?"":"is not a directory",t.uid===process.getuid?.()?"":"belongs to another user",(t.mode&Ty)===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 YP}from"os";var Ny=["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"],zP=32,XP=Ny.map((e)=>et(e));function Ui(e=YP()){let t=Object.values(e).flatMap((n)=>n??[]).filter((n)=>n.family==="IPv4").map((n)=>n.address).filter((n)=>{let r=gr(n);return r!==void 0&&!XP.some((o)=>hr(o,r))});return[...Ny,...[...new Set(t)].sort().map((n)=>`${n}/${zP}`)]}import{closeSync as QP,constants as Bi,existsSync as ru,fchmodSync as ZP,lstatSync as eO,mkdirSync as tO,openSync as nO,readdirSync as rO,readFileSync as Hy,renameSync as oO,rmSync as nu,writeSync as sO}from"fs";import{join as ji}from"path";var My="vms",iO="config.json",aO=448,Dy=384,cO=1e4,lO=250,uO=5000,Ly={darwin:"macos",linux:"linux"},dO=H({guestOs:Y(["linux","macos"]),pid:X().or(oe()),pool:N(),rosetta:Z(),secretBearing:Z()}),pO=H({os:N()});function ou(e,t){return ji(e,My,t)}function su(e){let t=ji(e,My);if(!ru(t))return[];return rO(t,{withFileTypes:!0}).filter((n)=>n.isDirectory()).map((n)=>({guestOs:mO(ji(t,n.name,iO)),name:n.name})).sort((n,r)=>n.name.localeCompare(r.name))}function Dr(e,t){return ru(ou(e,t))}function Gy(e){let t=()=>tO(e,{mode:aO,recursive:!0}),n=(r,o)=>ji(e,`${r}${o}`);return{dir:e,log:(r)=>(t(),n(r,".log")),read:(r)=>{let o=n(r,".json");if(!ru(o)||!eO(o).isFile())return;try{return dO(JSON.parse(Hy(o,"utf8")))}catch{return}},remove:(r)=>{nu(n(r,".json"),{force:!0}),nu(n(r,".log"),{force:!0})},write:(r,o)=>{t();let s=n(r,".json"),i=`${s}.${process.pid}.tmp`;nu(i,{force:!0});let a=Bi.O_WRONLY|Bi.O_CREAT|Bi.O_EXCL|Bi.O_NOFOLLOW,c=nO(i,a,Dy);try{ZP(c,Dy),sO(c,`${JSON.stringify(o)}
|
|
403
|
+
`)}finally{QP(c)}oO(i,s)}}}async function Pt(e,t){if(e===void 0||!fO(e))return!1;let n=await lt(["ps","-ww","-o","args=","-p",String(e)],{timeoutMs:cO}),r=n.stdout.trim().split(/\s+/);return n.exitCode===0&&r.includes("run")&&r.at(-1)===t}async function Vi(e,t,n){let r=Date.now()+n;while(await Pt(e,t)){if(Date.now()>=r)return!1;await Bun.sleep(lO)}return!0}async function Ki(e,t,n){if(e===void 0||await Vi(e,t,n))return!0;try{process.kill(e,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}return Vi(e,t,uO)}function fO(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function mO(e){try{let{os:t}=pO(JSON.parse(Hy(e,"utf8")));return Object.hasOwn(Ly,t)?Ly[t]:void 0}catch{return}}var qi="tart",RO=/^[a-z0-9]+$/,Uy=1048576,$O=1024*Uy,vO=1000,EO=2000,xO="Runner.log",By=/[^\P{Cc}\n\t]/gu,kO=/VZErrorDomain Code=6\b|virtualMachineLimitExceeded|number of virtual machines exceeds the limit/i;function zn(){return process.env.TART_HOME||SO(Fy(),".tart")}function Wi(e={}){let t={...Di,...e.limits},n=e.store??zn(),r=Hi(e.binary??Ii,t,Li(n)),o=e.fleet?_O(e.fleet):void 0,s=e.blocks??Ui(),i=(y)=>{if(o)return o;throw Error(`The tart driver needs a fleet to ${y}`)},a=(y,S)=>{let C=i(S);if(y.driver!==qi||!Hn(y.name,C.prefix))throw new Ae("invalid-name",S,y.name,`it is not a guest of fleet ${C.id}`);return C},c=(y,S,C)=>{let x=y.files.read(S);if(x)return x;throw new Ae("not-ready",C,S,"Hydra holds no record of creating it")},l=async(y,S,C,x)=>{let L=Date.now()+y;while(!await x()){if(Date.now()>=L)throw new Ae("not-ready",S,C,`no answer within ${y/vO} s`);await Bun.sleep(t.pollMs)}},u=async(y,S)=>{let C=su(n).filter((L)=>L.guestOs==="macos"&&L.name!==S);return(await Promise.all(C.map((L)=>Pt(y.files.read(L.name)?.pid,L.name)))).filter(Boolean).length},d=async(y)=>{let S={driver:qi,name:y.name,pool:y.pool},C=a(S,"create"),x=Mi(y.image);if(!x||x.guestOs!==y.guestOs||x.variant!==hn(y.secretBearing)){let L=`a ${y.secretBearing?"secret-bearing":"general"} ${y.guestOs} golden`;throw new Ae("refused-config","create",y.name,`${y.image} is not ${L}`)}if(r.unavailable())throw new Ae("unavailable","create",y.name,`${Ni} tart calls in a row timed out; a host check that finds the tool answering lifts this`);if(!Dr(n,y.image))throw new Ae("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,Ci(y.image,y.name),{timeoutMs:t.cloneMs});try{await r.run("size",y.name,ly(y.name,y.cpus,y.memoryMiB,y.diskGiB)),C.files.write(y.name,{guestOs:y.guestOs,pool:y.pool,rosetta:y.guestOs==="linux"&&y.foreignArch,secretBearing:y.secretBearing})}catch(L){throw await r.run("delete",y.name,Io(y.name),{check:!1}),C.files.remove(y.name),L}return S},p=async(y)=>{let S=a(y,"start"),C=c(S,y.name,"start");if(C.guestOs==="macos"&&await u(S,y.name)>=an)throw new Nr("start",y.name,`${an} macOS VMs already run on this host`);let x=S.files.log(y.name),L=r.launch(y.name,Ti({blocks:s,name:y.name,rosetta:C.rosetta}),x);S.files.write(y.name,{...C,pid:L}),await l(t.readyMs,"wait for the guest of",y.name,async()=>{if((await r.run("check the guest of",y.name,uy(y.name),{check:!1})).exitCode===0)return!0;if(await Pt(L,y.name))return!1;let K=AO(x);if(kO.test(K))throw new Nr("start",y.name,"Virtualization.framework refused another VM on this host");throw new Ae("not-ready","start",y.name,`the VM stopped before its guest was ready${K?`
|
|
404
|
+
${K}`:""}`)})},m=async(y)=>{let S=a(y,"read the state of a guest");if(!Dr(n,y.name))return{kind:"gone"};let C=S.files.read(y.name);if(C?.pid===void 0)return{kind:"preparing"};if(!await Pt(C.pid,y.name))return{code:ql,kind:"exited"};let x=await r.run("list the processes of",y.name,py(y.name),{check:!1});if(x.exitCode!==0)return{kind:"running"};let{exitCode:L,processes:V}=gy(x.stdout);if(L!==void 0)return{code:L,kind:"exited"};return V.includes(wi)?{busy:V.includes(bi),kind:"runner-alive"}:{kind:"running"}},g=async(y,S)=>{a(y,"hand the runner configuration to"),await r.run("hand the runner configuration to",y.name,dy(y.name),{stdin:S}),await l(t.runnerMs,"wait for the runner of",y.name,async()=>{let C=await m(y);if(C.kind==="runner-alive")return!0;if(C.kind==="running")return!1;throw new Ae("not-ready","start the runner of",y.name,"the runner or the VM stopped first")})},h=async(y)=>{let S=a(y,"destroy"),C=S.files.read(y.name)?.pid;if(Dr(n,y.name)||await Pt(C,y.name)){if(await r.run("stop",y.name,Oo(y.name),{check:!1,timeoutMs:t.stopMs}),!await Ki(C,y.name,t.exitMs))throw new Ae("failed","stop",y.name,`its tart run process ${C} outlived SIGKILL`)}if(Dr(n,y.name))await r.run("delete",y.name,Io(y.name));S.files.remove(y.name)},E=async(y)=>{let C=a(y,"verify the removal of").files.read(y.name)?.pid,x=[Dr(n,y.name)?`VM directory ${ou(n,y.name)}`:"",await Pt(C,y.name)?`tart run process ${C}`:""].filter(Boolean);return{checked:["store","process"],leftovers:x}},v=async()=>{let y=i("list its guests");return su(n).filter((S)=>Hn(S.name,y.prefix)).map((S)=>({driver:qi,name:S.name,pool:y.files.read(S.name)?.pool??""}))};async function*R(y,S){if(a(y,"read the logs of").files.read(y.name)?.secretBearing!==!1)return;let V=(await r.run("read the logs of",y.name,fy(y.name),{maxOutputChars:S.bytes})).stdout.replace(By,"");if(V)yield{file:xO,text:V.slice(Math.max(0,V.length-S.bytes))}}let _=async()=>{let y=await Py(r);if(y.answered)r.recover();return[...y.findings,...Oy(r.env.PATH),...Iy(n)]};return{capabilities:()=>He[qi].capabilities,capacity:async()=>{let y=i("report its capacity"),S=yO(gO(n)?n:Fy());return{cpus:wO(),diskGiB:Math.floor(S.bavail*S.bsize/$O),guests:Math.max(0,an-await u(y)),memoryMiB:Math.floor(bO()/Uy)}},checkHost:async()=>({findings:await _()}),create:d,destroy:h,health:async()=>{let y=await _();if(r.unavailable())y.push(CO());return{findings:y}},list:v,logs:R,runJit:g,start:p,state:m,store:n,verifyGone:E}}function _O(e){if(!RO.test(e.id))throw Error(`Invalid fleet id "${e.id}"`);return{files:Gy(e.stateDir),id:e.id,prefix:`hydra-${e.id}`}}function AO(e){try{let t=hO(e,"utf8").replace(By,"").trim();return t.slice(Math.max(0,t.length-EO))}catch{return""}}function CO(){return{code:"unresponsive",detail:`${Ni} 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 Ji(){return{"apple-container":Ri(),tart:Wi()}}var TO=Symbol.for("nodejs.util.inspect.custom"),PO=/[\r\n]/;function Yi(e){if(e.length===0||PO.test(e))throw Error("A stdin secret must be one non-empty line");return Object.defineProperty({contains:(n)=>n.includes(e),line:()=>`${e}
|
|
405
|
+
`,toJSON:()=>"[redacted]",toString:()=>"[redacted]"},TO,{value:()=>"[redacted]"})}var OO={full:"Docker",limited:"limited Docker",none:"no Docker"},IO={none:"no other architectures",qemu:"other architectures through QEMU",rosetta:"other architectures through Rosetta"},NO={"guest-side":"guest-side network filter","host-side":"host-side network filter",none:"no network filter"},DO={"host-user":"a host user each","user-space-kernel":"a user-space kernel each",vm:"a VM each"};function jy(e){let t=He[e].capabilities;return[`${t.guestOs.map((r)=>qt[r]).join(" and ")} guests on ${cn[t.hostOs]}, ${DO[t.isolation]}`,OO[t.docker],IO[t.foreignArch],t.guiSession?"desktop session":"",NO[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 Vy(e){let t=e.status==="available"?f.green("\u2713"):f.red("\u2717"),n=e.status==="available"?f.green(e.status):f.red(e.status);return[`${t} ${f.bold(e.driver)} ${n}`,...e.findings.flatMap(LO)]}function LO(e){return[` ${e.level==="error"?f.red(e.level):f.yellow(e.level)} ${e.code}: ${e.detail}`,f.dim(` Fix: ${e.fix}`)]}var HO=le({driver:{description:"Driver to check (default: every driver for this host)"}});class iu extends I{name="check";description="Check whether this host can run a slot driver, with a fix for each finding";positionals=HO;async execute(e){M(e.args,this.args,"Run 'hydra driver check --help' for supported options");let t=e.positionals.driver;if(t!==void 0&&!Vm(t))throw new w(`Unknown driver "${t}"`,`Choose one of: ${wt.join(", ")}`);let n=await ln(),r=t?[t]:n.os?Jm(n.os):[];if(r.length===0)throw new w(`Hydra has no slot driver for ${n.osName} hosts`);let o=Ji(),s=[];for(let a of r)s.push(await zm(a,n,o));k.info([`${f.bold("Host")} ${js(n)}`,"",...s.flatMap(Vy)].join(`
|
|
406
|
+
`));let i=s.filter((a)=>a.status==="unavailable");if(i.length===0)return;throw new w(t?`${t} is unavailable on this host`:`${i.length} of ${s.length} drivers are unavailable on this host`,"Each error above names its fix")}}var MO=["linux","macos"],GO={allowWeakerIsolation:!1,docker:"none",foreignArch:!1,guiSession:!1,secretBearing:!1};class au extends I{name="list";description="List slot drivers, what each guarantees and whether this host can run it";async execute(e){M(e.args,this.args,"Run 'hydra driver list --help' for supported options");let t=await ln(),n=Ji(),r=[`${f.bold("Host")} ${js(t)}`];for(let o of wt){let s=qs(o,t).find((c)=>c.level==="error"),i=s?`${f.red("\u2717")} ${s.detail}`:`${f.green("\u2713")} this host`,a=n[o]?"":f.dim(" \xB7 not in this version");r.push("",`${f.bold(o)} ${i}${a}`,f.dim(` ${jy(o)}`))}r.push("",`${f.bold("auto")} ${MO.map((o)=>FO(o,t)).join(" \xB7 ")}`),k.info(r.join(`
|
|
407
|
+
`))}}function FO(e,t){let n=Ks(ut,{...GO,guestOs:e},t);return`${qt[e]} guests: ${n.kind==="resolved"?n.driver:f.dim("none")}`}class zi extends I{name="driver";description="List slot drivers and check this host for them";init(){this.registerSubcommands([new au,new iu])}}var cu=["first_time_contributors_new_to_github","first_time_contributors","all_external_contributors"],Ky="public",qy=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B()),Wy=H({approval_policy:Y(cu)}).map((e)=>e.approval_policy),Jy=H({require_approval_for_fork_pr_workflows:Z(),run_workflows_from_fork_pull_requests:Z(),send_secrets_and_variables:Z(),send_write_tokens_to_workflows:Z()}).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})),UO=H({allows_public_repositories:Z(),default:Z(),id:qy,name:N(),restricted_to_workflows:Z().or(oe()),selected_workflows:ee(N()).or(oe()),visibility:N()}).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})),BO=H({full_name:N(),id:qy}).map((e)=>({id:e.id,name:e.full_name})),jO=H({private:Z(),visibility:Y(["internal","private","public"]).or(oe())}).map((e)=>e.visibility??(e.private?"private":Ky));function VO(e){return`/orgs/${encodeURIComponent(e)}/actions/permissions`}async function Yy(e,t){let n=VO(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:Jy});return{approval:await e.request({operation:`Read the fork pull request approval policy of ${t}`,path:`${n}/fork-pr-contributor-approval`,schema:Wy}),privateRepositories:r}}async function zy(e,t,n){return e.request({operation:`Read the visibility of ${t}/${n}`,path:ti({owner:t,repo:n}),schema:jO})}async function Xy(e,t,n,r){let o=`${ti({owner:t,repo:n})}/actions/permissions`;if(r===Ky)return{approval:await e.request({operation:`Read the fork pull request approval policy of ${t}/${n}`,path:`${o}/fork-pr-contributor-approval`,schema:Wy})};return{privateRepositories:await e.request({operation:`Read the fork pull request settings of ${t}/${n}`,path:`${o}/fork-pr-workflows-private-repos`,schema:Jy})}}async function Qy(e,t){return e.paginate({item:UO,key:"runner_groups",operation:`List the runner groups of ${t} with their settings`,path:Ct(t)})}async function Zy(e,t,n){return(await e.paginate({item:BO,key:"repositories",operation:`List the repositories that may use the runner group ${n.name} of ${t}`,path:`${Ct(t)}/${n.id}/repositories`})).sort((o,s)=>o.id-s.id)}var KO="selected";function Qi(e){return{async snapshots(t){let n=new Map,r=new Map,o=new Map,s=new Map,i=async(u,d)=>{let p=d.visibility===KO?await Zy(e,u,d):void 0;return{runners:(await ni(e,u,d)).map(ew),state:p?{...d,repositories:p}:d}},a=async(u,d)=>{let p=await Xi(n,u,()=>Yy(e,u)),g=(await Xi(r,u,()=>Qy(e,u))).find((E)=>E.name.toLowerCase()===d.toLowerCase());if(!g)return{forkPolicy:p,runners:[],scope:{groupName:d,kind:"org",org:u}};let h=await Xi(o,`${u}/${g.id}`,()=>i(u,g));return{forkPolicy:p,runners:h.runners,scope:{group:h.state,groupName:d,kind:"org",org:u}}},c=async(u,d)=>{let p=`${u}/${d}`;return Xi(s,p,async()=>{let m=await zy(e,u,d),g=await Xy(e,u,d,m),h=await dn(e,{kind:"repo",owner:u,repo:d});return{forkPolicy:g,runners:h.map(ew),scope:{kind:"repo",repository:p,visibility:m}}})},l={};for(let[u,d]of Object.entries(t)){let p=me(d.url),m=p.kind==="org"?await a(p.org,d.runnerGroup??""):await c(p.owner,p.repo);l[u]={...m,url:d.url}}return l}}}function Rt(e){return e.kind==="org"?`runner group ${e.groupName} of ${e.org}`:`repository ${e.repository}`}function ew(e){return{id:e.id,name:e.name}}async function Xi(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 qO="public",WO="the guard record holds no baseline for this pool",tw={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 Lo(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 pu(e,t){return e.ids.has(t.id)||e.names.has(t.name)}function ta({baseline:e,config:t,minted:n,snapshot:r}){let o=fu(t,r.scope);if(!e)return[...o,{detail:WO,kind:"unrecorded"}];let s=JO(e,t,r.scope);if(s)return[...o,{detail:s,kind:"unrecorded"}];o.push(...mu(e,r));let i=new Set(e.acceptedRunners.map((a)=>a.id));for(let a of r.runners){if(pu(n,a)||i.has(a.id))continue;o.push({detail:`runner ${a.id} in ${Rt(r.scope)} was not minted by this fleet`,kind:"foreign-runner",names:[a.name]})}return o}function fu(e,t){if(!e.secretBearing)return[];if(!(t.kind==="org"?t.group?.allowsPublicRepositories===!0:t.visibility===qO))return[];return[{detail:`${t.kind==="org"?`${Rt(t)} allows public repositories`:`${Rt(t)} is public`}, and the pool is secret-bearing`,kind:"public-access"}]}function mu(e,t){return[...YO(e.scope,t.scope),...XO(t.scope,e.forkPolicy,t.forkPolicy)]}function JO(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 YO(e,t){let n=Rt(t);if(e.kind==="repo"&&t.kind==="repo")return e.visibility===t.visibility?[]:[yn(`${n} is now ${t.visibility}, recorded ${e.visibility}`)];if(e.kind!=="org"||t.kind!=="org")return[yn(`${n} is not the recorded kind of target`)];if(!t.group)return[yn(`${n} no longer exists`)];if(!e.group)return[yn(`${n} exists again`)];return zO(n,e.group,t.group)}function zO(e,t,n){let r=[];if(t.id!==n.id)r.push(yn(`${e} is now id ${n.id}, recorded id ${t.id}`));if(t.visibility!==n.visibility)r.push(yn(`${e} now admits ${Zi(n.visibility)}, recorded ${Zi(t.visibility)}`));r.push(...lu(e,t.allowsPublicRepositories,n.allowsPublicRepositories,{off:"no longer allows public repositories",on:"now allows public repositories"}),...lu(e,t.restrictedToWorkflows,n.restrictedToWorkflows,{off:"is no longer restricted to selected workflows",on:"is now restricted to selected workflows"}));let o=rw(n.selectedWorkflows,t.selectedWorkflows),s=rw(t.selectedWorkflows,n.selectedWorkflows);if(o.length>0)r.push(uu(`${e} lists ${du(o.length,"workflow")} more`,o));if(s.length>0)r.push(uu(`${e} lists ${du(s.length,"workflow")} fewer`,s));if(t.repositories&&n.repositories){let i=new Set(t.repositories.map((u)=>u.id)),a=new Set(n.repositories.map((u)=>u.id)),c=n.repositories.filter((u)=>!i.has(u.id)),l=t.repositories.filter((u)=>!a.has(u.id));if(c.length>0)r.push(nw(`may now use ${e}`,c));if(l.length>0)r.push(nw(`may no longer use ${e}`,l))}return r}function XO(e,t,n){let r=e.kind==="org"?e.org:e.repository,o=[];if(t.approval&&n.approval&&t.approval!==n.approval)o.push(yn(`${r} now asks approval for fork pull request workflows of ${ea(n.approval)}, recorded ${ea(t.approval)}`));let s=t.privateRepositories,i=n.privateRepositories;if(!s||!i)return o;for(let a of Object.keys(tw))o.push(...lu(r,s[a],i[a],tw[a]));return o}function lu(e,t,n,r){return t===n?[]:[yn(`${e} ${n?r.on:r.off}`)]}function yn(e){return{detail:e,kind:"changed"}}function uu(e,t){return{detail:e,kind:"changed",names:t}}function nw(e,t){let n=t.map((r)=>r.id).join(", ");return uu(`${du(t.length,"repository","repositories")} (id ${n}) ${e}`,t.map((r)=>r.name))}function rw(e,t){let n=new Set(t);return e.filter((r)=>!n.has(r))}function du(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function Zi(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 ea(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 kw,lstatSync as HI,mkdirSync as MI,readFileSync as GI,renameSync as FI,rmSync as UI,writeFileSync as BI}from"fs";import{dirname as xu,join as jI}from"path";import{closeSync as ia,constants as zt,existsSync as RI,fstatSync as $u,fsyncSync as vu,ftruncateSync as $I,lstatSync as yw,mkdirSync as vI,openSync as ww,readFileSync as bw,writeSync as EI}from"fs";import{dirname as Sw,join as xI}from"path";var QO=[/\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],ZO=/[A-Za-z0-9+=_]{24,}/g,eI=/[A-Za-z]/,tI=/\d/,nI=/^[A-Za-z][A-Za-z0-9]{0,31}$/;function Xn(e){if(QO.some((t)=>t.test(e)))return!0;return[...e.matchAll(ZO)].some(([t])=>eI.test(t)&&tI.test(t))}function Ho(e,t){if(!nI.test(t)||Xn(t))return e;return e?`${e}.${t}`:t}function gu(e,t){if(typeof e==="string")return Xn(e)?t:void 0;if(typeof e!=="object"||e===null)return;for(let[n,r]of Object.entries(e)){if(Xn(n))return t;let o=gu(r,Ho(t,n));if(o!==void 0)return o}return}var ow=["lease-granted","lease-refused","prepare","ready","minted","online","job-started","exited","collected","drain","budget-unavailable","failed","canary-failed","timed-out","verified"],sw=120;var rI={destroying:5,finishing:5,preparing:10,registering:2},oI=["verified","withdrawn","quarantined"],sI=["admitted","preparing","registering","online","busy","finishing","destroying"],iI=["requested","waiting","admitted"],aI=["online","job-started","exited","canary-failed"],cI={"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 na 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 iw(e,t){return{driver:e.driver,name:e.name,phase:"requested",pool:e.pool,requestedAt:t,since:t}}function lI(e,t){if(!cI[t].includes(e.phase))return!1;if(t==="minted")return e.runner===void 0;if(aI.includes(t))return e.runner!==void 0;if(t==="verified"&&e.phase==="quarantined")return e.undestroyed===!0;return!0}function aw(e,t,n){if(!lI(e,t.kind))throw new na(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 iI.includes(e.phase)?r("withdrawn"):r("destroying",{teardown:"drained"});case"budget-unavailable":return r("destroying",{teardown:"budget-unavailable"});case"failed":return hu(e,{detail:t.detail,kind:"error",phase:e.phase},n);case"canary-failed":return hu(e,{detail:t.detail,kind:"canary",phase:e.phase},n);case"timed-out":return e.phase==="registering"?r("destroying",{teardown:"not-online"}):hu(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 pt(e){return oI.includes(e)}function cw(e){return sI.includes(e.phase)||Ve(e)}function Ve(e){return e.phase==="destroying"||e.phase==="quarantined"&&e.undestroyed===!0}function lw(e,t=120){let n=e.phase==="busy"?t:rI[e.phase];return n===void 0?void 0:Date.parse(e.since)+n*60000}function hu(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 ra=1,uI=63,oa=200,wu="entry",yu="event",dI=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,pI=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/,fI=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,mI=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,gI=/[\p{Cc}\p{Cf}]/u,fw=(e)=>N().map((t)=>t.length<=e&&dI.test(t)?t:B()),bu=(e)=>N().map((t)=>e.test(t)?t:B()),hI=bu(mI).map((e)=>Number.isNaN(Date.parse(e))?B():e),yI=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B()),wI=X().map((e)=>Number.isSafeInteger(e)?e:B()),uw=N().map((e)=>e.trim().length>0&&e.length<=oa&&!gI.test(e)?e:B()),mw=fw(uI),bI={at:hI,event:ur(),slot:mw,v:Y([ra])},Ot={},SI={"budget-unavailable":Ot,"canary-failed":{detail:uw},collected:Ot,drain:Ot,exited:{code:wI},failed:{detail:uw},"job-started":Ot,"lease-granted":{lease:bu(pI)},"lease-refused":Ot,minted:{runnerId:yI,runnerName:bu(fI)},online:Ot,prepare:Ot,ready:Ot,requested:{driver:Y(wt),pool:fw(Fn)},"timed-out":Ot,verified:Ot};function Su(e){let t=gu(e,"");if(t!==void 0)return{field:t||wu,reason:"secret-shaped"};if(!pw(e))return{field:wu,reason:"invalid"};let n=dw(e,bI,"");if(n)return n;let r=e.event;if(!pw(r))return{field:yu,reason:"invalid"};let o=r.kind;if(!Ru(o))return{field:Ho(yu,"kind"),reason:"invalid"};return dw(r,{...SI[o],kind:ur()},yu)}function gw(e){try{let t=mw(e);return Xn(t)?void 0:t}catch{return}}function Ru(e){return e==="requested"||ow.includes(e)}function dw(e,t,n){let r=Object.keys(e).find((o)=>!Object.hasOwn(t,o));if(r!==void 0)return{field:Ho(n,r)||wu,reason:"invalid"};for(let[o,s]of Object.entries(t))try{s(e[o])}catch{return{field:Ho(n,o),reason:"invalid"}}return}function pw(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Mo="ledger",kI="slots.jsonl",_I=448,AI=384,CI=18,Rw=10,TI="ELOOP",PI={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"},OI={duplicate:"requests a slot that an earlier line already requested","unknown-slot":"changes a slot that no earlier line requested"};class tt 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 $w 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}: ${PI[e](t)}`);this.reason=e;this.field=t;this.slot=n;this.event=r;this.name="LedgerEntryError"}}function Lr(e){return xI(e,Mo,kI)}function aa(e,t={}){let n=t.now??(()=>new Date),r=Lr(e),o=NI(r),s=Ew(r,o.text),i=o.mark,a=(l)=>{let u=JSON.stringify(l),d=JSON.parse(u),p=Su(d);if(p)throw hw(d,p.reason,p.field);let m=d,g=vw(s,m);if("refusal"in g)throw hw(m,g.refusal,void 0);return i=DI(r,`${u}
|
|
408
|
+
`,i),s.set(m.slot,g.record),g.record},c=()=>n().toISOString();return{destroyable:(l)=>{let u=s.get(l.name);return u?.driver===l.driver&&u.pool===l.pool&&Ve(u)},droppedBytes:o.droppedBytes,get:(l)=>s.get(l),path:r,record:(l,u)=>a({at:c(),event:u,slot:l,v:ra}),request:(l)=>a({at:c(),event:{driver:l.driver,kind:"requested",pool:l.pool},slot:l.name,v:ra}),slots:()=>[...s.values()]}}function vw(e,t){let n=e.get(t.slot),{event:r}=t;if(r.kind==="requested"){if(n)return{refusal:"duplicate"};return{record:iw({driver:r.driver,name:t.slot,pool:r.pool},t.at)}}if(!n)return{refusal:"unknown-slot"};return{record:aw(n,r,t.at)}}function hw(e,t,n){let{event:r,slot:o}=e??{},s=r?.kind;return new $w(t,n,gw(o),Ru(s)?s:void 0)}function Ew(e,t){let n=new Map,r=t.split(`
|
|
409
|
+
`).slice(0,-1);for(let[o,s]of r.entries()){let i=(d)=>new tt(e,"corrupt",d,o+1),a;try{a=JSON.parse(s)}catch{throw i("is not JSON")}let c=Su(a);if(c)throw i(II(c));let l=a,u;try{u=vw(n,l)}catch(d){if(d instanceof na)throw i(`asks for a change the slot cannot take: ${d.message}`);throw d}if("refusal"in u)throw i(OI[u.refusal]);n.set(l.slot,u.record)}return n}function II(e){return e.reason==="secret-shaped"?`holds a secret-shaped ${e.field}`:`has an invalid ${e.field}`}function xw(e){let t=Lr(e),n=Sw(t);sa(n,yw(n),"directory");let r=Eu(t,zt.O_RDONLY|zt.O_NOFOLLOW);try{sa(t,$u(r),"file");let o=bw(r),s=o.lastIndexOf(Rw)+1;return[...Ew(t,o.subarray(0,s).toString("utf-8")).values()]}finally{ia(r)}}function NI(e){let t=Sw(e);vI(t,{mode:_I,recursive:!0}),sa(t,yw(t),"directory");let n=!RI(e),r=Eu(e,zt.O_RDWR|zt.O_CREAT|zt.O_NOFOLLOW);try{let o=$u(r);sa(e,o,"file");let s=bw(r),i=s.lastIndexOf(Rw)+1,a=s.length-i;if(a>0)$I(r,i),vu(r);if(n)LI(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{ia(r)}}function DI(e,t,n){let r=Eu(e,zt.O_WRONLY|zt.O_APPEND|zt.O_NOFOLLOW);try{let o=$u(r);if(o.dev!==n.dev||o.ino!==n.ino||o.size!==n.size)throw new tt(e,"conflict","changed after it was read; open the ledger again");let s=Buffer.from(t),i=0;while(i<s.length)i+=EI(r,s,i);return vu(r),{...n,size:n.size+s.length}}finally{ia(r)}}function Eu(e,t){try{return ww(e,t,AI)}catch(n){if(n.code===TI)throw new tt(e,"unsafe","is a symbolic link");throw Error(`Could not open the slot ledger ${e}`,{cause:n})}}function sa(e,t,n){if(t.isSymbolicLink())throw new tt(e,"unsafe","is a symbolic link");if(!(n==="directory"?t.isDirectory():t.isFile()))throw new tt(e,"unsafe",`is not a ${n==="file"?"regular file":n}`);let o=process.getuid?.();if(o===void 0)throw new tt(e,"unsafe","cannot be checked for its owner on this platform");if(t.uid!==o)throw new tt(e,"unsafe",`is owned by uid ${t.uid}, not by the user running Hydra (uid ${o})`);if((t.mode&CI)!==0)throw new tt(e,"unsafe","can be written by other users")}function LI(e){let t=ww(e,zt.O_RDONLY);try{vu(t)}finally{ia(t)}}var VI="guard.json",_w=1,KI=448,qI=384,WI=18,Aw=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B()),Cw=H({id:Aw,name:N()}),JI=H({requireApproval:Z(),runWorkflows:Z(),sendSecrets:Z(),sendWriteTokens:Z()}),YI=H({approval:Y(cu).or(oe()),privateRepositories:JI.or(oe())}),zI=H({allowsPublicRepositories:Z(),default:Z(),id:Aw,name:N(),repositories:ee(Cw).or(oe()),restrictedToWorkflows:Z(),selectedWorkflows:ee(N()),visibility:N()}),XI=H({group:zI,groupName:N(),kind:Y(["org"]),org:N()}).map((e)=>e),QI=H({kind:Y(["repo"]),repository:N(),visibility:Y(["internal","private","public"])}).map((e)=>e),ZI=H({acceptedRunners:ee(Cw),forkPolicy:YI,scope:XI.or(QI),url:N()}),eN=H({pools:dr(ZI),recordedAt:N(),v:Y([_w])});class wn extends Error{path;_tag="GuardRecordError";constructor(e,t){super(`Guard record ${e} ${t}`);this.path=e;this.name="GuardRecordError"}}function Tw(e){return jI(e,Mo,VI)}function Pw(e,t){let{runners:n,...r}=e;return{...r,acceptedRunners:n.filter((o)=>!pu(t,o))}}function la(e){let t=Tw(e);if(!kw(t))return;ca(xu(t),"directory"),ca(t,"file");let n;try{n=eN(JSON.parse(GI(t,"utf8")))}catch{throw new wn(t,"is not a valid guard record")}if(Number.isNaN(Date.parse(n.recordedAt)))throw new wn(t,"has no valid recording time");return{pools:n.pools,recordedAt:n.recordedAt}}function Ow(e,t){let n=Tw(e);if(MI(xu(n),{mode:KI,recursive:!0}),ca(xu(n),"directory"),kw(n))ca(n,"file");let r=`${n}.${process.pid}.tmp`;UI(r,{force:!0}),BI(r,`${JSON.stringify({...t,v:_w},null,2)}
|
|
410
|
+
`,{flag:"wx",mode:qI}),FI(r,n)}function ca(e,t){let n=HI(e);if(!(t==="directory"?n.isDirectory():n.isFile()))throw new wn(e,t==="file"?"is not a regular file":"is not a directory");if(n.uid!==process.getuid?.())throw new wn(e,"is not owned by the user running Hydra");if((n.mode&WI)!==0)throw new wn(e,"can be written by other users")}var tN="RunnerScaleSetJobMessages",Iw="[redacted]",we=N().or(oe()).or(ht()).map((e)=>e??""),Fe=X().or(oe()).or(ht()).map((e)=>e==null?0:Number.isSafeInteger(e)&&e>=0?e:B()),ku=X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B()),nN=Fe.map((e)=>e>0?e:void 0),$t=N().map((e)=>e.trim()===""?B():e),Nw=Z().or(oe()).or(ht()).map((e)=>e??!1),rN=ee(N()).or(oe()).or(ht()).map((e)=>e??[]),_u=H({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})),oN=H({name:$t,type:we}),Go=H({createdOn:we,id:ku,labels:ee(oN).or(oe()).or(ht()).map((e)=>e??[]),name:$t,RunnerSetting:H({disableUpdate:Nw}).or(oe()).or(ht()).map((e)=>e??{disableUpdate:!1}),runnerGroupId:Fe,runnerGroupName:we,statistics:_u.or(oe()).or(ht())}).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}:{}})),Dw=H({id:ku,isDefaultGroup:Nw,name:$t,size:Fe}).map((e)=>({id:e.id,isDefault:e.isDefaultGroup,name:e.name,size:e.size})),da=H({id:ku,name:$t,runnerScaleSetId:nN}).map((e)=>({id:e.id,name:e.name,...e.runnerScaleSetId===void 0?{}:{scaleSetId:e.runnerScaleSetId}}));function Fo(e){return H({value:ee(e).or(oe()).or(ht())}).map((t)=>t.value??[])}var Lw=H({value:ee(Fe).or(oe()).or(ht()).map((e)=>e??[])}).map((e)=>e.value),Hw=H({encodedJITConfig:$t,runner:da}),Mw=H({messageQueueAccessToken:$t,messageQueueUrl:$t,ownerName:we,sessionId:$t,statistics:_u.or(oe()).or(ht())}),Gw=H({token:$t,url:$t}),Fw=H({expires_at:we,token:$t}),Uw=H({message:we,typeName:we}),ua=H({eventName:we,finishTime:we,jobDisplayName:we,jobId:we,jobWorkflowRef:we,ownerName:we,queueTime:we,repositoryName:we,requestLabels:rN,runnerAssignTime:we,runnerRequestId:Fe,scaleSetAssignTime:we,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})),sN=H({acquireJobUrl:we}),iN=H({runnerId:Fe,runnerName:we}),aN=H({result:we,runnerId:Fe,runnerName:we}),cN=H({messageType:we}),lN=H({body:we,messageId:Fe,messageType:we,statistics:_u});function Bw(e){return Object.freeze({reveal:()=>e,toJSON:()=>Iw,toString:()=>Iw})}function jw(e){let t=lN(e);if(t.messageType!==tN)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}=cN(o);switch(s){case"JobAvailable":n.jobsAvailable.push({...ua(o),...sN(o)});break;case"JobAssigned":n.jobsAssigned.push(ua(o));break;case"JobStarted":n.jobsStarted.push({...ua(o),...iN(o)});break;case"JobCompleted":n.jobsCompleted.push({...ua(o),...aN(o)});break;default:break}}return{kind:"message",message:n}}var uN="r5n-hydra",Vw="[redacted]",dN=4,pN=120000,fN=60000,mN=1000,gN=30000,hN=60000,Au=1000,yN=0.5,wN=200,bN=400,SN=401,RN=403,$N=404,vN=409,Cu=429,qw=500,EN=501,xN=503,kN=300,_N=399,Kw="\uFEFF",AN=[/\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],CN=/[\p{Cc}\p{Cf}]+/gu,TN=/\s+/g,PN=[["AgentExistsException","runner-exists"],["AgentNotFoundException","runner-not-found"],["JobStillRunningException","job-still-running"]];class ft 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 Ww(e={}){let t=e.maxRetries??dN,n=e.requestTimeoutMs??fN,r=e.retryBaseMs??mN,o=e.retryMaxMs??gN,s=e.sleep??HN;function i(l){let u=Math.min(r*2**l,o);return Math.min(u+Math.random()*u*yN,o)}function a(l,u,d){if(d>=t)return;if(u.kind==="failed")return l.idempotent?i(d):void 0;let{status:p}=u.response;if(p===Cu||p===xN&&l.idempotent){let m=Jw(u.response.headers)??i(d);return m<=hN?m:void 0}if(l.retryStatuses?.includes(p))return i(d);if(p>=qw&&p!==EN&&l.idempotent)return i(d);return}async function c(l){let u=l.timeoutMs??n,d=AbortSignal.timeout(u),p=l.signal?AbortSignal.any([l.signal,d]):d;try{let m=await fetch(l.url,{body:l.body===void 0?void 0:JSON.stringify(l.body),headers:{...l.headers,"User-Agent":uN,...l.body===void 0?{}:{"Content-Type":"application/json"}},method:l.method,redirect:"manual",signal:p}),g=await m.text();return{kind:"answered",response:{headers:m.headers,status:m.status,text:LN(g)}}}catch(m){if(l.signal?.aborted)throw Pe(l,void 0,"aborted","stopped by the caller");if(d.aborted)return{detail:`timed out after ${u/Au} s`,failure:"timeout",kind:"failed"};return{detail:m instanceof Error?m.message:String(m),failure:"network",kind:"failed"}}}return{pollTimeoutMs:e.pollTimeoutMs??pN,async send(l){for(let u=0;;u++){if(l.signal?.aborted)throw Pe(l,void 0,"aborted","stopped by the caller");let d=await c(l),p=a(l,d,u);if(p===void 0){if(d.kind==="failed")throw Pe(l,void 0,d.failure,d.detail);if(DN(d.response.status))throw Pe(l,d.response.status,"redirect","refused to follow a redirect");return d.response}try{await s(p,l.signal)}catch{throw Pe(l,void 0,"aborted","stopped by the caller")}}}}}function Pe(e,t,n,r){return new ft(e.operation,e.method,e.url.pathname,t,n,ON(r,e.secrets))}function Tu(e,t){let{exception:n,message:r}=IN(t),o=PN.find(([c])=>n.includes(c))?.[1],s=t.status===Cu,i=s?Jw(t.headers):void 0,a=[s?`rate limited${i===void 0?"":`; retry in ${i/Au} s`}`:"",r].filter(Boolean).join("; ");return Pe(e,t.status,o??NN(t.status),a)}function Uo(e,t,n){if(!n.includes(t.status))throw Tu(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 ON(e,t){let n=t.reduce((r,o)=>o?r.replaceAll(o,Vw):r,e);return AN.reduce((r,o)=>r.replace(o,Vw),n).replace(CN," ").replace(TN," ").trim().slice(0,wN)}function IN(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=Uw(JSON.parse(e.text));return{exception:t.typeName,message:t.message}}catch{return{exception:"",message:""}}}function NN(e){switch(e){case bN:return"bad-request";case SN:return"unauthorized";case RN:return"forbidden";case $N:return"not-found";case vN:return"conflict";case Cu:return"rate-limited";default:return e>=qw?"server":"unexpected-status"}}function DN(e){return e>=kN&&e<=_N}function Jw(e){let t=e.get("retry-after")?.trim();if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*Au);let r=Date.parse(t);return Number.isFinite(r)?Math.max(0,r-Date.now()):void 0}function LN(e){return e.startsWith(Kw)?e.slice(Kw.length):e}function HN(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 MN=60000,GN=1000,Yw=200,FN=299,UN=401,BN=403,zw=".actions.githubusercontent.com",jN=new Set(["127.0.0.1","[::1]"]),Xw=/\/+$/,VN=Array.from({length:FN-Yw+1},(e,t)=>Yw+t);function KN(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 Pu(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===fl){if(n.protocol!=="https:")return"it is not https";return n.hostname.endsWith(zw)?void 0:`its host is not under *${zw}`}if(n.hostname!==r.hostname)return`its host is not ${r.hostname}, the configured API host`;return n.protocol==="https:"||n.protocol==="http:"&&jN.has(n.hostname)?void 0:"it is not https"}function qN(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*GN:void 0}catch{return}}function Qw({apiUrl:e,github:t,http:n,now:r=Date.now,url:o}){let s=me(o),i=o.replace(Xw,""),a=new URL(`${e.replace(Xw,"")}/`),c=Me(s),l,u;async function d(p){let m=await t.request({idempotent:!0,method:"POST",operation:`Create a runner registration token for ${c}`,path:KN(s),schema:Fw}),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:[UN,BN],secrets:[m.token],signal:p,url:new URL("actions/runner-registration",a)},h=await n.send(g);Uo(g,h,VN);let E=Ke(g,h,Gw),v={...g,secrets:[m.token,E.token]},R=Pu(E.url,e);if(R)throw Pe(v,h.status,"refused-url",`refused the Actions service URL: ${R}`);let _=qN(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(p){for(;;){if(l&&l.expiresAt-MN>r())return l;u??=d(p).finally(()=>{u=void 0});try{return l=await u,l}catch(m){if(p?.aborted||!(m instanceof ft)||m.failure!=="aborted")throw m}}},invalidate(p){if(l?.token===p)l=void 0},target:s}}var WN=/[\p{Cc}\p{Cf}]/u;function vt(e,t){if(Number.isSafeInteger(e)&&e>0)return;throw RangeError(`${t} must be a positive integer, got ${String(e)}`)}function pa(e,t){if(Number.isSafeInteger(e)&&e>=0)return;throw RangeError(`${t} must be a whole number, got ${String(e)}`)}function It(e,t){if(typeof e==="string"&&e.trim()!==""&&!WN.test(e))return;throw RangeError(`${t} must be a non-empty name without control characters`)}var Nt="_apis/runtime/runnerscalesets",Zw="_apis/runtime/runnergroups/",fa="_apis/distributedtask/pools/0/agents",JN="6.0-preview",YN=401,zN=new Set(["DELETE","GET","PUT"]),XN=/\/+$/,QN=/^\/+/;function ZN(e,t,n={}){let r=new URL(e);r.pathname=`${r.pathname.replace(XN,"")}/${t.replace(QN,"")}`;for(let[o,s]of Object.entries(n))r.searchParams.set(o,s);if(!r.searchParams.has("api-version"))r.searchParams.set("api-version",JN);return r}function eb(e,t){return{admin:e,async call({bearer:n,body:r,expect:o,idempotent:s,method:i,operation:a,path:c,query:l,signal:u}){let d=await e.connection(u),p=n??d.token,m={body:r,headers:{Accept:"application/json",Authorization:`Bearer ${p}`},idempotent:s??zN.has(i),method:i,operation:a,secrets:[d.token,p],signal:u,url:ZN(d.serviceUrl,c,l)},g=await t.send(m);if(o.includes(g.status))return{request:m,response:g};if(g.status===YN&&n===void 0)e.invalidate(d.token);throw Tu(m,g)},http:t}}var Hr=2147483647,eD="X-ScaleSetMaxCapacity",Ou=200,tD=202,tb=204,nD=401,rD=404,oD="application/json; api-version=6.0-preview";async function nb(e,t,n,r){vt(t,"The scale set id"),It(n,"The session owner name");let o=`${Nt}/${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,R){let{request:_,response:T}=await e.call({body:E,expect:[Ou],method:m,operation:h,path:g,signal:R}),b=Ke(_,T,Mw),A={..._,secrets:[..._.secrets,b.messageQueueAccessToken]},y=Pu(b.messageQueueUrl,e.admin.apiUrl),S=b.statistics??v;if(y||!S)throw await l(b.sessionId).catch(()=>{return}),y?Pe(A,T.status,"refused-url",`refused the message queue URL: ${y}`):Pe(A,T.status,"response","the session carries no statistics");return{id:b.sessionId,ownerName:b.ownerName||n,queueToken:b.messageQueueAccessToken,queueUrl:new URL(b.messageQueueUrl),statistics:S}}async function l(m){await e.call({expect:[tb,rD],method:"DELETE",operation:`Close ${s}`,path:`${o}/${encodeURIComponent(m)}`})}async function u(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 ft)||h.status!==nD)throw h;return await u(g),m(i.queueToken)}}function p(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)pa(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:[Ou],idempotent:!0,method:"POST",operation:`Acquire ${m.length} job(s) for scale set ${t}`,path:`${Nt}/${t}/acquirejobs`,signal:g});return Ke(E,v,Lw)})},async close(){await l(i.id)},async deleteMessage(m){pa(m,"The message id"),await d(async(g)=>{let h=new URL(i.queueUrl);h.pathname=`${h.pathname}/${m}`;let E=p("DELETE",h,g,`Acknowledge message ${m} of ${s}`,{}),v=await e.http.send(E);Uo(E,v,[tb])})},async getMessage(m,g,h){if(pa(m,"The last message id"),!Number.isSafeInteger(g)||g<0||g>Hr)throw RangeError(`The advertised capacity must be an integer from 0 to ${Hr}`);return d(async(E)=>{let v=new URL(i.queueUrl);if(m>0)v.searchParams.set("lastMessageId",String(m));let R=p("GET",v,E,`Poll ${s}`,{headers:{Accept:oD,Authorization:`Bearer ${E}`,[eD]:String(g)},signal:h,timeoutMs:e.http.pollTimeoutMs}),_=await e.http.send(R);if(_.status===tD)return;Uo(R,_,[Ou]);let T=Ke(R,_,jw);if(T.kind==="unsupported")throw Pe(R,_.status,"unsupported-message",`unsupported message type ${JSON.stringify(T.messageType)}`);return T.message})},info(){return{id:i.id,ownerName:i.ownerName,scaleSetId:t,statistics:i.statistics}},async refresh(){await u(i.queueToken)},statistics(){return i.statistics}}}var sD=["requested","waiting","admitted","preparing","registering","online","busy"],Ie={now:()=>Date.now(),sleep:iD};class qe 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 Mr(e,t){return e.filter((n)=>n.pool===t&&sD.includes(n.phase))}function ma(e,t){return e.filter((n)=>n.pool===t&&n.phase==="busy").length}function Gr(e){return Number.isFinite(e)?Math.max(0,Math.min(Hr,Math.floor(e))):0}function iD(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 aD=300000,cD=60000,lD=3,uD="the guard has not yet compared the pool with its record";function rb(e){let t=e.clock??Ie,n=e.intervalMs??aD,r=e.retryMs??cD,o=Object.keys(e.pools),s=new Map,i=new Map,a=0,c=!1,l,u,d=(v,R)=>{let _=R.map((A)=>A.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 T=i.get(v)??new Set,b=new Set;for(let A of R){let y=`${A.kind}\x00${A.detail}`;if(b.add(y),T.has(y))continue;e.alert({detail:A.detail,pool:v,reason:A.kind==="foreign-runner"?"foreign-runner":"guard-drift"})}i.set(v,b)},p=(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 R=v instanceof Error?v.message:String(v);if(e.log(`the guard could not read the runner groups and policies (${a} in a row): ${R}`),a!==lD)return;e.alert({detail:`${a} rounds in a row failed; the last: ${dD(v)}`,reason:"guard-failed"})},g=(v)=>{let R=`the guard record cannot be read: ${v instanceof Error?v.message:String(v)}`;for(let _ of o)d(_,[{detail:R,kind:"unrecorded"}])};async function h(){let v;try{v=e.record()}catch(T){g(T);return}let R;try{R=await e.reader.snapshots(e.pools)}catch(T){m(T);return}a=0;let _=e.minted();for(let[T,b]of Object.entries(e.pools)){let A=R[T];if(!A)continue;let y=ta({baseline:v?.pools[T],config:b,minted:_,snapshot:A});if(y.length===0)p(T);else d(T,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:uD),round:h,start(){if(u)return;l=new AbortController,u=E(l.signal)},async stop(){l?.abort(),await u,l=void 0,u=void 0}}}function dD(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 tM}from"fs";var pD=20000,fD=409,mD={busy:"busy",deleted:"removed",gone:"gone"};function ob(e){let{github:t,labels:n,pool:r,reader:o}=e,s=me(e.url),i=e.clock??Ie,a=e.intervalMs??pD,c=0,l,u="idle",d,p,m,g=(_,T)=>{u=_,d=T};async function h(){if(s.kind==="repo")return Tg;let _=e.runnerGroup,T=_===void 0?void 0:await xr(t,s.org,_);if(T)return T.id;throw new qe(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(T){if(_.aborted)return;c=0,g("retrying",T instanceof Error?T.message:String(T))}await i.sleep(a,_)}}async function v(_){if(l===void 0)throw new qe(r,`Mint a runner for slot ${_}`,"not-started","the demand source has not started");return Og(t,s,{labels:n,name:_,runnerGroupId:l})}function R({encodedJitConfig:_,runner:T}){return{jit:Yi(_),runner:{id:T.id,name:T.name}}}return{desired(){return Math.min(Gr(e.capacity()),ma(e.slots(),r)+c)},kind:"poll",async mint(_){let T=`Mint a just-in-time runner for slot ${_}`;try{return R(await v(_))}catch(A){if(!(A instanceof Re)||A.status!==fD)throw A}let b=await Ig(t,s,_);if(b&&!ei(n,b.labels))throw new qe(r,T,"runner-exists",`a runner named ${_} lacks the pool's labels`);if(b&&(b.busy||await jn(t,s,b.id)==="busy"))throw new qe(r,T,"runner-exists",`the runner ${_} is running a job`);return R(await v(_))},pool:r,async release(_){return mD[await jn(t,s,_.id)]},async start(){if(m)return;l=await h();let _=new AbortController;p=_,m=E(_.signal)},status:()=>({demand:c,detail:d,kind:"poll",pool:r,state:u}),async stop(){p?.abort(),await m,p=void 0,m=void 0,g("stopped")}}}var bn=200,sb=204,Sn=404,gD="System",hD="_work";function Iu(e,t){let n=(r)=>[...new Set(r.map((o)=>o.toLowerCase()))].sort().join(`
|
|
411
|
+
`);return n(e.labels.map((r)=>r.name))===n(t)}function ga({apiUrl:e,github:t,http:n,now:r,url:o}){let s=Ww(n),i=eb(Qw({apiUrl:e,github:t,http:s,now:r,url:o}),s);function a(d,p,m){if(p.length<=1)return p[0];throw Pe(d.request,d.response.status,"response",`found ${p.length} ${m}`)}function c({labels:d,name:p,runnerGroupId:m}){vt(m,"The runner group id"),It(p,"The scale set name");for(let g of d)It(g,"A scale set label")}async function l(d){c(d);let{disableUpdate:p=!0,labels:m,name:g,runnerGroupId:h}=d,E=m.length>0?m:[g],v=await i.call({body:{labels:E.map((R)=>({name:R,type:gD})),name:g,RunnerSetting:p?{disableUpdate:p}:{},runnerGroupId:h},expect:[bn],method:"POST",operation:`Create the scale set ${g} in runner group ${h}`,path:Nt});return Ke(v.request,v.response,Go)}async function u(d,p){vt(d,"The runner group id"),It(p,"The scale set name");let m=await i.call({expect:[bn],method:"GET",operation:`Read the scale set ${p} in runner group ${d}`,path:Nt,query:{name:p,runnerGroupId:String(d)}});return a(m,Ke(m.request,m.response,Fo(Go)),"scale sets")}return{createScaleSet:l,async deleteScaleSet(d){vt(d,"The scale set id");let{response:p}=await i.call({expect:[sb,Sn],method:"DELETE",operation:`Delete scale set ${d}`,path:`${Nt}/${d}`});return p.status===Sn?"gone":"deleted"},async ensureScaleSet(d){c(d);let p=await u(d.runnerGroupId,d.name),m=p??await l(d),g=d.labels.length>0?d.labels:[d.name];return{created:p===void 0,labelsMatch:Iu(m,g),scaleSet:m}},async findRunnerByName(d){It(d,"The runner name");let p=await i.call({expect:[bn],method:"GET",operation:`Find the runner ${d}`,path:fa,query:{agentName:d}});return a(p,Ke(p.request,p.response,Fo(da)),"runners")},async generateJitConfig(d,{name:p,workFolder:m=hD}){vt(d,"The scale set id"),It(p,"The runner name"),It(m,"The work folder");let g=await i.call({body:{name:p,workFolder:m},expect:[bn],method:"POST",operation:`Generate a just-in-time configuration for runner ${p} in scale set ${d}`,path:`${Nt}/${d}/generatejitconfig`}),h=Ke(g.request,g.response,Hw);return{jitConfig:Bw(h.encodedJITConfig),runner:h.runner}},async getRunner(d){vt(d,"The runner id");let p=await i.call({expect:[bn,Sn],method:"GET",operation:`Read runner ${d}`,path:`${fa}/${d}`});return p.response.status===Sn?void 0:Ke(p.request,p.response,da)},async getRunnerGroup(d){It(d,"The runner group name");let p=await i.call({expect:[bn],method:"GET",operation:`Read the runner group ${d}`,path:Zw,query:{groupName:d}}),m=a(p,Ke(p.request,p.response,Fo(Dw)),"groups");if(m)return m;throw Pe(p.request,p.response.status,"not-found",`no runner group is named ${d}`)},getScaleSet:u,async getScaleSetById(d){vt(d,"The scale set id");let p=await i.call({expect:[bn,Sn],method:"GET",operation:`Read scale set ${d}`,path:`${Nt}/${d}`});return p.response.status===Sn?void 0:Ke(p.request,p.response,Go)},async listScaleSets(d){vt(d,"The runner group id");let p=await i.call({expect:[bn],method:"GET",operation:`List the scale sets in runner group ${d}`,path:Nt,query:{runnerGroupId:String(d)}});return Ke(p.request,p.response,Fo(Go))},async openSession(d,p,m){return nb(i,d,p,m)},async removeRunner(d){vt(d,"The runner id");try{let{response:p}=await i.call({expect:[sb,Sn],method:"DELETE",operation:`Remove runner ${d}`,path:`${fa}/${d}`});return p.status===Sn?"gone":"removed"}catch(p){if(p instanceof ft&&p.failure==="job-still-running")return"busy";throw p}}}}async function ib({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 yD=60000,Nu=1000,wD={alertAfterMs:5*yD,retryMs:30*Nu,slowRetryMs:60*Nu};function cb(e){let{client:t,labels:n,ownerName:r,pool:o,runnerGroupId:s,scaleSetId:i}=e,a=e.clock??Ie,c={...wD,...e.retry},l=()=>Gr(e.capacity()),u=0,d="idle",p,m,g,h=(A,y)=>{d=A,p=y};async function E(){let y=await t.getScaleSetById(i);if(!y)throw new qe(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 qe(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(!Iu(y,n))throw new qe(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(A){let y,S=!1;while(!A.aborted){h("connecting");try{return await t.openSession(i,r,A)}catch(C){if(A.aborted)return;let x=C instanceof ft&&C.failure==="conflict";y=x?y??a.now():void 0;let L=y!==void 0&&a.now()-y>=c.alertAfterMs;if(h(x?"conflict":"retrying",ab(C)),L&&!S)S=!0,e.alert?.({detail:`another session has held scale set ${i} for ${Math.round(c.alertAfterMs/Nu)} s`,pool:o,reason:"session-conflict"});await a.sleep(L?c.slowRetryMs:c.retryMs,A)}}return}function R(A){return async(y,S)=>{if(y){let C=[...new Set(y.jobsAvailable.map((x)=>x.runnerRequestId).filter((x)=>x>0))];if(C.length>0)await A.acquireJobs(C,S);u=y.statistics.totalAssignedJobs}await e.onDemand?.(S)}}async function _(A,y){h("listening");try{return await ib({capacity:l,handle:R(A),session:A,signal:y}),"stopped"}catch(S){if(y.aborted)return"stopped";if(S instanceof ft&&S.failure==="unsupported-message")return h("degraded",S.message),e.alert?.({detail:S.message,pool:o,reason:"unknown-message"}),"degraded";return h("retrying",ab(S)),"retry"}}async function T(A){while(!A.aborted){let y=await v(A);if(!y)return;let S=await _(y,A);if(u=0,await y.close().catch(()=>{return}),S!=="retry")return;await a.sleep(c.retryMs,A)}}function b({jitConfig:A,runner:y}){return{jit:Yi(A.reveal()),runner:{id:y.id,name:y.name}}}return{desired:()=>Math.min(l(),u),kind:"scaleset",async mint(A){let y=`Mint a just-in-time runner for slot ${A}`;try{return b(await t.generateJitConfig(i,{name:A}))}catch(C){if(!(C instanceof ft)||C.failure!=="runner-exists")throw C}let S=await t.findRunnerByName(A);if(S&&S.scaleSetId!==i)throw new qe(o,y,"runner-exists",`a runner named ${A} belongs to another scale set`);if(S&&await t.removeRunner(S.id)==="busy")throw new qe(o,y,"runner-exists",`the runner ${A} is running a job`);return b(await t.generateJitConfig(i,{name:A}))},pool:o,release:(A)=>t.removeRunner(A.id),async start(){if(g)return;await E();let A=new AbortController;m=A,g=T(A.signal)},status:()=>({demand:u,detail:p,kind:"scaleset",pool:o,state:d}),async stop(){m?.abort(),await g,m=void 0,g=void 0,h("stopped")}}}function ab(e){return e instanceof Error?e.message:String(e)}import{lstatSync as GD,unlinkSync as FD}from"fs";import{chmodSync as vD,mkdirSync as pb,mkdtempSync as ED,renameSync as xD,rmSync as fb,writeFileSync as Gu}from"fs";import{tmpdir as kD}from"os";import{join as Qn}from"path";var Hu="guest",Mu="Containerfile",bD=["ca-certificates","curl","git","jq","tar","unzip","util-linux","xz-utils","zstd"],SD={amd64:"x64",arm64:"arm64"},lb="apt-get install -y --no-install-recommends",Lu="rm -rf /var/lib/apt/lists/*",Du="/etc/apt/keyrings/docker.asc";function ya(e){let{arch:t,docker:n}=e,r=je;return`${[`FROM ${r.base.image}@${r.base.digest}`,"ARG DEBIAN_FRONTEND=noninteractive",Rn(["apt-get update",`${lb} ${bD.join(" ")}`,Lu]),Rn([`groupadd --gid ${Qe} ${mn}`,`useradd --uid ${Qe} --gid ${Qe} --create-home --shell /bin/bash ${mn}`]),Rn([...ha(r.runner[t],"/tmp/runner.tar.gz"),`mkdir -p ${gn}`,`tar -xzf /tmp/runner.tar.gz -C ${gn}`,"rm /tmp/runner.tar.gz","apt-get update",`${gn}/bin/installdependencies.sh`,Lu,`chown -R ${Qe}:${Qe} ${gn}`]),Rn([...ha(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=`${_o}/node/${s.version}/${SD[t]}`;return Rn([...ha(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"])}),Rn([`chown -R ${Qe}:${Qe} ${_o}`]),...n?[$D(t)]:[],`COPY ${Hu}/ ${Tt}/`,Rn([`chown -R 0:0 ${Tt}`,`chmod 0755 ${Tt}`,`chmod 0555 ${xo} ${gi} ${hi} ${Fl}`,`chmod 0444 ${Eh}`,`install -d -o ${Qe} -g ${Qe} -m 0700 ${Ul}`,`cd ${Bl}`,`find . -mindepth 1 | LC_ALL=C sort > ${yi}`,`chmod 0444 ${yi}`,"cd /","test ! -e /usr/bin/sudo","setpriv --help > /dev/null",`test "$(id -u ${mn})" = ${Qe}`,`test "$(id -g ${mn})" = ${Qe}`]),`ENV LANG=C.UTF-8 RUNNER_TOOL_CACHE=${_o} AGENT_TOOLSDIRECTORY=${_o} ACTIONS_RUNNER_HOOK_JOB_STARTED=${Fl}`,`LABEL ${RD(e).map(([s,i])=>`${s}="${i}"`).join(" ")}`,"WORKDIR /",`CMD ["${xo}"]`].join(`
|
|
412
|
+
`)}
|
|
413
|
+
`}function RD(e){return[["org.r5nlabs.hydra.image","runner-linux"],["org.r5nlabs.hydra.variant",e.docker?"docker":"plain"],["org.r5nlabs.hydra.runner",je.runner.version]]}function $D(e){let t=je.docker,n=Object.entries(t.packages).map(([r,o])=>`${r}=${o}`);return Rn(["install -d -m 0755 /etc/apt/keyrings",...ha(t.key,Du),`chmod 0644 ${Du}`,`echo "deb [arch=${e} signed-by=${Du}] ${t.repository} ${t.codename} stable" > /etc/apt/sources.list.d/docker.list`,"apt-get update",`${lb} ${n.join(" ")}`,Lu,`usermod -aG docker ${mn}`])}function ha(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 Rn(e){return`RUN set -eu; \\
|
|
414
|
+
${e.join(" \\\n && ")}`}var Bo=["container","podman"];class We 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 Fu="localhost/hydra/runner-linux",mb="-docker",gb="images",hb=448,yb=384,_D=3600000,AD=60000,CD=20,TD=1000,PD=/^sha256:[0-9a-f]{64}$/,Uu={container:"apple-container",podman:"podman-gvisor"},OD=ee(H({configuration:H({descriptor:H({digest:N()})})}));function wa(e){let t=e.docker?mb:"";return`${Fu}${t}:${je.runner.version}-${e.arch}`}function Bu(e,t,n){let r=[e,"build","--platform",`linux/${t.arch}`,"--file",Qn(n,Mu),"--tag",wa(t),...e==="container"?["--progress","plain"]:[],n];return Vt(Uu[e],r)}function ID(e,t){let n=e==="container"?["container","image","inspect",t]:["podman","image","inspect","--format","{{.Digest}}",t];return Vt(Uu[e],n)}function wb(e,t){let n=e==="container"?["container","image","delete",t]:["podman","image","rm",t];return Vt(Uu[e],n)}function bb(e){let t=e.reference.slice(0,e.reference.indexOf("@"));return(t===Fu||t===`${Fu}${mb}`)&&e.tag.startsWith(`${t}:`)&&e.reference===`${t}@${e.digest}`}function ND(e,t){Gu(Qn(t,Mu),ya(e),{mode:yb});let n=Qn(t,Hu);pb(n,{mode:hb});for(let r of kh(xh(e.docker))){let o=Qn(n,r.name);Gu(o,r.content),vD(o,r.mode)}}async function Sb(e){let t=wa(e),n=ED(Qn(kD(),"hydra-image-"));try{ND(e,n);let a=Bu(e.builder,e,n),c=await db(a,{stream:!0,timeoutMs:_D},"build",t);if(c.exitCode!==0)throw new We("build",t,ub(e.builder,c))}finally{fb(n,{force:!0,recursive:!0})}let r=ID(e.builder,t),o=await db(r,{stream:!1,timeoutMs:AD},"inspect",t);if(o.exitCode!==0)throw new We("inspect",t,ub(e.builder,o));let s=LD(e.builder,o.stdout);if(!s)throw new We("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:je.runner.version,tag:t,variant:e.docker?"docker":"plain"};return DD(e.home,i),i}function ju(e,t){return Qn(e,gb,`${t.replace(":","-")}.json`)}function DD(e,t){pb(Qn(e,gb),{mode:hb,recursive:!0});let n=ju(e,t.digest),r=`${n}.${process.pid}.tmp`;try{Gu(r,`${JSON.stringify(t,null,2)}
|
|
415
|
+
`,{flag:"wx",mode:yb}),xD(r,n)}finally{fb(r,{force:!0})}}function LD(e,t){let n=e==="container"?HD(t):t.trim();return n&&PD.test(n)?n:void 0}function HD(e){try{let[t]=OD(JSON.parse(e));return t?.configuration.descriptor.digest}catch{return}}function ub(e,t){let n=t.stderr.trim().split(`
|
|
416
|
+
`).slice(-CD).join(`
|
|
417
|
+
`);return`${e} exited with code ${t.exitCode}${n?`
|
|
418
|
+
${n}`:""}`}async function db(e,t,n,r){let o=await MD(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/TD} s`;return{exitCode:o.exitCode,stderr:`${o.stderr}
|
|
419
|
+
${s}`,stdout:o.stdout}}async function MD(e,t,n,r){try{return await lt(e,{echo:t.stream,timeoutMs:t.timeoutMs})}catch(o){let s=o instanceof Error?o.message:String(o);throw new We(n,r,`${e[0]} could not start (${s})`,{cause:o})}}class jo 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 vb=1000,UD=120*vb,BD=5;function ba(e={}){let t=e.timeoutMs??UD;return async(n)=>{let[r,...o]=wb(n.builder,n.reference),s=[e.binaries?.[n.builder]??r,...o],i=await lt(s,{timeoutMs:t}).catch((c)=>{throw new jo("delete the image",n.reference,`${r} could not start (${Vu(c)})`,{cause:c})});if(i.timedOut)throw new jo("delete the image",n.reference,`${r} did not finish within ${t/vb} s`);if(i.exitCode===0)return;let a=i.stderr.trim().split(`
|
|
420
|
+
`).slice(-BD).join(`
|
|
421
|
+
`);throw new jo("delete the image",n.reference,`${r} exited with code ${i.exitCode}${a?`: ${a}`:""}`)}}async function Sa(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),$b(o),r.images.push(s.reference)}catch(i){r.failed.push({detail:Vu(i),item:s.reference})}}for(let o of e.logs){if(n?.aborted)return r;try{$b(o.path),r.logs.push(o.name),r.freedBytes+=o.bytes}catch(s){r.failed.push({detail:Vu(s),item:o.path})}}return r}function Ra(e){let t=Rb(e.images.length,"image"),n=Rb(e.logs.length,"slot log");return`${t} and ${n}, freeing ${bt(e.freedBytes)} of logs`}function Rb(e,t){return`${e} ${t}${e===1?"":"s"}`}function $b(e){let t=GD(e,{throwIfNoEntry:!1});if(!t)return;if(!t.isFile())throw new jo("remove",e,"it is no longer a regular file");FD(e)}function Vu(e){return e instanceof Error?e.message:String(e)}var Ku=60000,jD=1440,VD={checkMs:Ku,dailyMs:jD*Ku,repruneMs:60*Ku},Eb={critical:3,low:2,normal:0,warn:1},KD={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 kb(e){let t=e.clock??Ie,n={...VD,...e.timing},r,o=!1,s,i,a=new AbortController,c,l=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): ${KD[m.state]}`;e.log(h);let E=Eb[m.state]>Eb[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: ${xb(m)}`);return o=!0,{worse:!1}}},u=(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 ${Ra(m)}`);for(let g of m.failed)e.log(`could not prune ${g.item}: ${g.detail}`)}catch(m){e.log(`could not prune: ${xb(m)}`)}},p=()=>(i??=(async()=>{let{reading:m,worse:g}=await l();if(u(m,g))await d()})().finally(()=>{i=void 0}),i);return{check:p,reading:()=>r,start(){if(c)return;if(a.signal.aborted)a=new AbortController;let{signal:m}=a;c=(async()=>{while(!m.aborted)await p(),await t.sleep(n.checkMs,m)})()},async stop(){a.abort(),await c,await i,c=void 0}}}function xb(e){return e instanceof Error?e.message:String(e)}import{createConnection as pH}from"net";import{closeSync as qD,constants as _b,fstatSync as WD,openSync as JD,readFileSync as YD}from"fs";import{isAbsolute as zD}from"path";var $n=["linux","macos-vm","native"];class Zn extends Error{path;_tag="HostBudgetError";constructor(e,t,n){super(`The host budget ${e} ${t}`,n);this.path=e;this.name="HostBudgetError"}}var Ib="/etc/hydra/host.json",Xt="/var/run/hydra",XD="/var/db/hydra",Vo=100,QD=2,ZD=2048,eL=1.25,tL=1,Ab=100,qu=16,Cb={criticalGiB:50,lowGiB:100,path:"/",warnGiB:150},nL=18,Tb=0,rL=/^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/,oL=["cpuCommitRatio","disk","fleets","freeMemoryReserveMiB","loadFactor","macosVmCap","memoryMiB","socketDir","stateDir"],sL="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",iL=["criticalGiB","lowGiB","path","warnGiB"],aL=["account","ceilings","guestRange","maxPriority","weight"],Ne=(e,t=Number.MAX_SAFE_INTEGER)=>X().map((n)=>Number.isSafeInteger(n)&&n>=e&&n<=t?n:B()),Pb=X().map((e)=>Number.isFinite(e)&&e>0&&e<=qu?e:B()),Wu=N().map((e)=>zD(e)?e:B()),cL=Ne(1).or(Y([ge])),lL=N().map((e)=>{let t=et(e);return t&&Ls(t)?e:B()});function Nb(e){let t;try{t=uL(e)}catch(n){if(n instanceof Zn)throw n;throw new Zn(e,`cannot be read (${Ob(n)})`,{cause:n})}try{return dL(JSON.parse(t))}catch(n){throw new Zn(e,`is not valid: ${Ob(n)}`,{cause:n})}}function uL(e){let t=JD(e,_b.O_RDONLY|_b.O_NONBLOCK);try{let n=Ju(WD(t),"file");if(n)throw new Zn(e,n);return YD(t,"utf-8")}finally{qD(t)}}function Ju(e,t){if(t==="directory"?!e.isDirectory():!e.isFile())return`must be a ${t}`;let n=process.geteuid?.()??Tb;if(e.uid!==n&&e.uid!==Tb)return`must be owned by root or by the user running the host daemon (uid ${n})`;return(e.mode&nL)===0?void 0:"must not be writable by its group or by other users"}function dL(e){let t=fe(e,"the budget");_e(t,oL,"budget","the host budget"),se(t.memoryMiB,Ne(1),"memoryMiB","the memory guests may commit, in whole MiB"),ae(t.cpuCommitRatio,Pb,"cpuCommitRatio",`a number above 0 and at most ${qu}`),ae(t.loadFactor,Pb,"loadFactor",`a number above 0 and at most ${qu}`),ae(t.freeMemoryReserveMiB,Ne(0),"freeMemoryReserveMiB","whole MiB"),ae(t.macosVmCap,Ne(0,an),"macosVmCap",`a whole number from 0 to ${an}, the macOS VMs a host may run at once`),ae(t.socketDir,Wu,"socketDir","an absolute path"),ae(t.stateDir,Wu,"stateDir","an absolute path");let n=t.macosVmCap??an,r=fL(t.fleets,n);return{cpuCommitRatio:t.cpuCommitRatio??QD,disk:pL(t.disk),fleets:r,freeMemoryReserveMiB:t.freeMemoryReserveMiB??ZD,loadFactor:t.loadFactor??eL,macosVmCap:n,memoryMiB:t.memoryMiB,socketDir:t.socketDir??Xt,stateDir:t.stateDir??XD}}function pL(e){if(e===void 0)return Cb;let t=fe(e,"disk");_e(t,iL,"disk","the disk thresholds"),ae(t.path,Wu,"disk.path","an absolute path on the volume that holds the guests");for(let r of["warnGiB","lowGiB","criticalGiB"])ae(t[r],Ne(0),`disk.${r}`,"whole GiB");let n={...Cb,...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 fL(e,t){if(e===void 0)throw Error("fleets is missing; expected one entry per fleet that may lease guests");let n=fe(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,gL(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 mL(o),o}function mL(e){let t=Object.entries(e).flatMap(([n,r])=>r.guestRange===void 0?[]:[{cidr:et(r.guestRange),id:n,range:r.guestRange}]);for(let[n,r]of t.entries()){let o=t.slice(n+1).find((s)=>Hs(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 gL(e,t,n){if(!Un(e))throw Error(`Fleet "${e}" must be lowercase letters and digits without hyphens, at most ${Ys} characters`);let r=`fleets.${e}`,o=fe(t,r);_e(o,aL,r,"a fleet's budget"),se(o.account,N().map((a)=>rL.test(a)?a:B()),`${r}.account`,"the user name the fleet runs as, which owns its socket"),ae(o.weight,Ne(1,Ab),`${r}.weight`,`a whole number from 1 to ${Ab}`),ae(o.maxPriority,Ne(0,Vo),`${r}.maxPriority`,`a whole number from 0 to ${Vo}`);let s=hL(o.ceilings,`${r}.ceilings`,n);return(s.linux===void 0?ae:se)(o.guestRange,lL,`${r}.guestRange`,sL),{account:o.account,ceilings:s,...o.guestRange===void 0?{}:{guestRange:o.guestRange},maxPriority:o.maxPriority??Vo,weight:o.weight??tL}}function hL(e,t,n){if(e===void 0)throw Error(`${t} is missing; expected a ceiling for each class the fleet may lease`);let r=fe(e,t);if(_e(r,$n,t,"a fleet's ceilings"),Object.keys(r).length===0)throw Error(`${t} must allow at least one class`);for(let s of $n)ae(r[s],cL,`${t}.${s}`,`a positive whole number or "${ge}"`);let o=r["macos-vm"];if(o!==void 0&&(o===ge||o>n))throw Error(`${t}.macos-vm must be at most macosVmCap (${n})`);return r}function Ob(e){return e instanceof Error?e.message:String(e)}import{closeSync as Db,fsyncSync as Lb,openSync as Hb,readFileSync as yL,renameSync as wL,rmSync as bL,writeFileSync as SL}from"fs";import{dirname as RL,join as $L}from"path";class Fr 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 vL="leases.json",Mb=1,EL=384,xL=64,kL=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,er={class:Y($n),cpus:Ne(1),diskGiB:Ne(1),memoryMiB:Ne(1),pool:N().map((e)=>So(e)?e:B()),priority:Ne(0,Vo),slot:N().map((e)=>CL(e)?e:B())},_L=H({...er,fleet:N().map((e)=>Un(e)?e:B()),grantedAt:N().map((e)=>Number.isNaN(Date.parse(e))?B():e),origin:Y(["adopted","granted"])}),AL=H({leases:ee(_L),version:Y([Mb])});function CL(e){return e.length<=xL&&kL.test(e)}function Gb(e){return $L(e,vL)}function Fb(e){let t;try{t=yL(e,"utf-8")}catch(n){if(n.code==="ENOENT")return[];throw new Fr(e,"read",Yu(n),{cause:n})}try{return AL(JSON.parse(t)).leases}catch(n){throw new Fr(e,"read",`it is not a valid lease file (${Yu(n)})`,{cause:n})}}function Ub(e,t){let n=`${e}.${process.pid}.tmp`;try{let r=Hb(n,"w",EL);try{SL(r,`${JSON.stringify({leases:t,version:Mb},null,2)}
|
|
422
|
+
`),Lb(r)}finally{Db(r)}wL(n,e),TL(RL(e))}catch(r){throw new Fr(e,"write",Yu(r),{cause:r})}finally{bL(n,{force:!0})}}function Bb(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 TL(e){let t=Hb(e,"r");try{Lb(t)}finally{Db(t)}}function Yu(e){return e instanceof Error?e.message:String(e)}import{statfs as PL}from"fs/promises";class Dt extends Error{reading;_tag="LiveReadingError";constructor(e,t,n){super(`Could not read ${e}: ${t}`,n);this.reading=e;this.name="LiveReadingError"}}var OL=1e4,jb=1048576,IL=1024*jb,NL=["kern.memorystatus_vm_pressure_level","hw.logicalcpu","vm.loadavg"],DL={"1":"normal","2":"warn","4":"critical"},LL=/page size of (\d+) bytes/,HL=/^Pages free:\s+(\d+)\.?$/m,ML=/^Pages inactive:\s+(\d+)\.?$/m,GL=/^\{\s*([\d.]+)\s/,Vb=10;function Kb(e,t={}){let n=t.now??Date.now,r=t.env??process.env;return async()=>{let[o,s,i]=await Promise.all([FL(r),UL(r),BL(e)]);return{...o,diskFreeGiB:i,freeMemoryMiB:s,readAt:n()}}}function $a(e,t){if(e<t.criticalGiB)return"critical";if(e<t.lowGiB)return"low";return e<t.warnGiB?"warn":"normal"}async function FL(e){let t=await qb(["sysctl","-n",...NL],e,"the kernel's memory pressure, CPUs and load"),[n,r,o]=t.trim().split(`
|
|
423
|
+
`),s=Number.parseInt(r??"",Vb),i=Number.parseFloat(GL.exec(o??"")?.[1]??"");if(!Number.isSafeInteger(s)||s<1||!Number.isFinite(i))throw new Dt("the kernel's CPUs and load","sysctl printed an unexpected value");return{cores:s,load1:i,pressure:DL[n?.trim()??""]??"critical"}}async function UL(e){let t=await qb(["vm_stat"],e,"free and inactive memory"),n=zu(LL.exec(t)?.[1]),r=zu(HL.exec(t)?.[1]),o=zu(ML.exec(t)?.[1]);if(n===void 0||r===void 0||o===void 0)throw new Dt("free and inactive memory","vm_stat printed no page size, free or inactive count");return Math.floor((r+o)*n/jb)}async function BL(e){try{let t=await PL(e);return t.bavail*t.bsize/IL}catch(t){throw new Dt(`free space on ${e}`,Wb(t),{cause:t})}}function zu(e){let t=Number.parseInt(e??"",Vb);return Number.isSafeInteger(t)?t:void 0}async function qb(e,t,n){try{let r=Bun.spawn([...e],{env:t,killSignal:"SIGKILL",stderr:"pipe",stdin:"ignore",stdout:"pipe",timeout:OL}),[o,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);if(r.signalCode!==null)throw new Dt(n,`${e[0]} was stopped by ${r.signalCode}`);if(i!==0)throw new Dt(n,`${e[0]} exited with code ${i}: ${s.trim()}`);return o}catch(r){if(r instanceof Dt)throw r;throw new Dt(n,`${e[0]} could not start (${Wb(r)})`,{cause:r})}}function Wb(e){return e instanceof Error?e.message:String(e)}var jL=60000,VL=0.5,KL=1024;function xa(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 vn(e,t){return Math.floor(t*e.cpuCommitRatio)}function Ea(e,t){return Math.min(t,e.maxPriority)}function ka(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=vn(n,r);if(t.cpus>s)return`${t.cpus} vCPU is more than the ${s} vCPU the host commits in all`;return}function qL(e,t){let{budget:n,leases:r,live:o,now:s}=t,{fleet:i,request:a}=e,c=n.fleets[i],l=$a(o.diskFreeGiB,n.disk),u=xa(r);if(l==="critical")return va(`free disk space is critical (${o.diskFreeGiB.toFixed(0)} GiB)`);if(l==="low"&&a.class==="macos-vm")return va(`free disk space is low (${o.diskFreeGiB.toFixed(0)} GiB), which stops new macOS VMs`);let d=c.ceilings[a.class]??0,p=r.filter((T)=>T.fleet===i&&T.class===a.class).length;if(d!==ge&&p>=d)return va(`the fleet holds its ${a.class} ceiling of ${d}`);if(a.class==="macos-vm"&&u.macosVms>=n.macosVmCap)return va(`the host runs its ${n.macosVmCap} macOS VMs`);let m=l==="low"?VL:1,g=l==="low"?", halved while free disk space is low":"",h=Math.floor(n.memoryMiB*m);if(u.memoryMiB+a.memoryMiB>h)return Ur(`committed memory ${Ue(u.memoryMiB)} of ${Ue(h)}${g}`);let E=Math.floor(vn(n,o.cores)*m);if(u.cpus+a.cpus>E)return Ur(`committed vCPU ${u.cpus} of ${E}${g}`);if(o.pressure!=="normal")return Ur(`the kernel reports ${o.pressure} memory pressure`);let v=r.filter((T)=>T.origin==="granted"&&s-Date.parse(T.grantedAt)<jL).reduce((T,b)=>T+b.memoryMiB,0),R=o.freeMemoryMiB-n.freeMemoryReserveMiB-v;if(R<a.memoryMiB)return Ur(`free memory ${Ue(Math.max(R,0))} after the reserve`);let _=o.cores*n.loadFactor;if(o.load1>=_)return Ur(`load average ${o.load1.toFixed(2)} of ${_.toFixed(2)}`);if(o.diskFreeGiB-a.diskGiB<n.disk.criticalGiB)return Ur(`${a.diskGiB} GiB of disk would take free space below ${n.disk.criticalGiB} GiB`);return}function WL(e,t,n){let r=(s)=>{let i=t.fleets[s.fleet],a=Ea(i,s.request.priority),c=n.filter((l)=>l.fleet===s.fleet&&Ea(i,l.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 Ko(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=WL(i,t.budget,r);for(let[l,u]of c.entries()){let d=qL(u,{...t,leases:r});if(!d){let p=JL(u,t.now);r.push(p),o.push({lease:p,seq:u.seq}),i=i.filter((g)=>g.seq!==u.seq);let m=n?.(u);if(m)i.push(m);a=!0;break}if(s.set(u.seq,d),d.scope==="own")continue;for(let p of c.slice(l+1)){let m=p.fleet===u.fleet?u.request.slot:"another fleet's request";s.set(p.seq,{reason:`behind ${m}, which waits for ${d.reason}`,scope:"shared"})}return{granted:o,held:s}}}return{granted:o,held:s}}function JL(e,t){return{...e.request,fleet:e.fleet,grantedAt:new Date(t).toISOString(),origin:"granted"}}function va(e){return{reason:e,scope:"own"}}function Ur(e){return{reason:e,scope:"shared"}}function Ue(e){return`${(e/KL).toFixed(1)} GiB`}var YL=600000,zL=60000,Jb=64,Br=32,XL=256,QL="offer",{slot:zY,...ZL}=er,zb={...ZL,assigned:Ne(0),ceiling:Ne(1).or(Y([ge]))};function Xb(){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)=>eH({...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,tH(t,s,o?.get(s.pool),r)])))}}}function Yb(e,t){return e.demandAt!==void 0&&t-e.demandAt<YL&&t-e.claimedAt<zL}function eH(e){let{entries:t,fleet:n,state:r}=e,o=e.open??(()=>!0),s=e.waiting.filter((l)=>o(l.request)),i=new Map(t.map((l)=>[l,nH(l,r,s,o)])),a=(l)=>i.get(l)??0,c=rH(t.filter((l)=>Yb(l,r.now)&&a(l)>0),a,s,r);return t.filter((l)=>l.fleet===n).map((l)=>{let u=c.get(l)??0,d=u===0&&a(l)>0&&oH(l,s,r);return{active:Yb(l,r.now),offer:d?1:u,pool:l.request.pool}})}function tH(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 nH(e,t,n,r){let o=Xu(e);if(!r(o)||ka(e.fleet,o,t.budget,t.live.cores))return 0;let{ceiling:s,pool:i}=e.request;if(s===ge)return Jb;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(Jb,s-a))}function rH(e,t,n,r){let o=new Map;if(e.length===0)return o;let s=new Map,i=Qb(n),a=0,c=(u)=>(s.set(i,u),{fleet:u.fleet,request:Xu(u),seq:i++}),l=(u)=>{let d=s.get(u.seq);if(!d)return;a++;let p=(o.get(d)??0)+1;return o.set(d,p),p<t(d)&&a<XL?c(d):void 0};return Ko([...n,...e.map(c)],r,l),o}function oH(e,t,n){let r=Qb(t),o={fleet:e.fleet,request:Xu(e),seq:r};return Ko([...t,o],n).granted.some((s)=>s.seq===r)}function Qb(e){return e.reduce((t,n)=>Math.max(t,n.seq+1),0)}function Xu(e){let{assigned:t,ceiling:n,...r}=e.request;return{...r,slot:QL}}var Zb=["lease","net.status","offer","release","report","status"];class Lt extends Error{id;_tag="HostProtocolError";constructor(e,t){super(t);this.id=e;this.name="HostProtocolError"}}var _a=65536,eS=4096,sH=Ne(0),tS=H(er),iH=ee(tS),aH=ee(H(zb)),cH=["id","op",...Object.keys(er)],lH={lease:cH,"net.status":["id","op"],offer:["id","op","pools"],release:["id","op","slot"],report:["id","op","slots"],status:["id","op"]};function nS(e){let t;try{t=JSON.parse(e)}catch{throw new Lt(null,"a request must be one JSON object per line")}let n=dH(t),r=tr(()=>sH(n.id),null,"id must be a whole number"),o=tr(()=>Y(Zb)(n.op),r,`op must be one of ${Zb.join(", ")}`);switch(tr(()=>_e(n,lH[o],"the request",`a ${o} request`),r),o){case"lease":return{id:r,op:o,request:tr(()=>tS(n),r,"the lease request is invalid")};case"offer":return{id:r,op:o,pools:uH(n.pools,r)};case"release":return{id:r,op:o,slot:tr(()=>er.slot(n.slot),r,"slot is not a slot name")};case"report":{if(Array.isArray(n.slots)&&n.slots.length>eS)throw new Lt(r,`a report lists at most ${eS} slots`);let s=tr(()=>iH(n.slots),r,"slots must list the fleet's slots");if(new Set(s.map((i)=>i.slot)).size!==s.length)throw new Lt(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 uH(e,t){if(Array.isArray(e)&&e.length>Br)throw new Lt(t,`an offer request lists at most ${Br} pools`);let n=tr(()=>aH(e),t,"pools must list the fleet's scale-set pools");if(new Set(n.map((r)=>r.pool)).size!==n.length)throw new Lt(t,"an offer request lists each pool once");return n}function qo(e){return`${JSON.stringify(e)}
|
|
424
|
+
`}function Je(e,t,n){return{error:{code:t,message:n},id:e,ok:!1}}function dH(e){try{return fe(e,"a request")}catch{throw new Lt(null,"a request must be a JSON object")}}function tr(e,t,n){try{return e()}catch(r){throw new Lt(t,n??(r instanceof Error?r.message:String(r)))}}class Ye extends Error{socket;code;_tag="HostClientError";constructor(e,t,n,r){super(n,r);this.socket=e;this.code=t;this.name="HostClientError"}}var fH=1e4;async function jr(e,t=fH){let n=await mH(e),r=new Map,o=1,s="",i=(c)=>{if(c.id===null)return;let l=r.get(c.id);if(!l)return;if(r.delete(c.id),clearTimeout(l.timer),!c.ok){l.reject(new Ye(e,c.error.code,c.error.message));return}let{id:u,ok:d,...p}=c;l.resolve(p)};n.setEncoding("utf8"),n.on("data",(c)=>{s+=c;for(let l=s.indexOf(`
|
|
425
|
+
`);l>=0;l=s.indexOf(`
|
|
426
|
+
`)){let u=s.slice(0,l);s=s.slice(l+1);try{i(JSON.parse(u))}catch{n.destroy()}}}),n.on("error",()=>n.destroy()),n.on("close",()=>{for(let c of r.values())clearTimeout(c.timer),c.reject(new Ye(e,"closed",`The host daemon closed ${e}`));r.clear()});let a=(c,l,u)=>new Promise((d,p)=>{if(n.destroyed){p(new Ye(e,"closed",`The connection to ${e} is closed`));return}let m=o++,g=u?void 0:setTimeout(()=>{r.delete(m),p(new Ye(e,"timeout",`The host daemon did not answer ${c} within ${t} ms`))},t);r.set(m,{reject:p,resolve:(h)=>d(h),timer:g}),n.write(qo({...l,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 mH(e){return new Promise((t,n)=>{let r=pH(e);r.once("connect",()=>{r.off("error",n),t(r)}),r.once("error",(o)=>n(new Ye(e,"unreachable",`Cannot reach the host daemon on ${e} (${o.message})`)))})}var gH=new Set(["closed","timeout","unreachable"]);function rS(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 Ye("","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(l){if(l instanceof Ye&&gH.has(l.code)&&n===c)n=void 0,t=void 0,c.close();throw l}};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 nr=50;function Wo(e){if(e.driver==="native")return"native";return br(e.driver,e.guestOs)?"macos-vm":"linux"}function oS(e,t,n,r){let o=e.fleets[t];if(!o)return[{detail:`The host budget has no fleet ${t}`,level:"error"}];let s=vn(e,r);return Object.entries(n).flatMap(([i,a])=>{let c=Wo(a),l=o.ceilings[c];if(l===void 0)return[{detail:`Pool ${i} needs ${c} leases, which fleet ${t} may not take`,level:"error"}];let u=[],{cpus:d,memoryMiB:p}=a.resources;if(p>e.memoryMiB)u.push({detail:`Pool ${i} asks for ${p} MiB, above the ${e.memoryMiB} MiB budget`,level:"error"});if(d>s)u.push({detail:`Pool ${i} asks for ${d} vCPU, above the ${s} vCPU this host commits`,level:"error"});if(l!==ge&&(a.ceiling===ge||a.ceiling>l))u.push({detail:`Pool ${i} runs at most ${l} at once: the fleet's ${c} ceiling`,level:"warning"});let m=a.priority??nr;if(Ea(o,m)<m)u.push({detail:`Pool ${i} waits at priority ${o.maxPriority}, the fleet's highest`,level:"warning"});return u})}class Aa 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 ${Br} pools of one fleet`);this.pools=e;this.name="HostOffersError"}}var hH=1e4,yH=120000,wH=1000;function bH(e,t,n){let{cpus:r,diskGiB:o,memoryMiB:s}=t.resources;return{assigned:n,ceiling:t.ceiling,class:Wo(t),cpus:r,diskGiB:o,memoryMiB:s,pool:e,priority:t.priority??nr}}function sS(e){let t=e.clock??Ie,n=e.intervalMs??hH,r=e.unreachableAlertMs??yH,o=Object.entries(e.pools).filter(([,h])=>h.demand==="scaleset");if(o.length>Br)throw new Aa(o.map(([h])=>h));let s=new Map,i,a=!1,c,l,u,d;async function p(){try{let h=e.slots(),E=new Map(o.map(([_])=>[_,Mr(h,_).length])),v=o.map(([_,T])=>bH(_,T,e.assigned(_))),R=new Map((await e.offer(v)).map((_)=>[_.pool,_.offer]));s=new Map(o.map(([_])=>[_,{live:E.get(_)??0,offer:R.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/wH)} s, so no new guest starts: ${SH(h)}`,reason:"host-daemon-unreachable"})}}function m(){if(!c)return c=p().finally(()=>{c=void 0}),c;return l??=c.then(()=>(l=void 0,m())),l}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=Mr(e.slots(),h).length,R=s.get(h),_=R?Math.max(0,R.offer-Math.max(0,v-R.live)):0,T=v+_;return Gr(E.ceiling===ge?T:Math.min(E.ceiling,T))},refresh:m,start(){if(d)return;let h=new AbortController;u=h,d=g(h.signal)},async stop(){u?.abort(),await d,u=void 0,d=void 0}}}function SH(e){return e instanceof Error?e.message:String(e)}var RH=1e4,$H=300000;function vH(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)&&ei(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 iS(e){let{client:t,pools:n}=e,r=e.clock??Ie,o=e.freshMs??RH,s=Lg(),i,a;async function c(d){let p=new Map,m=(v,R)=>{d.throwIfAborted();let _=R instanceof Error?R:Error(String(R));for(let T of v)if(!p.has(T))p.set(T,_)},g=new Map;for(let v of n)try{for(let R of await v.repositories()){let _=Dg(R),T=g.get(_)??{admittedBy:new Set,repository:R};T.admittedBy.add(v.pool),g.set(_,T)}}catch(R){m([v.pool],R)}let h=[];for(let{admittedBy:v,repository:R}of g.values())try{for(let _ of await Hg(t,R,s,d))h.push({admittedBy:v,labels:_})}catch(_){m(v,_)}let E=n.filter((v)=>!p.has(v.pool)).map(({labels:v,pool:R,priority:_,room:T})=>({labels:v,pool:R,priority:_,room:T()}));return{counts:vH(E,h),failures:p}}function l(d){let p=r.now();if(i&&p-i.at<o)return{round:Promise.resolve(i.round),signal:d};return a??={round:c(d).then((m)=>(i={at:p,round:m},m)).finally(()=>{a=void 0}),signal:d},a}async function u(d){for(;;){let p=l(d);try{return await p.round}catch(m){if(d.aborted||!p.signal.aborted)throw m}}}return{reader(d){if(!n.some((p)=>p.pool===d))throw Error(`Pool ${d} is not on the queued job board`);return{queued:async(p)=>{let m=await u(p),g=m.failures.get(d);if(g)throw g;return m.counts.get(d)??0}}}}}function aS(e){let{github:t,pool:n}=e,r=me(e.url);if(r.kind==="repo"){let u=[{owner:r.owner,repo:r.repo}];return async()=>u}let o=e.clock??Ie,s=e.refreshMs??$H,i=Rr(),a=Rr(),c=`Read the repositories whose jobs may reach pool ${n}`,l;return async()=>{let u=o.now();if(l&&u-l.at<s)return l.repositories;let d=e.runnerGroup,p=d===void 0?void 0:await xr(t,r.org,d,i);if(!p)throw new qe(n,c,"runner-group-missing",`${r.org} has no runner group named ${d??"(none set)"}`);let{visibility:m}=p;if(!Wg(m))throw new qe(n,c,"runner-group-visibility",`the runner group ${p.name} admits repositories by ${m}, which Hydra does not know`);let g=await Jg(t,r.org,{...p,visibility:m},a);return l={at:u,repositories:g},g}}import{closeSync as EH,constants as Ca,fchmodSync as xH,mkdirSync as kH,openSync as _H,writeSync as AH}from"fs";import{join as CH}from"path";var uS={pollMs:5000,retryMs:1e4,undestroyedRetryMs:900000},cS=5242880,TH=7,PH=448,lS=384,OH=/[\p{Cc}\p{Cf}]+/gu,IH="the error text was withheld because it looks like it holds a secret",NH=new Set(["busy","closed","conflict","timeout","unavailable","unreachable"]);function Qu(e,t,n){let{cpus:r,diskGiB:o,memoryMiB:s}=t.resources;return{class:Wo(t),cpus:r,diskGiB:o,memoryMiB:s,pool:e,priority:t.priority??nr,slot:n}}function Ce(e){let t=(e instanceof Error?e.message:String(e)).replace(OH," ").trim();if(Xn(t))return IH;return(t.length>oa?`${t.slice(0,oa-1)}\u2026`:t)||"an unknown error"}function dS(e,t,n){let{clock:r,host:o,ledger:s,log:i,signal:a,timing:c}=e,l=(x)=>r.sleep(x,a),u=(x)=>s.record(t,x),d=(x)=>e.pools[x.pool];async function p(x){let L=d(x);if(n.withdraw||!L){u({kind:"drain"});return}try{let V=await o.lease(Qu(x.pool,L,t));if(u({kind:"lease-granted",lease:V.grantedAt}),e.leaseChanged(),n.withdraw)u({kind:"drain"})}catch(V){if(a.aborted)return;let K=V instanceof Ye?V.code:"failed";if(K==="withdrawn"){u({kind:"drain"});return}if(x.phase==="requested")u({kind:"lease-refused"});if(NH.has(K)){await l(c.retryMs);return}u({kind:"drain"}),e.unavailable(x.pool,`the host daemon refused its guests: ${Ce(V)}`)}}async function m(x,L){if(n.withdraw){u({kind:"drain"});return}u({kind:"prepare"});try{await L.create(e.spec(x.pool,t)),await L.start(x)}catch(V){if(V instanceof Nr){i(`slot ${t} returns its lease: ${Ce(V)}`),u({kind:"budget-unavailable"});return}u({detail:Ce(V),kind:"failed"});return}u({kind:"ready"})}async function g(x,L){if(R(x)){u({kind:"timed-out"});return}let V=e.source(x.pool);if(!V){u({detail:"the pool has no demand source to mint its runner",kind:"failed"});return}let K=await _(L,x);if(!K){await l(c.pollMs);return}if(K.kind!=="running"){u({detail:`the guest was ${K.kind} before its runner was handed over`,kind:"failed"});return}let W;try{let pe=await V.mint(t);W=pe.jit,u({kind:"minted",runnerId:pe.runner.id,runnerName:pe.runner.name})}catch(pe){if(a.aborted)return;u({detail:Ce(pe),kind:"failed"});return}try{await L.runJit(x,W)}catch(pe){u({detail:Ce(pe),kind:"failed"})}}async function h(x){n.retire=!1;let L=e.source(x.pool);if(!L||!x.runner)return!1;if(await L.release(x.runner).catch(()=>"busy")==="busy")return!1;return u({kind:"drain"}),!0}async function E(x,L){if(n.retire&&x.phase==="online"&&await h(x))return;let V=await _(L,x);if(V)v(x,V);let K=s.get(t);if(K&&K.phase===x.phase&&R(K)){u({kind:"timed-out"});return}if(K?.phase===x.phase)await l(c.pollMs)}function v(x,L){switch(L.kind){case"runner-alive":if(L.busy&&x.phase!=="busy")u({kind:"job-started"});else if(!L.busy&&x.phase==="registering")u({kind:"online"});return;case"exited":if(u({code:L.code,kind:"exited"}),L.code===TH)e.alert({detail:`the runner of ${t} exited asking for a newer version`,pool:x.pool,reason:"runner-update-required",slot:t});return;case"gone":u({detail:"the guest disappeared",kind:"failed"});return;case"preparing":case"running":return}}function R(x){let L=lw(x,d(x)?.maxJobMinutes??sw);return L!==void 0&&r.now()>=L}async function _(x,L){try{return await x.state(L)}catch(V){i(`could not read the state of ${t}: ${Ce(V)}`);return}}async function T(x,L){let V=d(x);if(e.logsDir&&V&&!V.secretBearing)try{let K="";for await(let W of L.logs(x,{bytes:cS}))K=`${K}${W.text}`.slice(-cS);if(K)LH(e.logsDir,t,K)}catch(K){i(`could not copy the runner log of ${t}: ${Ce(K)}`)}u({kind:"collected"})}async function b(x,L){try{await bm(L,x,{fleetPrefix:e.fleetPrefix,protectedNames:e.protectedNames,recorded:async(W)=>s.destroyable(W)});let K=await L.verifyGone(x);if(K.leftovers.length>0)throw Error(`the guest left ${K.leftovers.join(", ")} behind`)}catch(K){let W=Ce(K);if(e.alert({detail:W,pool:x.pool,reason:"slot-undestroyed",slot:t}),x.phase==="destroying")e.ended(u({detail:W,kind:"failed"}),"undestroyed");await l(c.undestroyedRetryMs);return}await A(x);let V=u({kind:"verified"});if(await y(),x.phase!=="destroying"){i(`slot ${t} is gone at last; its lease is returned`);return}if(V.phase==="quarantined")e.alert({detail:V.fault?.detail,pool:x.pool,reason:"slot-quarantined",slot:t});e.ended(V,DH(V))}async function A(x){let L=e.source(x.pool),V=x.runner;if(!V||!L)return;try{if(await L.release(V)!=="busy")return;i(`GitHub still shows the runner of ${t} as busy; reconcile removes it later`)}catch(K){i(`could not remove the runner registration of ${t}: ${Ce(K)}`)}e.runnerLeft?.(x.pool,V)}async function y(){try{await o.release(t),e.released(t,!0)}catch(x){i(`could not return the lease of ${t}: ${Ce(x)}`),e.released(t,!1)}e.leaseChanged()}async function S(x){if(x.lease!==void 0)await y();e.ended(x,"withdrawn")}async function C(x){let L=e.driver(x.pool);if(x.phase==="requested"||x.phase==="waiting")return p(x);if(!L){i(`slot ${t} of pool ${x.pool} waits: its driver is not available`),await l(c.retryMs);return}switch(x.phase){case"admitted":return m(x,L);case"preparing":u({kind:"drain"});return;case"registering":return x.runner?E(x,L):g(x,L);case"online":case"busy":return E(x,L);case"finishing":return T(x,L);default:return b(x,L)}}return(async()=>{while(!a.aborted){let x=s.get(t);if(!x||pt(x.phase)&&!Ve(x)){if(x?.phase==="withdrawn")await S(x);return}await C(x)}})()}function DH(e){if(e.phase==="quarantined")return"quarantined";return e.teardown==="job-done"?"job-done":"verified"}function LH(e,t,n){kH(e,{mode:PH,recursive:!0});let r=Ca.O_WRONLY|Ca.O_CREAT|Ca.O_TRUNC|Ca.O_NOFOLLOW,o=_H(CH(e,`${t}.log`),r,lS);try{xH(o,lS),AH(o,n.replace(/[^\P{Cc}\n\t]/gu,""))}finally{EH(o)}}var Zu=60000,HH={busyRetryMs:30000,goneGapMs:3*Zu,refusedAlertMs:15*Zu,roundMs:5*Zu},MH=3,GH=/^[a-z0-9]{6}$/,FH=/[\p{Cc}\p{Cf}]/gu;function UH(e,t,n){let r=`hydra-${t}-${n}-`;return e.startsWith(r)&&GH.test(e.slice(r.length))}function pS(e){return pt(e.phase)&&!Ve(e)}function BH(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 jH(e,t,n){let r=`${t}-`;return e.startsWith(r)&&[...n].some((o)=>e.endsWith(`-${o}`)&&e.length>r.length+o.length+1)}function Jo(e){return e.replace(FH,"?")}function fS(e){return(e.kind==="repo"?`repo:${e.owner}/${e.repo}`:`org:${e.org}`).toLowerCase()}function mS(e){let{fleet:t,github:n,ledger:r,log:o,registrations:s}=e,i=e.clock??Ie,a={...HH,...e.timing},c=new AbortController,l=new Map,u=new Map,d=new Map,p=new Set,m=new Map,g=new Set,h=0,E=[],v=()=>{let C=new Map;for(let[x,L]of Object.entries(s)){let V=fS(L.target),K=C.get(V)??{pools:[],target:L.target};K.pools.push(x),C.set(V,K)}return[...C.values()]},R=(C,x,L)=>{let V=`${C}:${x}`;if(d.has(V))return;d.set(V,x),o(L)},_=(C,x)=>{if(!l.has(x.id))l.set(x.id,{alerted:!1,failing:!1,pool:C,runner:x,since:i.now()})};async function T(){let C={failures:[],foreign:[],removed:[],retired:[]},x=new Map(r.slots().map((Q)=>[Q.name,Q])),L=new Map,V=new Set,K=new Set,W=async(Q,J,P)=>{try{return await P()}catch(G){V.add(Q),C.failures.push(`${J}: ${Ce(G)}`);return}},pe=async(Q,J)=>{let P=s[Q];if(!P)return;let G=await W("runner",`remove the runner ${J.name}`,()=>P.remove(J));if(G===void 0)return;if(G==="busy"){_(Q,J),R("busy",J.id,`GitHub reports the runner ${J.name} busy; Hydra retries its removal`);return}if(l.delete(J.id),G==="gone")return;C.removed.push(J.name),o(`removed the registration of runner ${J.name} (id ${J.id}), which its ended slot left behind`)},D=async(Q,J)=>{let P={id:J.id,name:J.name},G=x.get(J.name);if(G){if(!Q.pools.includes(G.pool)||!pS(G))return;let ce=s[G.pool];if(G.runner?.id!==J.id&&ce?.kind==="scaleset"){if(await W("runner",`read the runner ${J.name}`,()=>ce.locate(P))!=="here")return}await pe(G.pool,P);return}let F=Q.pools.find((ce)=>UH(J.name,t,ce));if(!F){let ce=`runner ${Jo(J.name)} (id ${J.id}) carries no slot name of this fleet`;R("foreign",J.id,`${ce}; Hydra leaves it alone`);return}if(r.get(J.name))return;let j=s[F],z=`runner ${J.name} (id ${J.id}) carries a slot name of pool ${F} that the ledger does not hold`;if(j?.kind!=="scaleset"||!Er(J)||J.busy){R("unheld",J.id,`${z}; Hydra leaves it alone`);return}if(K.add(J.id),!g.has(J.id))return;let Se=await W("runner",`read the runner ${J.name}`,()=>j.locate(P));if(Se==="elsewhere")R("elsewhere",J.id,`${z} in another scale set; Hydra leaves it alone`);if(Se==="here")await pe(F,P)},U=async(Q,J)=>{for(let P of r.slots()){let G=s[P.pool],F=P.runner;if(!G||!F||P.phase!=="online"||!Q.pools.includes(P.pool))continue;if(J.has(F.id)){u.delete(P.name);continue}let j=await W("runner",`read the runner of ${P.name}`,()=>G.locate(F));if(j===void 0)continue;if(j!=="gone"){u.delete(P.name);continue}let z=u.get(P.name);if(z===void 0){u.set(P.name,i.now());continue}if(i.now()-z<a.goneGapMs||r.get(P.name)?.phase!=="online")continue;u.delete(P.name),C.retired.push(P.name),o(`the runner of ${P.name} is gone from GitHub while it waits for a job; retiring the slot`),e.retire(P.name)}},te=async()=>{let Q=await W("scale-set","read the scale set records",async()=>e.records());if(!Q)return;let J=new Set(Object.values(Q).map((F)=>F.id)),P=BH(t,Q),G=new Map;for(let[F,j]of Object.entries(Q)){let z=s[F];if(z?.kind==="scaleset")G.set(`${fS(z.target)}#${j.runnerGroupId}`,z)}for(let F of G.values()){let j=Me(F.target),z=await W("scale-set",`list the scale sets of ${j}`,()=>F.scaleSets());for(let Se of z??[]){if(J.has(Se.id)||!jH(Se.name,t,P))continue;L.set(`scale-set:${Se.id}`,{category:"scale-set",detail:`scale set ${Jo(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 ${Jo(Se.name)}`})}}},ye=async()=>{let Q=new Map;for(let J of Object.values(e.drivers))Q.set(J.capabilities().id,J);for(let[J,P]of Q){let G=await W("guest",`list the ${J} guests`,()=>P.list());for(let F of G??[]){let j=r.get(F.name),z=x.get(F.name);if(j&&!(z&&pS(z)))continue;L.set(`guest:${F.name}`,{category:"guest",detail:j?`guest ${F.name} exists, though its slot ended ${j.phase}`:`guest ${F.name} carries this fleet's prefix, but the ledger holds no slot of that name`,reason:"foreign-guest",subject:`guest ${F.name}`})}}},xe=async()=>{for(let Q of e.networks??[]){let J=await W("network","read the guest networks",()=>Q.status());for(let P of J?.unplanned??[])L.set(`network:${P}`,{category:"network",detail:`network ${Jo(P)} carries this fleet's prefix, but lies outside its network range`,reason:"foreign-network",subject:`network ${Jo(P)}`})}},$e=new Set,be=!0;for(let Q of v()){let J=`list the runners of ${Me(Q.target)}`,P=await W("runner",J,()=>dn(n,Q.target));if(!P){be=!1;continue}for(let G of P)$e.add(G.id);for(let G of P)await D(Q,G);await U(Q,new Set(P.map((G)=>G.id)))}await te(),await ye(),await xe();for(let Q of u.keys())if(r.get(Q)?.phase!=="online")u.delete(Q);if(g=K,be){for(let[Q,J]of d)if(!$e.has(J))d.delete(Q)}return b(L,V,C),A(C.failures),C}function b(C,x,L){for(let[K,W]of C){if(!m.has(K)||p.has(K))continue;p.add(K),L.foreign.push(W.detail),o(`${W.detail}; Hydra leaves it alone, and no pool takes new jobs`),e.alert({detail:W.detail,reason:W.reason}),e.degrade(`found ${W.subject}, which Hydra did not create`)}let V=[...m].filter(([,K])=>x.has(K.category));m=new Map([...V,...C]);for(let K of p)if(!m.has(K))p.delete(K)}function A(C){for(let L of C)o(`reconcile could not ${L}`);if(h=C.length>0?h+1:0,h!==MH)return;let x=C.length>1?` and ${C.length-1} more`:"";e.alert({detail:`could not ${C[0]}${x}`,reason:"reconcile-failed"})}async function y(){for(let[C,x]of[...l]){let L=s[x.pool];if(!L){l.delete(C);continue}let V;try{V=await L.remove(x.runner)}catch(K){if(!x.failing)o(`could not remove the runner ${x.runner.name}: ${Ce(K)}`);x.failing=!0;continue}if(x.failing=!1,V!=="busy"){if(l.delete(C),V==="removed")o(`removed the registration of runner ${x.runner.name} (id ${C})`);continue}if(x.alerted||i.now()-x.since<a.refusedAlertMs)continue;x.alerted=!0,e.alert({detail:`GitHub still reports the runner ${x.runner.name} (id ${C}) busy after its guest was destroyed, so its registration stays`,pool:x.pool,reason:"registration-refused",slot:x.runner.name})}}let S=async(C,x)=>{while(!c.signal.aborted)await x().catch((L)=>o(`reconcile stopped on an error: ${Ce(L)}`)),await i.sleep(C,c.signal)};return{left:_,retry:y,round:T,start(){if(E.length>0||c.signal.aborted)return;E=[S(a.roundMs,T),S(a.busyRetryMs,y)]},async stop(){c.abort(),await Promise.allSettled(E)}}}var VH={busy:"busy",deleted:"removed",gone:"gone"};function KH(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 qH(e,t){return{kind:"poll",async locate(n){let r=await pn(e,t,n.id);if(!r)return"gone";return r.name===n.name?"here":"elsewhere"},remove:async(n)=>VH[await jn(e,t,n.id)],scaleSets:async()=>[],target:t}}function gS(e,t,n){let r={};for(let[o,s]of Object.entries(e)){let i=me(s.url);if(s.demand==="poll"){r[o]=qH(n.github,i);continue}let a=t[o];if(a)r[o]=KH(n.scaleSetClient(s.url),a,i)}return r}import{randomBytes as WH}from"crypto";var JH={...uS,healthMs:60000,stopMs:1e4,tickMs:5000},YH=3,zH=4,hS=6,XH=36,QH=["requested","waiting"],ZH=["online"],eM=["idle","connecting","conflict","retrying"];function yS(e,t){return e.slots().flatMap((n)=>{let r=t[n.pool];return r&&cw(n)?[Qu(n.pool,r,n.name)]:[]})}async function wS(e){let{host:t,ledger:n,log:r}=e,o=e.clock??Ie,s={...JH,...e.timing},i=new AbortController,a=new Map,c=new Map(Object.entries(e.unavailable??{})),l=new Map,u=new Map,d=new Map,p=new Set,m=new Set(n.slots().filter((D)=>!pt(D.phase)||Ve(D)).map((D)=>D.name)),g=`hydra-${e.fleet}`,h=!1,E=(D,U)=>{if(c.has(D))return;c.set(D,U),r(`pool ${D} takes no new jobs: ${U}`),e.alert({detail:U,pool:D,reason:"pool-unavailable"})},v=(D,U)=>{if(r(`slot ${D.name} of pool ${D.pool} ended ${U}`),U==="job-done")d.set(D.pool,0);if(U!=="quarantined"&&U!=="undestroyed"||m.has(D.name))return;let te=(d.get(D.pool)??0)+1;if(d.set(D.pool,te),te<YH||l.has(D.pool))return;let ye=`${te} slots in a row were quarantined, the last one ${D.name}`;l.set(D.pool,ye),r(`pool ${D.pool} is degraded: ${ye}`),e.alert({detail:ye,pool:D.pool,reason:"pool-degraded"})},R=(D)=>{let U=e.drivers[D];return U&&!u.has(U.capabilities().id)?U:void 0},_={alert:e.alert,clock:o,driver:(D)=>e.drivers[D],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:(D,U)=>{if(U)p.delete(D);else p.add(D)},runnerLeft:e.runnerLeft,signal:i.signal,source:(D)=>e.sources[D],spec:e.spec,timing:s,unavailable:E},T=(D)=>{if(a.has(D)||h)return;let U={retire:!1,withdraw:!1},te=dS(_,D,U).catch((ye)=>r(`slot ${D} stopped on an error: ${Ce(ye)}`)).finally(()=>a.delete(D));a.set(D,{control:U,done:te})},b=(D)=>{for(;;){let U=BigInt(`0x${WH(zH).toString("hex")}`).toString(XH).padStart(hS,"0").slice(-hS),te=`${g}-${D}-${U}`;if(!n.get(te))return te}},A=(D)=>!c.has(D)&&!l.has(D)&&R(D)!==void 0&&e.held?.(D)===void 0,y=(D,U,te)=>{let ye=($e)=>D.filter((be)=>$e.includes(be.phase)&&!a.get(be.name)?.control.withdraw).sort((be,Q)=>Date.parse(Q.requestedAt)-Date.parse(be.requestedAt)),xe=ye(QH).slice(0,U);for(let $e of xe){let be=a.get($e.name);if(!be)continue;be.control.withdraw=!0,t.release($e.name).catch(()=>{return})}if(!te)return;for(let $e of ye(ZH).slice(0,U-xe.length)){let be=a.get($e.name);if(be)be.control.retire=!0}},S=(D)=>{let U=Mr(n.slots(),D),te=e.sources[D],ye=te!==void 0&&A(D);if(ye&&eM.includes(te.status().state))return;let xe=ye?te.desired():0,$e=U.filter((Q)=>a.get(Q.name)?.control.withdraw).length;if(xe<U.length){let Q=ye||e.held?.(D)!==void 0;if(xe<U.length-$e)y(U,U.length-$e-xe,Q);return}let be=e.drivers[D];if(!be)return;for(let Q=U.length;Q<xe;Q++){let J=b(D);n.request({driver:be.capabilities().id,name:J,pool:D}),r(`requested slot ${J} for pool ${D}`),T(J)}},C=()=>{if(h)return;try{for(let D of Object.keys(e.pools))S(D);for(let D of n.slots())if(!pt(D.phase)||Ve(D))T(D.name)}catch(D){r(`could not balance the pools: ${Ce(D)}`)}for(let D of p)t.release(D).then(()=>p.delete(D),()=>{return})},x=(D)=>{for(let U of D.unlisted){let te=n.get(U);if(!te||pt(te.phase)&&!Ve(te))p.add(U)}if(D.adopted.length>0)r(`the host daemon adopted the leases of ${D.adopted.join(", ")}`)},L=async()=>{let D=new Map(Object.values(e.drivers).map((U)=>[U.capabilities().id,U]));for(let[U,te]of D){let ye=await te.health().then((be)=>be.findings.filter((Q)=>Q.level==="error").map((Q)=>Q.detail)).catch((be)=>[Ce(be)]),xe=u.get(U);if(ye.length===0){if(xe!==void 0)r(`driver ${U} is available again`);u.delete(U);continue}if(xe!==void 0)continue;let $e=ye.join("; ");u.set(U,$e),r(`driver ${U} is unavailable, so its pools take no new jobs: ${$e}`),e.alert({detail:`${U}: ${$e}`,reason:"driver-unavailable"})}},V=async(D,U)=>{while(!i.signal.aborted)await U(),await o.sleep(D,i.signal)};for(let[D,U]of Object.entries(e.sources))try{await U.start()}catch(te){E(D,Ce(te))}await L(),e.offers?.start();let K=[V(s.tickMs,C),V(s.healthMs,L)];return r(`serving ${Object.keys(e.pools).length} pools of fleet ${e.fleet}`),{degrade(D){for(let U of Object.keys(e.pools)){if(l.has(U))continue;l.set(U,D),r(`pool ${U} is degraded: ${D}`)}},reported:x,retire(D){let U=a.get(D);if(U)U.control.retire=!0},async settle(){while(a.size>0)await Promise.allSettled([...a.values()].map((D)=>D.done))},status(){let D=n.slots(),U=Object.keys(e.pools).map((te)=>{let ye=c.get(te)??l.get(te)??e.held?.(te)??pe(te),xe=W(te),$e=e.sources[te]?.status();return{...$e?{demand:$e}:{},...ye?{detail:ye}:{},health:xe,live:Mr(D,te).length,pool:te}});return{host:t.connected()?"connected":"disconnected",pools:U,slots:a.size}},async stop(){if(h)return;h=!0,i.abort(),await Promise.all(Object.values(e.sources).map((U)=>U.stop().catch(()=>{return}))),await e.offers?.stop(),t.close();let D=Promise.allSettled([...K,...[...a.values()].map((U)=>U.done)]);await Promise.race([D,Bun.sleep(s.stopMs)])},tick:C};function W(D){if(l.has(D))return"degraded";if(e.held?.(D)!==void 0)return"drained";return A(D)?"serving":"unavailable"}function pe(D){let U=e.drivers[D]?.capabilities().id;return U===void 0?"no driver":u.get(U)}}var nM="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 Ta(e){let t=e.get("pools")??{};if(Object.keys(t).length===0)throw new w("This home has no pools to guard","Add one with hydra pool add");return t}async function Pa(e,t){try{return await Qi(At(e).client).snapshots(t)}catch(n){if(n instanceof Re)throw new w(n.message,nM);throw n}}function Vr(e){try{return la(e)}catch(t){if(t instanceof wn)throw new w(t.message,"Repair or remove it, then run hydra guard record");throw t}}function Oa(e){let t=ie(e);if(!tM(Lr(t)))return Lo([]);try{return Lo(xw(t))}catch(n){if(n instanceof tt)throw new w(n.message,"Repair the ledger, or restore it from a backup");throw n}}function Ia(e){return[rM(e),oM(e)].map((t)=>` ${t}`)}function Na(e,t=f.red("\u2717")){return e.flatMap((n)=>[` ${t} ${n.detail}`,...(n.names??[]).map((r)=>f.dim(` ${fo(r)}`))])}function rM({scope:e}){if(e.kind==="repo")return`${Rt(e)}: ${e.visibility}`;let t=e.group;if(!t)return`${Rt(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`${Rt(e)} (id ${t.id}): ${Zi(t.visibility)}${n}, ${o}, ${r}`}function oM({forkPolicy:e}){return`fork pull requests: ${[sM(e),e.approval?`approval for ${ea(e.approval)}`:""].filter(Boolean).join("; ")}`}function sM({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(", ")}`}class ed extends I{name="check";description="Compare each pool's runner group or repository and the fork pull request policy with the guard record";async execute(e){M(e.args,this.args,"Run 'hydra guard check --help' for supported options");let t=Ta(e.config),n=Vr(ie(e.config));if(!n)throw new w("This home has no guard record","Run hydra guard record once the runner groups and policies are as they should be");let r=await Pa(e.config,t),o=Oa(e.config),s=[f.dim(`Guard recorded at ${n.recordedAt}`)],i=0;for(let[a,c]of Object.entries(t)){let l=r[a];if(!l)continue;let u=ta({baseline:n.pools[a],config:c,minted:o,snapshot:l});if(u.length>0)i++;let d=u.length===0?f.green("\u2713"):f.red("\u2717");s.push(`${d} ${f.bold(a)}`,...Ia(l),...Na(u))}if(k.info(s.join(`
|
|
427
|
+
`)),i===0)return;throw new w(`${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")}}class td extends I{name="record";description="Record each pool's runner group or repository, the fork pull request policy and the runners Hydra did not mint";async execute(e){M(e.args,this.args,"Run 'hydra guard record --help' for supported options");let t=Ta(e.config),n=ie(e.config),r=Vr(n),o=await Pa(e.config,t),s=Object.entries(o).flatMap(([u,{scope:d}])=>d.kind==="org"&&!d.group?[`pool ${u}: ${Rt(d)} does not exist`]:[]);if(s.length>0)throw new w(s.join(`
|
|
428
|
+
`),"Create the runner group, or name an existing one in the pool's runnerGroup");let i=Object.entries(t).flatMap(([u,d])=>{let p=o[u];return p?fu(d,p.scope).map((m)=>`pool ${u}: ${m.detail}`):[]});if(i.length>0)throw new w(i.join(`
|
|
429
|
+
`),"Refuse public repositories for that runner group or repository, or keep secrets out of the pool");let a=Oa(e.config),c={},l=[`Recorded the guard for ${Object.keys(o).length} pool(s)`];for(let[u,d]of Object.entries(o)){let p=Pw(d,a);c[u]=p;let m=r?.pools[u],g=m?.url===p.url?mu(m,d):[];l.push(f.bold(u),...Ia(p),...iM(p),...aM(g))}Ow(n,{pools:c,recordedAt:new Date().toISOString()}),k.success(l.join(`
|
|
430
|
+
`))}}function iM(e){let t=e.acceptedRunners;if(t.length===0)return[];return[f.yellow(` accepted ${t.length} runner(s) Hydra did not mint:`),...t.map((n)=>f.dim(` ${n.id} ${fo(n.name)}`))]}function aM(e){if(e.length===0)return[];return[f.yellow(" accepted these changes since the last record:"),...Na(e,f.yellow("!"))]}class Da extends I{name="guard";description="Record the pools' runner groups and fork pull request policy, or compare them with the record";init(){this.registerSubcommands([new td,new ed])}}import{mkdirSync as FM,statSync as UM}from"fs";import{join as BM}from"path";import{closeSync as gM,fsyncSync as hM,openSync as yM,readFileSync as wM,renameSync as bM,rmSync as vS,writeFileSync as SM}from"fs";import{join as ES}from"path";import{networkInterfaces as cM}from"os";var Qt="com.apple/hydra",rd='anchor "com.apple/*"',La=["hydra_guests","hydra_block4","hydra_self"],lM=["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"],[Kr,bS,SS]=La,uM=/^bridge(\d+)$/,dM=/^[a-z][a-z0-9]{0,15}$/,pM=["IPv4",4],fM=/^(No ALTQ support in kernel|ALTQ related functions disabled)/;function Ha(e){return Object.values(e.fleets).flatMap((t)=>t.guestRange===void 0?[]:[t.guestRange])}function Ma(e,t=cM()){let n=e.map((i)=>et(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 l=pM.includes(c.family)?gr(c.address):void 0;if(l===void 0)continue;if(r.set(l,c.address),!n.some((d)=>hr(d,l)))continue;let u=uM.exec(i);if(u)o.set(Number(u[1]),i);else s.push(`${dM.test(i)?i:"interface"} address ${c.address}`)}return{bridges:RS(o),clashes:s,guestRanges:[...e],self:RS(r)}}function Ga(e){let t=[`block drop in quick inet from <${Kr}> to <${SS}>`,`block drop in quick inet from <${Kr}> to <${bS}>`,...e.bridges.map((o)=>`block drop in quick on ${o} inet6 all`),`pass in quick inet proto tcp from <${Kr}> to any flags S/SA keep state`,`pass in quick inet proto udp from <${Kr}> to any keep state`,`pass in quick inet proto icmp from <${Kr}> to any keep state`],n={hydra_block4:[...lM],hydra_guests:[...e.guestRanges],hydra_self:[...e.self]},r=[nd(Kr,"const",n.hydra_guests),nd(bS,"const",n.hydra_block4),nd(SS,"persist",n.hydra_self),...t,""].join(`
|
|
431
|
+
`);return{inputs:e,rules:t,tables:n,text:r}}function Yo(e){return e.split(`
|
|
432
|
+
`).map((t)=>t.trim().replace(/\s+/g," ")).filter((t)=>t.length>0&&!fM.test(t))}function $S(e){return Yo(e).sort()}function od(e,t){let n=e.rules.join(`
|
|
433
|
+
`)===t.rules.join(`
|
|
434
|
+
`)?[]:[...qr(e.rules,t.rules).map((o)=>`rule missing: ${o}`),...qr(t.rules,e.rules).map((o)=>`rule not rendered: ${o}`),...mM(e.rules,t.rules)?["rules in another order"]:[]],r=La.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[...qr(s,i).map((a)=>`table <${o}> lacks ${a}`),...qr(i,s).map((a)=>`table <${o}> also holds ${a}`)]});return[...n,...r]}function nd(e,t,n){return n.length===0?`table <${e}> ${t}`:`table <${e}> ${t} { ${n.join(", ")} }`}function RS(e){return[...e.entries()].sort(([t],[n])=>t-n).map(([,t])=>t)}function qr(e,t){let n=new Set(t);return e.filter((r)=>!n.has(r))}function mM(e,t){return qr(e,t).length===0&&qr(t,e).length===0}var RM="pf-reference.json",$M="pf-anchor.conf",vM=384,EM=/^\d+$/;function _S(e){return{...AS("off"),findings:[{code:"unsupported",detail:e,fix:"Run the host daemon on macOS to load the pf anchor",level:"warning"}]}}function AS(e){return{anchor:Qt,bridges:[],checkedAt:null,enforced:!1,findings:[],lastDrift:null,loadedAt:null,reference:!1,state:e}}function CS(e){let{log:t,pfctl:n,stateDir:r}=e,o=e.now??Date.now,s=e.interfaces,i=ES(r,RM),a=ES(r,$M),c,l,u=null,d=null,p=Number.NEGATIVE_INFINITY,m=AS("failing"),g,h=()=>new Date(o()).toISOString(),E=async(b,A)=>{let y=A?kM(i):void 0,S=await n.enable();if(c=S,xS(i,`${JSON.stringify({takenAt:h(),token:S})}
|
|
435
|
+
`),t(`took a pf enable reference${y?", replacing the one recorded before":""}`),!y||y===S)return;await n.release(y).catch((C)=>{let x=`The pf enable reference recorded before this one could not be released: ${kS(C)}`;t(x),b.push({code:"reference-release",detail:x,fix:"pfctl -s References lists the references pf holds; a stale one only keeps pf enabled",level:"warning"})})},v=async()=>{let b=await n.anchorRules(Qt),A={};for(let y of La)A[y]=await n.table(Qt,y);return{rules:b,tables:A}},R=async(b,A)=>{l=void 0,xS(a,b.text),await n.load(Qt,a),l={readback:await v(),rendered:b},d=h(),t(`loaded the pf anchor ${Qt}: ${A}`)},_=async(b,A)=>{if(!l)await R(b,d===null?"first load since the daemon started":"the last load was not confirmed");else{let S=od(l.readback,await v());if(S.length>0)u={at:h(),differences:S},t(`the loaded pf anchor ${Qt} changed outside the daemon: ${S.join("; ")}`),await R(b,"restored after a change outside the daemon");else if(b.text!==l.rendered.text)await R(b,xM(l.rendered,b))}let y=od(b,l.readback);if(y.length===0)return!0;return A.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},T=async()=>{let b=[],A=Ga(Ma(e.guestRanges,s?.())),y=!1;try{if(c===void 0)await E(b,!0);if(!await n.enabled()){if(b.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(b,!1),!await n.enabled())throw Error("pf stays disabled after pfctl -E")}let S=(await n.mainRules()).some((x)=>x.startsWith(rd));if(!S)b.push({code:"anchor-point",detail:`The main pf ruleset has no ${rd} anchor point, so pf never evaluates ${Qt}`,fix:"Reload the stock ruleset with pfctl -f /etc/pf.conf, and find what replaced it; Hydra never edits pf.conf",level:"error"});let C=A.inputs.clashes;if(C.length>0)b.push({code:"guest-range-clash",detail:`The guest ranges hold this host's own ${C.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 _(A,b)&&S}catch(S){b.push({code:"pf-failed",detail:kS(S),fix:"Run the host daemon as root, check that pfctl answers, and run hydra net verify",level:"error"})}return p=o(),m={anchor:Qt,bridges:[...A.inputs.bridges],checkedAt:h(),enforced:y,findings:b,lastDrift:u,loadedAt:d,reference:c!==void 0,state:b.some((S)=>S.level==="error")?"failing":"ok"},m};return{check:(b=0)=>{if(g)return g;if(o()-p<b)return Promise.resolve(m);return g=T().finally(()=>{g=void 0}),g},status:()=>m}}function xM(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 kM(e){try{let t=JSON.parse(wM(e,"utf-8"));return typeof t.token==="string"&&EM.test(t.token)?t.token:void 0}catch{return}}function xS(e,t){let n=`${e}.${process.pid}.tmp`;vS(n,{force:!0});try{let r=yM(n,"wx",vM);try{SM(r,t),hM(r)}finally{gM(r)}bM(n,e)}finally{vS(n,{force:!0})}}function kS(e){return e instanceof Error?e.message:String(e)}import{chmodSync as _M,chownSync as AM,lstatSync as CM,rmSync as TS}from"fs";import{createConnection as TM,createServer as PM}from"net";var OM=384,IM=127,NM=-1,DM=64,LM=1;async function PS(e,t,n){await MM(e);let r=new Set,o=PM((i)=>{r.add(i),HM(i,n,()=>r.delete(i))});o.maxConnections=DM;let s=process.umask(IM);try{await new Promise((i,a)=>{o.once("error",a),o.listen(e,()=>{o.off("error",a),i()})})}finally{process.umask(s)}return AM(e,t,NM),_M(e,OM),{close:async()=>{for(let i of r)i.destroy();await new Promise((i)=>o.close(()=>i())),TS(e,{force:!0})},path:e}}function HM(e,t,n){let r={close:()=>e.end(),id:LM++,send:(a)=>{if(!e.destroyed&&e.writable)e.write(qo(a))}},o="",s=!1,i=()=>{s=!0,o="",e.end(qo(Je(null,"invalid",`a request line may hold at most ${_a} bytes`)),()=>e.destroy())};e.setEncoding("utf8"),e.on("data",(a)=>{if(s)return;o+=a;for(let c=o.indexOf(`
|
|
436
|
+
`);c>=0;c=o.indexOf(`
|
|
437
|
+
`)){let l=o.slice(0,c).trim();if(o=o.slice(c+1),Buffer.byteLength(l)>_a)return i();if(l)t.line(r,l)}if(Buffer.byteLength(o)>_a)i()}),e.on("error",()=>e.destroy()),e.on("close",()=>{n(),t.closed(r)})}async function MM(e){try{if(!CM(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 GM(e))throw Error(`another host daemon answers on ${e}; stop it first`);TS(e)}function GM(e){return new Promise((t)=>{let n=TM(e);n.once("connect",()=>{n.destroy(),t(!0)}),n.once("error",()=>t(!1))})}class Et extends Error{hint;_tag="HostDaemonError";constructor(e,t,n){super(e,n);this.hint=t;this.name="HostDaemonError"}}var jM=1e4,VM=60000,KM=5000,sd="linux",qM=20,OS=1024,WM=448,JM=493,DS=1e4,YM=1000,zM=0,XM=/^\d+$/;function IS(e,t){return BM(e.socketDir,`${t}.sock`)}async function LS(e){let{budget:t,firewall:n,log:r}=e,o=e.now??Date.now;NS(t.stateDir,WM),NS(t.socketDir,JM);let s=Gb(t.stateDir),i=Fb(s),a=[...new Set(i.map((P)=>P.fleet))].filter((P)=>!t.fleets[P]);if(a.length>0)throw new Et(`${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(),l,u=()=>(l??=e.live().then((P)=>(c=P,P)).finally(()=>{l=void 0}),l),d=[];for(let[P,G]of Object.entries(t.fleets))d.push([P,await e.uidOf(G.account)]);let p=[],m=Xb(),g=new Set,h=new Map,E=0,v,R=!1,_=!1,T=(P)=>r(`${new Date(o()).toISOString()} ${P}`),b=(P)=>{Ub(s,P),i=P},A=()=>{if(v||p.length===0)return;v=setTimeout(()=>{v=void 0,y().catch((P)=>T(`admission failed: ${nt(P)}`))},qM)},y=async()=>{if(R){_=!0;return}R=!0;try{do{if(_=!1,p.length===0)return;try{await u()}catch(j){let z=`the host's live state cannot be read (${nt(j)})`;h=new Map(p.map((Se)=>[Se.seq,{reason:z,scope:"shared"}])),T(`granted nothing: ${z}`);return}let P=S(),G=P?p.filter((j)=>j.request.class!==sd):p,F=Ko(G,{budget:t,leases:i,live:c,now:o()});if(h=F.held,P){for(let j of p)if(j.request.class===sd)h.set(j.seq,{reason:P,scope:"own"})}if(F.granted.length===0)continue;try{b([...i,...F.granted.map((j)=>j.lease)])}catch(j){T(`granted nothing: ${nt(j)}`);return}for(let j of F.granted){let[z]=p.splice(p.findIndex((Se)=>Se.seq===j.seq),1);z?.connection.send({id:z.replyId,lease:j.lease,ok:!0}),T(`granted ${Fa(j.lease.fleet,j.lease)}`)}}while(_)}finally{R=!1}},S=()=>{let P=n?.status();if(!P||P.enforced)return;let G=P.findings.find((F)=>F.level==="error")?.detail;return`the pf anchor ${P.anchor} to hold${G?` (${G})`:""}`},C=async(P)=>{let G=P.status(),F=await P.check();if(F.enforced!==G.enforced||G.checkedAt===null)T(`the pf anchor ${F.anchor} ${F.enforced?"holds":"does not hold; no linux guest is admitted"}`);let j=new Set(G.findings.map((z)=>z.detail));for(let z of F.findings)if(!j.has(z.detail))T(`pf ${z.level}: ${z.detail}`);A()},x=(P)=>{let G=S()?(F)=>F.class!==sd:void 0;return m.offers({fleet:P,open:G,state:{budget:t,leases:i,live:c,now:o()},waiting:p})},L=async(P,G,F,j)=>{m.report(P,j,o());try{await u()}catch(z){G.send(Je(F,"unavailable",`the host's live state cannot be read (${nt(z)})`));return}G.send({id:F,offers:x(P),ok:!0})},V=async(P,G)=>{let F=n?await n.check(KM):_S("this host daemon loads no pf anchor");P.send({id:G,net:F,ok:!0})},K=(P,G,F,j)=>{let z=i.find((ce)=>ce.fleet===P&&ce.slot===j.slot);if(z){G.send(Bb(z,j)?{id:F,lease:z,ok:!0}:Je(F,"conflict",`slot ${j.slot} already holds a lease with other resources`));return}if(p.some((ce)=>ce.fleet===P&&ce.request.slot===j.slot)){G.send(Je(F,"conflict",`slot ${j.slot} already waits for a lease`));return}let Se=ka(P,j,t,c.cores);if(Se){T(`refused ${Fa(P,j)}: ${Se}`),G.send(Je(F,"refused",Se));return}if(p.filter((ce)=>ce.fleet===P).length>=OS){G.send(Je(F,"busy",`fleet ${P} already has ${OS} requests waiting`));return}m.claim(P,j.pool,o()),p.push({connection:G,fleet:P,replyId:F,request:j,seq:E++,since:o()}),A()},W=(P,G,F,j)=>{let z=p.findIndex((ce)=>ce.fleet===P&&ce.request.slot===j);if(z>=0){let[ce]=p.splice(z,1);ce?.connection.send(Je(ce.replyId,"withdrawn",`the lease request for ${j} was withdrawn`)),G.send({id:F,ok:!0,released:!1,withdrawn:!0}),A();return}let Se=i.find((ce)=>ce.fleet===P&&ce.slot===j);if(!Se){G.send({id:F,ok:!0,released:!1,withdrawn:!1});return}try{b(i.filter((ce)=>ce!==Se))}catch(ce){G.send(Je(F,"unavailable",nt(ce)));return}T(`released ${Fa(P,Se)}`),G.send({id:F,ok:!0,released:!0,withdrawn:!1}),A()},pe=(P,G,F,j)=>{let z=i.filter((ke)=>ke.fleet===P),Se=new Date(o()).toISOString(),ce=j.filter((ke)=>!z.some((es)=>es.slot===ke.slot)).map((ke)=>({...ke,fleet:P,grantedAt:Se,origin:"adopted"}));if(ce.length>0)try{b([...i,...ce])}catch(ke){G.send(Je(F,"unavailable",nt(ke)));return}for(let ke of ce){T(`adopted ${Fa(P,ke)}`);let es=p.findIndex((pp)=>pp.fleet===P&&pp.request.slot===ke.slot),[dp]=es>=0?p.splice(es,1):[];dp?.connection.send({id:dp.replyId,lease:ke,ok:!0})}g.add(P);let up=new Set(j.map((ke)=>ke.slot)),J$=z.filter((ke)=>!up.has(ke.slot)).map((ke)=>ke.slot);G.send({adopted:ce.map((ke)=>ke.slot),id:F,ok:!0,unlisted:J$})},D=async(P,G,F)=>{await u().catch(()=>c),G.send({id:F,ok:!0,status:U(P)})},U=(P)=>{let G=t.fleets[P];return{budget:{cpus:vn(t,c.cores),macosVmCap:t.macosVmCap,memoryMiB:t.memoryMiB},committed:xa(i),disk:$a(c.diskFreeGiB,t.disk),fleet:{...G,id:P,reported:g.has(P)},leases:i.filter((F)=>F.fleet===P),live:c,offers:x(P),others:xa(i.filter((F)=>F.fleet!==P)),waiting:p.filter((F)=>F.fleet===P).map((F)=>({class:F.request.class,hold:h.get(F.seq)?.reason??null,pool:F.request.pool,since:new Date(F.since).toISOString(),slot:F.request.slot}))}},te=(P,G,F)=>{let j;try{j=nS(F)}catch(z){if(!(z instanceof Lt))throw z;G.send(Je(z.id,"invalid",z.message));return}switch(j.op){case"lease":return K(P,G,j.id,j.request);case"net.status":return V(G,j.id).catch((z)=>G.send(Je(j.id,"unavailable",nt(z))));case"offer":return L(P,G,j.id,j.pools).catch((z)=>G.send(Je(j.id,"unavailable",nt(z))));case"release":return W(P,G,j.id,j.slot);case"report":return pe(P,G,j.id,j.slots);case"status":return D(P,G,j.id).catch((z)=>G.send(Je(j.id,"unavailable",nt(z))))}},ye=(P)=>{let G=p.filter((F)=>F.connection===P);if(G.length===0)return;for(let F of G)p.splice(p.indexOf(F),1);T(`withdrew ${G.length} waiting request${G.length===1?"":"s"}: the fleet closed its connection`),A()},xe=[],$e=()=>Promise.all(xe.map((P)=>P.close()));try{for(let[P,G]of d)xe.push(await PS(IS(t,P),G,{closed:ye,line:(F,j)=>te(P,F,j)}))}catch(P){throw await $e(),new Et(`Could not open the fleet sockets: ${nt(P)}`,"Run hydra host serve as root",{cause:P})}let be=(P)=>C(P).catch((G)=>T(`pf check failed: ${nt(G)}`));if(n)await be(n);let Q=setInterval(A,e.tickMs??jM),J=n?setInterval(()=>be(n),e.firewallTickMs??VM):void 0;return T(`serving ${d.length} fleet${d.length===1?"":"s"} with ${i.length} recorded leases`),{leases:()=>i,socketPath:(P)=>IS(t,P),stop:async()=>{clearInterval(Q),clearInterval(J),clearTimeout(v),p.splice(0),await $e()}}}async function HS(e){let t=QM(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&&XM.test(s))return Number(s);throw new Et(`The account ${e} has no user id (${ZM(o,t.signalCode,r)})`,"Create the fleet's account, or correct its account in the host budget")}function MS(e){let t=new Map;return async(n)=>{let r=await e(n);if(r===zM)throw new Et(`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 Et(`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 QM(e){try{return Bun.spawn(["id","-u",e],{killSignal:"SIGKILL",stderr:"pipe",stdin:"ignore",stdout:"pipe",timeout:DS})}catch(t){throw new Et(`Could not look up the account ${e}: ${nt(t)}`,"Put the id tool on the daemon's PATH",{cause:t})}}function ZM(e,t,n){if(t!==null)return`id was stopped by ${t} after at most ${DS/YM} s`;if(e===0)return"id printed no user id";return n.trim()||`id exited with code ${e}`}function NS(e,t){try{FM(e,{mode:t,recursive:!0})}catch(r){throw new Et(`Could not create ${e}: ${nt(r)}`,"Run hydra host serve as root",{cause:r})}let n=Ju(UM(e),"directory");if(n)throw new Et(`${e} ${n}`,`Fix the owner and mode of ${e}`)}function Fa(e,t){return`${e}/${t.slot} (${t.pool}, ${t.class}, ${t.cpus} vCPU, ${Ue(t.memoryMiB)}, ${t.diskGiB} GiB disk)`}function nt(e){return e instanceof Error?e.message:String(e)}import{isAbsolute as eG}from"path";class Zt 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 tG="pfctl",nG=15000,rG=1000,oG=1048576,sG=5,iG=/Token\s*:\s*(\d+)/,aG=/^\d+$/,cG=/^Status:\s*Enabled\b/m,lG=/Table does not exist/i,uG=/^com\.apple\/hydra(-[a-z0-9]+)?$/,dG=/^hydra_[a-z0-9_]+$/,pG="<token>",fG=/DIOCGETRULES: (Invalid argument|No such file or directory)|Anchor does not exist/i;function GS(e={}){let t=e.binary??tG,n=e.timeoutMs??nG,r=(a)=>{if(uG.test(a))return a;throw new Zt(["-a",a],!1,"was refused: Hydra only touches its own anchors under com.apple/")},o=(a)=>{if(dG.test(a))return a;throw new Zt(["-t",a],!1,"was refused: Hydra only reads its own hydra_ tables")},s=(a)=>{if(eG(a))return a;throw new Zt(["-f",a],!1,"was refused: Hydra loads anchors only from absolute paths")},i=async(a,c,l=a)=>{let u=await lt([t,...a],{maxOutputChars:oG,timeoutMs:n}).catch((d)=>{throw new Zt(l,!1,`could not start (${d instanceof Error?d.message:d})`)});if(u.timedOut)throw new Zt(l,!0,`did not answer within ${n/rG} s and was stopped`);if(u.exitCode!==0&&!c?.(u.stderr))throw new Zt(l,!1,`exited with code ${u.exitCode}: ${mG(u.stderr)}`);return u};return{anchorRules:async(a)=>{let c=await i(["-a",r(a),"-s","rules"],(l)=>fG.test(l));return c.exitCode===0?Yo(c.stdout):[]},enable:async()=>{let a=await i(["-E"]),c=iG.exec(`${a.stdout}
|
|
438
|
+
${a.stderr}`)?.[1];if(!c)throw new Zt(["-E"],!1,"printed no enable reference token");return c},enabled:async()=>cG.test((await i(["-s","info"])).stdout),load:async(a,c)=>{await i(["-a",r(a),"-f",s(c)])},mainRules:async()=>Yo((await i(["-s","rules"])).stdout),release:async(a)=>{if(!aG.test(a))throw new Zt(["-X"],!1,"was given a token that is not a number");await i(["-X",a],void 0,["-X",pG])},table:async(a,c)=>{let l=await i(["-a",r(a),"-t",o(c),"-T","show"],(u)=>lG.test(u));return l.exitCode===0?$S(l.stdout):null}}}function mG(e){let t=Yo(e);return t.length===0?"(no output)":t.slice(-sG).join("; ")}function Ht(e){return e||Ib}function En(e){try{return Nb(e)}catch(t){if(!(t instanceof Zn))throw t;throw new w(t.message,"Fix the file, then run hydra host-budget check")}}var FS=q({budget:{description:"Read the host budget from this file",displayDefault:Ht(void 0),type:"string"}}),US=["SIGINT","SIGTERM"];class id extends I{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=FS;async execute(e){if(M(e.args,FS,"Run 'hydra host serve --help' for supported options"),process.platform!=="darwin")throw new w("hydra host serve reads the host's live state on macOS only","Run it on a macOS host");let t=En(Ht(e.args.budget)),n=(o)=>process.stdout.write(`${o}
|
|
439
|
+
`),r=await LS({budget:t,firewall:CS({guestRanges:Ha(t),log:(o)=>n(`${new Date().toISOString()} ${o}`),pfctl:GS(),stateDir:t.stateDir}),live:Kb(t.disk.path),log:n,uidOf:MS(HS)}).catch((o)=>{throw gG(o)});await hG(),await r.stop()}}function gG(e){if(e instanceof Et)return new w(e.message,e.hint);if(e instanceof Dt)return new w(e.message,"The daemon grants nothing it cannot measure");if(e instanceof Fr)return new w(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 hG(){return new Promise((e)=>{let t=()=>{for(let n of US)process.off(n,t);e()};for(let n of US)process.on(n,t)})}import{join as RG}from"path";function BS(e,t){let{budget:n,committed:r,fleet:o,live:s}=t,i=$n.flatMap((a)=>{let c=o.ceilings[a];return c===void 0?[]:[`${a} ${c}`]});return[`${f.bold("Host daemon")} ${e}`,`${f.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}`,`${f.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})`,`${f.bold("Fleet")} ${o.id} \xB7 weight ${o.weight} \xB7 highest priority ${o.maxPriority} \xB7 ceilings ${i.join(", ")}${o.reported?"":f.dim(" \xB7 has not reported its slots since the daemon started")}`,"",`${f.bold(`Leases (${t.leases.length})`)}`,...t.leases.length===0?[f.dim(" none")]:t.leases.map(yG),"",`${f.bold(`Waiting (${t.waiting.length})`)}`,...t.waiting.length===0?[f.dim(" none")]:t.waiting.map(wG),"",`${f.bold(`Offers (${t.offers.length})`)}`,...t.offers.length===0?[f.dim(" no scale-set pool has asked")]:t.offers.map(bG),"",`${f.bold("Other fleets")} ${SG(t.others)}`]}function yG(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 wG(e){let t=e.hold?f.dim(` \xB7 waits for ${e.hold}`):"";return` ${e.slot} ${e.pool} \xB7 ${e.class} \xB7 since ${e.since}${t}`}function bG(e){let t=e.active?"shares the headroom":f.dim("no recent demand, so one slot at most");return` ${e.pool} ${e.offer} more \xB7 ${t}`}function SG(e){if(e.leases===0)return f.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 jS=q({json:{alias:"j",default:!1,description:"Print the daemon's answer as JSON",type:"boolean"},socket:{description:"Ask the host daemon on this socket",displayDefault:`${Xt}/<fleet id>.sock`,type:"string"}});class ad extends I{name="status";description="Show this fleet's leases and waiting requests, the host budget and the host's live state";args=jS;async execute(e){M(e.args,jS,"Run 'hydra host status --help' for supported options");let t=e.args.socket||cd(e.config.get("fleet")?.id),n=await $G(t).catch((r)=>{if(!(r instanceof Ye))throw r;throw new w(r.message,"Start the host daemon with hydra host serve, or pass --socket")});if(e.args.json){process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
440
|
+
`);return}k.info(BS(t,n).join(`
|
|
441
|
+
`))}}function cd(e){if(!e)throw new w("config.json names no fleet","Set fleet.id, or pass --socket <path>");return RG(Xt,`${e}.sock`)}async function $G(e){let t=await jr(e);try{return await t.status()}finally{t.close()}}class Ua extends I{name="host";description="Run the host daemon that admits guests, or ask it for leases and live state";init(){this.registerSubcommands([new id,new ad])}}import{availableParallelism as vG}from"os";var xn=q({budget:{description:"Read the host budget from this file",displayDefault:Ht(void 0),type:"string"}});class ld extends I{name="print";description="Print the host budget with every default filled in";args=xn;async execute(e){M(e.args,xn,"Run 'hydra host-budget print --help' for supported options");let t=En(Ht(e.args.budget));process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
442
|
+
`)}}class ud extends I{name="check";description="Check the host budget, and that this home's pools fit its fleet's share";args=xn;async execute(e){M(e.args,xn,"Run 'hydra host-budget check --help' for supported options");let t=Ht(e.args.budget),n=En(t),r=vG(),o=[`${f.green("\u2713")} ${t}`,...EG(n,r)],s=e.config.get("fleet"),i=e.config.get("pools")??{},a=s?oS(n,s.id,i,r):[];o.push("",s?`${f.bold("Pools")} of fleet ${s.id}: ${Object.keys(i).length}`:f.dim("config.json names no fleet, so no pools were checked"),...a.map((l)=>l.level==="error"?`${f.red("\u2717")} ${l.detail}`:`${f.yellow("!")} ${l.detail}`)),k.info(o.join(`
|
|
443
|
+
`));let c=a.filter((l)=>l.level==="error").length;if(c>0)throw new w(`${c} pool${c===1?"":"s"} cannot run within the host budget`)}}function EG(e,t){let{disk:n}=e;return[`${f.bold("Budget")} ${Ue(e.memoryMiB)} of memory \xB7 ${vn(e,t)} vCPU on this host's ${t} cores \xB7 ${e.macosVmCap} macOS VMs`,`${f.bold("Live")} ${Ue(e.freeMemoryReserveMiB)} free memory kept \xB7 load below ${e.loadFactor} per core \xB7 disk on ${n.path}: warn ${n.warnGiB}, low ${n.lowGiB}, critical ${n.criticalGiB} GiB`,...Object.entries(e.fleets).map(([r,o])=>{let s=$n.flatMap((a)=>o.ceilings[a]===void 0?[]:[`${a} ${o.ceilings[a]}`]),i=o.guestRange?` \xB7 guests in ${o.guestRange}`:"";return`${f.bold(r)} account ${o.account} \xB7 weight ${o.weight} \xB7 highest priority ${o.maxPriority} \xB7 ${s.join(", ")}${i}`})]}class Ba extends I{name="host-budget";description="Print or check the host budget the host daemon admits guests against";init(){this.registerSubcommands([new ld,new ud])}}import{existsSync as xG,lstatSync as kG,readdirSync as _G,readFileSync as AG}from"fs";import{join as VS}from"path";var CG="images",TG=".json",PG=18,OG=/^[A-Za-z0-9][^\s@]*@sha256:[0-9a-f]{64}$/,IG=H({arch:Y(Ao),builder:Y(Bo),builtAt:N(),digest:N(),kind:Y(["linux"]),reference:N(),runner:N(),tag:N(),variant:Y(["docker","plain"])});function KS(e,t,n){return dd(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 dd(e){let t=VS(e,CG);if(!xG(t)||!qS(t,"directory"))return[];return _G(t).filter((n)=>n.endsWith(TG)).sort().flatMap((n)=>NG(VS(t,n)))}function NG(e){if(!qS(e,"file"))return[];try{let t=IG(JSON.parse(AG(e,"utf8")));return OG.test(t.reference)&&t.reference.endsWith(`@${t.digest}`)&&!Number.isNaN(Date.parse(t.builtAt))?[{path:e,record:t}]:[]}catch{return[]}}function qS(e,t){let n=kG(e);return(t==="directory"?n.isDirectory():n.isFile())&&n.uid===process.getuid?.()&&(n.mode&PG)===0}import{mkdtempSync as tF,readFileSync as nF,rmSync as rF}from"fs";import{tmpdir as oF}from"os";import{join as oR}from"path";var WS=`#!/bin/sh
|
|
444
|
+
set -eu
|
|
445
|
+
. "\${0%/*}/layout"
|
|
446
|
+
|
|
447
|
+
fail() {
|
|
448
|
+
printf 'hydra-guest accept: %s\\n' "$1" >&2
|
|
449
|
+
exit 1
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
[ "$(id -u)" -eq 0 ] || exec sudo -n "$0"
|
|
453
|
+
umask 077
|
|
454
|
+
"\${0%/*}/ready" >/dev/null 2>&1 || fail "the guest is not waiting for a runner configuration"
|
|
455
|
+
|
|
456
|
+
line=
|
|
457
|
+
IFS= read -r line || [ -n "$line" ] || fail "standard input holds no runner configuration"
|
|
458
|
+
[ -n "$line" ] || fail "the runner configuration is empty"
|
|
459
|
+
case $line in
|
|
460
|
+
*[!A-Za-z0-9+/=]*) fail "the runner configuration is not one line of base64" ;;
|
|
461
|
+
esac
|
|
462
|
+
extra=
|
|
463
|
+
if IFS= read -r extra || [ -n "$extra" ]; then
|
|
464
|
+
fail "standard input holds more than one line"
|
|
465
|
+
fi
|
|
466
|
+
|
|
467
|
+
staged="$HYDRA_RUN_DIR/jit.$$"
|
|
468
|
+
rm -f "$staged"
|
|
469
|
+
(
|
|
470
|
+
set -C
|
|
471
|
+
printf '%s\\n' "$line" >"$staged"
|
|
472
|
+
) || fail "could not stage the runner configuration"
|
|
473
|
+
line=
|
|
474
|
+
chmod 0600 "$staged"
|
|
475
|
+
chown "$HYDRA_RUNNER_UID:$HYDRA_RUNNER_GID" "$staged"
|
|
476
|
+
if ! ln "$staged" "$HYDRA_RUN_DIR/jit" 2>/dev/null; then
|
|
477
|
+
rm -f "$staged"
|
|
478
|
+
fail "the guest already holds a runner configuration"
|
|
479
|
+
fi
|
|
480
|
+
rm -f "$staged"
|
|
481
|
+
|
|
482
|
+
if [ "$HYDRA_OS" = macos ]; then
|
|
483
|
+
launchctl kickstart "gui/$HYDRA_RUNNER_UID/$HYDRA_SERVICE" >/dev/null || fail "the runner did not start"
|
|
484
|
+
else
|
|
485
|
+
systemctl start --no-block "$HYDRA_SERVICE" || fail "the runner did not start"
|
|
486
|
+
fi
|
|
487
|
+
`;var JS=`#!/bin/sh
|
|
488
|
+
set -eu
|
|
489
|
+
. "\${0%/*}/layout"
|
|
490
|
+
|
|
491
|
+
fail() {
|
|
492
|
+
printf '::error::Hydra stopped this job: %s\\n' "$1"
|
|
493
|
+
exit 1
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
[ ! -e "$HYDRA_RUN_DIR/jit" ] || fail "the runner configuration is still on the guest"
|
|
497
|
+
(set -C && : >"$HYDRA_RUN_DIR/job-started") 2>/dev/null || fail "this guest has already started a job"
|
|
498
|
+
workspace=\${GITHUB_WORKSPACE:-}
|
|
499
|
+
if [ -n "$workspace" ] && [ -d "$workspace" ] && [ -n "$(ls -A "$workspace")" ]; then
|
|
500
|
+
fail "the workspace is not empty"
|
|
501
|
+
fi
|
|
502
|
+
`;var YS=`#!/bin/sh
|
|
503
|
+
set -eu
|
|
504
|
+
. "\${0%/*}/layout"
|
|
505
|
+
|
|
506
|
+
[ "$HYDRA_SECRET_BEARING" = 1 ] || exit 0
|
|
507
|
+
found=$(find / -xdev \\( -name '*.p8' -o -name '*.p12' -o -name '*.keychain-db' -o -name '*.mobileprovision' -o -name '*.jks' \\) \\
|
|
508
|
+
-not -path "$HYDRA_RUNNER_HOME/*" -not -path "$HYDRA_RUNNER_DIR/_work/_temp/*" -not -path '/System/*' \\
|
|
509
|
+
-not -path '/Library/Keychains/*' -not -path '/private/var/db/*' 2>/dev/null | head -n 5)
|
|
510
|
+
if [ -n "$found" ]; then
|
|
511
|
+
printf '::error::Hydra failed this job: signing material outside the RAM disks:\\n%s\\n' "$found"
|
|
512
|
+
exit 1
|
|
513
|
+
fi
|
|
514
|
+
`;var zS=`#!/bin/sh
|
|
515
|
+
set -eu
|
|
516
|
+
. "\${0%/*}/layout"
|
|
517
|
+
|
|
518
|
+
fail() {
|
|
519
|
+
printf 'hydra-guest ramdisks: %s\\n' "$1" >&2
|
|
520
|
+
exit 1
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
ramdisk() {
|
|
524
|
+
target=$1
|
|
525
|
+
mib=$2
|
|
526
|
+
mkdir -p "$target"
|
|
527
|
+
if [ "$HYDRA_OS" = macos ]; then
|
|
528
|
+
device=$(hdiutil attach -nomount "ram://$((mib * 2048))" | awk 'NR == 1 { print $1 }')
|
|
529
|
+
[ -n "$device" ] || fail "hdiutil made no RAM disk for $target"
|
|
530
|
+
newfs_hfs -v hydra "$device" >/dev/null
|
|
531
|
+
mount -t hfs -o nobrowse,nodev,nosuid "$device" "$target"
|
|
532
|
+
else
|
|
533
|
+
mount -t tmpfs -o "size=\${mib}m,mode=0700,nodev,nosuid" tmpfs "$target"
|
|
534
|
+
fi
|
|
535
|
+
chown "$HYDRA_RUNNER_UID:$HYDRA_RUNNER_GID" "$target"
|
|
536
|
+
chmod 0700 "$target"
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
umask 077
|
|
540
|
+
ramdisk "$HYDRA_RUN_DIR" "$HYDRA_RAM_RUN_MIB"
|
|
541
|
+
if [ "$HYDRA_SECRET_BEARING" = 1 ]; then
|
|
542
|
+
ramdisk "$HYDRA_RUNNER_HOME" "$HYDRA_RAM_HOME_MIB"
|
|
543
|
+
ditto "$HYDRA_HOME_SKELETON" "$HYDRA_RUNNER_HOME" 2>/dev/null || cp -Rp "$HYDRA_HOME_SKELETON/." "$HYDRA_RUNNER_HOME"
|
|
544
|
+
chown -R "$HYDRA_RUNNER_UID:$HYDRA_RUNNER_GID" "$HYDRA_RUNNER_HOME"
|
|
545
|
+
ramdisk "$HYDRA_RUNNER_DIR/_work/_temp" "$HYDRA_RAM_TEMP_MIB"
|
|
546
|
+
fi
|
|
547
|
+
: >"$HYDRA_RUN_DIR/mounted"
|
|
548
|
+
`;var XS=`#!/bin/sh
|
|
549
|
+
set -eu
|
|
550
|
+
. "\${0%/*}/layout"
|
|
551
|
+
|
|
552
|
+
fail() {
|
|
553
|
+
printf 'hydra-guest ready: %s\\n' "$1" >&2
|
|
554
|
+
exit 1
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
mounted() {
|
|
558
|
+
[ "$(df -P "$1" 2>/dev/null | awk 'NR == 2 { print $NF }')" = "$1" ]
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
mounted "$HYDRA_RUN_DIR" || fail "the runner's RAM disk is not mounted"
|
|
562
|
+
[ -f "$HYDRA_RUN_DIR/mounted" ] || fail "the RAM disks are not ready"
|
|
563
|
+
if [ "$HYDRA_SECRET_BEARING" = 1 ]; then
|
|
564
|
+
mounted "$HYDRA_RUNNER_HOME" || fail "the runner's home is not on a RAM disk"
|
|
565
|
+
mounted "$HYDRA_RUNNER_DIR/_work/_temp" || fail "the runner's temporary directory is not on a RAM disk"
|
|
566
|
+
fi
|
|
567
|
+
for marker in jit started exit; do
|
|
568
|
+
[ ! -e "$HYDRA_RUN_DIR/$marker" ] || fail "the guest has already taken a runner configuration"
|
|
569
|
+
done
|
|
570
|
+
if [ "$HYDRA_OS" = macos ]; then
|
|
571
|
+
launchctl print "gui/$HYDRA_RUNNER_UID/$HYDRA_SERVICE" >/dev/null 2>&1 || fail "the runner's desktop session is not up"
|
|
572
|
+
else
|
|
573
|
+
systemctl cat "$HYDRA_SERVICE" >/dev/null 2>&1 || fail "the runner service is not installed"
|
|
574
|
+
fi
|
|
575
|
+
`;var QS=`#!/bin/sh
|
|
576
|
+
set -eu
|
|
577
|
+
. "\${0%/*}/layout"
|
|
578
|
+
|
|
579
|
+
fail() {
|
|
580
|
+
printf 'hydra-guest runner: %s\\n' "$1" >&2
|
|
581
|
+
printf '%s\\n' 1 >"$HYDRA_RUN_DIR/exit"
|
|
582
|
+
exit 1
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
umask 077
|
|
586
|
+
(set -C && : >"$HYDRA_RUN_DIR/started") 2>/dev/null || fail "this guest has already started a runner"
|
|
587
|
+
jit=
|
|
588
|
+
IFS= read -r jit <"$HYDRA_RUN_DIR/jit" || :
|
|
589
|
+
rm -f "$HYDRA_RUN_DIR/jit"
|
|
590
|
+
[ -n "$jit" ] || fail "the runner configuration is empty"
|
|
591
|
+
|
|
592
|
+
status=0
|
|
593
|
+
ACTIONS_RUNNER_INPUT_JITCONFIG=$jit HOME=$HYDRA_RUNNER_HOME "$HYDRA_RUNNER_DIR/bin/Runner.Listener" run || status=$?
|
|
594
|
+
printf '%s\\n' "$status" >"$HYDRA_RUN_DIR/exit.new"
|
|
595
|
+
mv -f "$HYDRA_RUN_DIR/exit.new" "$HYDRA_RUN_DIR/exit"
|
|
596
|
+
exit "$status"
|
|
597
|
+
`;var UG="/opt/actions-runner",fd="org.r5nlabs.hydra.runner",ZS="org.r5nlabs.hydra.ramdisks",tR="hydra-runner.service",pd="hydra-ramdisks.service",BG=16,jG=2048,VG=4096,md="hydra-golden-provisioned",Wr=365,KG=292,qG=/^[A-Za-z0-9_./:-]*$/,WG={gid:20,home:"/Users/admin",uid:501,user:"admin"},JG={gid:1001,home:"/home/runner",uid:1001,user:"runner"};function nR(e,t){let n=e==="macos"?WG:JG;return{guestOs:e,homeSkeleton:`${Ge}/home.skel`,ramHomeMiB:jG,ramRunMiB:BG,ramTempMiB:VG,runDir:Zl,runner:e==="macos"?Hh:je.runner.arm64,runnerDir:UG,runnerGid:n.gid,runnerHome:n.home,runnerUid:n.uid,runnerUser:n.user,secretBearing:t,service:e==="macos"?fd:tR}}function YG(e){return[{content:WS,mode:Wr,name:"accept"},{content:XS,mode:Wr,name:"ready"},{content:QS,mode:Wr,name:"runner"},{content:zS,mode:Wr,name:"ramdisks"},{content:JS,mode:Wr,name:"canary"},{content:YS,mode:Wr,name:"completed"},{content:eF(e),mode:KG,name:"layout"}]}function rR(e){let{layout:t}=e,n=t.guestOs==="macos",r=n?"root:wheel":"root:root",o=YG(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)=>ja("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?[]:zG(t),`mkdir -p ${Ge}`,`chown ${r} ${Ge}`,`chmod 0755 ${Ge}`,...o,`curl -fsSL -o /tmp/hydra-runner.tar.gz '${ja("runner",t.runner.url)}'`,`check ${ja("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?XG(s):QG(t,s),...t.secretBearing?ZG(t):[],"sync",`echo ${md}`].join(`
|
|
598
|
+
`)}
|
|
599
|
+
`}function zG(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 XG(e){let t=`/Library/LaunchAgents/${fd}.plist`,n=`/Library/LaunchDaemons/${ZS}.plist`;return[`cat >${t} <<'PLIST'`,eR(fd,`${Ge}/runner`,"<key>LimitLoadToSessionType</key><string>Aqua</string>"),"PLIST",`cat >${n} <<'PLIST'`,eR(ZS,`${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 QG(e,t){return[`cat >/etc/systemd/system/${tR} <<'UNIT'`,"[Unit]",`After=${pd}`,"[Service]","Type=simple",`User=${e.runnerUser}`,`ExecStart=${Ge}/runner`,"NoNewPrivileges=yes","UNIT",`cat >/etc/systemd/system/${pd} <<'UNIT'`,"[Unit]","DefaultDependencies=no","After=local-fs.target","[Service]","Type=oneshot","RemainAfterExit=yes",`ExecStart=${Ge}/ramdisks`,"[Install]","WantedBy=multi-user.target","UNIT",`systemctl enable ${pd}`,"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 ZG(e){return[`rm -rf ${e.homeSkeleton}`,`cp -Rp ${e.runnerHome} ${e.homeSkeleton}`,`chmod 0700 ${e.homeSkeleton}`]}function eR(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(`
|
|
600
|
+
`)}function eF(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}='${ja(r,String(o))}'`),"export PATH"].join(`
|
|
601
|
+
`)}
|
|
602
|
+
`}function ja(e,t){if(!qG.test(t))throw Error(`Refused guest value for ${e}: ${JSON.stringify(t)}`);return t}var sF={...Di,bootMs:600000,provisionMs:3600000,pullMs:7200000},iF=/^[a-z0-9][a-z0-9.-]*(?::\d+)?\/[a-z0-9._/-]+(?::[A-Za-z0-9._-]+)?@sha256:[0-9a-f]{64}$/,aF=2000;function gd(e){return iF.test(e)}function hd(e){return["exec","-i",e,"sudo","-n","/bin/sh","-s"]}function yd(e){return rR({dns:e.dns,layout:nR(e.guestOs,e.secretBearing)})}async function sR(e){if(!gd(e.base))throw new We("clone",e.base,"the base image must be a registry reference pinned by its sha256 digest");let t={...sF,...e.limits},n=Hi(e.binary??Ii,t,Li(e.store)),r=$y(e.guestOs,hn(e.secretBearing)),o=tF(oR(oF(),"hydra-golden-")),s=oR(o,"run.log"),i,a=(l,u)=>new We(l,r,u),c=async(l,u,d,p)=>{let m=await n.run(l,r,u,{check:!1,echo:p!==void 0,input:p,timeoutMs:d});if(m.exitCode!==0)throw a(l,`tart exited with code ${m.exitCode}
|
|
603
|
+
${m.stderr.trim()}`);return m};try{if(await c("clone",Ci(e.base,r),t.pullMs),i=n.launch(r,Ti({blocks:e.blocks??Ui(),name:r,rosetta:!1}),s),await cF(n,r,i,t,s),e.guestOs==="macos")await lF(n,r,e.hostVersion);if(!(await c("provision",hd(r),t.provisionMs,yd(e))).stdout.includes(md))throw a("provision","the script did not finish");if(await n.run("stop",r,Oo(r),{check:!1,timeoutMs:t.stopMs}),!await Vi(i,r,t.exitMs))throw a("stop","the VM did not stop after provisioning");i=void 0;let u={base:e.base,builtAt:(e.now?.()??new Date).toISOString(),guestOs:e.guestOs,name:r,runner:je.runner.version,sha256:await tu(e.store,r),status:"candidate",variant:hn(e.secretBearing)};return Gi(e.home,u),u}catch(l){if(i!==void 0&&await Pt(i,r))await n.run("stop",r,Oo(r),{check:!1,timeoutMs:t.stopMs}).catch(()=>{return}),await Ki(i,r,t.exitMs).catch(()=>{return});if(await n.run("delete",r,Io(r),{check:!1}).catch(()=>{return}),l instanceof We)throw l;throw a("build",l instanceof Error?l.message:String(l))}finally{rF(o,{force:!0,recursive:!0})}}async function cF(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 Pt(n,t))throw new We("boot",t,`the VM stopped before its guest agent answered
|
|
604
|
+
${uF(o)}`);if(Date.now()>=s)throw new We("boot",t,"the guest agent did not answer in time");await Bun.sleep(r.pollMs)}}async function lF(e,t,n){let o=(await e.run("read the macOS version of",t,["exec",t,"sw_vers","-productVersion"])).stdout.trim(),[s,i]=[bo(o),bo(n)];if(s===void 0||i===void 0||s>i)throw new We("check",t,`the guest runs macOS ${o||"(unknown)"}, which must not be newer than the host's ${n??"(unknown)"}`)}function uF(e){try{let t=nF(e,"utf8").trim();return t.slice(Math.max(0,t.length-aF))}catch{return""}}var iR=q({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"}}),dF=le({kind:{description:"Image to build: linux, macos or tart-linux"}}),aR=["linux","macos","tart-linux"],pF={arm64:"arm64",x64:"amd64"};class wd extends I{name="build";description="Build the pinned Linux runner image, or a Tart golden VM, and record it";args=iR;positionals=dF;async execute(e){M(e.args,iR,"Run 'hydra image build --help' for supported options");let t=e.positionals.kind;if(t===void 0||!aR.includes(t))throw new w(`Unknown image "${t??""}"`,`Choose one of: ${aR.join(", ")}`);if(t!=="linux"){await fF(e,t==="macos"?"macos":"linux");return}let n={arch:mF(e.args.arch),docker:e.args.docker},r=gF(e.args.builder);if(e.args.dryRun){process.stdout.write(ya(n)),k.info([Bu(r,n,"<context>").join(" "),f.dim("The context holds this Containerfile and the guest files; nothing was built.")].join(`
|
|
605
|
+
`));return}k.info(`Building ${wa(n)} with runner ${je.runner.version}`);let o=await Sb({...n,builder:r,home:ie(e.config)}).catch((s)=>{if(s instanceof We)throw new w(s.message,"Fix the build error above and run it again");throw s});k.success([`${f.bold(o.reference)}`,f.dim(`Recorded in ${ju(ie(e.config),o.digest)}`)].join(`
|
|
606
|
+
`))}}async function fF(e,t){let n=e.args.base;if(!n||!gd(n))throw new w("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??Kl,guestOs:t,secretBearing:e.args.secretBearing};if(e.args.dryRun){process.stdout.write(yd(r)),k.info([`tart clone ${n} <golden>`,`tart ${hd("<golden>").join(" ")} < the script above`,f.dim("Nothing was cloned or recorded.")].join(`
|
|
607
|
+
`));return}let o=ie(e.config),s=await ln();k.info(`Building a ${e.args.secretBearing?"secret-bearing ":""}${t} golden from ${n}`);let i=await sR({...r,base:n,home:o,hostVersion:s.version,store:zn()}).catch((a)=>{if(a instanceof We)throw new w(a.message,"Fix the build error above and run it again");throw a});k.success([`${f.bold(i.name)} is a candidate`,`disk sha256 ${i.sha256.disk}`,f.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(`
|
|
608
|
+
`))}function mF(e){let t=e??pF[process.arch];if(t!==void 0&&Mh(t))return t;throw new w(`Unknown architecture "${e??process.arch}"`,`Choose one of: ${Ao.join(", ")}`)}function gF(e){let t=e??(process.platform==="linux"?"podman":"container");if(hF(t))return t;throw new w(`Unknown image builder "${t}"`,`Choose one of: ${Bo.join(", ")}`)}function hF(e){return Bo.includes(e)}class bd extends I{name="list";description="List the Tart goldens this home recorded, with their state and disk hash";async execute(e){M(e.args,this.args,"Run 'hydra image list --help' for supported options");let t=Do(ie(e.config));if(t.length===0){k.info("No Tart goldens are recorded; build one with hydra image build macos --base <image@sha256:digest>");return}let n=t.map((r)=>[`${f.bold(r.name)} ${r.status}`,f.dim(` ${r.guestOs} \xB7 ${r.variant==="secret"?"secret-bearing":"general"} \xB7 built ${r.builtAt}`),f.dim(` base ${r.base}`),f.dim(` disk sha256 ${r.sha256.disk}`)].join(`
|
|
609
|
+
`));k.info(n.join(`
|
|
610
|
+
|
|
611
|
+
`))}}var cR=q({approve:{description:"The SHA-256 of the golden's disk, which a golden for secret-bearing pools needs",type:"string"}}),yF=le({golden:{description:"The candidate golden to promote"}});class Sd extends I{name="promote";description="Promote a candidate Tart golden, so new guests of its pools start from it";args=cR;positionals=yF;async execute(e){M(e.args,cR,"Run 'hydra image promote --help' for supported options");let t=e.positionals.golden;if(!t)throw new w("Name the golden to promote","hydra image list shows the candidates");k.info(`Checking the disk and configuration of ${t} against its recorded hashes`);let n=await ky({approve:e.args.approve,home:ie(e.config),name:t,store:zn()}).catch((r)=>{if(!(r instanceof Jn))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 w(r.message,o)});k.success(`${f.bold(n.name)} is the promoted ${n.variant==="secret"?"secret-bearing ":""}${n.guestOs} golden`)}}class Va extends I{name="image";description="Build, list and promote the images and goldens that slot drivers start guests from";init(){this.registerSubcommands([new wd,new bd,new Sd])}}var wF="https://github.com/r5n-labs/clis/blob/develop/packages/hydra/docs/migrating.md",bF="Profiles are deprecated: pools run each job in a fresh guest that Hydra destroys afterwards",lR=`Move this fleet to pools: ${wF}`,SF=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 he(){k.warn(f.yellow(bF)),k.info(f.dim(lR))}function uR(e){let t=e===void 0?void 0:SF.get(e);if(t===void 0)return;return new w(`hydra ${e} is now hydra ${t}: profiles are deprecated in favour of pools`,`Run hydra ${t} --help for its options. ${lR}`)}var pR=0,RF={logs:"file(s)",shared:"version(s)",work:"item(s)"},dR=q({days:{alias:"d",default:pR,description:"Override log retention",displayDefault:`config or ${As} 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 Rd extends I{name="cleanup";description="Remove logs, workspaces, and old runner versions";args=dR;async execute(e){he(),M(e.args,dR,"Run 'hydra legacy cleanup --help' for supported options");let t=e.config.get("profiles");if(Object.keys(t).length===0)throw new w("No profiles configured","Run hydra legacy init to set up a profile");let n=di(e.config.get("cleanup")),r=this.explicitTargets(e),o=r.length>0?r:n.targets,s=e.args.days>pR?e.args.days:n.olderThanDays;if(o.includes("work")&&!e.args.dryRun&&!e.args.yes){if(!await gt({message:"Delete _work contents (checkouts and caches) of stopped runners?"}))o=o.filter((c)=>c!=="work")}let i=await fi({dryRun:e.args.dryRun,entries:e.config.get("runners")??[],now:Date.now(),olderThanDays:s,sharedDir:Bt(ie(e.config)).shared,targets:o});if(this.printReport(i,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[s,i]of Object.entries(e)){if(!i)continue;let a=RF[s],c=bt(i.freedBytes),l=t?`would remove ${i.removed} ${a}, ${c}`:`removed ${i.removed} ${a}, freed ${c}`;if(n.push(`${f.bold(s)}: ${i.removed>0?l:f.dim("nothing to do")}`),i.skipped.length>0)n.push(f.dim(` skipped running runner(s): ${i.skipped.join(", ")}`))}if(n.length===0){k.info(f.dim("Nothing to clean."));return}let r=pi(e),o=t?"Would free":"Freed";n.push(f.dim(`${o} ${bt(r)} total`)),k.info(n.join(`
|
|
612
|
+
`))}}async function Ka(e){try{let t=di(e.config.get("cleanup"));if(!t.auto)return;if(!Il(t,Date.now()))return;let n=await fi({dryRun:!1,entries:e.config.get("runners")??[],now:Date.now(),olderThanDays:t.olderThanDays,sharedDir:Bt(ie(e.config)).shared,targets:t.targets});e.config.set("cleanup",{...e.config.get("cleanup"),lastRun:new Date().toISOString()});let r=pi(n);if(r>0)k.info(f.dim(`Auto cleanup freed ${bt(r)}`))}catch(t){let n=t instanceof Error?t.message:String(t);k.warn(f.yellow(`Auto cleanup failed: ${n}`))}}import{existsSync as fR}from"fs";import{join as mR}from"path";var $F=le({profile:{description:"Profile to use"},count:{description:"Runner count override"}});class $d extends I{name="create";description="Download and register runners";positionals=$F;async execute(e){he(),M(e.args,this.args,"Run 'hydra legacy create --help' for supported options");let{name:t,profile:n}=e.interactive?Le(e.config,await ct(e.config)):Le(e.config,e.positionals.profile),r=e.interactive?await this.promptCount(n.numberOfMachines):Ln(e.positionals.count??n.numberOfMachines),o=e.config.get("runners")??[],s=o.filter((g)=>g.profile===t),i=r-s.length;if(i<=0){k.warn(`Already have ${s.length} runner(s) for profile "${t}". Nothing to create.`);return}let a=ve(n,e.config),c=ze();c.start("Downloading runner binary...");let{version:l}=await a.download();c.stop(`Runner v${l} ready`);let u=new Set(o.map((g)=>g.id)),d=1;for(let g=0;g<i;){let h=`${n.name}-${d++}`;if(u.has(h))continue;g++;let E={createdAt:new Date().toISOString(),directory:mR(n.directory,h),id:h,name:h,profile:t,provider:n.provider,url:n.url},v=fR(E.directory);c.start(`Registering ${h}...`);try{await a.create([h])}finally{if(!v&&fR(mR(E.directory,Yt))){let{agentId:R}=await vo(E.directory);o.push(R===void 0?E:{...E,agentId:R}),e.config.set("runners",o)}}c.stop(`${f.green("+")} ${h}`)}let m=t===e.config.get("defaultProfile")?"":` ${t}`;k.info(`${f.green("Created")} ${i} runner(s) for "${t}". Run ${f.green(`hydra legacy start${m}`)} to start them.`)}async promptCount(e){let t=await Ft({initialValue:String(e),message:"Number of runners to create",validate:Is});return Ln(t)}}import{existsSync as kF}from"fs";import{join as _F}from"path";var vF=/[.*+?^${}()|[\]\\]/g,EF="-[1-9][0-9]*",xF=["unrecorded","online","busy","foreign","local","elsewhere"];function bR({elsewhere:e,elsewhereUnreadable:t,github:n,local:r,prefixes:o}){let s=o.map((m)=>new RegExp(`^${m.replace(vF,"\\$&")}${EF}$`)),i=r.filter((m)=>!m.orphaned),a=r.filter((m)=>m.orphaned),c=wR(i),l=wR(r),u=new Set([...e].map(zo)),d=new Set,p=[];for(let m of n){let g=zo(m.name),h=yR(m,i,d);if(h){d.add(h),p.push({github:m,local:h,placement:"both"});continue}let E={elsewhere:u.has(g),foreign:!s.some((_)=>_.test(m.name))},v=yR(m,a,d);if(!v){let _=hR({...E,local:l.has(g),unrecorded:!0});p.push({github:m,keep:_,placement:"github"});continue}d.add(v);let R=hR({...E,busy:m.busy,local:c.has(g),online:!Er(m)});p.push({github:m,keep:R.length===0&&t?["unreadable"]:R,local:v,placement:"recorded"})}for(let m of r)if(!d.has(m))p.push({local:m,placement:"local"});return p.sort((m,g)=>gR(m).localeCompare(gR(g),void 0,{numeric:!0}))}function kn(e){return e.placement==="recorded"&&e.keep.length===0}function SR(e){return e.placement==="recorded"&&e.keep.includes("unreadable")}function gR(e){return e.placement==="github"?e.github.name:e.local.name}function hR(e){return xF.filter((t)=>e[t])}function yR(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)=>zo(s)===zo(e.name)))}function wR(e){return new Set(e.flatMap((t)=>t.names.map(zo)))}function zo(e){return e.toLowerCase()}var AF=new Set([401,403,404]),CF="Nothing was changed; retry once GitHub answers",TF="Registrations reported as deleted stay deleted; run hydra legacy reconcile again to finish";function Jr(e){return At(e)}async function qa(e,t){let n=await PF(e),r=NF(e),o=[];for(let s of n){let i=await rt(t,s.target,CF,()=>dn(t.client,s.target)),a=bR({elsewhere:r.names,elsewhereUnreadable:r.unreadable.length>0,github:i,local:s.local,prefixes:s.prefixes});o.push({...s,rows:a})}return{scopes:o,unreadableHomes:r.unreadable}}async function Wa(e,t,n,r=TF){return rt(e,t,r,async()=>{let o=await pn(e.client,t,n.id);if(!o)return"gone";if(o.name!==n.name)return"renamed";if(!Er(o)||o.busy)return"changed";return jn(e.client,t,n.id)})}function $R(e){return kF(_F(e.directory,Yt))}async function PF(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 s=vd(r,o.url),i=Yr(s),a=n.get(i)??{key:i,local:[],prefixes:[],target:s};n.set(i,a),a.prefixes.push(o.name);let c=await ve(o,e).list(),l=t.filter((u)=>u.profile===r);a.local.push(...OF(l,c))}return[...n.values()]}function OF(e,t){let n=new Map(t.map((o)=>[o.id,o]));return[...e.map((o)=>{let s=n.get(o.id);return n.delete(o.id),RR(o.id,o.directory,s,o)}),...[...n.values()].map((o)=>RR(o.id,o.directory,o,void 0))]}function RR(e,t,n,r){let o=n?IF(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 IF(e){return e.name===kr?void 0:e.name}function NF(e){let t=new Set,n=[];for(let r of Os(ie(e),process.cwd(),process.env)){let o=fm(r.path);if(!o)n.push(r.path);for(let s of o??[])t.add(s)}return{names:t,unreadable:n}}function vd(e,t){try{return me(t)}catch(n){throw new w(`profiles.${e}.url: ${n.message}`,"Use a github.com repository or organisation URL")}}function Yr(e){return(e.kind==="repo"?`repo:${e.owner}/${e.repo}`:`org:${e.org}`).toLowerCase()}async function rt(e,t,n,r){try{return await r()}catch(o){if(!(o instanceof Re))throw o;let s=o.status!==void 0&&AF.has(o.status);throw new w(o.message,s?Zs(e.credentials.kind,t):n)}}var vR="hydra-drain",ER="Nothing was changed; retry once GitHub answers",DF="Drained runners move only into a group no repository can use; name another one with --group";async function Ja(e,t,n){return rt(e,t,ER,async()=>{let r=await xr(e.client,t.org,n);if(!r)return;await kR(e,t,r);let o=await ni(e.client,t.org,r);return{group:r,members:new Map(o.map((s)=>[s.id,s]))}})}async function xR(e,t,n){let r=await Ja(e,t,n);if(r)return r;return rt(e,t,ER,async()=>{let o=await Ug(e.client,t.org,n);return await kR(e,t,o),{group:o,members:new Map}})}async function kR(e,t,n){let r=Vg(n,await Bg(e.client,t.org,n));if(r)throw new w(`The runner group ${n.name} of ${t.org} is not closed: ${r}`,DF)}function rr(e){return e.kind==="org"?e:void 0}async function zr(e,t,n){let r=new Map;for(let o of t){let s=rr(o.target),i=s?await Ja(e,s,n):void 0;if(i)r.set(o.key,i)}return r}function Xo(e,t){return t.github!==void 0&&t.scope!==void 0?e.get(t.scope.key)?.members.has(t.github.id)??!1:!1}var _n=q({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"}}),Xr=q({group:{default:vR,description:"Runner group that drained runners move into; no repository may use it",type:"string"}});function An(e){if(e.dryRun&&e.yes)throw new w("Pass either --dry-run or --yes, not both")}async function Cn(e,t){if(e.yes)return!0;if(!process.stdout.isTTY)throw new w("This step requires confirmation","Pass --yes to go ahead, or --dry-run to only list what it would do");return gt({initialValue:!1,message:t})}function ot(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 Qr(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 LF(e){let t=e.registration&&!e.registration.disableUpdate?", updates itself":"";return`${MF(e.layout)}${t}`}function HF(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 _R(e,t){let n=` ${e.name} ${[ot(e.process),HF(e,t),LF(e)].join(" \xB7 ")}`;return e.refusal?`${n} \xB7 ${f.dim(`left alone: ${e.refusal}`)}`:n}function Ze(e,t){return` ${f.dim("leave")} ${e.name} \xB7 ${t}`}function xt(e,t,n=""){return` ${e} ${t.name}${n?` \xB7 ${n}`:""}`}function MF(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 o1,readdir as s1}from"fs/promises";import{basename as i1,dirname as a1,join as c1,resolve as Xa}from"path";import{readdir as GF,readFile as FF,readlink as UF}from"fs/promises";import{join as AR}from"path";var BF="externals",jF=/(?:^|\/)externals\.(\d+\.\d+\.\d+)$/,VF=/^(?:bin|externals)\.\d+\.\d+\.\d+$/,KF=/^[\w.-]+\.sh(?:\.template)?$/,qF=/^\uFEFF/,WF=new Set([".DS_Store",".credentials",".credentials_migrated",".credentials_rsaparams",".env",".path",".pid",".runner",".runner_migrated","_diag","_update","_work","bin","externals","hydra-hooks"]);async function CR(e){try{let t=await UF(AR(e,BF)),n=_r(t);if(n)return{kind:"shared",version:n};let r=t.match(jF)?.[1];return r?{kind:"self-updated",version:r}:{kind:"unknown"}}catch(t){return t.code==="EINVAL"?{kind:"copied"}:{kind:"missing"}}}async function TR(e){let t;try{t=JSON.parse((await FF(AR(e,".runner"),"utf-8")).replace(qF,""))}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 Ed(e){return(await GF(e)).filter((n)=>!OR(n)).sort()}function PR(e){return e.filter(OR)}function OR(e){return WF.has(e)||VF.test(e)||KF.test(e)}import{realpathSync as JF}from"fs";import{readFile as YF,unlink as zF}from"fs/promises";import{join as NR}from"path";var DR=".pid",XF=1,QF=30000,ZF=200,e1=/^\s*(\d+)\s+(\d+)\s+(.*)$/,t1=/[.*+?^${}()|[\]\\]/g,IR="Listener";async function Ya(){let e=await Bun.$`ps -A -o pid= -o pgid= -o command=`.quiet().nothrow();if(e.exitCode!==0)throw new w("Cannot list the host's processes with ps",e.stderr.toString().trim()||"Nothing was changed");return e.stdout.toString().split(`
|
|
613
|
+
`).flatMap((t)=>{let n=t.match(e1);return n?[{command:n[3],pgid:Number(n[2]),pid:Number(n[1])}]:[]})}async function xd(e){try{let t=Number((await YF(NR(e,DR),"utf-8")).trim());return Number.isSafeInteger(t)&&t>XF?t:void 0}catch{return}}function za(e,t,n){let r=n1(e),o=n.flatMap((l)=>{let u=l.command.match(r)?.[1];return u?[{...l,role:u}]:[]}),s=o.some((l)=>l.role!==IR),i=t!==void 0&&n.some((l)=>l.pid===t);if(o.length===0)return i&&t!==void 0?{kind:"stale",pid:t}:{kind:"stopped"};if(i&&o.some((l)=>l.role===IR)&&o.every((l)=>l.pgid===t)&&t!==void 0)return{kind:"running",pid:t,worker:s};return{kind:"unproven",pids:[...new Set([...i&&t!==void 0?[t]:[],...o.map(({pid:l})=>l)])],worker:s}}async function LR(e,t){try{process.kill(-t,"SIGTERM")}catch(r){if(r.code!=="ESRCH")throw r}let n=Date.now()+QF;while(Date.now()<n){if(za(e,t,await Ya()).kind==="stopped")return await zF(NR(e,DR)).catch(()=>{return}),"stopped";await Bun.sleep(ZF)}return"timeout"}function n1(e){let t=[...new Set([e,r1(e)])].map((n)=>n.replace(t1,"\\$&"));return new RegExp(`(?:^|\\s)(?:${t.join("|")})/bin(?:\\.[^/\\s]+)?/Runner\\.(Listener|Worker)(?:\\s|$)`)}function r1(e){try{return JF(e)}catch{return e}}var l1="Nothing was changed; retry once GitHub answers",HR="config.json does not record it",MR="its directory is missing";async function u1(e,t){let n=e.get("profiles"),r=new Map;for(let[c,l]of Object.entries(n)){if(l.provider!=="github")continue;let u=vd(c,l.url);r.set(Yr(u),{key:Yr(u),registered:new Map,target:u})}for(let c of r.values()){let l=await rt(t,c.target,l1,()=>dn(t.client,c.target));for(let u of l)c.registered.set(u.id,u)}let o=await Ya(),s=[],i=new Set;for(let c of e.get("runners")??[]){i.add(Xa(c.directory));let l=Object.hasOwn(n,c.profile)?n[c.profile]:void 0;s.push(await d1(c,l,r,o))}let a=new Set(Object.values(n).filter((c)=>c.provider==="github").map((c)=>Xa(c.directory)));for(let c of a)for(let l of await g1(c)){if(i.has(l))continue;i.add(l),s.push(await p1(l,r,o))}return{runners:s,scopes:[...r.values()]}}function Mt(e){return e.refusal===void 0&&e.entry!==void 0&&e.scope!==void 0}function GR(e){return e.refusal===MR&&e.entry!==void 0&&e.scope!==void 0&&e.process.kind==="stopped"}function FR(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"&&kd(s,o.name)):o.id===t)}async function or(e){return za(e.directory,await xd(e.directory),await Ya())}async function d1(e,t,n,r){let o=await UR(Xa(e.directory),r),s=t?.provider==="github"?n.get(Yr(me(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 f1(a,t)}}async function p1(e,t,n){let r=await UR(e,n),o=m1(r.registration,t),s=r.registration?.agentId,i=s===void 0?void 0:o?.registered.get(s),a=r.registration?.agentName??i1(e);return{...r,github:i,name:a,refusal:HR,scope:o}}async function UR(e,t){let n=await xd(e);return{directory:e,layout:await CR(e),pid:n,process:za(e,n,t),registration:await TR(e)}}async function f1(e,t){let{directory:n,entry:r,github:o,registration:s,scope:i}=e;if(!r)return HR;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(a1(n)!==Xa(t.directory))return"its directory is not in its profile's directory";let a=await _d(n);if(a==="missing")return MR;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((l)=>typeof l==="string").some((l)=>kd(l,s.agentName)))return`it is registered as ${s.agentName}, not as ${r.id}`;if(BR(s)!==i.key)return"its .runner file names another organisation or repository";if(o&&!kd(o.name,s.agentName))return`GitHub lists runner ${o.id} as ${o.name}`;return}function m1(e,t){let n=BR(e);return n===void 0?void 0:t.get(n)}function BR(e){if(!e?.gitHubUrl)return;try{return Yr(me(e.gitHubUrl))}catch{return}}async function g1(e){try{return(await s1(e,{withFileTypes:!0})).filter((n)=>n.isDirectory()).map((n)=>c1(e,n.name))}catch{return[]}}async function _d(e){try{return(await o1(e)).isDirectory()?"directory":"other"}catch(t){return t.code==="ENOENT"?"missing":"other"}}function kd(e,t){return e.toLowerCase()===t.toLowerCase()}async function Gt(e){if(Object.keys(e.get("profiles")).length===0)throw new w("No profiles configured",`Select the 0.x fleet's home with ${Ee} <path> or ${at}`);let t=Jr(e);return{github:t,inventory:await u1(e,t)}}var h1={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"},VR="recorded, no runner here";function Ad(e){return`${f.bold(Me(e.target))} ${f.dim("on GitHub")}`}function Qa(e){return`${e.status}, ${e.busy?"busy":"idle"}`}function Cd(e){return e.keep.map((t)=>t==="online"?e.github.status:h1[t]).join(", ")}function KR(e){let t=[Ad(e)];if(e.rows.length===0)return[...t,f.dim(" No runners here or on GitHub.")];for(let n of e.rows)t.push(` ${y1(n)}`);return t.push(f.dim(` ${b1(e.rows)}`)),t}function y1(e){switch(e.placement){case"both":return`${e.local.name} ${e.local.status} \xB7 ${Qa(e.github)} \xB7 id ${e.github.id}`;case"local":return`${e.local.name} ${w1(e.local)} \xB7 ${f.yellow("not on GitHub")}`;case"recorded":return`${e.local.name} ${VR} \xB7 ${jR(e)}`;case"github":return`${e.github.name} not in this home \xB7 ${jR(e)}`}}function w1(e){return e.orphaned?VR:e.status}function jR(e){let t=kn(e)?f.yellow("stale"):f.dim(`left alone: ${Cd(e)}`);return`${Qa(e.github)} \xB7 id ${e.github.id} \xB7 ${t}`}function b1(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(kn).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(" ")}var qR=q({..._n}),S1="Registrations reported as deleted stay deleted; run hydra legacy deregister again to finish",R1={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 Td extends I{name="deregister";description="Delete the GitHub registrations of stopped 0.x runners by id";args=qR;async execute(e){M(e.args,qR,"Run 'hydra legacy deregister --help' for supported options"),An(e.args);let{github:t,inventory:n}=await Gt(e.config),r=[],o=[];for(let i of n.runners)if(!Mt(i))o.push(Ze(i,i.refusal??"config.json does not record it"));else if(!i.github)o.push(xt(f.dim("done"),i,"not registered on GitHub"));else if(i.process.kind!=="stopped")o.push(Ze(i,`${ot(i.process)}; ${Qr(i.process)}`));else{r.push(i);let a=f.red(e.args.dryRun?"would deregister":"deregister");o.push(xt(a,i,`id ${i.github.id} \xB7 ${i.github.status}`))}if(k.info(o.join(`
|
|
614
|
+
`)),r.length===0){k.info(f.dim("Nothing to deregister."));return}if(e.args.dryRun){k.info(`Would deregister ${r.length} runner(s). Run ${f.green("hydra legacy deregister --yes")} to do it.`);return}if(!await Cn(e.args,`Delete ${r.length} registration(s) from GitHub?`))return;let s=0;for(let i of r){let a=await or(i);if(a.kind!=="stopped"||!i.github){k.info(`${i.name} \xB7 ${f.yellow(`kept: ${ot(a)}`)}`);continue}let c=await Wa(t,i.scope.target,i.github,S1);if(c==="deleted")s++;let l=R1[c];k.info(`${i.name} \xB7 id ${i.github.id} \xB7 ${c==="deleted"?f.green(l):l}`)}k.info(`${f.green("Deregistered")} ${s} of ${r.length} runner(s).`)}}var WR=q({..._n,...Xr}),$1="Runners reported as moved stay drained; run hydra legacy drain again to finish";class Pd extends I{name="drain";description="Move a 0.x fleet's runners into a runner group no repository can use";args=WR;async execute(e){M(e.args,WR,"Run 'hydra legacy drain --help' for supported options"),An(e.args);let{group:t,dryRun:n}=e.args,{github:r,inventory:o}=await Gt(e.config),s=await zr(r,o.scopes,t),i=new Map,a=[];for(let u of o.runners){if(!Mt(u)){a.push(Ze(u,u.refusal??"config.json does not record it"));continue}if(!u.github){a.push(Ze(u,"not registered on GitHub"));continue}if(!rr(u.scope.target)){a.push(Ze(u,"repository runners have no runner groups; stop it with hydra legacy halt once idle"));continue}if(s.get(u.scope.key)?.members.has(u.github.id)){a.push(xt(f.dim("drained"),u,`already in ${t}`));continue}i.set(u.scope,[...i.get(u.scope)??[],{id:u.github.id,runner:u}]);let d=u.github.busy?"busy, its job keeps running":"idle";a.push(xt(f.yellow(n?"would move":"move"),u,`id ${u.github.id} \xB7 ${d}`))}for(let u of i.keys())if(!s.has(u.key))a.push(f.dim(` ${n?"would create":"create"} ${t}`));k.info(a.join(`
|
|
615
|
+
`));let c=[...i.values()].reduce((u,d)=>u+d.length,0);if(c===0){k.info(f.dim("Nothing to drain."));return}if(n){k.info(`Would move ${c} runner(s) into ${t}. Run ${f.green("hydra legacy drain --yes")} to move them.`);return}if(!await Cn(e.args,`Move ${c} runner(s) into ${t}?`))return;let l=0;for(let[u,d]of i){let p=rr(u.target);if(!p)continue;let m=s.get(u.key)??await xR(r,p,t);for(let{id:g,runner:h}of d)await rt(r,p,$1,()=>jg(r.client,p.org,m.group,g)),l++,k.info(`${h.name} \xB7 id ${g} \xB7 ${f.green(`moved into ${m.group.name}`)}`)}k.info(`${f.green("Drained")} ${l} runner(s). They take no new jobs; run ${f.green("hydra legacy stop --wait")} to stop them once their jobs finish.`)}}var v1=le({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class Od extends I{name="halt";description="Stop runners at once, without waiting for a running job";positionals=v1;async execute(e){he(),M(e.args,this.args,"Run 'hydra legacy halt --help' for supported options");let{name:t,profile:n}=e.interactive?Le(e.config,await ct(e.config)):Le(e.config,e.positionals.profile),o=(e.config.get("runners")??[]).filter((p)=>p.profile===t);if(o.length===0)throw new w(`No runners found for profile "${t}"`,"Run hydra legacy create to provision runners");let s=ve(n,e.config),i=ze();i.start("Fetching runner status...");let a=await s.list();i.stop("Runner status fetched");let c=new Set(a.filter((p)=>p.status==="running").map((p)=>p.id)),l=o.map((p)=>p.id).filter((p)=>c.has(p)),u=e.interactive?await this.promptRunnerSelection(l):mr(e.positionals.ids??[],o.map((p)=>p.id)),d=0;for(let p of u){if(!c.has(p)){i.start(""),i.stop(`${f.dim("\u25CF")} ${p} ${f.dim("not running")}`);continue}i.start(`Stopping ${p}...`),await s.stop([p]),i.stop(`${f.red("\u25A0")} ${p}`),d++}k.info(`${f.green("Stopped")} ${d} runner(s).`)}async promptRunnerSelection(e){if(e.length===0)throw new w("No runners are currently running");return On({message:"Select runners to stop",options:e.map((t)=>({label:t,value:t})),required:!0})}}import{mkdir as Id}from"fs/promises";var JR=1,E1=448,x1=le({url:{description:"GitHub repository or organization URL"}}),k1=q({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 Nd extends I{name="init";description="Set up a runner profile";positionals=x1;args=k1;prompts=!0;async execute(e){he(),M(e.args,this.args,"Run 'hydra legacy init --help' for supported options");let t=e.interactive?await this.promptProfileName(e):e.args.profile??go,n=!e.config.exists();if(!n&&Object.hasOwn(e.config.get("profiles"),t)&&!e.args.force){if(!e.interactive)throw new w(`Profile "${t}" already exists. Use --force to overwrite.`);if(!await gt({initialValue:!1,message:`Profile "${t}" already exists. Overwrite?`}))return}let o=Bt(ie(e.config)),s=e.interactive?await this.runInitForm(o.runners):this.buildProfileFromArgs(e,o.runners);await this.ensureDirectories(o);let i={...n?{}:e.config.get("profiles"),[t]:s};if(e.config.set("profiles",i),!e.config.get("defaultProfile"))e.config.set("defaultProfile",t);ir([`${f.dim("Profile:")} ${t}`,`${f.dim("URL:")} ${s.url}`,`${f.dim("Runners:")} ${s.numberOfMachines}`,`${f.dim("Name:")} ${s.name}`,s.labels?`${f.dim("Labels:")} ${s.labels}`:"","",`Run ${f.green(`${_s} legacy create${t!==e.config.get("defaultProfile")?` ${t}`:""}`)} to provision runners.`].filter(Boolean).join(`
|
|
616
|
+
`),f.green(n?"Hydra initialized":`Profile "${t}" added`))}async promptProfileName(e){return Ft({initialValue:e.args.profile??go,message:"Profile name"})}async ensureDirectories(e){await Id(e.home,{mode:E1,recursive:!0}),await Id(e.shared,{recursive:!0}),await Id(e.runners,{recursive:!0})}async runInitForm(e){let t=await as({url:()=>Ft({message:"GitHub repository or organization URL",placeholder:"https://github.com/owner/repo",validate:(n)=>{if(!n)return"URL is required";try{me(n)}catch{return"Must be a GitHub repository or organization URL (https://github.com/<owner>/<repo> or https://github.com/<org>)"}return}}),name:()=>Ft({initialValue:"runner",message:"Base name for runners",placeholder:"runner"}),runners:()=>Ft({initialValue:String(JR),message:"Number of runners",placeholder:"1",validate:Is}),labels:()=>Ft({message:"Additional labels (comma-separated, optional)",placeholder:"self-hosted,macOS,ARM64"})},{onCancel:()=>{throw new mt}});return{directory:e,jobHooks:ii(),labels:t.labels||void 0,name:t.name,numberOfMachines:Ln(t.runners),os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:t.url}}buildProfileFromArgs(e,t){if(!e.positionals.url)throw new w("URL is required","Usage: hydra legacy init <url>");return this.validateUrl(e.positionals.url),{directory:t,jobHooks:ii(),labels:e.args.labels,name:e.args.name??"runner",numberOfMachines:Ln(e.args.runners??JR),os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:e.positionals.url}}validateUrl(e){try{me(e)}catch(t){throw new w(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"}}var YR=q({...Xr});class Dd extends I{name="inventory";description="List a 0.x fleet's runners, here and on GitHub";args=YR;async execute(e){M(e.args,YR,"Run 'hydra legacy inventory --help' for supported options");let{github:t,inventory:n}=await Gt(e.config),r=await zr(t,n.scopes,e.args.group),o=e.config.get("profiles"),s=new Map;for(let l of n.runners){let u=l.entry?l.entry.profile:"";s.set(u,[...s.get(u)??[],l])}let i=[];for(let[l,u]of s){if(i.length>0)i.push("");let d=Object.hasOwn(o,l)?o[l]?.url:void 0;i.push(l?`${f.bold(l)} ${f.dim(d??"no such profile")}`:f.bold("Not recorded"));let p=u.sort((m,g)=>m.name.localeCompare(g.name,void 0,{numeric:!0}));for(let m of p)i.push(_R(m,Xo(r,m)))}if(i.length===0)i.push(f.dim("No runners in this home."));let a=n.runners,c=(l)=>a.filter(l).length;i.push("",f.dim([`${a.length} runner(s)`,`${c(Mt)} provably this home's`,`${c((l)=>l.process.kind==="running"||l.process.kind==="unproven")} running`,`${c((l)=>l.github?.busy===!0)} busy`,`${c((l)=>Xo(r,l))} drained into ${e.args.group}`,`${c((l)=>l.layout.kind==="self-updated")} self-updated`,`${c((l)=>l.refusal!==void 0)} left alone`].join(", "))),k.info(i.join(`
|
|
617
|
+
`))}}import{existsSync as _1}from"fs";import{readFile as A1}from"fs/promises";var C1=100,T1={runner:"runner daemon log",worker:"job log"},P1=q({lines:{alias:"n",default:C1,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"}}),O1=le({id:{description:"Runner ID"}});class Ld extends I{name="logs";description="Show recent runner logs";args=P1;positionals=O1;async execute(e){he();let t=e.config.get("runners")??[];if(t.length===0)throw new w("No runners found","Run hydra legacy 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 w(`Profile "${n.profile}" not found for runner "${n.id}"`,"Run hydra legacy init to set it up");if(!_1(n.directory))throw new w(`Runner directory not found: ${n.directory}`,"Run hydra legacy create to provision this runner");let i=await ve(o,e.config).logFiles(n.id);if(i.length===0)this.noLogs(n.id);if(e.args.list){this.printList(n,i);return}let a=this.selectFile(e,n,i);if(e.args.open){await this.openFile(a);return}await this.printTail(n,a,e.args.lines)}async resolveEntry(e,t){let n=e.positionals.id;if(n){let o=t.find((s)=>s.id===n);if(!o)throw new w(`Runner "${n}" not found`,`Known runners: ${t.map((s)=>s.id).join(", ")}`);return o}if(e.interactive)return Pn({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 w("Multiple runners found",`Pass a runner id: hydra legacy logs <id> (${t.map((o)=>o.id).join(", ")})`)}selectFile(e,t,n){if(e.args.runner){let o=n.find((s)=>s.type==="runner");if(!o)throw new w(`No runner daemon logs found for "${t.id}"`,"Start the runner first: hydra legacy start");return o}let r=El(n,"worker");if(!r)this.noLogs(t.id);if(r.fallback)k.warn(f.yellow("No job (Worker) logs yet; showing the runner daemon log instead"));return r.file}noLogs(e){throw new w(`No logs found for runner "${e}"`,"Logs appear once the runner has started; run hydra legacy start")}printList(e,t){let n=[`${f.bold(e.name)} ${f.dim(e.directory)}`];for(let r of t){let o=r.type==="worker"?f.green("worker"):f.blue("runner");n.push(` ${o} ${r.name} ${f.dim(`${r.mtime.toISOString()} \xB7 ${bt(r.size)}`)}`)}k.info(n.join(`
|
|
618
|
+
`))}async printTail(e,t,n){let r=await A1(t.path,"utf-8"),o=[`${f.bold(e.name)} ${f.dim(T1[t.type])}`,f.dim(t.path),f.dim(`Last modified: ${t.mtime.toISOString()}`)];k.info(o.join(`
|
|
619
|
+
`)),console.log(xl(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 w("No editor configured","Set $EDITOR to open log files")}}var I1=le({name:{description:"Profile name to set as default"}});class Hd extends I{name="default";description="Set the default profile";positionals=I1;async execute(e){he(),M(e.args,this.args,"Run 'hydra legacy profile default --help' for supported options");let t=e.interactive?await ct(e.config):e.positionals.name;if(!t)throw new w("Profile name is required","Usage: hydra legacy profile default <name>");let{name:n}=Le(e.config,t);if(e.config.get("defaultProfile")===n){k.info(`"${n}" is already the default profile.`);return}e.config.set("defaultProfile",n),k.info(`${f.green("Default profile set to")} "${n}".`)}}class Md extends I{name="list";description="List profiles";async execute(e){he();let t=e.config.get("profiles"),n=Object.keys(t);if(n.length===0)throw new w("No profiles configured","Run hydra legacy init to set up a profile");let r=e.config.get("runners")??[],o=e.config.get("defaultProfile");for(let s of n){let i=t[s],c=await ve(i,e.config).list(),l=r.filter((h)=>h.profile===s),u=new Set(c.filter((h)=>h.status==="running").map((h)=>h.id)),d=l.filter((h)=>u.has(h.id)).length,p=s===o,m=[`${f.dim("URL:")} ${i.url}`,`${f.dim("Provider:")} ${i.provider}`,`${f.dim("OS:")} ${i.os}`,`${f.dim("Name:")} ${i.name}`,`${f.dim("Runners:")} ${l.length}/${i.numberOfMachines} created, ${f.green(`${d} running`)}`];if(i.labels)m.push(`${f.dim("Labels:")} ${i.labels}`);let g=p?`${s} ${f.dim("(default)")}`:s;ir(m.join(`
|
|
620
|
+
`),g)}k.info(f.dim(`${n.length} profile(s)`))}}import{rm as N1}from"fs/promises";import{join as D1}from"path";var L1=le({name:{description:"Profile name to remove"}}),H1=q({yes:{alias:"y",default:!1,description:"Skip runner removal confirmation",type:"boolean"}});class Gd extends I{name="remove";description="Delete a profile and its runners";positionals=L1;args=H1;async execute(e){he(),M(e.args,this.args,"Run 'hydra legacy profile remove --help' for supported options");let t=e.interactive?await ct(e.config):e.positionals.name;if(!t)throw new w("Profile name is required","Usage: hydra legacy profile remove <name>");let{profile:n}=Le(e.config,t),r=e.config.get("runners")??[],o=r.filter((c)=>c.profile===t);if(o.length>0){if(!e.args.yes){if(!process.stdout.isTTY)throw new w("Runner removal requires confirmation","Pass --yes to remove the profile and its runners without a prompt");if(!await gt({initialValue:!0,message:`This will stop and remove ${o.length} runner(s). Continue?`}))return}await this.removeRunners(e,n,o.map((l)=>l.id));let c=r.filter((l)=>l.profile!==t);e.config.set("runners",c)}let{[t]:s,...i}=e.config.get("profiles");if(e.config.set("profiles",i),e.config.get("defaultProfile")===t){let c=Object.keys(i);e.config.set("defaultProfile",c[0])}k.info(`${f.green("Removed")} profile "${t}".`)}async removeRunners(e,t,n){let r=ve(t,e.config),o=ze();for(let s of n)o.start(`Stopping and removing ${s}...`),await r.remove([s]),await N1(D1(t.directory,s),{force:!0,recursive:!0}),e.config.set("runners",(e.config.get("runners")??[]).filter((i)=>i.id!==s)),o.stop(`${f.red("-")} ${s}`)}}class Fd extends I{name="profile";description="Manage profiles";init(){this.registerSubcommands([new Md,new Gd,new Hd])}}var zR=q({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"}}),M1={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 Ud extends I{name="reconcile";description="Delete stale GitHub registrations of this home's runners";args=zR;async execute(e){if(he(),M(e.args,zR,"Run 'hydra legacy reconcile --help' for supported options"),e.args.dryRun&&e.args.yes)throw new w("Pass either --dry-run or --yes, not both");if(Object.keys(e.config.get("profiles")).length===0)throw new w("No profiles configured","Run hydra legacy init to set up a profile");let t=Jr(e.config),{scopes:n,unreadableHomes:r}=await qa(e.config,t);if(n.length===0){k.info(f.dim("No GitHub profiles to reconcile."));return}let o=n.flatMap((s)=>s.rows.filter(kn).map((i)=>({row:i,scope:s})));k.info(this.planLines(n,e.args.dryRun).join(`
|
|
621
|
+
`));for(let s of r)k.warn(f.yellow(`Cannot read the runner records of ${s}`));if(n.some((s)=>s.rows.some(SR)))throw new w("Not deleting: another Hydra home may record these runners","Repair or move the home named above, then run hydra legacy reconcile again");if(o.length===0){k.info(f.dim("Nothing to delete."));return}if(e.args.dryRun){k.info(`Would delete ${o.length} registration(s). Run ${f.green("hydra legacy 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(Ad(r));let o=r.rows.filter((s)=>s.placement!=="both");if(o.length===0)n.push(f.dim(" Every runner here matches a registration on GitHub."));for(let s of o){if(s.placement==="local"){n.push(` ${s.local.name} ${f.dim("is in this home but not registered on GitHub")}`);continue}let i=`${s.github.name} \xB7 id ${s.github.id}`;n.push(kn(s)?` ${f.red(t?"would delete":"delete")} ${i} \xB7 ${Qa(s.github)}`:` ${f.dim("keep")} ${i} \xB7 ${Cd(s)}`)}}return n}async confirmed(e,t){if(e.args.yes)return!0;if(!process.stdout.isTTY)throw new w("Deleting registrations requires confirmation","Pass --yes to delete them, or --dry-run to only list them");return gt({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 s=$R(r.local)?"returned":await Wa(e,o.target,r.github);if(s==="deleted")n++;let i=M1[s];k.info(`${r.github.name} \xB7 id ${r.github.id} \xB7 ${s==="deleted"?f.green(i):i}`)}k.info(`${f.green("Deleted")} ${n} of ${t.length} registration(s).`)}}import{rm as G1}from"fs/promises";import{join as F1}from"path";var U1=le({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class Bd extends I{name="remove";description="Deregister and delete runners";positionals=U1;async execute(e){he(),M(e.args,this.args,"Run 'hydra legacy remove --help' for supported options");let{name:t,profile:n}=e.interactive?Le(e.config,await ct(e.config)):Le(e.config,e.positionals.profile),o=(e.config.get("runners")??[]).filter((c)=>c.profile===t);if(o.length===0)throw new w(`No runners found for profile "${t}"`,"Run hydra legacy create to provision runners");let s=e.interactive?await this.promptRunnerSelection(o.map((c)=>c.id)):mr(e.positionals.ids??[],o.map((c)=>c.id)),i=ve(n,e.config),a=ze();for(let c of s)a.start(`Stopping and removing ${c}...`),await i.remove([c]),await G1(F1(n.directory,c),{force:!0,recursive:!0}),e.config.set("runners",(e.config.get("runners")??[]).filter((l)=>l.id!==c)),a.stop(`${f.red("-")} ${c}`);k.info(`${f.green("Removed")} ${s.length} runner(s).`)}async promptRunnerSelection(e){return On({message:"Select runners to remove",options:e.map((t)=>({label:t,value:t})),required:!0})}}var B1=le({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class jd extends I{name="start";description="Start runners";positionals=B1;async execute(e){he(),M(e.args,this.args,"Run 'hydra legacy start --help' for supported options");let{name:t,profile:n}=e.interactive?Le(e.config,await ct(e.config)):Le(e.config,e.positionals.profile),o=(e.config.get("runners")??[]).filter((p)=>p.profile===t);if(o.length===0)throw new w(`No runners found for profile "${t}"`,"Run hydra legacy create to provision runners");let s=ve(n,e.config),i=ze();i.start("Fetching runner status...");let a=await s.list();i.stop("Runner status fetched");let c=new Set(a.filter((p)=>p.status==="running").map((p)=>p.id)),l=o.map((p)=>p.id).filter((p)=>!c.has(p)),u=e.interactive?await this.promptRunnerSelection(l):mr(e.positionals.ids??[],o.map((p)=>p.id)),d=0;for(let p of u){if(c.has(p)){i.start(""),i.stop(`${f.dim("\u25CF")} ${p} ${f.dim("already running")}`);continue}i.start(`Starting ${p}...`),await s.start([p]),i.stop(`${f.green("\u25B6")} ${p}`),d++}k.info(`${f.green("Started")} ${d} runner(s).`),await Ka(e)}async promptRunnerSelection(e){if(e.length===0)throw new w("All runners are already running");return On({message:"Select runners to start",options:e.map((t)=>({label:t,value:t})),required:!0})}}var XR=q({github:{alias:"g",default:!1,description:"Compare with the runners registered on GitHub",type:"boolean"}}),j1={registered:f.yellow,running:f.green,stopped:f.red,unknown:f.dim};class Vd extends I{name="status";description="Show status across profiles";args=XR;async execute(e){he(),M(e.args,XR,"Run 'hydra legacy status --help' for supported options");let t=e.config.get("profiles"),n=Object.keys(t);if(n.length===0)throw new w("No profiles configured","Run hydra legacy init to set up a profile");let r=e.config.get("runners")??[],o=0,s=0,i=[];for(let a of n){let c=t[a],u=await ve(c,e.config).list();if(i.length>0)i.push("");i.push(`${f.bold(a)} ${f.dim(c.url)}`);let d=new Set(r.filter((m)=>m.profile===a).map((m)=>m.id)),p=u.filter((m)=>d.has(m.id)).sort((m,g)=>m.name.localeCompare(g.name,void 0,{numeric:!0}));this.formatRunners(p,i),o+=p.length,s+=p.filter((m)=>m.status==="running").length}if(i.push(""),i.push(f.dim(`${o} runner(s) total, ${s} running`)),k.info(i.join(`
|
|
622
|
+
`)),e.args.github)await this.printGitHubComparison(e)}async printGitHubComparison(e){let{scopes:t,unreadableHomes:n}=await qa(e.config,Jr(e.config));if(t.length===0){k.info(f.dim("No GitHub profiles to compare."));return}let r=t.flatMap((s,i)=>[...i>0?[""]:[],...KR(s)]),o=t.flatMap((s)=>s.rows.filter(kn)).length;if(o>0)r.push("",f.yellow(`Run ${f.green("hydra legacy reconcile --dry-run")} to review ${o} stale registration(s).`));k.info(r.join(`
|
|
623
|
+
`));for(let s of n)k.warn(f.yellow(`Cannot read the runner records of ${s}`))}formatRunners(e,t){if(e.length===0){t.push(f.dim(" No runners."));return}for(let n of e){let r=j1[n.status]??f.dim,o=n.pid?f.dim(` (pid: ${n.pid})`):"";t.push(` ${r("\u25CF")} ${n.name} ${r(n.status)}${o}`)}}}var QR=q({..._n,...Xr,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"}}),Kd=1000,V1=60,K1="Nothing more was stopped; run hydra legacy stop again";class qd extends I{name="stop";description="Stop drained 0.x runners once GitHub and the host show them idle";args=QR;async execute(e){M(e.args,QR,"Run 'hydra legacy stop --help' for supported options"),An(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 Gt(e.config),c=await zr(i,a.scopes,n),l=[],u=[],d=0;for(let g of a.runners.filter((h)=>h.process.kind!=="stopped")){let h=q1(g,Xo(c,g),n);if(h||!Mt(g)){if(g.process.kind!=="stale")d++;u.push(Ze(g,h??"config.json does not record it"));continue}l.push(g);let E=g.github?.busy||"worker"in g.process&&g.process.worker?"busy":"idle";u.push(xt(f.yellow(t?"would stop":"stop"),g,`${ot(g.process)} \xB7 ${E}`))}if(u.length===0)u.push(f.dim(" No runner of this home is running."));if(k.info(u.join(`
|
|
624
|
+
`)),l.length===0)return ZR(d,0,s);if(t){k.info(`Would stop ${l.length} runner(s), each only once it is idle.`);return}if(!await Cn(e.args,`Stop ${l.length} runner(s) once each is idle?`))return;let p=Date.now()+o*V1*Kd,m=l;while(!0){let g=[],h=await this.drainGroups(i,m,n);for(let E of m){let v=await this.attempt(i,E,h.get(E.scope.key));if(v==="busy")g.push(E);if(v==="left")d++}if(m=g,m.length===0||!s||Date.now()+r*Kd>p)break;k.info(f.dim(`Waiting for ${m.length} busy runner(s)...`)),await Bun.sleep(r*Kd)}for(let g of m)k.info(`${g.name} \xB7 ${f.yellow("still busy, left running")}`);ZR(d,m.length,s)}async drainGroups(e,t,n){let r=new Map;for(let o of t){let s=rr(o.scope.target);if(!s||r.has(o.scope.key))continue;r.set(o.scope.key,await Ja(e,s,n))}return r}async attempt(e,t,n){let r=t.github?.id;if(r===void 0||!n?.members.has(r))return k.info(`${t.name} \xB7 ${f.yellow("left running: it is no longer in the drain group")}`),"left";if(n.members.get(r)?.busy)return"busy";let o=await rt(e,t.scope.target,K1,()=>pn(e.client,t.scope.target,r));if(!o||o.name.toLowerCase()!==t.github?.name.toLowerCase())return k.info(`${t.name} \xB7 ${f.yellow("left running: GitHub no longer lists it under this id and name")}`),"left";if(o.busy)return"busy";let s=await or(t);if(s.kind==="stopped")return k.info(`${t.name} \xB7 already stopped`),"stopped";if(s.kind==="unproven"||s.kind==="stale")return k.info(`${t.name} \xB7 ${f.yellow(`left running: ${ot(s)}`)}`),"left";if(s.worker)return"busy";if(await LR(t.directory,s.pid)==="timeout")return k.info(`${t.name} \xB7 ${f.yellow("did not stop in time; check it with hydra legacy inventory")}`),"left";return k.info(`${t.name} \xB7 ${f.green("stopped")}`),"stopped"}}function ZR(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 w(`${e+t} runner(s) are still running`,r)}function q1(e,t,n){if(e.refusal)return e.refusal;if(e.process.kind==="stale")return`${ot(e.process)}; ${Qr(e.process)}`;if(e.process.kind==="unproven")return ot(e.process);if(!e.github)return"not registered on GitHub, so Hydra cannot prove it takes no jobs";if(e.scope&&!rr(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}class Wd extends I{name="update";description="Update runner binaries and job hooks";async execute(e){he(),M(e.args,this.args,"Run 'hydra legacy update --help' for supported options");let t=e.config.get("profiles"),n=e.config.get("runners")??[];if(n.length===0)throw new w("No runners found","Run hydra legacy create to provision runners");let r=ze(),o=Map.groupBy(n,(c)=>c.profile);for(let c of o.keys()){let l=Object.hasOwn(t,c)?t[c]:void 0;if(l)Jt(l.jobHooks)}let s=0,i=0,a=new Map;for(let[c,l]of o){let u=Object.hasOwn(t,c)?t[c]:void 0;if(!u)continue;let d=ve(u,e.config);r.start(`Checking for updates for "${c}"...`);let{version:p}=await d.download();r.stop(`Latest: v${p}`);let m=await d.list(),g=new Set(m.filter((h)=>h.status==="running").map((h)=>h.id));for(let h of l){let E=g.has(h.id);if(await d.currentVersion(h.id)===p){let R=await d.configureJobHooks(h.id);if(!R.envChanged&&!R.scriptsChanged)continue;if(i++,R.envChanged&&E){let _=a.get(c)??{ids:[],total:l.length};a.set(c,{..._,ids:[..._.ids,h.id]})}r.start(""),r.stop(`${f.green("\u2713")} ${h.id} ${f.dim("(job hooks)")}`);continue}if(r.start(`Updating ${h.id}...`),E)await d.stop([h.id]);if(await d.update([h.id]),E)await d.start([h.id]);s++;let v=E?` ${f.dim("(restarted)")}`:"";r.stop(`${f.green("\u2713")} ${h.id}${v}`)}}if(k.info(s>0?`${f.green("Updated")} ${s} runner(s).`:"All runners are already on the latest version."),i>0)k.info(`${f.green("Refreshed")} job hooks on ${i} runner(s).`);this.printRestartHint(a),await Ka(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 s=r.length===o?n:`${n} ${r.join(" ")}`;t.push(` ${f.green(`hydra legacy halt ${s} && hydra legacy start ${s}`)}`)}k.warn(t.join(`
|
|
625
|
+
`))}}import{readdir as W1,rm as e$,rmdir as J1}from"fs/promises";import{join as t$}from"path";var n$=q({..._n}),Y1="Nothing more was wiped; run hydra legacy wipe again",Qo="Its .runner file is kept; fix the cause, then run hydra legacy wipe again",z1="Delete what is left of the directory, then run hydra legacy wipe again to drop its record",X1=2;class Jd extends I{name="wipe";description="Delete the directories and records of stopped, deregistered 0.x runners";args=n$;async execute(e){M(e.args,n$,"Run 'hydra legacy wipe --help' for supported options"),An(e.args);let{github:t,inventory:n}=await Gt(e.config),r=(u)=>f.red(e.args.dryRun?`would ${u}`:u),o=[],s=[],i=[],a=[];for(let u of n.runners)if(GR(u)){let d=FR(u);if(d){a.push(Ze(u,`its directory is missing but GitHub lists id ${d.id}; run hydra legacy reconcile`));continue}s.push(u),a.push(xt(r("drop"),u,"its directory is missing, so only its record is left"))}else if(!Mt(u))a.push(Ze(u,u.refusal??"config.json does not record it"));else if(u.github)a.push(Ze(u,`registered on GitHub as id ${u.github.id}; run hydra legacy deregister first`));else if(u.process.kind!=="stopped")a.push(Ze(u,`${ot(u.process)}; ${Qr(u.process)}`));else{let d=await Zr(u,Qo,()=>Ed(u.directory));if(d.length>0)i.push(` ${u.name}: ${d.join(", ")}`);o.push(u),a.push(xt(r("wipe"),u,u.directory))}if(k.info(a.join(`
|
|
626
|
+
`)),i.length>0)throw k.warn(f.yellow(["Unexpected entries in runner directories:",...i].join(`
|
|
627
|
+
`))),new w("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;if(c===0){k.info(f.dim("Nothing to wipe."));return}if(e.args.dryRun){k.info(`Would wipe ${c} runner(s). Run ${f.green("hydra legacy wipe --yes")} to do it.`);return}if(!await Cn(e.args,`Delete ${o.length} runner directory(ies) and ${c} record(s)?`))return;let l=0;for(let u of o){let d=await this.keepReason(t,u);if(d){k.info(`${u.name} \xB7 ${f.yellow(`kept: ${d}`)}`);continue}await Z1(u),r$(e.config,u.entry),l++,k.info(`${u.name} \xB7 ${f.green("wiped")}`)}for(let u of s){let d=await Q1(u);if(d){k.info(`${u.name} \xB7 ${f.yellow(`kept: ${d}`)}`);continue}r$(e.config,u.entry),l++,k.info(`${u.name} \xB7 ${f.green("record dropped")}`)}k.info(`${f.green("Wiped")} ${l} of ${c} runner(s).`)}async keepReason(e,t){let n=await or(t);if(n.kind!=="stopped")return ot(n);let r=t.registration?.agentId;if(r===void 0)return"its .runner file records no runner id";if(await rt(e,t.scope.target,Y1,()=>pn(e.client,t.scope.target,r)))return`GitHub lists it again as id ${r}`;let s=await Zr(t,Qo,()=>Ed(t.directory));return s.length>0?`unexpected entries: ${s.join(", ")}`:void 0}}async function Q1(e){let t=await or(e);if(t.kind!=="stopped")return ot(t);return await _d(e.directory)==="missing"?void 0:"its directory exists again"}async function Z1(e){let{directory:t}=e;for(let n=0;n<X1;n++){let r=await Zr(e,Qo,()=>W1(t));for(let o of PR(r).filter((s)=>s!==Yt))await Zr(e,Qo,()=>e$(t$(t,o),{force:!0,recursive:!0}))}await Zr(e,Qo,()=>e$(t$(t,Yt),{force:!0})),await Zr(e,z1,()=>J1(t))}async function Zr(e,t,n){try{return await n()}catch(r){throw new w(`Cannot wipe ${e.name} in ${e.directory}: ${r.message}`,t)}}function r$(e,t){e.set("runners",(e.get("runners")??[]).filter((n)=>n.id!==t.id||n.profile!==t.profile))}class Za extends I{name="legacy";description="Run a 0.x fleet of profiles, or drain, stop, deregister and wipe it";init(){this.registerSubcommands([new Nd,new $d,new jd,new Od,new Vd,new Ud,new Ld,new Rd,new Wd,new Bd,new Fd,new Dd,new Pd,new qd,new Td,new Jd])}}var o$="Default",eU="self-hosted",tU=",",nU="pool",rU=2,oU=1,sU=/[^a-z0-9]+/g,s$=/^-+|-+$/g,iU={linux:"linux",osx:"macos"},aU={linux:"Linux",macos:"macOS"},i$={arm:"ARM",arm64:"ARM64",ia32:"X86",x64:"X64"},cU={linux:"scaleset",macos:"poll"},lU={linux:{cpus:2,diskGiB:30,memoryMiB:4096},macos:{cpus:4,diskGiB:60,memoryMiB:8192}};function c$(e,t){let n=new Set(t.taken),r={pools:[],skipped:[]};for(let[o,s]of Object.entries(e)){let i=uU(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 uU(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=fU(t.url);if(!o)return{profile:e,reason:"its url is not a GitHub organisation or repository URL"};let s=iU[t.os],i=dl(o),a=pU(e,r),c=Object.hasOwn(i$,n)?i$[n]:void 0,l=t.numberOfMachines??oU,u=br(ut,s),d=Math.min(l,u?.guests??l),p=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`,u&&d<l?`ceiling ${d}, not ${l}: ${u.driver} runs at most ${d} macOS guests per host`:"",o.kind==="org"&&!p?`runner group ${o$}, which 0.x runners joined without one`:"",o.kind==="repo"&&p?"runnerGroup dropped: repository runners belong to no group":""].filter(Boolean),g={ceiling:d,demand:cU[s],driver:ut,guestOs:s,labels:dU(t.labels,s,c),resources:{...lU[s]},...o.kind==="org"?{runnerGroup:p||o$}:{},secretBearing:!0,url:i};try{return{name:a,notes:m,pool:Ro(a,g),profile:e}}catch(h){return{profile:e,reason:`its pool would be refused: ${h instanceof Error?h.message:String(h)}`}}}function dU(e,t,n){let r=(e??"").split(tU).map((s)=>s.trim()),o=[];for(let s of[eU,aU[t],n??"",...r])if(s&&!o.some((i)=>i.toLowerCase()===s.toLowerCase()))o.push(s);return o}function pU(e,t){let n=a$(e,Fn)||nU;if(!t.has(n))return n;for(let r=rU;;r++){let o=`-${r}`,s=`${a$(n,Fn-o.length)}${o}`;if(!t.has(s))return s}}function a$(e,t){return e.toLowerCase().replace(sU,"-").replace(s$,"").slice(0,t).replace(s$,"")}function fU(e){try{return me(e)}catch{return}}var l$=q({dryRun:{alias:"n",default:!1,description:"Print the v2 pools for this home's 0.x profiles, write nothing",type:"boolean"}}),mU=2;class ec extends I{name="migrate";description="Print v2 pools for this home's 0.x profiles";args=l$;async execute(e){if(M(e.args,l$,"Run 'hydra migrate --help' for supported options"),!e.args.dryRun)throw new w("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 w("No profiles to migrate",`Select the home that holds them with ${Ee}`);let n=e.config.get("pools")??{},r=c$(t,{arch:process.arch,taken:Object.keys(n)}),o=[...r.pools.flatMap(gU),...r.skipped.map(({profile:a,reason:c})=>`${f.bold(a)} ${f.yellow("skipped")}: ${c}`)];if(k.info(o.join(`
|
|
628
|
+
`)),r.pools.length===0){k.info(f.dim("No profile maps to a pool. Nothing was written."));return}let s=Object.fromEntries(r.pools.map(({name:a,pool:c})=>[a,c]));console.log(JSON.stringify({pools:s},null,mU));let i=e.config.get("fleet")?"":', with a fleet id in "fleet": { "id": "<name>" }';k.info(f.dim([`Nothing was written. To use these pools, add them to the pools in ${e.config.path}${i}.`,"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(`
|
|
629
|
+
`)))}}function gU({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[`${f.bold(r)} \u2192 pool ${f.bold(e)}`,` ${o}`,` labels ${n.labels.join(", ")}`,` ${qt[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)=>f.dim(` ${c}`))]}class Yd extends I{name="print";description="Print the pf anchor rendered from the host budget and this host's interfaces";args=xn;async execute(e){M(e.args,xn,"Run 'hydra net print --help' for supported options");let t=En(Ht(e.args.budget));process.stdout.write(Ga(Ma(Ha(t))).text)}}var u$=q({json:{alias:"j",default:!1,description:"Print the daemon's answer as JSON",type:"boolean"},socket:{description:"Ask the host daemon on this socket",displayDefault:`${Xt}/<fleet id>.sock`,type:"string"}}),hU=120000;class zd extends I{name="verify";description="Ask the host daemon to compare the loaded pf anchor with the rendered one, and report the pf reference";args=u$;async execute(e){M(e.args,u$,"Run 'hydra net verify --help' for supported options");let t=e.args.socket||cd(e.config.get("fleet")?.id),n=await wU(t).catch((r)=>{if(!(r instanceof Ye))throw r;throw new w(r.message,"Start the host daemon with hydra host serve, or pass --socket")});if(e.args.json)process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
630
|
+
`);else k.info(yU(t,n).join(`
|
|
631
|
+
`));if(n.state==="ok"&&n.enforced)return;throw new w(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 yU(e,t){let n=t.enforced?f.green("holds"):f.red("does not hold"),r=t.reference?"enable reference held":"no enable reference",o=t.lastDrift;return[`${f.bold("Host daemon")} ${e}`,`${f.bold("pf anchor")} ${t.anchor} \xB7 ${n} \xB7 ${r} \xB7 loaded ${t.loadedAt??"never"} \xB7 checked ${t.checkedAt??"never"}`,`${f.bold("Guest bridges")} ${t.bridges.length===0?f.dim("none"):t.bridges.join(", ")}`,...o?[`${f.bold("Last change outside the daemon")} ${o.at}: ${o.differences.join("; ")}`]:[],...t.findings.map((s)=>`${s.level==="error"?f.red("\u2717"):f.yellow("!")} ${s.detail}
|
|
632
|
+
${f.dim(s.fix)}`)]}async function wU(e){let t=await jr(e,hU);try{return await t.netStatus()}finally{t.close()}}class tc extends I{name="net";description="Print the pf anchor that keeps guests off the host, or verify the one the host daemon loaded";init(){this.registerSubcommands([new Yd,new zd])}}import{existsSync as LU}from"fs";import{existsSync as d$,lstatSync as bU,mkdirSync as SU,readFileSync as RU,renameSync as $U,rmSync as vU,writeFileSync as EU}from"fs";import{hostname as xU}from"os";import{dirname as Xd,join as kU}from"path";var _U="scalesets.json",rc=16,AU="Default",p$=1,CU=448,TU=384,PU=18,OU=/^[a-z0-9]+$/,IU=/[^a-z0-9]/g,NU=H({id:X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B()),labels:ee(N()),name:N(),runnerGroupId:X().map((e)=>Number.isSafeInteger(e)&&e>0?e:B())}),DU=H({scaleSets:dr(NU),v:Y([p$])});class Zo extends Error{path;_tag="ScaleSetRecordsError";constructor(e,t){super(`Scale set records ${e} ${t}`);this.path=e;this.name="ScaleSetRecordsError"}}class oc 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 f$(e){return kU(e,Mo,_U)}function m$(e){return e.length<=rc&&OU.test(e)}function g$(e=xU()){let t=(e.split(".")[0]??"").toLowerCase().replace(IU,"").slice(0,rc);return t===""?void 0:t}function h$(e,t,n){return`${e}-${t}-${n}`}function sr(e){let t=f$(e);if(!d$(t))return{};nc(Xd(t),"directory"),nc(t,"file");try{return DU(JSON.parse(RU(t,"utf8"))).scaleSets}catch{throw new Zo(t,"is not a valid scale set record file")}}function sc(e,t){let n=f$(e);if(SU(Xd(n),{mode:CU,recursive:!0}),nc(Xd(n),"directory"),d$(n))nc(n,"file");let r=`${n}.${process.pid}.tmp`;vU(r,{force:!0}),EU(r,`${JSON.stringify({scaleSets:t,v:p$},null,2)}
|
|
633
|
+
`,{flag:"wx",mode:TU}),$U(r,n)}function nc(e,t){let n=bU(e);if(!(t==="directory"?n.isDirectory():n.isFile()))throw new Zo(e,t==="file"?"is not a regular file":"is not a directory");if(n.uid!==process.getuid?.())throw new Zo(e,"is not owned by the user running Hydra");if((n.mode&PU)!==0)throw new Zo(e,"can be written by other users")}async function y$(e,t,n){let r=await e.getRunnerGroup(t.runnerGroup??AU),{created:o,labelsMatch:s,scaleSet:i}=await e.ensureScaleSet({labels:t.labels,name:n,runnerGroupId:r.id});if(!s)throw new oc(n,i.id);return{adopted:!o,record:{id:i.id,labels:[...t.labels],name:i.name,runnerGroupId:r.id}}}var ic="Check the GitHub credentials: scale sets need the Self-hosted runners organisation permission (read and write)",HU="Delete that scale set first, or give this host another id with --host";function Qd(e,t){return ga({apiUrl:un(process.env),github:At(e).client,url:t})}function ac(e,t,n){try{return Ro(e,t)}catch(r){throw new w(r.message,n)}}function cc(e){let t=e??g$();if(t!==void 0&&m$(t))return t;throw new w(`The host id "${t??""}" is not lowercase letters and digits, at most ${rc} characters`,"Name this host with --host, for example --host build1")}async function lc(e,t,n,r,o){let s=ie(e),i=sr(s),a=i[n];if(a)return`Pool ${n} keeps scale set ${a.name} (id ${a.id})`;let c,l;try{({adopted:l,record:c}=await y$(Qd(e,r.url),r,h$(t,n,o)))}catch(u){throw new w(u.message,u instanceof oc?HU:ic)}return sc(s,{...i,[n]:c}),`${l?"Adopted":"Created"} scale set ${c.name} (id ${c.id}) in runner group ${c.runnerGroupId}`}function w$(e,t){let n=ie(e);if(!LU(Lr(n)))return 0;return aa(n).slots().filter((r)=>r.pool===t&&(!pt(r.phase)||Ve(r))).length}var b$=q({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 ${ge}`,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"}}),MU=le({pool:{description:"Name of the new pool",required:!0}}),S$="Run 'hydra pool add --help' for the settings a pool takes",GU=["allowWeakerIsolation","foreignArch","guiSession","secretBearing"];class Zd extends I{name="add";description="Add a pool; a scale-set pool gets its scale set in its runner group";args=b$;positionals=MU;async execute(e){M(e.args,b$,S$);let t=e.positionals.pool;if(!So(t))throw new w(`"${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 w(`Pool ${t} already exists`,"hydra pool set changes it; hydra pool remove deletes it");let r=FU(e),o=ac(t,UU(e.args),S$),s=o.demand==="scaleset"?cc(e.args.host):void 0,i=[`Added pool ${f.bold(t)} (${o.demand} demand)`];if(s!==void 0)i.push(await lc(e.config,r,t,o,s));if(!e.config.get("fleet"))e.config.set("fleet",{id:r});e.config.set("pools",{...n,[t]:o}),k.success(i.join(`
|
|
634
|
+
`))}}function FU(e){let t=e.config.get("fleet")?.id,n=e.args.fleet;if(t!==void 0&&n!==void 0&&n!==t)throw new w(`This home belongs to fleet ${t}`,"Leave out --fleet, or use another Hydra home");let r=t??n;if(r!==void 0&&Un(r))return r;throw new w(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 UU(e){let t=e.labels?.split(",").map((o)=>o.trim()),r={ceiling:e.ceiling===void 0||e.ceiling===ge?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 GU)if(e[o])r[o]=!0;return Object.fromEntries(Object.entries(r).filter(([,o])=>o!==void 0))}var BU=le({pool:{description:"Pool to remove",required:!0}});class ep extends I{name="remove";description="Remove a pool and delete its scale set";positionals=BU;async execute(e){M(e.args,this.args,"Run 'hydra pool remove --help' for supported options");let t=e.positionals.pool,n=ie(e.config),r=e.config.get("pools")??{},o=r[t],s=sr(n),i=s[t];if(!o&&!i)throw new w(`No pool is named ${t}`);let a=w$(e.config,t);if(a>0)throw new w(`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 w(`Pool ${t} has a scale set but no settings`,"Add the pool again, then remove it");let p=await jU(Qd(e.config,d),i),{[t]:m,...g}=s;sc(n,g),c.push(p==="gone"?`Scale set ${i.name} (id ${i.id}) was already gone`:`Deleted scale set ${i.name} (id ${i.id})`)}let{[t]:l,...u}=r;e.config.set("pools",u),k.success([`Removed pool ${f.bold(t)}`,...c].join(`
|
|
635
|
+
`))}}async function jU(e,t){let n;try{n=await e.getScaleSetById(t.id)}catch(r){throw new w(r.message,ic)}if(!n)return"gone";if(n.name!==t.name||n.runnerGroupId!==t.runnerGroupId)throw new w(`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 w(r.message,ic)}}var R$=q({ceiling:{description:`Most jobs the pool runs at once, or ${ge}`,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"}}),VU=le({pool:{description:"Pool to change",required:!0}}),$$="Run 'hydra pool set --help' for the settings it changes";class tp extends I{name="set";description="Change a pool's demand source or ceiling";args=R$;positionals=VU;async execute(e){M(e.args,R$,$$);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 w(`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 w("Name a change","Use --demand or --ceiling");let a=ac(t,{...r,...i===void 0?{}:{demand:i},...s===void 0?{}:{ceiling:s===ge?s:Number(s)}},$$),c=[`Pool ${f.bold(t)} takes ${a.demand} demand with a ceiling of ${a.ceiling}`];if(a.demand==="scaleset")c.push(await lc(e.config,o,t,a,cc(e.args.host)));if(a.demand==="poll"&&r.demand==="scaleset")c.push(f.dim("Its scale set stays registered; hydra pool remove deletes it"));e.config.set("pools",{...n,[t]:a}),k.success(c.join(`
|
|
636
|
+
`))}}class uc extends I{name="pool";description="Add, change and remove pools and their scale sets";init(){this.registerSubcommands([new Zd,new tp,new ep])}}import{existsSync as KU,lstatSync as qU,readdirSync as WU}from"fs";import{join as v$}from"path";var np="slot-logs",rp=14,JU=86400000,E$=".log",YU=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,zU=18,XU=["current","previous"];function dc(e){let t={images:[],kept:[],logs:[],notes:[]};return QU(e,t),tB(e,t),t}function QU(e,t){let n=new Map;for(let r of dd(e.home)){if(!bb(r.record))continue;let o=eB(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=ZU(s,i.record,e.serving);if(a)t.kept.push({reason:a,record:i.record});else t.images.push(i)}}}function ZU(e,t,n){let r=XU[e];if(r)return r;if(n===void 0)return"serving-unknown";return n.includes(t.reference)?"serving":void 0}function eB(e){return[e.kind,e.builder,e.arch,e.variant].join("/")}function tB(e,t){if(e.fleet===void 0)return;let n=v$(e.home,np);if(!KU(n))return;if(!x$(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-rp*JU;for(let s of WU(n).sort()){if(!nB(s,r))continue;let i=v$(n,s),a=k$(i);if(!a?.isFile()||!x$(i,"file")||a.mtimeMs>o)continue;t.logs.push({bytes:a.size,modifiedAt:a.mtimeMs,name:s,path:i})}}function nB(e,t){if(!e.startsWith(t)||!e.endsWith(E$))return!1;return YU.test(e.slice(t.length,-E$.length))}function x$(e,t){let n=k$(e);if(!n)return!1;return(t==="directory"?n.isDirectory():n.isFile())&&n.uid===process.getuid?.()&&(n.mode&zU)===0}function k$(e){try{return qU(e)}catch{return}}import{lstatSync as _$,readFileSync as rB,renameSync as oB,rmSync as A$,writeFileSync as sB}from"fs";import{join as iB}from"path";var aB="serving.json",cB=384,lB=18,uB=H({images:ee(N()),startedAt:N()});function op(e){return iB(e,aB)}function dB(e,t,n=new Date){let r=op(e),o=`${r}.${process.pid}.tmp`;try{let s={images:[...new Set(t)].sort(),startedAt:n.toISOString()};sB(o,`${JSON.stringify(s,null,2)}
|
|
637
|
+
`,{flag:"wx",mode:cB}),oB(o,r)}finally{A$(o,{force:!0})}}function C$(e,t,n,r=new Date){let o=n?sp(e):[];if(o===void 0)return;let s=[...new Set([...t,...o])].sort();return dB(e,s,r),s}function T$(e,t){if(!t)pB(e)}function pB(e){let t=op(e);if(_$(t,{throwIfNoEntry:!1})?.isFile())A$(t,{force:!0})}function sp(e){let t=op(e),n=_$(t,{throwIfNoEntry:!1});if(!n)return[];if(!n.isFile()||n.uid!==process.getuid?.()||(n.mode&lB)!==0)return;try{return uB(JSON.parse(rB(t,"utf8"))).images}catch{return}}var P$=q({yes:{alias:"y",default:!1,description:"Remove what the dry run lists",type:"boolean"}}),fB={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"},mB=86400000;class pc extends I{name="prune";description="List, or with --yes remove, the runner images and slot logs Hydra recorded and no longer needs";args=P$;async execute(e){M(e.args,P$,"Run 'hydra prune --help' for supported options");let t=ie(e.config),n=Date.now(),r=dc({fleet:e.config.get("fleet")?.id,home:t,now:n,serving:sp(t)});if(k.info(gB(r,n)),r.images.length+r.logs.length===0)return;if(!e.args.yes){k.info(f.dim("Nothing was removed. Run hydra prune --yes to remove what is listed."));return}let o=await Sa(r,ba());if(k.info(hB(o)),o.failed.length>0)throw new w(`Could not prune ${o.failed.length} of ${r.images.length+r.logs.length} items`,"Each item above that could not be removed stays listed; fix its problem and run hydra prune --yes again")}}function gB(e,t){let n=[...e.images.map(({record:o})=>`${f.bold("image")} ${o.reference} ${f.dim(`(${o.variant}, ${o.arch}, built ${o.builtAt})`)}`),...e.logs.map((o)=>`${f.bold("slot log")} ${o.name} ${f.dim(`(${bt(o.bytes)}, ${Math.floor((t-o.modifiedAt)/mB)} days old)`)}`)];if(n.length===0)n.push(`Nothing to prune: no image beyond the two newest, no slot log older than ${rp} days`);let r=e.kept.map(({reason:o,record:s})=>f.dim(`keeps ${s.reference}: ${fB[o]}`));return[...n,...r,...e.notes.map((o)=>f.yellow(o))].join(`
|
|
638
|
+
`)}function hB(e){return[`Removed ${Ra(e)}`,...e.failed.map((n)=>f.yellow(`${n.item}: ${n.detail}`))].join(`
|
|
639
|
+
`)}import{join as L$}from"path";import{join as yB}from"path";var wB={arm64:"arm64",x86_64:"amd64"},bB="tart";function O$(e,t,n,r){let o={drivers:{},images:{},networks:[],unavailable:{}},s=new Map;for(let[i,a]of Object.entries(t)){let c=Ks(a.driver,Ws(a),n);if(c.kind==="refused"){o.unavailable[i]=c.refusals.map((p)=>p.detail).join("; ");continue}let l=c.driver;if(!s.has(l))s.set(l,RB(l,e,o,r));let u=s.get(l);if(typeof u==="string"){o.unavailable[i]=u;continue}if(u)o.drivers[i]=u;let d=l==="tart"?$B(r,a):vB(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 I$(e,t,n){let r=n.scaleSetClient??ip(n.apiUrl,n.github),o=iS({client:n.github,pools:SB(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 l=n.records[i];if(!l){t.unavailable[i]=`no scale set is recorded for it; hydra pool set ${i} --demand scaleset creates one`;continue}s[i]=cb({...c,capacity:()=>n.capacity(i),client:r(a.url),labels:a.labels,ownerName:l.name,pool:i,runnerGroupId:l.runnerGroupId,scaleSetId:l.id});continue}s[i]=ob({...c,capacity:()=>N$(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 SB(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??nr,repositories:aS({github:n.github,pool:r,runnerGroup:o.runnerGroup,url:o.url}),room:()=>n.serving?.(r)??!0?N$(o)-ma(n.ledger.slots(),r):0}))}function N$(e){return e.ceiling===ge?Hr:e.ceiling}function ip(e,t){let n=new Map;return(r)=>{let o=n.get(r);if(o)return o;let s=ga({apiUrl:e,github:t,url:r});return n.set(r,s),s}}function D$(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 RB(e,t,n,r){if(e==="tart"){let s=xy(r,zn());return Wi({checkImage:s,fleet:{id:t.id,stateDir:yB(r,bB)}})}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=Ri({fleet:{dns:t.dns,id:t.id,networks:t.networks}});return n.networks.push(o.networks()),o}function $B(e,t){let n=hn(t.secretBearing??!1),r=vy(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 vB(e,t,n){let r=wB[t.arch];if(!r)return`Hydra builds no Linux image for ${t.arch} hosts`;let o=(n.docker??"none")!=="none";return KS(e,r,o?"docker":"plain")??`no ${o?"Docker ":""}Linux image is recorded; run hydra image build linux${o?" --docker":""}`}var H$=q({socket:{description:"Ask the host daemon on this socket for leases",displayDefault:`${Xt}/<fleet id>.sock`,type:"string"}}),M$=["SIGINT","SIGTERM"],EB=30000;class fc extends I{name="serve";description="Run this fleet's pools: start a fresh guest for each job their demand sources bring, until stopped";args=H$;async execute(e){M(e.args,H$,"Run 'hydra serve --help' for supported options");let t=e.config.get("fleet"),n=e.config.get("pools")??{};if(!t||Object.keys(n).length===0)throw new w("This home has no pools to serve","Add one with hydra pool add");let r=e.config.get("alerts");if(yt(r).length===0)throw new w("Pools need an alert sink",Dn);let o=ie(e.config);if(!Vr(o))throw new w("Pools need a guard record","Run hydra guard record once the runner groups and policies are as they should be");let s=xB(o),i=(S)=>process.stdout.write(`${new Date().toISOString()} ${S}
|
|
640
|
+
`),a=$s({fleet:t.id,sinks:vs(r,{env:process.env,version:rn}),store:xs(o)}),c=()=>{a.deliver().catch((S)=>i(`alert delivery failed: ${String(S)}`))},l=(S)=>{a.raise(S),i(`alert ${S.reason}${S.pool?` for pool ${S.pool}`:""}${S.detail?`: ${S.detail}`:""}`),c()},u=At(e.config).client,d=rb({alert:l,log:i,minted:()=>Lo(s.slots()),pools:n,reader:Qi(u),record:()=>la(o)}),p=O$(t,n,await ln(),o),m,g=rS({connect:()=>jr(e.args.socket||L$(Xt,`${t.id}.sock`)),reported:(S)=>m?.reported(S),slots:()=>yS(s,n)}),h=un(process.env),E=ip(h,u),v=sr(o),R=I$(n,p,{alert:l,apiUrl:h,capacity:(S)=>d.held(S)===void 0?_.capacity(S):0,github:u,ledger:s,onDemand:async()=>m?.tick(),records:v,scaleSetClient:E,serving:(S)=>(m?.status().pools.find((C)=>C.pool===S)?.health??"serving")==="serving"}),_=kB(()=>sS({alert:l,assigned:(S)=>R[S]?.status().demand??0,offer:(S)=>g.offer(S),pools:Object.fromEntries(Object.entries(n).filter(([S])=>R[S]!==void 0)),slots:()=>s.slots()}));for(let[S,C]of Object.entries(p.unavailable))i(`pool ${S} takes no new jobs: ${C}`);let T=C$(o,Object.values(p.images),G$(s));if(!T)i("could not read the images an earlier hydra serve started guests from; every image is kept");let b=kb({alert:l,log:i,prune:(S)=>Sa(dc({fleet:t.id,home:o,now:Date.now(),serving:T}),ba(),S),read:async()=>{let S=await g.status();return{freeGiB:S.live.diskFreeGiB,state:S.disk}}});await _B(p.networks,i);let A=mS({alert:l,degrade:(S)=>m?.degrade(S),drivers:p.drivers,fleet:t.id,github:u,ledger:s,log:i,networks:p.networks,records:()=>sr(o),registrations:gS(n,v,{github:u,scaleSetClient:E}),retire:(S)=>m?.retire(S)});await d.round(),m=await wS({alert:l,drivers:p.drivers,fleet:t.id,held:d.held,host:g,ledger:s,log:i,logsDir:L$(o,np),offers:_,pools:n,runnerLeft:A.left,sources:R,spec:D$(n,p.images),unavailable:p.unavailable}),A.start(),d.start(),b.start();let y=setInterval(c,EB);await AB(),clearInterval(y),i("stopping; running guests keep their jobs"),await A.stop(),await d.stop(),await b.stop(),await m.stop(),T$(o,G$(s)),await a.deliver({flush:!0}).catch(()=>{return})}}function G$(e){return e.slots().some((t)=>!pt(t.phase)||Ve(t))}function xB(e){try{return aa(e)}catch(t){if(t instanceof tt)throw new w(t.message,"Repair the ledger, or restore it from a backup");throw t}}function kB(e){try{return e()}catch(t){if(t instanceof Aa)throw new w(t.message,"Split the pools between fleets");throw t}}async function _B(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 AB(){return new Promise((e)=>{let t=()=>{for(let n of M$)process.off(n,t);e()};for(let n of M$)process.on(n,t)})}var F$=q({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"}}),CB=0;class ap extends I{name="print";description="Print this fleet's LaunchDaemon, or with --host the host daemon's, with an explicit environment";args=F$;async execute(e){if(M(e.args,F$,"Run 'hydra service print --help' for supported options"),e.args.host&&e.args.socket!==void 0)throw new w("--socket is for a fleet's service, not --host");if(!e.args.host&&e.args.budget!==void 0)throw new w("--budget goes with --host");if(e.args.script!==(e.args.stage!==void 0))throw new w("--script and --stage go together","Pass the directory the reviewed property list is staged in");try{let t=e.args.host?Zh({budget:e.args.budget}):TB(e.config,e.args.socket);process.stdout.write(e.args.stage===void 0?t.plist:ty({service:t,stage:e.args.stage}))}catch(t){if(t instanceof Ei||t instanceof Co||t instanceof Ar)throw new w(t.message);throw t}}}function TB(e,t){let n=e.get("fleet");if(!n)throw new w("config.json names no fleet","Run hydra service print as the fleet's account, with its home");if(process.getuid?.()===CB)throw new w("A fleet's service never runs as root","Run hydra service print as the fleet's account, or pass --host");let r=wh();return ey({account:r.name,accountHome:r.home,fleet:n.id,home:ie(e),socket:t})}class mc extends I{name="service";description="Print the LaunchDaemons that run the host daemon and this fleet, or the root script that installs them";init(){this.registerSubcommands([new ap])}}var U$=q({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 ${Tr}@${qn}`,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"}});class cp extends I{name="print";description="Print the pinned artefacts to download, or with --script the install script for root";args=U$;async execute(e){M(e.args,U$,"Run 'hydra toolchain print --help' for supported options");let t=PB(e.args.integrity);if(!e.args.script){if(e.args.stage!==void 0||e.args.group!==void 0)throw new w("--stage and --group go with --script","Add --script to print the install script");process.stdout.write(Vh(t));return}if(e.args.stage===void 0||e.args.group===void 0)throw new w("--script needs --stage and --group","Pass the directory the artefacts were downloaded to and the fleet account's group");process.stdout.write(OB(t,e.args.stage,e.args.group))}}function PB(e){let t=`Read it with npm view ${Tr}@${qn} dist.integrity`;if(e===void 0)throw new w("hydra toolchain print needs --integrity",t);try{return jh(e)}catch(n){if(n instanceof $i)throw new w(`--integrity ${n.message}`,t);throw n}}function OB(e,t,n){try{return Kh({group:n,pins:e,stage:t})}catch(r){if(r instanceof Or)throw new w(r.message);throw r}}class lp extends I{name="verify";description="Check that every file and directory Hydra runs from is owned and writable only by root and matches its recorded checksum";async execute(e){M(e.args,this.args,"Run 'hydra toolchain verify --help' for supported options");let{findings:t,lines:n,report:r}=await ki();if(!r.installed)throw new w(`No toolchain is installed in ${Cr}`,"Install it with the script from hydra toolchain print --script");if(k.info(n.join(`
|
|
641
|
+
`)),t.length>0)throw new w(_i(t),"Fix each path above, then verify again")}}class gc extends I{name="toolchain";description="Print the pinned host toolchain and its root install script, or verify the installed one";init(){this.registerSubcommands([new cp,new lp])}}var IB="--",NB=new Set(["--help","-h"]),B$="help",DB=new Set(["doctor","driver","host serve","host-budget print","toolchain"]),LB=new Set(["alerts test","guard check","host status","host-budget check","legacy logs","legacy profile list","legacy status","migrate","service print"]),HB=3,MB={...Hc,home:Ps};function j$(e){let t=q$(e);return t?.command===B$?t.restArgs[0]:t?.command}function V$(e){let t=q$(e);if(!t)return"write";let{command:n,flags:r,restArgs:o}=t;if(!n)return r.version||!r.interactive?"help":"write";if(n===B$)return"help";let s=GB(n,o);if(s.some((i)=>DB.has(i)))return"diagnose";if(FB(Boolean(r.help),o))return"help";return s.some((i)=>LB.has(i))?"read":"write"}function K$({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 w(`This directory holds the Hydra home ${o}, but no home was selected, so this command would act on ${e}`,`Pass ${Ee} <path> or set ${at} to choose ${o} or ${e}`)}function q$(e){try{return io([...e],MB)}catch{return}}function GB(e,t){let n=[e,...t.slice(0,HB-1)];return n.map((r,o)=>n.slice(0,o+1).join(" "))}function FB(e,t){if(e)return!0;let n=t.indexOf(IB);return(n<0?t:t.slice(0,n)).some((r)=>NB.has(r))}class W$ extends Mc{constructor(e,t){super(e,{bin:_s,clearOnStart:t,description:"Run each GitHub Actions job in a fresh guest on this machine.",exitLabel:"Exit",goodbyeMessage:"Heads down.",name:"HYDRA",promptMessage:"What do you need?",version:rn})}init(){this.globalArgs.home=Ps,this.registerCommands([new uc,new fc,new zi,new Va,new Da,new ks,new Ua,new Ba,new tc,new gc,new mc,new pc,new Ai,new ec,new Za])}}function UB(e,t){k.warn(f.yellow(`Ignoring ${t}: Hydra keeps its state in ${e}`)),k.info(f.dim(`To manage that fleet, pass ${Ee} ${t} or set ${at}=${t}`))}function BB(e){if(e instanceof w){if(k.warn(f.yellow(e.message)),e.hint)k.info(f.dim(e.hint));process.exit(e.exitCode)}k.error(f.red(e instanceof Error?e.message:String(e))),process.exit(1)}async function jB(){let e=lm(process.argv.slice(2),process.env),t=uR(j$(e.argv));if(t)throw t;let n=V$(e.argv),r=K$(e,n,process.cwd()),o=ug(e.home);if(r)UB(e.home,r);let s=n==="read"||n==="write"?zs(o):void 0;if(s)throw s;await new W$(o,r===void 0).run(e.argv)}jB().catch(BB);
|