@r5n/hydra 0.7.0 → 0.9.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 CHANGED
@@ -64,6 +64,19 @@ Bare `hydra` prints help. `hydra -i` opens an interactive menu that walks throug
64
64
  - `-l, --list` list available log files with timestamps and sizes
65
65
  - `-o, --open` open the log in `$EDITOR` (falls back to `open` on macOS)
66
66
 
67
+ ### cleanup
68
+
69
+ `hydra cleanup` frees disk space. By default it prunes `_diag` log files older than 7 days (always keeping the newest runner and worker log per runner) and removes shared runner versions no runner's `externals` link points to (the newest installed version is always kept). `_work` holds job checkouts and caches, so it is never cleaned by default — pass `-w` explicitly. Runners that are currently running are skipped for `_work` cleanup.
70
+
71
+ - `-l, --logs` prune old `_diag` log files
72
+ - `-w, --work` delete `_work` contents of stopped runners
73
+ - `-s, --shared` remove unused shared runner versions
74
+ - `-d, --days` age threshold in days for log pruning (default: 7, or `cleanup.olderThanDays`)
75
+ - `-n, --dry-run` list what would be deleted with sizes, delete nothing
76
+ - `-y, --yes` skip confirmation prompts
77
+
78
+ Passing any of `-l`/`-w`/`-s` cleans only those targets; with none, the targets come from the `cleanup` config section (default: logs and shared).
79
+
67
80
  ### update
68
81
 
69
82
  `hydra update` checks the latest `actions/runner` release, and if it differs from the installed version, swaps the binaries for every runner. Runners that were running are stopped, updated, and restarted.
@@ -104,6 +117,14 @@ Bare `hydra` prints help. `hydra -i` opens an interactive menu that walks throug
104
117
 
105
118
  `os` is one of `osx` | `linux` | `windows` (auto-detected by `init`). An optional `runnerGroup` string is passed through to `config.sh --runnergroup`; runner groups only apply to organization runners. The `runners` array is Hydra's record of what it created — leave it alone.
106
119
 
120
+ An optional `cleanup` section controls `hydra cleanup` and automatic cleanup:
121
+
122
+ ```json
123
+ "cleanup": { "auto": true, "intervalHours": 24, "olderThanDays": 7, "targets": ["logs", "shared"] }
124
+ ```
125
+
126
+ All fields are optional; the values above (with `auto: false`) are the defaults. With `auto` enabled, `hydra start` and `hydra update` run a cleanup afterwards whenever the last run is more than `intervalHours` ago. Automatic runs never prompt and only touch the configured `targets` — `work` only if you list it explicitly. Hydra records `lastRun` itself; leave it alone.
127
+
107
128
  The `url` is either a repository URL (`https://github.com/owner/repo`) or an organization URL (`https://github.com/org`). Repository URLs mint tokens from the repository endpoint (requires repo admin); organization URLs use the organization endpoint (requires the `admin:org` scope).
108
129
 
109
130
  ## How it works
package/dist/cli.js CHANGED
@@ -1,98 +1,99 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var ni=Object.create;var{getPrototypeOf:oi,defineProperty:An,getOwnPropertyNames:ii}=Object;var ei=Object.prototype.hasOwnProperty;function ti(r){return this[r]}var ai,si,Jn=(r,n,o)=>{var i=r!=null&&typeof r==="object";if(i){var e=n?ai??=new WeakMap:si??=new WeakMap,t=e.get(r);if(t)return t}o=r!=null?ni(oi(r)):{};let a=n||!r||!r.__esModule?An(o,"default",{value:r,enumerable:!0}):o;for(let s of ii(r))if(!ei.call(a,s))An(a,s,{get:ti.bind(r,s),enumerable:!0});if(i)e.set(r,a);return a};var ci=(r,n)=>()=>(n||r((n={exports:{}}).exports,n),n.exports);var fn=ci((ft,oo)=>{var cn={to(r,n){if(!n)return`\x1B[${r+1}G`;return`\x1B[${n+1};${r+1}H`},move(r,n){let o="";if(r<0)o+=`\x1B[${-r}D`;else if(r>0)o+=`\x1B[${r}C`;if(n<0)o+=`\x1B[${-n}A`;else if(n>0)o+=`\x1B[${n}B`;return o},up:(r=1)=>`\x1B[${r}A`,down:(r=1)=>`\x1B[${r}B`,forward:(r=1)=>`\x1B[${r}C`,backward:(r=1)=>`\x1B[${r}D`,nextLine:(r=1)=>"\x1B[E".repeat(r),prevLine:(r=1)=>"\x1B[F".repeat(r),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Ci={up:(r=1)=>"\x1B[S".repeat(r),down:(r=1)=>"\x1B[T".repeat(r)},Fi={screen:"\x1B[2J",up:(r=1)=>"\x1B[1J".repeat(r),down:(r=1)=>"\x1B[J".repeat(r),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(r){let n="";for(let o=0;o<r;o++)n+=this.line+(o<r-1?cn.up():"");if(r)n+=cn.left;return n}};oo.exports={cursor:cn,scroll:Ci,erase:Fi,beep:"\x07"}});class X extends Error{constructor(r="Operation cancelled"){super(r)}}class v extends Error{hint;constructor(r,n){super(r);this.hint=n}}import{styleText as jr}from"util";import{stdout as dn,stdin as ao}from"process";import*as or from"readline";import ki from"readline";var xn=(()=>{let r=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(n)=>{let o=0;r.lastIndex=0;while(r.test(n))o+=1;return n.length-o}})(),Kn=(r)=>{return r===12288||r>=65281&&r<=65376||r>=65504&&r<=65510},Yn=(r)=>{return r===8987||r===9001||r>=12272&&r<=12287||r>=12289&&r<=12350||r>=12441&&r<=12543||r>=12549&&r<=12591||r>=12593&&r<=12686||r>=12688&&r<=12771||r>=12783&&r<=12830||r>=12832&&r<=12871||r>=12880&&r<=19903||r>=65040&&r<=65049||r>=65072&&r<=65106||r>=65108&&r<=65126||r>=65128&&r<=65131||r>=127488&&r<=127490||r>=127504&&r<=127547||r>=127552&&r<=127560||r>=131072&&r<=196605||r>=196608&&r<=262141};var fi=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,mi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Zn=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,ui=/\t{1,1000}/y,Qn=/[\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,pi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,di=/\p{M}+/gu,li={limit:1/0,ellipsis:""},Xn=(r,n={},o={})=>{let i=n.limit??1/0,e=n.ellipsis??"",t=n?.ellipsisWidth??(e?Xn(e,li,o).width:0),a=0,s=o.controlWidth??0,c=o.tabWidth??8,f=o.emojiWidth??2,l=2,g=o.regularWidth??1,u=o.wideWidth??2,h=[[pi,g],[fi,0],[mi,s],[ui,c],[Qn,f],[Zn,u]],d=0,b=0,k=r.length,D=0,C=!1,G=k,H=Math.max(0,i-t),F=0,U=0,j=0,I=0;r:while(!0){if(U>F||b>=k&&b>d){let M=r.slice(F,U)||r.slice(d,b);D=0;for(let V of M.replaceAll(di,"")){let J=V.codePointAt(0)||0;if(Kn(J))I=2;else if(Yn(J))I=u;else I=g;if(j+I>H)G=Math.min(G,Math.max(F,d)+D);if(j+I>i){C=!0;break r}D+=V.length,j+=I}F=U=0}if(b>=k)break r;for(let M=0,V=h.length;M<V;M++){let[J,yr]=h[M];if(J.lastIndex=b,J.test(r)){if(D=J===Zn?xn(r.slice(b,J.lastIndex)):J===Qn?1:J.lastIndex-b,I=D*yr,j+I>H)G=Math.min(G,b+Math.floor((H-j)/yr));if(j+I>i){C=!0;break r}j+=I,F=d,U=b,b=d=J.lastIndex;continue r}}b+=1}return{width:C?H:j,index:C?G:k,truncated:C,ellipsed:C&&i>=t}},Vn=Xn;var gi={limit:1/0,ellipsis:"",ellipsisWidth:0},hi=(r,n={})=>{return Vn(r,gi,n).width},x=hi;var Lr="\x1B",Tn="\x9B",bi=39,an="\x07",ro="[",vi="]",no="m",sn=`${vi}8;;`,On=new RegExp(`(?:\\${ro}(?<code>\\d+)m|\\${sn}(?<uri>.*)${an})`,"y"),Sn=(r)=>{if(r>=30&&r<=37)return 39;if(r>=90&&r<=97)return 39;if(r>=40&&r<=47)return 49;if(r>=100&&r<=107)return 49;if(r===1||r===2)return 22;if(r===3)return 23;if(r===4)return 24;if(r===7)return 27;if(r===8)return 28;if(r===9)return 29;if(r===0)return 0;return},Bn=(r)=>`${Lr}${ro}${r}${no}`,_n=(r)=>`${Lr}${sn}${r}${an}`,tn=(r,n,o)=>{let i=n[Symbol.iterator](),e=!1,t=!1,a=r.at(-1),s=a===void 0?0:x(a),c=i.next(),f=i.next(),l=0;while(!c.done){let g=c.value,u=x(g);if(s+u<=o)r[r.length-1]+=g;else r.push(g),s=0;if(g===Lr||g===Tn)e=!0,t=n.startsWith(sn,l+1);if(e){if(t){if(g===an)e=!1,t=!1}else if(g===no)e=!1}else if(s+=u,s===o&&!f.done)r.push(""),s=0;c=f,f=i.next(),l+=g.length}if(a=r.at(-1),!s&&a!==void 0&&a.length&&r.length>1)r[r.length-2]+=r.pop()},wi=(r)=>{let n=r.split(" "),o=n.length;while(o){if(x(n[o-1]))break;o--}if(o===n.length)return r;return n.slice(0,o).join(" ")+n.slice(o).join("")},$i=(r,n,o={})=>{if(o.trim!==!1&&r.trim()==="")return"";let i="",e,t,a=r.split(" "),s=[""],c=0;for(let g=0;g<a.length;g++){let u=a[g];if(o.trim!==!1){let d=s.at(-1)??"",b=d.trimStart();if(d.length!==b.length)s[s.length-1]=b,c=x(b)}if(g!==0){if(c>=n&&(o.wordWrap===!1||o.trim===!1))s.push(""),c=0;if(c||o.trim===!1)s[s.length-1]+=" ",c++}let h=x(u);if(o.hard&&h>n){let d=n-c,b=1+Math.floor((h-d-1)/n);if(Math.floor((h-1)/n)<b)s.push("");tn(s,u,n),c=x(s.at(-1)??"");continue}if(c+h>n&&c&&h){if(o.wordWrap===!1&&c<n){tn(s,u,n),c=x(s.at(-1)??"");continue}s.push(""),c=0}if(c+h>n&&o.wordWrap===!1){tn(s,u,n),c=x(s.at(-1)??"");continue}s[s.length-1]+=u,c+=h}if(o.trim!==!1)s=s.map((g)=>wi(g));let f=s.join(`
4
- `),l=!1;for(let g=0;g<f.length;g++){let u=f[g];if(i+=u,!l){if(l=u>="\uD800"&&u<="\uDBFF",l)continue}else l=!1;if(u===Lr||u===Tn){On.lastIndex=g+1;let d=On.exec(f)?.groups;if(d?.code!==void 0){let b=Number.parseFloat(d.code);e=b===bi?void 0:b}else if(d?.uri!==void 0)t=d.uri.length===0?void 0:d.uri}if(f[g+1]===`
5
- `){if(t)i+=_n("");let h=e?Sn(e):void 0;if(e&&h)i+=Bn(h)}else if(u===`
6
- `){if(e&&Sn(e))i+=Bn(e);if(t)i+=_n(t)}}return i},Pi=/\r?\n/;function O(r,n,o){return String(r).normalize().split(Pi).map((i)=>$i(i,n,o)).join(`
7
- `)}var W=Jn(fn(),1);import{ReadStream as io}from"tty";function _(r,n,o){if(!o.some((a)=>!a.disabled))return r;let i=r+n,e=Math.max(o.length-1,0),t=i<0?e:i>e?0:i;return o[t]?.disabled?_(t,n<0?-1:1,o):t}function Rr(r,n,o,i){let e=i.split(`
8
- `),t=0,a=r;for(let c of e){if(a<=c.length)break;a-=c.length+1,t++}for(t=Math.max(0,Math.min(e.length-1,t+o)),a=Math.min(a,e[t].length)+n;a<0&&t>0;)t--,a+=e[t].length+1;for(;a>e[t].length&&t<e.length-1;)a-=e[t].length+1,t++;a=Math.max(0,Math.min(e[t].length,a));let s=0;for(let c=0;c<t;c++)s+=e[c].length+1;return s+a}var yi=["up","down","left","right","space","enter","cancel"],Ii=["January","February","March","April","May","June","July","August","September","October","November","December"],N={actions:new Set(yi),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:[...Ii],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(r,n)=>`There are only ${r} days in ${n}`,afterMin:(r)=>`Date must be on or after ${r.toISOString().slice(0,10)}`,beforeMax:(r)=>`Date must be on or before ${r.toISOString().slice(0,10)}`}}};function ln(r,n){if(typeof r=="string")return N.aliases.get(r)===n;for(let o of r)if(o!==void 0&&ln(o,n))return!0;return!1}function Li(r,n){if(r===n)return;let o=r.split(`
9
- `),i=n.split(`
10
- `),e=Math.max(o.length,i.length),t=[];for(let a=0;a<e;a++)o[a]!==i[a]&&t.push(a);return{lines:t,numLinesBefore:o.length,numLinesAfter:i.length,numLines:e}}var Ri=globalThis.process.platform.startsWith("win"),un=Symbol("clack:cancel");function lr(r){return r===un}function Dr(r,n){let o=r;o.isTTY&&o.setRawMode(n)}function so({input:r=ao,output:n=dn,overwrite:o=!0,hideCursor:i=!0}={}){let e=or.createInterface({input:r,output:n,prompt:"",tabSize:1});or.emitKeypressEvents(r,e),r instanceof io&&r.isTTY&&r.setRawMode(!0);let t=(a,{name:s,sequence:c})=>{let f=String(a);if(ln([f,s,c],"cancel")){i&&n.write(W.cursor.show),process.exit(0);return}if(!o)return;or.moveCursor(n,s==="return"?0:-1,s==="return"?-1:0,()=>{or.clearLine(n,1,()=>{r.once("keypress",t)})})};return i&&n.write(W.cursor.hide),r.once("keypress",t),()=>{r.off("keypress",t),i&&n.write(W.cursor.show),r instanceof io&&r.isTTY&&!Ri&&r.setRawMode(!1),e.terminal=!1,e.close()}}var gr=(r)=>("columns"in r)&&typeof r.columns=="number"?r.columns:80,gn=(r)=>("rows"in r)&&typeof r.rows=="number"?r.rows:20;function ir(r,n,o,i=o,e=o,t){let a=gr(r??dn);return O(n,a-o.length,{hard:!0,trim:!1}).split(`
11
- `).map((s,c,f)=>{let l=t?t(s,c):s;return c===0?`${i}${l}`:c===f.length-1?`${e}${l}`:`${o}${l}`}).join(`
12
- `)}function co(r,n){if("~standard"in r){let o=r["~standard"].validate(n);if(o instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return o.issues?.at(0)?.message}return r(n)}class T{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(r,n=!0){let{input:o=ao,output:i=dn,render:e,signal:t,...a}=r;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=e.bind(this),this._track=n,this._abortSignal=t,this.input=o,this.output=i}unsubscribe(){this._subscribers.clear()}setSubscriber(r,n){let o=this._subscribers.get(r)??[];o.push(n),this._subscribers.set(r,o)}on(r,n){this.setSubscriber(r,{cb:n})}once(r,n){this.setSubscriber(r,{cb:n,once:!0})}emit(r,...n){let o=this._subscribers.get(r)??[],i=[];for(let e of o)e.cb(...n),e.once&&i.push(()=>o.splice(o.indexOf(e),1));for(let e of i)e()}prompt(){return new Promise((r)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),r(un);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=ki.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),Dr(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(W.cursor.show),this.output.off("resize",this.render),Dr(this.input,!1),r(this.value)}),this.once("cancel",()=>{this.output.write(W.cursor.show),this.output.off("resize",this.render),Dr(this.input,!1),r(un)})})}_isActionKey(r,n){return r==="\t"}_shouldSubmit(r,n){return!0}_setValue(r){this.value=r,this.emit("value",this.value)}_setUserInput(r,n){this.userInput=r??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(r,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(r,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&N.aliases.has(n.name)&&this.emit("cursor",N.aliases.get(n.name)),N.actions.has(n.name)&&this.emit("cursor",n.name)),r&&(r.toLowerCase()==="y"||r.toLowerCase()==="n")&&this.emit("confirm",r.toLowerCase()==="y"),this.emit("key",r,n),n?.name==="return"&&this._shouldSubmit(r,n)){if(this.opts.validate){let o=co(this.opts.validate,this.value);o&&(this.error=o instanceof Error?o.message:o,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}ln([r,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
13
- `),Dr(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let r=O(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
14
- `).length-1;this.output.write(W.cursor.move(-999,r*-1))}render(){let r=O(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(r!==this._prevFrame){if(this.state==="initial")this.output.write(W.cursor.hide);else{let n=Li(this._prevFrame,r),o=gn(this.output);if(this.restoreCursor(),n){let i=Math.max(0,n.numLinesAfter-o),e=Math.max(0,n.numLinesBefore-o),t=n.lines.find((a)=>a>=i);if(t===void 0){this._prevFrame=r;return}if(n.lines.length===1){this.output.write(W.cursor.move(0,t-e)),this.output.write(W.erase.lines(1));let a=r.split(`
15
- `);this.output.write(a[t]),this._prevFrame=r,this.output.write(W.cursor.move(0,a.length-t-1));return}else if(n.lines.length>1){if(i<e)t=i;else{let s=t-e;s>0&&this.output.write(W.cursor.move(0,s))}this.output.write(W.erase.down());let a=r.split(`
3
+ var Ro=Object.create;var{getPrototypeOf:Lo,defineProperty:Tn,getOwnPropertyNames:Do}=Object;var Io=Object.prototype.hasOwnProperty;function Eo(r){return this[r]}var Ho,Uo,re=(r,n,e)=>{var o=r!=null&&typeof r==="object";if(o){var i=n?Ho??=new WeakMap:Uo??=new WeakMap,t=i.get(r);if(t)return t}e=r!=null?Ro(Lo(r)):{};let a=n||!r||!r.__esModule?Tn(e,"default",{value:r,enumerable:!0}):e;for(let s of Do(r))if(!Io.call(a,s))Tn(a,s,{get:Eo.bind(r,s),enumerable:!0});if(o)i.set(r,a);return a};var No=(r,n)=>()=>(n||r((n={exports:{}}).exports,n),n.exports);var Cn=No((St,ge)=>{var wn={to(r,n){if(!n)return`\x1B[${r+1}G`;return`\x1B[${n+1};${r+1}H`},move(r,n){let e="";if(r<0)e+=`\x1B[${-r}D`;else if(r>0)e+=`\x1B[${r}C`;if(n<0)e+=`\x1B[${-n}A`;else if(n>0)e+=`\x1B[${n}B`;return e},up:(r=1)=>`\x1B[${r}A`,down:(r=1)=>`\x1B[${r}B`,forward:(r=1)=>`\x1B[${r}C`,backward:(r=1)=>`\x1B[${r}D`,nextLine:(r=1)=>"\x1B[E".repeat(r),prevLine:(r=1)=>"\x1B[F".repeat(r),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Oo={up:(r=1)=>"\x1B[S".repeat(r),down:(r=1)=>"\x1B[T".repeat(r)},Xo={screen:"\x1B[2J",up:(r=1)=>"\x1B[1J".repeat(r),down:(r=1)=>"\x1B[J".repeat(r),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(r){let n="";for(let e=0;e<r;e++)n+=this.line+(e<r-1?wn.up():"");if(r)n+=wn.left;return n}};ge.exports={cursor:wn,scroll:Oo,erase:Xo,beep:"\x07"}});class O extends Error{constructor(r="Operation cancelled"){super(r)}}class w extends Error{hint;constructor(r,n){super(r);this.hint=n}}import{styleText as Mr}from"util";import{stdout as Fn,stdin as we}from"process";import*as er from"readline";import Vo from"readline";var ne=(()=>{let r=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(n)=>{let e=0;r.lastIndex=0;while(r.test(n))e+=1;return n.length-e}})(),ee=(r)=>{return r===12288||r>=65281&&r<=65376||r>=65504&&r<=65510},oe=(r)=>{return r===8987||r===9001||r>=12272&&r<=12287||r>=12289&&r<=12350||r>=12441&&r<=12543||r>=12549&&r<=12591||r>=12593&&r<=12686||r>=12688&&r<=12771||r>=12783&&r<=12830||r>=12832&&r<=12871||r>=12880&&r<=19903||r>=65040&&r<=65049||r>=65072&&r<=65106||r>=65108&&r<=65126||r>=65128&&r<=65131||r>=127488&&r<=127490||r>=127504&&r<=127547||r>=127552&&r<=127560||r>=131072&&r<=196605||r>=196608&&r<=262141};var jo=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Ao=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ie=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Mo=/\t{1,1000}/y,te=/[\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,Go=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,xo=/\p{M}+/gu,qo={limit:1/0,ellipsis:""},ae=(r,n={},e={})=>{let o=n.limit??1/0,i=n.ellipsis??"",t=n?.ellipsisWidth??(i?ae(i,qo,e).width:0),a=0,s=e.controlWidth??0,c=e.tabWidth??8,f=e.emojiWidth??2,d=2,g=e.regularWidth??1,p=e.wideWidth??2,h=[[Go,g],[jo,0],[Ao,s],[Mo,c],[te,f],[ie,p]],l=0,b=0,F=r.length,I=0,y=!1,A=F,E=Math.max(0,o-t),P=0,j=0,H=0,L=0;r:while(!0){if(j>P||b>=F&&b>l){let N=r.slice(P,j)||r.slice(l,b);I=0;for(let X of N.replaceAll(xo,"")){let W=X.codePointAt(0)||0;if(ee(W))L=2;else if(oe(W))L=p;else L=g;if(H+L>E)A=Math.min(A,Math.max(P,l)+I);if(H+L>o){y=!0;break r}I+=X.length,H+=L}P=j=0}if(b>=F)break r;for(let N=0,X=h.length;N<X;N++){let[W,Er]=h[N];if(W.lastIndex=b,W.test(r)){if(I=W===ie?ne(r.slice(b,W.lastIndex)):W===te?1:W.lastIndex-b,L=I*Er,H+L>E)A=Math.min(A,b+Math.floor((E-H)/Er));if(H+L>o){y=!0;break r}H+=L,P=l,j=b,b=l=W.lastIndex;continue r}}b+=1}return{width:y?E:H,index:y?A:F,truncated:y,ellipsed:y&&o>=t}},se=ae;var zo={limit:1/0,ellipsis:"",ellipsisWidth:0},Wo=(r,n={})=>{return se(r,zo,n).width},J=Wo;var Ur="\x1B",me="\x9B",Jo=39,bn="\x07",le="[",Yo="]",de="m",vn=`${Yo}8;;`,ce=new RegExp(`(?:\\${le}(?<code>\\d+)m|\\${vn}(?<uri>.*)${bn})`,"y"),fe=(r)=>{if(r>=30&&r<=37)return 39;if(r>=90&&r<=97)return 39;if(r>=40&&r<=47)return 49;if(r>=100&&r<=107)return 49;if(r===1||r===2)return 22;if(r===3)return 23;if(r===4)return 24;if(r===7)return 27;if(r===8)return 28;if(r===9)return 29;if(r===0)return 0;return},ue=(r)=>`${Ur}${le}${r}${de}`,pe=(r)=>`${Ur}${vn}${r}${bn}`,hn=(r,n,e)=>{let o=n[Symbol.iterator](),i=!1,t=!1,a=r.at(-1),s=a===void 0?0:J(a),c=o.next(),f=o.next(),d=0;while(!c.done){let g=c.value,p=J(g);if(s+p<=e)r[r.length-1]+=g;else r.push(g),s=0;if(g===Ur||g===me)i=!0,t=n.startsWith(vn,d+1);if(i){if(t){if(g===bn)i=!1,t=!1}else if(g===de)i=!1}else if(s+=p,s===e&&!f.done)r.push(""),s=0;c=f,f=o.next(),d+=g.length}if(a=r.at(-1),!s&&a!==void 0&&a.length&&r.length>1)r[r.length-2]+=r.pop()},Ko=(r)=>{let n=r.split(" "),e=n.length;while(e){if(J(n[e-1]))break;e--}if(e===n.length)return r;return n.slice(0,e).join(" ")+n.slice(e).join("")},Zo=(r,n,e={})=>{if(e.trim!==!1&&r.trim()==="")return"";let o="",i,t,a=r.split(" "),s=[""],c=0;for(let g=0;g<a.length;g++){let p=a[g];if(e.trim!==!1){let l=s.at(-1)??"",b=l.trimStart();if(l.length!==b.length)s[s.length-1]=b,c=J(b)}if(g!==0){if(c>=n&&(e.wordWrap===!1||e.trim===!1))s.push(""),c=0;if(c||e.trim===!1)s[s.length-1]+=" ",c++}let h=J(p);if(e.hard&&h>n){let l=n-c,b=1+Math.floor((h-l-1)/n);if(Math.floor((h-1)/n)<b)s.push("");hn(s,p,n),c=J(s.at(-1)??"");continue}if(c+h>n&&c&&h){if(e.wordWrap===!1&&c<n){hn(s,p,n),c=J(s.at(-1)??"");continue}s.push(""),c=0}if(c+h>n&&e.wordWrap===!1){hn(s,p,n),c=J(s.at(-1)??"");continue}s[s.length-1]+=p,c+=h}if(e.trim!==!1)s=s.map((g)=>Ko(g));let f=s.join(`
4
+ `),d=!1;for(let g=0;g<f.length;g++){let p=f[g];if(o+=p,!d){if(d=p>="\uD800"&&p<="\uDBFF",d)continue}else d=!1;if(p===Ur||p===me){ce.lastIndex=g+1;let l=ce.exec(f)?.groups;if(l?.code!==void 0){let b=Number.parseFloat(l.code);i=b===Jo?void 0:b}else if(l?.uri!==void 0)t=l.uri.length===0?void 0:l.uri}if(f[g+1]===`
5
+ `){if(t)o+=pe("");let h=i?fe(i):void 0;if(i&&h)o+=ue(h)}else if(p===`
6
+ `){if(i&&fe(i))o+=ue(i);if(t)o+=pe(t)}}return o},Qo=/\r?\n/;function V(r,n,e){return String(r).normalize().split(Qo).map((o)=>Zo(o,n,e)).join(`
7
+ `)}var q=re(Cn(),1);import{ReadStream as he}from"tty";function _(r,n,e){if(!e.some((a)=>!a.disabled))return r;let o=r+n,i=Math.max(e.length-1,0),t=o<0?i:o>i?0:o;return e[t]?.disabled?_(t,n<0?-1:1,e):t}function Nr(r,n,e,o){let i=o.split(`
8
+ `),t=0,a=r;for(let c of i){if(a<=c.length)break;a-=c.length+1,t++}for(t=Math.max(0,Math.min(i.length-1,t+e)),a=Math.min(a,i[t].length)+n;a<0&&t>0;)t--,a+=i[t].length+1;for(;a>i[t].length&&t<i.length-1;)a-=i[t].length+1,t++;a=Math.max(0,Math.min(i[t].length,a));let s=0;for(let c=0;c<t;c++)s+=i[c].length+1;return s+a}var So=["up","down","left","right","space","enter","cancel"],Bo=["January","February","March","April","May","June","July","August","September","October","November","December"],M={actions:new Set(So),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:[...Bo],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(r,n)=>`There are only ${r} days in ${n}`,afterMin:(r)=>`Date must be on or after ${r.toISOString().slice(0,10)}`,beforeMax:(r)=>`Date must be on or before ${r.toISOString().slice(0,10)}`}}};function kn(r,n){if(typeof r=="string")return M.aliases.get(r)===n;for(let e of r)if(e!==void 0&&kn(e,n))return!0;return!1}function _o(r,n){if(r===n)return;let e=r.split(`
9
+ `),o=n.split(`
10
+ `),i=Math.max(e.length,o.length),t=[];for(let a=0;a<i;a++)e[a]!==o[a]&&t.push(a);return{lines:t,numLinesBefore:e.length,numLinesAfter:o.length,numLines:i}}var To=globalThis.process.platform.startsWith("win"),yn=Symbol("clack:cancel");function vr(r){return r===yn}function jr(r,n){let e=r;e.isTTY&&e.setRawMode(n)}function Ce({input:r=we,output:n=Fn,overwrite:e=!0,hideCursor:o=!0}={}){let i=er.createInterface({input:r,output:n,prompt:"",tabSize:1});er.emitKeypressEvents(r,i),r instanceof he&&r.isTTY&&r.setRawMode(!0);let t=(a,{name:s,sequence:c})=>{let f=String(a);if(kn([f,s,c],"cancel")){o&&n.write(q.cursor.show),process.exit(0);return}if(!e)return;er.moveCursor(n,s==="return"?0:-1,s==="return"?-1:0,()=>{er.clearLine(n,1,()=>{r.once("keypress",t)})})};return o&&n.write(q.cursor.hide),r.once("keypress",t),()=>{r.off("keypress",t),o&&n.write(q.cursor.show),r instanceof he&&r.isTTY&&!To&&r.setRawMode(!1),i.terminal=!1,i.close()}}var wr=(r)=>("columns"in r)&&typeof r.columns=="number"?r.columns:80,Rn=(r)=>("rows"in r)&&typeof r.rows=="number"?r.rows:20;function or(r,n,e,o=e,i=e,t){let a=wr(r??Fn);return V(n,a-e.length,{hard:!0,trim:!1}).split(`
11
+ `).map((s,c,f)=>{let d=t?t(s,c):s;return c===0?`${o}${d}`:c===f.length-1?`${i}${d}`:`${e}${d}`}).join(`
12
+ `)}function $e(r,n){if("~standard"in r){let e=r["~standard"].validate(n);if(e instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return e.issues?.at(0)?.message}return r(n)}class T{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(r,n=!0){let{input:e=we,output:o=Fn,render:i,signal:t,...a}=r;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=n,this._abortSignal=t,this.input=e,this.output=o}unsubscribe(){this._subscribers.clear()}setSubscriber(r,n){let e=this._subscribers.get(r)??[];e.push(n),this._subscribers.set(r,e)}on(r,n){this.setSubscriber(r,{cb:n})}once(r,n){this.setSubscriber(r,{cb:n,once:!0})}emit(r,...n){let e=this._subscribers.get(r)??[],o=[];for(let i of e)i.cb(...n),i.once&&o.push(()=>e.splice(e.indexOf(i),1));for(let i of o)i()}prompt(){return new Promise((r)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),r(yn);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Vo.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),jr(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(q.cursor.show),this.output.off("resize",this.render),jr(this.input,!1),r(this.value)}),this.once("cancel",()=>{this.output.write(q.cursor.show),this.output.off("resize",this.render),jr(this.input,!1),r(yn)})})}_isActionKey(r,n){return r==="\t"}_shouldSubmit(r,n){return!0}_setValue(r){this.value=r,this.emit("value",this.value)}_setUserInput(r,n){this.userInput=r??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(r,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(r,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&M.aliases.has(n.name)&&this.emit("cursor",M.aliases.get(n.name)),M.actions.has(n.name)&&this.emit("cursor",n.name)),r&&(r.toLowerCase()==="y"||r.toLowerCase()==="n")&&this.emit("confirm",r.toLowerCase()==="y"),this.emit("key",r,n),n?.name==="return"&&this._shouldSubmit(r,n)){if(this.opts.validate){let e=$e(this.opts.validate,this.value);e&&(this.error=e instanceof Error?e.message:e,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}kn([r,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
13
+ `),jr(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let r=V(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
14
+ `).length-1;this.output.write(q.cursor.move(-999,r*-1))}render(){let r=V(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(r!==this._prevFrame){if(this.state==="initial")this.output.write(q.cursor.hide);else{let n=_o(this._prevFrame,r),e=Rn(this.output);if(this.restoreCursor(),n){let o=Math.max(0,n.numLinesAfter-e),i=Math.max(0,n.numLinesBefore-e),t=n.lines.find((a)=>a>=o);if(t===void 0){this._prevFrame=r;return}if(n.lines.length===1){this.output.write(q.cursor.move(0,t-i)),this.output.write(q.erase.lines(1));let a=r.split(`
15
+ `);this.output.write(a[t]),this._prevFrame=r,this.output.write(q.cursor.move(0,a.length-t-1));return}else if(n.lines.length>1){if(o<i)t=o;else{let s=t-i;s>0&&this.output.write(q.cursor.move(0,s))}this.output.write(q.erase.down());let a=r.split(`
16
16
  `).slice(t);this.output.write(a.join(`
17
- `)),this._prevFrame=r;return}}this.output.write(W.erase.down())}this.output.write(r),this.state==="initial"&&(this.state="active"),this._prevFrame=r}}}function Di(r,n){if(r===void 0||n.length===0)return 0;let o=n.findIndex((i)=>i.value===r);return o!==-1?o:0}function Hi(r,n){return(n.label??String(n.value)).toLowerCase().includes(r.toLowerCase())}function ji(r,n){if(n)return r?n:n[0]}var Ei=class extends T{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#e="";#r;#t;#s;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return jr(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let n=this.userInput.slice(0,this.cursor),o=this.userInput.slice(this.cursor,this.cursor+1),i=this.userInput.slice(this.cursor+1);return`${n}${jr("inverse",o)}${i}`}get options(){return typeof this.#t=="function"?this.#t():this.#t}constructor(n){super(n),this.#t=n.options,this.#s=n.placeholder;let o=this.options;this.filteredOptions=[...o],this.multiple=n.multiple===!0,this.#r=typeof n.options=="function"?n.filter:n.filter??Hi;let i;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?i=n.initialValue:i=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(i=[this.options[0]?.value]),i)for(let e of i){let t=o.findIndex((a)=>a.value===e);t!==-1&&(this.toggleSelected(e),this.#n=t)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(e,t)=>this.#o(e,t)),this.on("userInput",(e)=>this.#i(e))}_isActionKey(n,o){return n==="\t"||this.multiple&&this.isNavigating&&o.name==="space"&&n!==void 0&&n!==""}#o(n,o){let i=o.name==="up",e=o.name==="down",t=o.name==="return",a=this.userInput===""||this.userInput==="\t",s=this.#s,c=this.options,f=s!==void 0&&s!==""&&c.some((l)=>!l.disabled&&(this.#r?this.#r(s,l):!0));if(o.name==="tab"&&a&&f){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(s,!0),this.isNavigating=!1;return}i||e?(this.#n=_(this.#n,i?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):t?this.value=ji(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(o.name==="tab"||this.isNavigating&&o.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(n){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(n)?this.selectedValues=this.selectedValues.filter((o)=>o!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#i(n){if(n!==this.#e){this.#e=n;let o=this.options;n&&this.#r?this.filteredOptions=o.filter((t)=>this.#r?.(n,t)):this.filteredOptions=[...o];let i=Di(this.focusedValue,this.filteredOptions);this.#n=_(i,0,this.filteredOptions);let e=this.filteredOptions[this.#n];e&&!e.disabled?this.focusedValue=e.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class hn extends T{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(r){super(r,!1),this.value=!!r.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(n)=>{this.output.write(W.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var Mi={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function eo(r){return[...r].map((n)=>Mi[n])}function Ui(r){let n=new Intl.DateTimeFormat(r,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),o=[],i="/";for(let e of n)e.type==="literal"?i=e.value.trim()||e.value:(e.type==="year"||e.type==="month"||e.type==="day")&&o.push({type:e.type,len:e.type==="year"?4:2});return{segments:o,separator:i}}function mn(r){return Number.parseInt((r||"0").replace(/_/g,"0"),10)||0}function Hr(r){return{year:mn(r.year),month:mn(r.month),day:mn(r.day)}}function pn(r,n){return new Date(r||2001,n||1,0).getDate()}function fo(r){let{year:n,month:o,day:i}=Hr(r);if(!n||n<0||n>9999||!o||o<1||o>12||!i||i<1)return;let e=new Date(Date.UTC(n,o-1,i));if(!(e.getUTCFullYear()!==n||e.getUTCMonth()!==o-1||e.getUTCDate()!==i))return{year:n,month:o,day:i}}function to(r){let n=fo(r);return n?new Date(Date.UTC(n.year,n.month-1,n.day)):void 0}function Gi(r,n,o,i){let e=o?{year:o.getUTCFullYear(),month:o.getUTCMonth()+1,day:o.getUTCDate()}:null,t=i?{year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate()}:null;return r==="year"?{min:e?.year??1,max:t?.year??9999}:r==="month"?{min:e&&n.year===e.year?e.month:1,max:t&&n.year===t.year?t.month:12}:{min:e&&n.year===e.year&&n.month===e.month?e.day:1,max:t&&n.year===t.year&&n.month===t.month?t.day:pn(n.year,n.month)}}class mo extends T{#n;#e;#r;#t;#s;#o={segmentIndex:0,positionInSegment:0};#i=!0;#a=null;inlineError="";get segmentCursor(){return{...this.#o}}get segmentValues(){return{...this.#r}}get segments(){return this.#n}get separator(){return this.#e}get formattedValue(){return this.#u(this.#r)}#u(r){return this.#n.map((n)=>r[n.type]).join(this.#e)}#c(){this._setUserInput(this.#u(this.#r)),this._setValue(to(this.#r)??void 0)}constructor(r){let n=r.format?{segments:eo(r.format),separator:r.separator??"/"}:Ui(r.locale),o=r.separator??n.separator,i=r.format?eo(r.format):n.segments,e=r.initialValue??r.defaultValue,t=e?{year:String(e.getUTCFullYear()).padStart(4,"0"),month:String(e.getUTCMonth()+1).padStart(2,"0"),day:String(e.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},a=i.map((s)=>t[s.type]).join(o);super({...r,initialUserInput:a},!1),this.#n=i,this.#e=o,this.#r=t,this.#t=r.minDate,this.#s=r.maxDate,this.#c(),this.on("cursor",(s)=>this.#l(s)),this.on("key",(s,c)=>this.#g(s,c)),this.on("finalize",()=>this.#h(r))}#f(){let r=Math.max(0,Math.min(this.#o.segmentIndex,this.#n.length-1)),n=this.#n[r];if(n)return this.#o.positionInSegment=Math.max(0,Math.min(this.#o.positionInSegment,n.len-1)),{segment:n,index:r}}#m(r){this.inlineError="",this.#a=null;let n=this.#f();n&&(this.#o.segmentIndex=Math.max(0,Math.min(this.#n.length-1,n.index+r)),this.#o.positionInSegment=0,this.#i=!0)}#p(r){let n=this.#f();if(!n)return;let{segment:o}=n,i=this.#r[o.type],e=!i||i.replace(/_/g,"")==="",t=Number.parseInt((i||"0").replace(/_/g,"0"),10)||0,a=Gi(o.type,Hr(this.#r),this.#t,this.#s),s;e?s=r===1?a.min:a.max:s=Math.max(Math.min(a.max,t+r),a.min),this.#r={...this.#r,[o.type]:s.toString().padStart(o.len,"0")},this.#i=!0,this.#a=null,this.#c()}#l(r){if(r)switch(r){case"right":return this.#m(1);case"left":return this.#m(-1);case"up":return this.#p(1);case"down":return this.#p(-1)}}#g(r,n){if(n?.name==="backspace"||n?.sequence==="\x7F"||n?.sequence==="\b"||r==="\x7F"||r==="\b"){this.inlineError="";let o=this.#f();if(!o)return;if(!this.#r[o.segment.type].replace(/_/g,"")){this.#m(-1);return}this.#r[o.segment.type]="_".repeat(o.segment.len),this.#i=!0,this.#o.positionInSegment=0,this.#c();return}if(n?.name==="tab"){this.inlineError="";let o=this.#f();if(!o)return;let i=n.shift?-1:1,e=o.index+i;e>=0&&e<this.#n.length&&(this.#o.segmentIndex=e,this.#o.positionInSegment=0,this.#i=!0);return}if(r&&/^[0-9]$/.test(r)){let o=this.#f();if(!o)return;let{segment:i}=o,e=!this.#r[i.type].replace(/_/g,"");if(this.#i&&this.#a!==null&&!e){let u=this.#a+r,h={...this.#r,[i.type]:u},d=this.#d(h,i);if(d){this.inlineError=d,this.#a=null,this.#i=!1;return}this.inlineError="",this.#r[i.type]=u,this.#a=null,this.#i=!1,this.#c(),o.index<this.#n.length-1&&(this.#o.segmentIndex=o.index+1,this.#o.positionInSegment=0,this.#i=!0);return}this.#i&&!e&&(this.#r[i.type]="_".repeat(i.len),this.#o.positionInSegment=0),this.#i=!1,this.#a=null;let t=this.#r[i.type],a=t.indexOf("_"),s=a>=0?a:Math.min(this.#o.positionInSegment,i.len-1);if(s<0||s>=i.len)return;let c=t.slice(0,s)+r+t.slice(s+1),f=!1;if(s===0&&t==="__"&&(i.type==="month"||i.type==="day")){let u=Number.parseInt(r,10);c=`0${r}`,f=u<=(i.type==="month"?1:2)}if(i.type==="year"&&(c=(t.replace(/_/g,"")+r).padStart(i.len,"_")),!c.includes("_")){let u={...this.#r,[i.type]:c},h=this.#d(u,i);if(h){this.inlineError=h;return}}this.inlineError="",this.#r[i.type]=c;let l=c.includes("_")?void 0:fo(this.#r);if(l){let{year:u,month:h}=l,d=pn(u,h);this.#r={year:String(Math.max(0,Math.min(9999,u))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,h))).padStart(2,"0"),day:String(Math.max(1,Math.min(d,l.day))).padStart(2,"0")}}this.#c();let g=c.indexOf("_");f?(this.#i=!0,this.#a=r):g>=0?this.#o.positionInSegment=g:a>=0&&o.index<this.#n.length-1?(this.#o.segmentIndex=o.index+1,this.#o.positionInSegment=0,this.#i=!0):this.#o.positionInSegment=Math.min(s+1,i.len-1)}}#d(r,n){let{month:o,day:i}=Hr(r);if(n.type==="month"&&(o<0||o>12))return N.date.messages.invalidMonth;if(n.type==="day"&&(i<0||i>31))return N.date.messages.invalidDay(31,"any month")}#h(r){let{year:n,month:o,day:i}=Hr(this.#r);if(n&&o&&i){let e=pn(n,o);this.#r={...this.#r,day:String(Math.min(i,e)).padStart(2,"0")}}this.value=to(this.#r)??r.defaultValue??void 0}}var Ni=class extends T{options;cursor=0;#n;getGroupItems(n){return this.options.filter((o)=>o.group===n)}isGroupSelected(n){let o=this.getGroupItems(n),i=this.value;return i===void 0?!1:o.every((e)=>i.includes(e.value))}toggleValue(){let n=this.options[this.cursor];if(n!==void 0)if(this.value===void 0&&(this.value=[]),n.group===!0){let o=n.value,i=this.getGroupItems(o);this.isGroupSelected(o)?this.value=this.value.filter((e)=>i.findIndex((t)=>t.value===e)===-1):this.value=[...this.value,...i.map((e)=>e.value)],this.value=Array.from(new Set(this.value))}else{let o=this.value.includes(n.value);this.value=o?this.value.filter((i)=>i!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:o}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(o).flatMap(([i,e])=>[{value:i,group:!0,label:i},...e.map((t)=>({...t,group:i}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:i})=>i===n.cursorAt),this.#n?0:1),this.on("cursor",(i)=>{switch(i){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let e=this.options[this.cursor]?.group===!0;!this.#n&&e&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let e=this.options[this.cursor]?.group===!0;!this.#n&&e&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},qi=new Set(["up","down","left","right"]);class uo extends T{#n=!1;#e;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let r=this.userInput;if(this.cursor>=r.length)return`${r}\u2588`;let n=r.slice(0,this.cursor),o=r.slice(this.cursor,this.cursor+1),i=r.slice(this.cursor+1);return o===`
17
+ `)),this._prevFrame=r;return}}this.output.write(q.erase.down())}this.output.write(r),this.state==="initial"&&(this.state="active"),this._prevFrame=r}}}function ri(r,n){if(r===void 0||n.length===0)return 0;let e=n.findIndex((o)=>o.value===r);return e!==-1?e:0}function ni(r,n){return(n.label??String(n.value)).toLowerCase().includes(r.toLowerCase())}function ei(r,n){if(n)return r?n:n[0]}var oi=class extends T{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#i="";#r;#t;#s;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return Mr(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let n=this.userInput.slice(0,this.cursor),e=this.userInput.slice(this.cursor,this.cursor+1),o=this.userInput.slice(this.cursor+1);return`${n}${Mr("inverse",e)}${o}`}get options(){return typeof this.#t=="function"?this.#t():this.#t}constructor(n){super(n),this.#t=n.options,this.#s=n.placeholder;let e=this.options;this.filteredOptions=[...e],this.multiple=n.multiple===!0,this.#r=typeof n.options=="function"?n.filter:n.filter??ni;let o;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?o=n.initialValue:o=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(o=[this.options[0]?.value]),o)for(let i of o){let t=e.findIndex((a)=>a.value===i);t!==-1&&(this.toggleSelected(i),this.#n=t)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(i,t)=>this.#e(i,t)),this.on("userInput",(i)=>this.#o(i))}_isActionKey(n,e){return n==="\t"||this.multiple&&this.isNavigating&&e.name==="space"&&n!==void 0&&n!==""}#e(n,e){let o=e.name==="up",i=e.name==="down",t=e.name==="return",a=this.userInput===""||this.userInput==="\t",s=this.#s,c=this.options,f=s!==void 0&&s!==""&&c.some((d)=>!d.disabled&&(this.#r?this.#r(s,d):!0));if(e.name==="tab"&&a&&f){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(s,!0),this.isNavigating=!1;return}o||i?(this.#n=_(this.#n,o?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):t?this.value=ei(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(e.name==="tab"||this.isNavigating&&e.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(n){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(n)?this.selectedValues=this.selectedValues.filter((e)=>e!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#o(n){if(n!==this.#i){this.#i=n;let e=this.options;n&&this.#r?this.filteredOptions=e.filter((t)=>this.#r?.(n,t)):this.filteredOptions=[...e];let o=ri(this.focusedValue,this.filteredOptions);this.#n=_(o,0,this.filteredOptions);let i=this.filteredOptions[this.#n];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class Ln extends T{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(r){super(r,!1),this.value=!!r.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(n)=>{this.output.write(q.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var ii={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function be(r){return[...r].map((n)=>ii[n])}function ti(r){let n=new Intl.DateTimeFormat(r,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),e=[],o="/";for(let i of n)i.type==="literal"?o=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&e.push({type:i.type,len:i.type==="year"?4:2});return{segments:e,separator:o}}function $n(r){return Number.parseInt((r||"0").replace(/_/g,"0"),10)||0}function Ar(r){return{year:$n(r.year),month:$n(r.month),day:$n(r.day)}}function Pn(r,n){return new Date(r||2001,n||1,0).getDate()}function ye(r){let{year:n,month:e,day:o}=Ar(r);if(!n||n<0||n>9999||!e||e<1||e>12||!o||o<1)return;let i=new Date(Date.UTC(n,e-1,o));if(!(i.getUTCFullYear()!==n||i.getUTCMonth()!==e-1||i.getUTCDate()!==o))return{year:n,month:e,day:o}}function ve(r){let n=ye(r);return n?new Date(Date.UTC(n.year,n.month-1,n.day)):void 0}function ai(r,n,e,o){let i=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}:null,t=o?{year:o.getUTCFullYear(),month:o.getUTCMonth()+1,day:o.getUTCDate()}:null;return r==="year"?{min:i?.year??1,max:t?.year??9999}:r==="month"?{min:i&&n.year===i.year?i.month:1,max:t&&n.year===t.year?t.month:12}:{min:i&&n.year===i.year&&n.month===i.month?i.day:1,max:t&&n.year===t.year&&n.month===t.month?t.day:Pn(n.year,n.month)}}class Pe extends T{#n;#i;#r;#t;#s;#e={segmentIndex:0,positionInSegment:0};#o=!0;#a=null;inlineError="";get segmentCursor(){return{...this.#e}}get segmentValues(){return{...this.#r}}get segments(){return this.#n}get separator(){return this.#i}get formattedValue(){return this.#p(this.#r)}#p(r){return this.#n.map((n)=>r[n.type]).join(this.#i)}#c(){this._setUserInput(this.#p(this.#r)),this._setValue(ve(this.#r)??void 0)}constructor(r){let n=r.format?{segments:be(r.format),separator:r.separator??"/"}:ti(r.locale),e=r.separator??n.separator,o=r.format?be(r.format):n.segments,i=r.initialValue??r.defaultValue,t=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},a=o.map((s)=>t[s.type]).join(e);super({...r,initialUserInput:a},!1),this.#n=o,this.#i=e,this.#r=t,this.#t=r.minDate,this.#s=r.maxDate,this.#c(),this.on("cursor",(s)=>this.#d(s)),this.on("key",(s,c)=>this.#g(s,c)),this.on("finalize",()=>this.#h(r))}#f(){let r=Math.max(0,Math.min(this.#e.segmentIndex,this.#n.length-1)),n=this.#n[r];if(n)return this.#e.positionInSegment=Math.max(0,Math.min(this.#e.positionInSegment,n.len-1)),{segment:n,index:r}}#u(r){this.inlineError="",this.#a=null;let n=this.#f();n&&(this.#e.segmentIndex=Math.max(0,Math.min(this.#n.length-1,n.index+r)),this.#e.positionInSegment=0,this.#o=!0)}#m(r){let n=this.#f();if(!n)return;let{segment:e}=n,o=this.#r[e.type],i=!o||o.replace(/_/g,"")==="",t=Number.parseInt((o||"0").replace(/_/g,"0"),10)||0,a=ai(e.type,Ar(this.#r),this.#t,this.#s),s;i?s=r===1?a.min:a.max:s=Math.max(Math.min(a.max,t+r),a.min),this.#r={...this.#r,[e.type]:s.toString().padStart(e.len,"0")},this.#o=!0,this.#a=null,this.#c()}#d(r){if(r)switch(r){case"right":return this.#u(1);case"left":return this.#u(-1);case"up":return this.#m(1);case"down":return this.#m(-1)}}#g(r,n){if(n?.name==="backspace"||n?.sequence==="\x7F"||n?.sequence==="\b"||r==="\x7F"||r==="\b"){this.inlineError="";let e=this.#f();if(!e)return;if(!this.#r[e.segment.type].replace(/_/g,"")){this.#u(-1);return}this.#r[e.segment.type]="_".repeat(e.segment.len),this.#o=!0,this.#e.positionInSegment=0,this.#c();return}if(n?.name==="tab"){this.inlineError="";let e=this.#f();if(!e)return;let o=n.shift?-1:1,i=e.index+o;i>=0&&i<this.#n.length&&(this.#e.segmentIndex=i,this.#e.positionInSegment=0,this.#o=!0);return}if(r&&/^[0-9]$/.test(r)){let e=this.#f();if(!e)return;let{segment:o}=e,i=!this.#r[o.type].replace(/_/g,"");if(this.#o&&this.#a!==null&&!i){let p=this.#a+r,h={...this.#r,[o.type]:p},l=this.#l(h,o);if(l){this.inlineError=l,this.#a=null,this.#o=!1;return}this.inlineError="",this.#r[o.type]=p,this.#a=null,this.#o=!1,this.#c(),e.index<this.#n.length-1&&(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#o=!0);return}this.#o&&!i&&(this.#r[o.type]="_".repeat(o.len),this.#e.positionInSegment=0),this.#o=!1,this.#a=null;let t=this.#r[o.type],a=t.indexOf("_"),s=a>=0?a:Math.min(this.#e.positionInSegment,o.len-1);if(s<0||s>=o.len)return;let c=t.slice(0,s)+r+t.slice(s+1),f=!1;if(s===0&&t==="__"&&(o.type==="month"||o.type==="day")){let p=Number.parseInt(r,10);c=`0${r}`,f=p<=(o.type==="month"?1:2)}if(o.type==="year"&&(c=(t.replace(/_/g,"")+r).padStart(o.len,"_")),!c.includes("_")){let p={...this.#r,[o.type]:c},h=this.#l(p,o);if(h){this.inlineError=h;return}}this.inlineError="",this.#r[o.type]=c;let d=c.includes("_")?void 0:ye(this.#r);if(d){let{year:p,month:h}=d,l=Pn(p,h);this.#r={year:String(Math.max(0,Math.min(9999,p))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,h))).padStart(2,"0"),day:String(Math.max(1,Math.min(l,d.day))).padStart(2,"0")}}this.#c();let g=c.indexOf("_");f?(this.#o=!0,this.#a=r):g>=0?this.#e.positionInSegment=g:a>=0&&e.index<this.#n.length-1?(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#o=!0):this.#e.positionInSegment=Math.min(s+1,o.len-1)}}#l(r,n){let{month:e,day:o}=Ar(r);if(n.type==="month"&&(e<0||e>12))return M.date.messages.invalidMonth;if(n.type==="day"&&(o<0||o>31))return M.date.messages.invalidDay(31,"any month")}#h(r){let{year:n,month:e,day:o}=Ar(this.#r);if(n&&e&&o){let i=Pn(n,e);this.#r={...this.#r,day:String(Math.min(o,i)).padStart(2,"0")}}this.value=ve(this.#r)??r.defaultValue??void 0}}var si=class extends T{options;cursor=0;#n;getGroupItems(n){return this.options.filter((e)=>e.group===n)}isGroupSelected(n){let e=this.getGroupItems(n),o=this.value;return o===void 0?!1:e.every((i)=>o.includes(i.value))}toggleValue(){let n=this.options[this.cursor];if(n!==void 0)if(this.value===void 0&&(this.value=[]),n.group===!0){let e=n.value,o=this.getGroupItems(e);this.isGroupSelected(e)?this.value=this.value.filter((i)=>o.findIndex((t)=>t.value===i)===-1):this.value=[...this.value,...o.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let e=this.value.includes(n.value);this.value=e?this.value.filter((o)=>o!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:e}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(e).flatMap(([o,i])=>[{value:o,group:!0,label:o},...i.map((t)=>({...t,group:o}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:o})=>o===n.cursorAt),this.#n?0:1),this.on("cursor",(o)=>{switch(o){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},ci=new Set(["up","down","left","right"]);class Fe extends T{#n=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let r=this.userInput;if(this.cursor>=r.length)return`${r}\u2588`;let n=r.slice(0,this.cursor),e=r.slice(this.cursor,this.cursor+1),o=r.slice(this.cursor+1);return e===`
18
18
  `?`${n}\u2588
19
- ${i}`:`${n}${jr("inverse",o)}${i}`}get cursor(){return this._cursor}#r(r){if(this.userInput.length===0){this._setUserInput(r);return}this._setUserInput(this.userInput.slice(0,this.cursor)+r+this.userInput.slice(this.cursor))}#t(r){let n=this.value??"";switch(r){case"up":this._cursor=Rr(this._cursor,0,-1,n);return;case"down":this._cursor=Rr(this._cursor,0,1,n);return;case"left":this._cursor=Rr(this._cursor,-1,0,n);return;case"right":this._cursor=Rr(this._cursor,1,0,n);return}}_shouldSubmit(r,n){if(this.#e)return this.focused==="submit"?!0:(this.#r(`
20
- `),this._cursor++,!1);let o=this.#n;return this.#n=!0,o&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
19
+ ${o}`:`${n}${Mr("inverse",e)}${o}`}get cursor(){return this._cursor}#r(r){if(this.userInput.length===0){this._setUserInput(r);return}this._setUserInput(this.userInput.slice(0,this.cursor)+r+this.userInput.slice(this.cursor))}#t(r){let n=this.value??"";switch(r){case"up":this._cursor=Nr(this._cursor,0,-1,n);return;case"down":this._cursor=Nr(this._cursor,0,1,n);return;case"left":this._cursor=Nr(this._cursor,-1,0,n);return;case"right":this._cursor=Nr(this._cursor,1,0,n);return}}_shouldSubmit(r,n){if(this.#i)return this.focused==="submit"?!0:(this.#r(`
20
+ `),this._cursor++,!1);let e=this.#n;return this.#n=!0,e&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
21
21
  `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#r(`
22
- `),this._cursor++,!1)}constructor(r){let n=r.initialUserInput??r.initialValue;super({...r,initialUserInput:n},!1),n!==void 0&&(this._cursor=n.length),this.#e=r.showSubmit??!1,this.on("key",(o,i)=>{if(i?.name&&qi.has(i.name)){this.#n=!1,this.#t(i.name);return}if(o==="\t"&&this.#e){this.focused=this.focused==="editor"?"submit":"editor";return}if(i?.name!=="return"){if(this.#n=!1,i?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(i?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}o&&(this.#e&&this.focused==="submit"&&(this.focused="editor"),this.#r(o??""),this._cursor++)}}),this.on("userInput",(o)=>{this._setValue(o)}),this.on("finalize",()=>{this.value||(this.value=r.defaultValue),this.value===void 0&&(this.value="")})}}class bn extends T{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((r)=>r.disabled!==!0)}toggleAll(){let r=this._enabledOptions,n=this.value!==void 0&&this.value.length===r.length;this.value=n?[]:r.map((o)=>o.value)}toggleInvert(){let r=this.value;if(!r)return;let n=this._enabledOptions.filter((o)=>!r.includes(o.value));this.value=n.map((o)=>o.value)}toggleValue(){this.value===void 0&&(this.value=[]);let r=this.value.includes(this._value);this.value=r?this.value.filter((n)=>n!==this._value):[...this.value,this._value]}constructor(r){super(r,!1),this.options=r.options,this.value=[...r.initialValues??[]];let n=Math.max(this.options.findIndex(({value:o})=>o===r.cursorAt),0);this.cursor=this.options[n]?.disabled?_(n,1,this.options):n,this.on("key",(o,i)=>{i.name==="a"&&this.toggleAll(),i.name==="i"&&this.toggleInvert()}),this.on("cursor",(o)=>{switch(o){case"left":case"up":this.cursor=_(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=_(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var po=class extends T{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let n=this._selectedValue;this.value=n===void 0?void 0:n.value}constructor(n){super(n,!1),this.options=n.options;let o=this.options.findIndex(({value:e})=>e===n.initialValue),i=o===-1?0:o;this.cursor=this.options[i]?.disabled?_(i,1,this.options):i,this.changeValue(),this.on("cursor",(e)=>{switch(e){case"left":case"up":this.cursor=_(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=_(this.cursor,1,this.options);break}this.changeValue()})}};class vn extends T{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let r=this.userInput;if(this.cursor>=r.length)return`${this.userInput}\u2588`;let n=r.slice(0,this.cursor),o=r.slice(this.cursor,this.cursor+1),i=r.slice(this.cursor+1);return`${n}${jr("inverse",o)}${i}`}get cursor(){return this._cursor}constructor(r){super({...r,initialUserInput:r.initialUserInput??r.initialValue}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=r.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as m,stripVTControlCharacters as Pt}from"util";import Z from"process";var br=Jn(fn(),1);function zi(){if(Z.platform!=="win32")return Z.env.TERM!=="linux";return Boolean(Z.env.CI)||Boolean(Z.env.WT_SESSION)||Boolean(Z.env.TERMINUS_SUBLIME)||Z.env.ConEmuTask==="{cmd::Cmder}"||Z.env.TERM_PROGRAM==="Terminus-Sublime"||Z.env.TERM_PROGRAM==="vscode"||Z.env.TERM==="xterm-256color"||Z.env.TERM==="alacritty"||Z.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var wn=zi(),Wi=()=>process.env.CI==="true";var y=(r,n)=>wn?r:n,Ai=y("\u25C6","*"),vo=y("\u25A0","x"),wo=y("\u25B2","x"),Ur=y("\u25C7","o"),Ji=y("\u250C","T"),P=y("\u2502","|"),er=y("\u2514","\u2014"),yt=y("\u2510","T"),It=y("\u2518","\u2014"),$n=y("\u25CF",">"),Mr=y("\u25CB"," "),xi=y("\u25FB","[\u2022]"),lo=y("\u25FC","[+]"),go=y("\u25FB","[ ]"),Lt=y("\u25AA","\u2022"),ho=y("\u2500","-"),Ki=y("\u256E","+"),Yi=y("\u251C","+"),Zi=y("\u256F","+"),Qi=y("\u2570","+"),Rt=y("\u256D","+"),Xi=y("\u25CF","\u2022"),Vi=y("\u25C6","*"),Oi=y("\u25B2","!"),Si=y("\u25A0","x"),Gr=(r)=>{switch(r){case"initial":case"active":return m("cyan",Ai);case"cancel":return m("red",vo);case"error":return m("yellow",wo);case"submit":return m("green",Ur)}},$o=(r)=>{switch(r){case"initial":case"active":return m("cyan",P);case"cancel":return m("red",P);case"error":return m("yellow",P);case"submit":return m("green",P)}};function Po(r,n){let o=[`${n?`${m("cyan",P)} `:""}${r.join(" \u2022 ")}`];return n&&o.push(m("cyan",er)),o}var bo=(r,n,o,i,e,t=!1)=>{let a=n,s=0;if(t)for(let c=i-1;c>=o;c--){let f=r[c];if(f&&(a-=f.length),s++,a<=e)break}else for(let c=o;c<i;c++){let f=r[c];if(f&&(a-=f.length),s++,a<=e)break}return{lineCount:a,removals:s}},Pn=({cursor:r,options:n,style:o,output:i=process.stdout,maxItems:e=Number.POSITIVE_INFINITY,columnPadding:t=0,rowPadding:a=4})=>{let s=gr(i)-t,c=gn(i),f=m("dim","..."),l=Math.max(c-a,0),g=Math.max(Math.min(e,l),5),u=0;r>=g-3&&(u=Math.max(Math.min(r-g+3,n.length-g),0));let h=g<n.length&&u>0,d=g<n.length&&u+g<n.length,b=Math.min(u+g,n.length),k=[],D=0;h&&D++,d&&D++;let C=u+(h?1:0),G=b-(d?1:0);for(let F=C;F<G;F++){let U=n[F],j=U?o(U,F===r):"",I=O(j,s,{hard:!0,trim:!1}).split(`
23
- `);k.push(I),D+=I.length}if(D>l){let F=0,U=0,j=D,I=r-C,M=l,V=()=>bo(k,j,0,I,M),J=()=>bo(k,j,I+1,k.length,M,!0);h?({lineCount:j,removals:F}=V(),j>M&&(d||(M-=1),{lineCount:j,removals:U}=J())):(d||(M-=1),{lineCount:j,removals:U}=J(),j>M&&(M-=1,{lineCount:j,removals:F}=V())),F>0&&(h=!0,k.splice(0,F)),U>0&&(d=!0,k.splice(k.length-U,U))}let H=[];h&&H.push(f);for(let F of k)for(let U of F)H.push(U);return d&&H.push(f),H};var Co=(r)=>{let n=r.active??"Yes",o=r.inactive??"No";return new hn({active:n,inactive:o,signal:r.signal,input:r.input,output:r.output,initialValue:r.initialValue??!0,render(){let i=r.withGuide??N.withGuide,e=`${Gr(this.state)} `,t=i?`${m("gray",P)} `:"",a=ir(r.output,r.message,t,e),s=`${i?`${m("gray",P)}
22
+ `),this._cursor++,!1)}constructor(r){let n=r.initialUserInput??r.initialValue;super({...r,initialUserInput:n},!1),n!==void 0&&(this._cursor=n.length),this.#i=r.showSubmit??!1,this.on("key",(e,o)=>{if(o?.name&&ci.has(o.name)){this.#n=!1,this.#t(o.name);return}if(e==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(o?.name!=="return"){if(this.#n=!1,o?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(o?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}e&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#r(e??""),this._cursor++)}}),this.on("userInput",(e)=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=r.defaultValue),this.value===void 0&&(this.value="")})}}class Dn extends T{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((r)=>r.disabled!==!0)}toggleAll(){let r=this._enabledOptions,n=this.value!==void 0&&this.value.length===r.length;this.value=n?[]:r.map((e)=>e.value)}toggleInvert(){let r=this.value;if(!r)return;let n=this._enabledOptions.filter((e)=>!r.includes(e.value));this.value=n.map((e)=>e.value)}toggleValue(){this.value===void 0&&(this.value=[]);let r=this.value.includes(this._value);this.value=r?this.value.filter((n)=>n!==this._value):[...this.value,this._value]}constructor(r){super(r,!1),this.options=r.options,this.value=[...r.initialValues??[]];let n=Math.max(this.options.findIndex(({value:e})=>e===r.cursorAt),0);this.cursor=this.options[n]?.disabled?_(n,1,this.options):n,this.on("key",(e,o)=>{o.name==="a"&&this.toggleAll(),o.name==="i"&&this.toggleInvert()}),this.on("cursor",(e)=>{switch(e){case"left":case"up":this.cursor=_(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=_(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var ke=class extends T{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let n=this._selectedValue;this.value=n===void 0?void 0:n.value}constructor(n){super(n,!1),this.options=n.options;let e=this.options.findIndex(({value:i})=>i===n.initialValue),o=e===-1?0:e;this.cursor=this.options[o]?.disabled?_(o,1,this.options):o,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=_(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=_(this.cursor,1,this.options);break}this.changeValue()})}};class In extends T{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let r=this.userInput;if(this.cursor>=r.length)return`${this.userInput}\u2588`;let n=r.slice(0,this.cursor),e=r.slice(this.cursor,this.cursor+1),o=r.slice(this.cursor+1);return`${n}${Mr("inverse",e)}${o}`}get cursor(){return this._cursor}constructor(r){super({...r,initialUserInput:r.initialUserInput??r.initialValue}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=r.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as u,stripVTControlCharacters as ca}from"util";import Z from"process";var $r=re(Cn(),1);function fi(){if(Z.platform!=="win32")return Z.env.TERM!=="linux";return Boolean(Z.env.CI)||Boolean(Z.env.WT_SESSION)||Boolean(Z.env.TERMINUS_SUBLIME)||Z.env.ConEmuTask==="{cmd::Cmder}"||Z.env.TERM_PROGRAM==="Terminus-Sublime"||Z.env.TERM_PROGRAM==="vscode"||Z.env.TERM==="xterm-256color"||Z.env.TERM==="alacritty"||Z.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var En=fi(),ui=()=>process.env.CI==="true";var k=(r,n)=>En?r:n,pi=k("\u25C6","*"),Ee=k("\u25A0","x"),He=k("\u25B2","x"),qr=k("\u25C7","o"),mi=k("\u250C","T"),$=k("\u2502","|"),ir=k("\u2514","\u2014"),ma=k("\u2510","T"),la=k("\u2518","\u2014"),Hn=k("\u25CF",">"),xr=k("\u25CB"," "),li=k("\u25FB","[\u2022]"),Re=k("\u25FC","[+]"),Le=k("\u25FB","[ ]"),da=k("\u25AA","\u2022"),De=k("\u2500","-"),di=k("\u256E","+"),gi=k("\u251C","+"),hi=k("\u256F","+"),bi=k("\u2570","+"),ga=k("\u256D","+"),vi=k("\u25CF","\u2022"),wi=k("\u25C6","*"),Ci=k("\u25B2","!"),$i=k("\u25A0","x"),zr=(r)=>{switch(r){case"initial":case"active":return u("cyan",pi);case"cancel":return u("red",Ee);case"error":return u("yellow",He);case"submit":return u("green",qr)}},Ue=(r)=>{switch(r){case"initial":case"active":return u("cyan",$);case"cancel":return u("red",$);case"error":return u("yellow",$);case"submit":return u("green",$)}};function Ne(r,n){let e=[`${n?`${u("cyan",$)} `:""}${r.join(" \u2022 ")}`];return n&&e.push(u("cyan",ir)),e}var Ie=(r,n,e,o,i,t=!1)=>{let a=n,s=0;if(t)for(let c=o-1;c>=e;c--){let f=r[c];if(f&&(a-=f.length),s++,a<=i)break}else for(let c=e;c<o;c++){let f=r[c];if(f&&(a-=f.length),s++,a<=i)break}return{lineCount:a,removals:s}},Un=({cursor:r,options:n,style:e,output:o=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:t=0,rowPadding:a=4})=>{let s=wr(o)-t,c=Rn(o),f=u("dim","..."),d=Math.max(c-a,0),g=Math.max(Math.min(i,d),5),p=0;r>=g-3&&(p=Math.max(Math.min(r-g+3,n.length-g),0));let h=g<n.length&&p>0,l=g<n.length&&p+g<n.length,b=Math.min(p+g,n.length),F=[],I=0;h&&I++,l&&I++;let y=p+(h?1:0),A=b-(l?1:0);for(let P=y;P<A;P++){let j=n[P],H=j?e(j,P===r):"",L=V(H,s,{hard:!0,trim:!1}).split(`
23
+ `);F.push(L),I+=L.length}if(I>d){let P=0,j=0,H=I,L=r-y,N=d,X=()=>Ie(F,H,0,L,N),W=()=>Ie(F,H,L+1,F.length,N,!0);h?({lineCount:H,removals:P}=X(),H>N&&(l||(N-=1),{lineCount:H,removals:j}=W())):(l||(N-=1),{lineCount:H,removals:j}=W(),H>N&&(N-=1,{lineCount:H,removals:P}=X())),P>0&&(h=!0,F.splice(0,P)),j>0&&(l=!0,F.splice(F.length-j,j))}let E=[];h&&E.push(f);for(let P of F)for(let j of P)E.push(j);return l&&E.push(f),E};var je=(r)=>{let n=r.active??"Yes",e=r.inactive??"No";return new Ln({active:n,inactive:e,signal:r.signal,input:r.input,output:r.output,initialValue:r.initialValue??!0,render(){let o=r.withGuide??M.withGuide,i=`${zr(this.state)} `,t=o?`${u("gray",$)} `:"",a=or(r.output,r.message,t,i),s=`${o?`${u("gray",$)}
24
24
  `:""}${a}
25
- `,c=this.value?n:o;switch(this.state){case"submit":{let f=i?`${m("gray",P)} `:"";return`${s}${f}${m("dim",c)}`}case"cancel":{let f=i?`${m("gray",P)} `:"";return`${s}${f}${m(["strikethrough","dim"],c)}${i?`
26
- ${m("gray",P)}`:""}`}default:{let f=i?`${m("cyan",P)} `:"",l=i?m("cyan",er):"";return`${s}${f}${this.value?`${m("green",$n)} ${n}`:`${m("dim",Mr)} ${m("dim",n)}`}${r.vertical?i?`
27
- ${m("cyan",P)} `:`
28
- `:` ${m("dim","/")} `}${this.value?`${m("dim",Mr)} ${m("dim",o)}`:`${m("green",$n)} ${o}`}
29
- ${l}
30
- `}}}}).prompt()};var Nr=async(r,n)=>{let o={},i=Object.keys(r);for(let e of i){let t=r[e],a=await t({results:o})?.catch((s)=>{throw s});if(typeof n?.onCancel=="function"&&lr(a)){o[e]="canceled",n.onCancel({results:o});continue}o[e]=a}return o},Bi=[`${m("dim","\u2191/\u2193")} to navigate`,`${m("dim","Space:")} select`,`${m("dim","Enter:")} confirm`],hr=(r,n)=>r.split(`
31
- `).map((o)=>n(o)).join(`
32
- `),Fo=(r)=>{let n=(e,t)=>{let a=e.label??String(e.value);return t==="disabled"?`${m("gray",go)} ${hr(a,(s)=>m(["strikethrough","gray"],s))}${e.hint?` ${m("dim",`(${e.hint??"disabled"})`)}`:""}`:t==="active"?`${m("cyan",xi)} ${a}${e.hint?` ${m("dim",`(${e.hint})`)}`:""}`:t==="selected"?`${m("green",lo)} ${hr(a,(s)=>m("dim",s))}${e.hint?` ${m("dim",`(${e.hint})`)}`:""}`:t==="cancelled"?`${hr(a,(s)=>m(["strikethrough","dim"],s))}`:t==="active-selected"?`${m("green",lo)} ${a}${e.hint?` ${m("dim",`(${e.hint})`)}`:""}`:t==="submitted"?`${hr(a,(s)=>m("dim",s))}`:`${m("dim",go)} ${hr(a,(s)=>m("dim",s))}`},o=r.required??!0,i=r.showInstructions??!0;return new bn({options:r.options,signal:r.signal,input:r.input,output:r.output,initialValues:r.initialValues,required:o,cursorAt:r.cursorAt,validate(e){if(o&&(e===void 0||e.length===0))return`Please select at least one option.
33
- ${m("reset",m("dim",`Press ${m(["gray","bgWhite","inverse"]," space ")} to select, ${m("gray",m("bgWhite",m("inverse"," enter ")))} to submit`))}`},render(){let e=r.withGuide??N.withGuide,t=ir(r.output,r.message,e?`${$o(this.state)} `:"",`${Gr(this.state)} `),a=`${e?`${m("gray",P)}
25
+ `,c=this.value?n:e;switch(this.state){case"submit":{let f=o?`${u("gray",$)} `:"";return`${s}${f}${u("dim",c)}`}case"cancel":{let f=o?`${u("gray",$)} `:"";return`${s}${f}${u(["strikethrough","dim"],c)}${o?`
26
+ ${u("gray",$)}`:""}`}default:{let f=o?`${u("cyan",$)} `:"",d=o?u("cyan",ir):"";return`${s}${f}${this.value?`${u("green",Hn)} ${n}`:`${u("dim",xr)} ${u("dim",n)}`}${r.vertical?o?`
27
+ ${u("cyan",$)} `:`
28
+ `:` ${u("dim","/")} `}${this.value?`${u("dim",xr)} ${u("dim",e)}`:`${u("green",Hn)} ${e}`}
29
+ ${d}
30
+ `}}}}).prompt()};var Wr=async(r,n)=>{let e={},o=Object.keys(r);for(let i of o){let t=r[i],a=await t({results:e})?.catch((s)=>{throw s});if(typeof n?.onCancel=="function"&&vr(a)){e[i]="canceled",n.onCancel({results:e});continue}e[i]=a}return e},yi=[`${u("dim","\u2191/\u2193")} to navigate`,`${u("dim","Space:")} select`,`${u("dim","Enter:")} confirm`],Cr=(r,n)=>r.split(`
31
+ `).map((e)=>n(e)).join(`
32
+ `),Ae=(r)=>{let n=(i,t)=>{let a=i.label??String(i.value);return t==="disabled"?`${u("gray",Le)} ${Cr(a,(s)=>u(["strikethrough","gray"],s))}${i.hint?` ${u("dim",`(${i.hint??"disabled"})`)}`:""}`:t==="active"?`${u("cyan",li)} ${a}${i.hint?` ${u("dim",`(${i.hint})`)}`:""}`:t==="selected"?`${u("green",Re)} ${Cr(a,(s)=>u("dim",s))}${i.hint?` ${u("dim",`(${i.hint})`)}`:""}`:t==="cancelled"?`${Cr(a,(s)=>u(["strikethrough","dim"],s))}`:t==="active-selected"?`${u("green",Re)} ${a}${i.hint?` ${u("dim",`(${i.hint})`)}`:""}`:t==="submitted"?`${Cr(a,(s)=>u("dim",s))}`:`${u("dim",Le)} ${Cr(a,(s)=>u("dim",s))}`},e=r.required??!0,o=r.showInstructions??!0;return new Dn({options:r.options,signal:r.signal,input:r.input,output:r.output,initialValues:r.initialValues,required:e,cursorAt:r.cursorAt,validate(i){if(e&&(i===void 0||i.length===0))return`Please select at least one option.
33
+ ${u("reset",u("dim",`Press ${u(["gray","bgWhite","inverse"]," space ")} to select, ${u("gray",u("bgWhite",u("inverse"," enter ")))} to submit`))}`},render(){let i=r.withGuide??M.withGuide,t=or(r.output,r.message,i?`${Ue(this.state)} `:"",`${zr(this.state)} `),a=`${i?`${u("gray",$)}
34
34
  `:""}${t}
35
- `,s=this.value??[],c=(f,l)=>{if(f.disabled)return n(f,"disabled");let g=s.includes(f.value);return l&&g?n(f,"active-selected"):g?n(f,"selected"):n(f,l?"active":"inactive")};switch(this.state){case"submit":{let f=this.options.filter(({value:g})=>s.includes(g)).map((g)=>n(g,"submitted")).join(m("dim",", "))||m("dim","none"),l=ir(r.output,f,e?`${m("gray",P)} `:"");return`${a}${l}`}case"cancel":{let f=this.options.filter(({value:g})=>s.includes(g)).map((g)=>n(g,"cancelled")).join(m("dim",", "));if(f.trim()==="")return`${a}${m("gray",P)}`;let l=ir(r.output,f,e?`${m("gray",P)} `:"");return`${a}${l}${e?`
36
- ${m("gray",P)}`:""}`}case"error":{let f=e?`${m("yellow",P)} `:"",l=this.error.split(`
37
- `).map((h,d)=>d===0?`${e?`${m("yellow",er)} `:""}${m("yellow",h)}`:` ${h}`).join(`
35
+ `,s=this.value??[],c=(f,d)=>{if(f.disabled)return n(f,"disabled");let g=s.includes(f.value);return d&&g?n(f,"active-selected"):g?n(f,"selected"):n(f,d?"active":"inactive")};switch(this.state){case"submit":{let f=this.options.filter(({value:g})=>s.includes(g)).map((g)=>n(g,"submitted")).join(u("dim",", "))||u("dim","none"),d=or(r.output,f,i?`${u("gray",$)} `:"");return`${a}${d}`}case"cancel":{let f=this.options.filter(({value:g})=>s.includes(g)).map((g)=>n(g,"cancelled")).join(u("dim",", "));if(f.trim()==="")return`${a}${u("gray",$)}`;let d=or(r.output,f,i?`${u("gray",$)} `:"");return`${a}${d}${i?`
36
+ ${u("gray",$)}`:""}`}case"error":{let f=i?`${u("yellow",$)} `:"",d=this.error.split(`
37
+ `).map((h,l)=>l===0?`${i?`${u("yellow",ir)} `:""}${u("yellow",h)}`:` ${h}`).join(`
38
38
  `),g=a.split(`
39
- `).length,u=l.split(`
40
- `).length+1;return`${a}${f}${Pn({output:r.output,options:this.options,cursor:this.cursor,maxItems:r.maxItems,columnPadding:f.length,rowPadding:g+u,style:c}).join(`
39
+ `).length,p=d.split(`
40
+ `).length+1;return`${a}${f}${Un({output:r.output,options:this.options,cursor:this.cursor,maxItems:r.maxItems,columnPadding:f.length,rowPadding:g+p,style:c}).join(`
41
41
  ${f}`)}
42
- ${l}
43
- `}default:{let f=e?`${m("cyan",P)} `:"",l=a.split(`
44
- `).length,g=i?Po(Bi,e):e?[m("cyan",er)]:[],u=g.join(`
45
- `),h=g.length+1;return`${a}${f}${Pn({output:r.output,options:this.options,cursor:this.cursor,maxItems:r.maxItems,columnPadding:f.length,rowPadding:l+h,style:c}).join(`
42
+ ${d}
43
+ `}default:{let f=i?`${u("cyan",$)} `:"",d=a.split(`
44
+ `).length,g=o?Ne(yi,i):i?[u("cyan",ir)]:[],p=g.join(`
45
+ `),h=g.length+1;return`${a}${f}${Un({output:r.output,options:this.options,cursor:this.cursor,maxItems:r.maxItems,columnPadding:f.length,rowPadding:d+h,style:c}).join(`
46
46
  ${f}`)}
47
- ${u}
48
- `}}}}).prompt()};var w={message:(r=[],{symbol:n=m("gray",P),secondarySymbol:o=m("gray",P),output:i=process.stdout,spacing:e=1,withGuide:t}={})=>{let a=[],s=t??N.withGuide,c=s?o:"",f=s?`${n} `:"",l=s?`${o} `:"";for(let u=0;u<e;u++)a.push(c);let g=Array.isArray(r)?r:r.split(`
49
- `);if(g.length>0){let[u,...h]=g;u.length>0?a.push(`${f}${u}`):a.push(s?n:"");for(let d of h)d.length>0?a.push(`${l}${d}`):a.push(s?o:"")}i.write(`${a.join(`
47
+ ${p}
48
+ `}}}}).prompt()};var v={message:(r=[],{symbol:n=u("gray",$),secondarySymbol:e=u("gray",$),output:o=process.stdout,spacing:i=1,withGuide:t}={})=>{let a=[],s=t??M.withGuide,c=s?e:"",f=s?`${n} `:"",d=s?`${e} `:"";for(let p=0;p<i;p++)a.push(c);let g=Array.isArray(r)?r:r.split(`
49
+ `);if(g.length>0){let[p,...h]=g;p.length>0?a.push(`${f}${p}`):a.push(s?n:"");for(let l of h)l.length>0?a.push(`${d}${l}`):a.push(s?e:"")}o.write(`${a.join(`
50
50
  `)}
51
- `)},info:(r,n)=>{w.message(r,{...n,symbol:m("blue",Xi)})},success:(r,n)=>{w.message(r,{...n,symbol:m("green",Vi)})},step:(r,n)=>{w.message(r,{...n,symbol:m("green",Ur)})},warn:(r,n)=>{w.message(r,{...n,symbol:m("yellow",Oi)})},warning:(r,n)=>{w.warn(r,n)},error:(r,n)=>{w.message(r,{...n,symbol:m("red",Si)})}};var qr=(r="",n)=>{let o=n?.output??process.stdout,i=n?.withGuide??N.withGuide?`${m("gray",Ji)} `:"";o.write(`${i}${r}
52
- `)},zr=(r="",n)=>{let o=n?.output??process.stdout,i=n?.withGuide??N.withGuide?`${m("gray",P)}
53
- ${m("gray",er)} `:"";o.write(`${i}${r}
51
+ `)},info:(r,n)=>{v.message(r,{...n,symbol:u("blue",vi)})},success:(r,n)=>{v.message(r,{...n,symbol:u("green",wi)})},step:(r,n)=>{v.message(r,{...n,symbol:u("green",qr)})},warn:(r,n)=>{v.message(r,{...n,symbol:u("yellow",Ci)})},warning:(r,n)=>{v.warn(r,n)},error:(r,n)=>{v.message(r,{...n,symbol:u("red",$i)})}};var Jr=(r="",n)=>{let e=n?.output??process.stdout,o=n?.withGuide??M.withGuide?`${u("gray",mi)} `:"";e.write(`${o}${r}
52
+ `)},Yr=(r="",n)=>{let e=n?.output??process.stdout,o=n?.withGuide??M.withGuide?`${u("gray",$)}
53
+ ${u("gray",ir)} `:"";e.write(`${o}${r}
54
54
 
55
- `)};var _i=(r)=>r,Ti=(r,n,o)=>{let i={hard:!0,trim:!1},e=O(r,n,i).split(`
56
- `),t=e.reduce((c,f)=>Math.max(x(f),c),0),a=e.map(o).reduce((c,f)=>Math.max(x(f),c),0),s=n-(a-t);return O(r,s,i)},cr=(r="",n="",o)=>{let i=o?.output??Z.stdout,e=o?.withGuide??N.withGuide,t=o?.format??_i,a=["",...Ti(r,gr(i)-6,t).split(`
57
- `).map(t),""],s=x(n),c=Math.max(a.reduce((u,h)=>{let d=x(h);return d>u?d:u},0),s)+2,f=a.map((u)=>`${m("gray",P)} ${u}${" ".repeat(c-x(u))}${m("gray",P)}`).join(`
58
- `),l=e?`${m("gray",P)}
59
- `:"",g=e?Yi:Qi;i.write(`${l}${m("green",Ur)} ${m("reset",n)} ${m("gray",ho.repeat(Math.max(c-s-1,1))+Ki)}
55
+ `)};var Pi=(r)=>r,Fi=(r,n,e)=>{let o={hard:!0,trim:!1},i=V(r,n,o).split(`
56
+ `),t=i.reduce((c,f)=>Math.max(J(f),c),0),a=i.map(e).reduce((c,f)=>Math.max(J(f),c),0),s=n-(a-t);return V(r,s,o)},lr=(r="",n="",e)=>{let o=e?.output??Z.stdout,i=e?.withGuide??M.withGuide,t=e?.format??Pi,a=["",...Fi(r,wr(o)-6,t).split(`
57
+ `).map(t),""],s=J(n),c=Math.max(a.reduce((p,h)=>{let l=J(h);return l>p?l:p},0),s)+2,f=a.map((p)=>`${u("gray",$)} ${p}${" ".repeat(c-J(p))}${u("gray",$)}`).join(`
58
+ `),d=i?`${u("gray",$)}
59
+ `:"",g=i?gi:bi;o.write(`${d}${u("green",qr)} ${u("reset",n)} ${u("gray",De.repeat(Math.max(c-s-1,1))+di)}
60
60
  ${f}
61
- ${m("gray",g+ho.repeat(c+2)+Zi)}
62
- `)};var re=(r)=>m("magenta",r),K=({indicator:r="dots",onCancel:n,output:o=process.stdout,cancelMessage:i,errorMessage:e,frames:t=wn?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:a=wn?80:120,signal:s,...c}={})=>{let f=Wi(),l,g,u=!1,h=!1,d="",b,k=performance.now(),D=gr(o),C=c?.styleFrame??re,G=(E)=>{let Y=E>1?e??N.messages.error:i??N.messages.cancel;h=E===1,u&&(dr(Y,E),h&&typeof n=="function"&&n())},H=()=>G(2),F=()=>G(1),U=()=>{process.on("uncaughtExceptionMonitor",H),process.on("unhandledRejection",H),process.on("SIGINT",F),process.on("SIGTERM",F),process.on("exit",G),s&&s.addEventListener("abort",F)},j=()=>{process.removeListener("uncaughtExceptionMonitor",H),process.removeListener("unhandledRejection",H),process.removeListener("SIGINT",F),process.removeListener("SIGTERM",F),process.removeListener("exit",G),s&&s.removeEventListener("abort",F)},I=()=>{if(b===void 0)return;f&&o.write(`
63
- `);let E=O(b,D,{hard:!0,trim:!1}).split(`
64
- `);E.length>1&&o.write(br.cursor.up(E.length-1)),o.write(br.cursor.to(0)),o.write(br.erase.down())},M=(E)=>E.replace(/\.+$/,""),V=(E)=>{let Y=(performance.now()-E)/1000,S=Math.floor(Y/60),B=Math.floor(Y%60);return S>0?`[${S}m ${B}s]`:`[${B}s]`},J=c.withGuide??N.withGuide,yr=(E="")=>{u=!0,l=so({output:o}),d=M(E),k=performance.now(),J&&o.write(`${m("gray",P)}
65
- `);let Y=0,S=0;U(),g=setInterval(()=>{if(f&&d===b)return;I(),b=d;let B=C(t[Y]),Ir;if(f)Ir=`${B} ${d}...`;else if(r==="timer")Ir=`${B} ${d} ${V(k)}`;else{let ri=".".repeat(Math.floor(S)).slice(0,3);Ir=`${B} ${d}${ri}`}let To=O(Ir,D,{hard:!0,trim:!1});o.write(To),Y=Y+1<t.length?Y+1:0,S=S<4?S+0.125:0},a)},dr=(E="",Y=0,S=!1)=>{if(!u)return;u=!1,clearInterval(g),I();let B=Y===0?m("green",Ur):Y===1?m("red",vo):m("red",wo);d=E??d,S||(r==="timer"?o.write(`${B} ${d} ${V(k)}
66
- `):o.write(`${B} ${d}
67
- `)),j(),l()};return{start:yr,stop:(E="")=>dr(E,0),message:(E="")=>{d=M(E??d)},cancel:(E="")=>dr(E,1),error:(E="")=>dr(E,2),clear:()=>dr("",0,!0),get isCancelled(){return h}}},Dt={light:y("\u2500","-"),heavy:y("\u2501","="),block:y("\u2588","#")};var ne=[`${m("dim","\u2191/\u2193")} to navigate`,`${m("dim","Enter:")} confirm`],Er=(r,n)=>r.includes(`
61
+ ${u("gray",g+De.repeat(c+2)+hi)}
62
+ `)};var ki=(r)=>u("magenta",r),Y=({indicator:r="dots",onCancel:n,output:e=process.stdout,cancelMessage:o,errorMessage:i,frames:t=En?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:a=En?80:120,signal:s,...c}={})=>{let f=ui(),d,g,p=!1,h=!1,l="",b,F=performance.now(),I=wr(e),y=c?.styleFrame??ki,A=(U)=>{let K=U>1?i??M.messages.error:o??M.messages.cancel;h=U===1,p&&(br(K,U),h&&typeof n=="function"&&n())},E=()=>A(2),P=()=>A(1),j=()=>{process.on("uncaughtExceptionMonitor",E),process.on("unhandledRejection",E),process.on("SIGINT",P),process.on("SIGTERM",P),process.on("exit",A),s&&s.addEventListener("abort",P)},H=()=>{process.removeListener("uncaughtExceptionMonitor",E),process.removeListener("unhandledRejection",E),process.removeListener("SIGINT",P),process.removeListener("SIGTERM",P),process.removeListener("exit",A),s&&s.removeEventListener("abort",P)},L=()=>{if(b===void 0)return;f&&e.write(`
63
+ `);let U=V(b,I,{hard:!0,trim:!1}).split(`
64
+ `);U.length>1&&e.write($r.cursor.up(U.length-1)),e.write($r.cursor.to(0)),e.write($r.erase.down())},N=(U)=>U.replace(/\.+$/,""),X=(U)=>{let K=(performance.now()-U)/1000,S=Math.floor(K/60),B=Math.floor(K%60);return S>0?`[${S}m ${B}s]`:`[${B}s]`},W=c.withGuide??M.withGuide,Er=(U="")=>{p=!0,d=Ce({output:e}),l=N(U),F=performance.now(),W&&e.write(`${u("gray",$)}
65
+ `);let K=0,S=0;j(),g=setInterval(()=>{if(f&&l===b)return;L(),b=l;let B=y(t[K]),Hr;if(f)Hr=`${B} ${l}...`;else if(r==="timer")Hr=`${B} ${l} ${X(F)}`;else{let ko=".".repeat(Math.floor(S)).slice(0,3);Hr=`${B} ${l}${ko}`}let Fo=V(Hr,I,{hard:!0,trim:!1});e.write(Fo),K=K+1<t.length?K+1:0,S=S<4?S+0.125:0},a)},br=(U="",K=0,S=!1)=>{if(!p)return;p=!1,clearInterval(g),L();let B=K===0?u("green",qr):K===1?u("red",Ee):u("red",He);l=U??l,S||(r==="timer"?e.write(`${B} ${l} ${X(F)}
66
+ `):e.write(`${B} ${l}
67
+ `)),H(),d()};return{start:Er,stop:(U="")=>br(U,0),message:(U="")=>{l=N(U??l)},cancel:(U="")=>br(U,1),error:(U="")=>br(U,2),clear:()=>br("",0,!0),get isCancelled(){return h}}},ha={light:k("\u2500","-"),heavy:k("\u2501","="),block:k("\u2588","#")};var Ri=[`${u("dim","\u2191/\u2193")} to navigate`,`${u("dim","Enter:")} confirm`],Gr=(r,n)=>r.includes(`
68
68
  `)?r.split(`
69
- `).map((o)=>n(o)).join(`
70
- `):n(r),ko=(r)=>{let n=(i,e)=>{if(i===void 0)return"";let t=i.label??String(i.value);switch(e){case"disabled":return`${m("gray",Mr)} ${Er(t,(a)=>m("gray",a))}${i.hint?` ${m("dim",`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${Er(t,(a)=>m("dim",a))}`;case"active":return`${m("green",$n)} ${t}${i.hint?` ${m("dim",`(${i.hint})`)}`:""}`;case"cancelled":return`${Er(t,(a)=>m(["strikethrough","dim"],a))}`;default:return`${m("dim",Mr)} ${Er(t,(a)=>m("dim",a))}`}},o=r.showInstructions??!0;return new po({options:r.options,signal:r.signal,input:r.input,output:r.output,initialValue:r.initialValue,render(){let i=r.withGuide??N.withGuide,e=`${Gr(this.state)} `,t=`${$o(this.state)} `,a=ir(r.output,r.message,t,e),s=`${i?`${m("gray",P)}
69
+ `).map((e)=>n(e)).join(`
70
+ `):n(r),Me=(r)=>{let n=(o,i)=>{if(o===void 0)return"";let t=o.label??String(o.value);switch(i){case"disabled":return`${u("gray",xr)} ${Gr(t,(a)=>u("gray",a))}${o.hint?` ${u("dim",`(${o.hint??"disabled"})`)}`:""}`;case"selected":return`${Gr(t,(a)=>u("dim",a))}`;case"active":return`${u("green",Hn)} ${t}${o.hint?` ${u("dim",`(${o.hint})`)}`:""}`;case"cancelled":return`${Gr(t,(a)=>u(["strikethrough","dim"],a))}`;default:return`${u("dim",xr)} ${Gr(t,(a)=>u("dim",a))}`}},e=r.showInstructions??!0;return new ke({options:r.options,signal:r.signal,input:r.input,output:r.output,initialValue:r.initialValue,render(){let o=r.withGuide??M.withGuide,i=`${zr(this.state)} `,t=`${Ue(this.state)} `,a=or(r.output,r.message,t,i),s=`${o?`${u("gray",$)}
71
71
  `:""}${a}
72
- `;switch(this.state){case"submit":{let c=i?`${m("gray",P)} `:"",f=ir(r.output,n(this.options[this.cursor],"selected"),c);return`${s}${f}`}case"cancel":{let c=i?`${m("gray",P)} `:"",f=ir(r.output,n(this.options[this.cursor],"cancelled"),c);return`${s}${f}${i?`
73
- ${m("gray",P)}`:""}`}default:{let c=i?`${m("cyan",P)} `:"",f=s.split(`
74
- `).length,l=o?Po(ne,i):i?[m("cyan",er)]:[],g=l.join(`
75
- `),u=l.length+1;return`${s}${c}${Pn({output:r.output,cursor:this.cursor,options:this.options,maxItems:r.maxItems,columnPadding:c.length,rowPadding:f+u,style:(h,d)=>n(h,h.disabled?"disabled":d?"active":"inactive")}).join(`
72
+ `;switch(this.state){case"submit":{let c=o?`${u("gray",$)} `:"",f=or(r.output,n(this.options[this.cursor],"selected"),c);return`${s}${f}`}case"cancel":{let c=o?`${u("gray",$)} `:"",f=or(r.output,n(this.options[this.cursor],"cancelled"),c);return`${s}${f}${o?`
73
+ ${u("gray",$)}`:""}`}default:{let c=o?`${u("cyan",$)} `:"",f=s.split(`
74
+ `).length,d=e?Ne(Ri,o):o?[u("cyan",ir)]:[],g=d.join(`
75
+ `),p=d.length+1;return`${s}${c}${Un({output:r.output,cursor:this.cursor,options:this.options,maxItems:r.maxItems,columnPadding:c.length,rowPadding:f+p,style:(h,l)=>n(h,h.disabled?"disabled":l?"active":"inactive")}).join(`
76
76
  ${c}`)}
77
77
  ${g}
78
- `}}}}).prompt()};var Ht=`${m("gray",P)} `;var yo=(r)=>new vn({validate:r.validate,placeholder:r.placeholder,defaultValue:r.defaultValue,initialValue:r.initialValue,output:r.output,signal:r.signal,input:r.input,render(){let n=r?.withGuide??N.withGuide,o=`${`${n?`${m("gray",P)}
79
- `:""}${Gr(this.state)} `}${r.message}
80
- `,i=r.placeholder&&r.placeholder.length>0?m("inverse",r.placeholder[0])+m("dim",r.placeholder.slice(1)):m(["inverse","hidden"],"_"),e=this.userInput?this.userInputWithCursor:i,t=this.value??"";switch(this.state){case"error":{let a=this.error?` ${m("yellow",this.error)}`:"",s=n?`${m("yellow",P)} `:"",c=n?m("yellow",er):"";return`${o.trim()}
81
- ${s}${e}
78
+ `}}}}).prompt()};var ba=`${u("gray",$)} `;var Ge=(r)=>new In({validate:r.validate,placeholder:r.placeholder,defaultValue:r.defaultValue,initialValue:r.initialValue,output:r.output,signal:r.signal,input:r.input,render(){let n=r?.withGuide??M.withGuide,e=`${`${n?`${u("gray",$)}
79
+ `:""}${zr(this.state)} `}${r.message}
80
+ `,o=r.placeholder&&r.placeholder.length>0?u("inverse",r.placeholder[0])+u("dim",r.placeholder.slice(1)):u(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:o,t=this.value??"";switch(this.state){case"error":{let a=this.error?` ${u("yellow",this.error)}`:"",s=n?`${u("yellow",$)} `:"",c=n?u("yellow",ir):"";return`${e.trim()}
81
+ ${s}${i}
82
82
  ${c}${a}
83
- `}case"submit":{let a=t?` ${m("dim",t)}`:"",s=n?m("gray",P):"";return`${o}${s}${a}`}case"cancel":{let a=t?` ${m(["strikethrough","dim"],t)}`:"",s=n?m("gray",P):"";return`${o}${s}${a}${t.trim()?`
84
- ${s}`:""}`}default:{let a=n?`${m("cyan",P)} `:"",s=n?m("cyan",er):"";return`${o}${a}${e}
83
+ `}case"submit":{let a=t?` ${u("dim",t)}`:"",s=n?u("gray",$):"";return`${e}${s}${a}`}case"cancel":{let a=t?` ${u(["strikethrough","dim"],t)}`:"",s=n?u("gray",$):"";return`${e}${s}${a}${t.trim()?`
84
+ ${s}`:""}`}default:{let a=n?`${u("cyan",$)} `:"",s=n?u("cyan",ir):"";return`${e}${a}${i}
85
85
  ${s}
86
- `}}}}).prompt();var ie=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),Ro=["black","blue","cyan","gray","green","magenta","red","white","yellow"],ee=["bold","dim","italic","underline","reset"],Do={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},te={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"},ae={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"},Io={"\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 Wr(r){return(n)=>ie?`${r}${n}${Do.reset}`:n}function se(r){for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);if(o<32&&o!==27)return!1}return!0}function Lo({bright:r=!1,color:n}){let o=Bun.color(n,"ansi"),i=typeof o==="string"&&o.length>0&&se(o)?o:te[n];if(!i)return"";return r&&i in Io?Io[i]:i}var ce=Ro.reduce((r,n)=>{let o=Lo({color:n});if(o)r[n]=Wr(o);let i=Lo({bright:!0,color:n});if(i)r[`${n}Bright`]=Wr(i);return r},{}),fe=ee.reduce((r,n)=>{return r[n]=Wr(Do[n]),r},{}),me=Ro.reduce((r,n)=>{let o=ae[n];if(o){let i=`bg${n.charAt(0).toUpperCase()}${n.slice(1)}`;r[i]=Wr(o)}return r},{}),p={...ce,...fe,...me};function Ar(r){if(lr(r))throw new X;return r}function pe(r){return r.map((n)=>n.key?`${p.bold(n.key)} ${p.dim(n.text)}`:p.dim(n.text)).join(p.dim(" \xB7 "))}function Jr(r){w.info(pe(r))}var xr={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 vr(r){return Jr(xr.confirm),Ar(await Co(r))}async function rr(r){return Jr(xr.text),Ar(await yo(r))}async function tr(r){return Jr(xr.select),Ar(await ko({showInstructions:!1,...r}))}async function ar(r){return Jr(xr.multiselect),Ar(await Fo({showInstructions:!1,...r}))}var $={arg:p.magenta,cmd:p.cyan,default:p.blue,desc:p.white,flag:p.green,header:(r)=>p.bold(p.yellow(r)),hint:p.dim,name:(r)=>p.bold(p.cyan(r)),placeholder:p.magenta};class Cn{metadata;commands;globalArgs;constructor(r,n,o){this.metadata=r;this.commands=n;this.globalArgs=o}version(){return`${$.name(this.metadata.name)} ${$.hint(this.metadata.version??"0.0.0")}`}global(){let r=[],{name:n,bin:o,version:i,description:e}=this.metadata;if(r.push(""),r.push(`${$.name(n)}${i?` ${$.hint(`v${i}`)}`:""}`),e)r.push($.desc(e));r.push(""),r.push($.header("Usage:")),r.push(` ${$.cmd(o)} ${$.placeholder("[command]")} ${$.hint("[options]")}`),r.push(""),r.push($.header("Commands:"));let t=Array.from(this.commands.values()).map((a)=>[` ${$.cmd(a.name)}`,$.desc(a.description)]);return r.push(...this.formatColumns(t)),r.push(""),r.push($.header("Options:")),r.push(...this.formatArgDefs(this.globalArgs)),r.push(""),r.push($.hint(`Run "${o} <command> --help" for command-specific options.`)),r.push(""),r.join(`
87
- `)}command(r,n){let o=[],i=n??this.metadata.bin,e=`${$.cmd(i)} ${$.cmd(r.name)}`;o.push(""),o.push(`${$.name(r.name)} ${$.hint("-")} ${$.desc(r.description)}`),o.push(""),o.push($.header("Usage:"));let t=this.formatPositionalUsage(r.positionals);if(r.hasSubcommands())o.push(` ${e} ${$.placeholder("<subcommand>")} ${$.hint("[options]")}`);else{let c=[e];if(t)c.push(t);c.push($.hint("[options]")),o.push(` ${c.join(" ")}`)}if(r.prompts)o.push(` ${e} ${$.hint("- runs interactively")}`);if(o.push(""),r.hasSubcommands()){o.push($.header("Subcommands:"));let c=r.getSubcommands().map((f)=>[` ${$.cmd(f.name)}`,$.desc(f.description)]);o.push(...this.formatColumns(c)),o.push("")}if(Object.entries(r.positionals).length>0)o.push($.header("Arguments:")),o.push(...this.formatPositionalDefs(r.positionals)),o.push("");if(Object.entries(r.args).length>0)o.push($.header("Options:")),o.push(...this.formatArgDefs(r.args)),o.push("");return o.join(`
88
- `)}formatPositionalUsage(r){return Object.entries(r).map(([n,o])=>{let i=o.variadic?`${n}...`:n;return o.required?$.arg(`<${i}>`):$.arg(`[${i}]`)}).join(" ")}formatPositionalDefs(r){let n=Object.entries(r).map(([o,i])=>{let e=i.variadic?`${o}...`:o,t=$.desc(i.description??""),a=i.required?"":$.hint(" (optional)");return[` ${$.arg(e)}`,`${t}${a}`]});return this.formatColumns(n)}formatArgDefs(r){let n=[];for(let[o,i]of Object.entries(r)){let t=`${i.alias?`${$.flag(`-${i.alias}`)}, `:" "}${$.flag(`--${o}`)}`,a=$.desc(i.description??""),s=i.default!==void 0?$.hint(` (default: ${$.default(this.formatDefault(i))})`):"";n.push([` ${t}`,`${a}${s}`])}return this.formatColumns(n)}formatDefault(r){if(r.type==="string")return`"${r.default}"`;return String(r.default)}formatColumns(r){if(r.length===0)return[];let n=Math.max(...r.map(([i])=>this.stripAnsi(i).length)),o=2;return r.map(([i,e])=>{let t=n-this.stripAnsi(i).length+o;return`${i}${" ".repeat(t)}${e}`})}stripAnsi(r){return r.replace(/\x1b\[[0-9;]*m/g,"")}}var nr=new Uint32Array(65536),de=(r,n)=>{let o=r.length,i=n.length,e=1<<o-1,t=-1,a=0,s=o,c=o;while(c--)nr[r.charCodeAt(c)]|=1<<c;for(c=0;c<i;c++){let f=nr[n.charCodeAt(c)],l=f|a;if(f|=(f&t)+t^t,a|=~(f|t),t&=f,a&e)s++;if(t&e)s--;a=a<<1|1,t=t<<1|~(l|a),a&=l}c=o;while(c--)nr[r.charCodeAt(c)]=0;return s},le=(r,n)=>{let o=n.length,i=r.length,e=[],t=[],a=Math.ceil(o/32),s=Math.ceil(i/32);for(let d=0;d<a;d++)t[d]=-1,e[d]=0;let c=0;for(;c<s-1;c++){let d=0,b=-1,k=c*32,D=Math.min(32,i)+k;for(let C=k;C<D;C++)nr[r.charCodeAt(C)]|=1<<C;for(let C=0;C<o;C++){let G=nr[n.charCodeAt(C)],H=t[C/32|0]>>>C&1,F=e[C/32|0]>>>C&1,U=G|d,j=((G|F)&b)+b^b|G|F,I=d|~(j|b),M=b&j;if(I>>>31^H)t[C/32|0]^=1<<C;if(M>>>31^F)e[C/32|0]^=1<<C;I=I<<1|H,M=M<<1|F,b=M|~(U|I),d=I&U}for(let C=k;C<D;C++)nr[r.charCodeAt(C)]=0}let f=0,l=-1,g=c*32,u=Math.min(32,i-g)+g;for(let d=g;d<u;d++)nr[r.charCodeAt(d)]|=1<<d;let h=i;for(let d=0;d<o;d++){let b=nr[n.charCodeAt(d)],k=t[d/32|0]>>>d&1,D=e[d/32|0]>>>d&1,C=b|f,G=((b|D)&l)+l^l|b|D,H=f|~(G|l),F=l&G;if(h+=H>>>i-1&1,h-=F>>>i-1&1,H>>>31^k)t[d/32|0]^=1<<d;if(F>>>31^D)e[d/32|0]^=1<<d;H=H<<1|k,F=F<<1|D,l=F|~(C|H),f=H&C}for(let d=g;d<u;d++)nr[r.charCodeAt(d)]=0;return h},ge=(r,n)=>{if(r.length<n.length){let o=n;n=r,r=o}if(n.length===0)return r.length;if(r.length<=32)return de(r,n);return le(r,n)},Ho=(r,n)=>{let o=1/0,i=0;for(let e=0;e<n.length;e++){let t=ge(r,n[e]);if(t<o)o=t,i=e}return n[i]};function Kr(r,n,o,i){let e=Ho(n,o);if(console.error(p.red(`Unknown ${r}: ${n}`)),e)console.error(p.yellow(`Did you mean "${e}"?`));console.error(`
89
- Run "${i} --help" for usage.`),process.exit(1)}function wr(r,n){let o=(e)=>e&&typeof e==="object";if(!o(r)||!o(n))return n;let i={...r};for(let e of Object.keys(n)){let t=i[e],a=n[e];if(Array.isArray(t)&&Array.isArray(a))i[e]=[...a];else if(o(t)&&o(a))i[e]=wr(t,a);else i[e]=a}return i}function Fn(r){return r==null?[]:Array.isArray(r)?r:[r]}function he(r,n,o,i){var e,t=r[n],a=~i.string.indexOf(n)?o==null||o===!0?"":String(o):typeof o==="boolean"?o:~i.boolean.indexOf(n)?o==="false"?!1:o==="true"||(r._.push((e=+o,e*0===0)?e:o),!!o):(e=+o,e*0===0)?e:o;r[n]=t==null?a:Array.isArray(t)?t.concat(a):[t,a]}function Yr(r,n){r=r||[],n=n||{};var o,i,e,t,a,s={_:[]},c=0,f=0,l=0,g=r.length;let u=n.alias!==void 0,h=n.unknown!==void 0,d=n.default!==void 0;if(n.alias=n.alias||{},n.string=Fn(n.string),n.boolean=Fn(n.boolean),u)for(o in n.alias){i=n.alias[o]=Fn(n.alias[o]);for(c=0;c<i.length;c++)(n.alias[i[c]]=i.concat(o)).splice(c,1)}for(c=n.boolean.length;c-- >0;){i=n.alias[n.boolean[c]]||[];for(f=i.length;f-- >0;)n.boolean.push(i[f])}for(c=n.string.length;c-- >0;){i=n.alias[n.string[c]]||[];for(f=i.length;f-- >0;)n.string.push(i[f])}if(d){for(o in n.default)if(t=typeof n.default[o],i=n.alias[o]=n.alias[o]||[],n[t]!==void 0){n[t].push(o);for(c=0;c<i.length;c++)n[t].push(i[c])}}let b=h?Object.keys(n.alias):[];for(c=0;c<g;c++){if(e=r[c],e==="--"){s._=s._.concat(r.slice(++c));break}for(f=0;f<e.length;f++)if(e.charCodeAt(f)!==45)break;if(f===0)s._.push(e);else if(e.substring(f,f+3)==="no-"){if(t=e.substring(f+3),h&&!~b.indexOf(t))return n.unknown(e);s[t]=!1}else{for(l=f+1;l<e.length;l++)if(e.charCodeAt(l)===61)break;t=e.substring(f,l),a=e.substring(++l)||(c+1===g||(""+r[c+1]).charCodeAt(0)===45||r[++c]),i=f===2?[t]:t;for(l=0;l<i.length;l++){if(t=i[l],h&&!~b.indexOf(t))return n.unknown("-".repeat(f)+t);he(s,t,l+1<i.length||a,n)}}}if(d){for(o in n.default)if(s[o]===void 0)s[o]=n.default[o]}if(u)for(o in s){i=n.alias[o]||[];while(i.length>0)s[i.shift()]=s[o]}return s}function be(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function jo(r){let n={alias:{},boolean:[],default:{},string:[]};for(let[o,i]of Object.entries(r)){if(i.type==="boolean")n.boolean.push(o);else n.string.push(o);if(i.alias)n.alias[i.alias]=o;let e=be(o);if(e!==o)n.alias[e]=o;if(i.default!==void 0)n.default[o]=i.default}return n}function Eo(r,n){let o={...r};for(let[i,e]of Object.entries(n)){if(e.type!=="number")continue;let t=r[i];if(t===void 0||typeof t==="boolean")continue;let a=Number(t);if(Number.isNaN(a))throw Error(`Invalid number for --${i}: "${t}"`);o[i]=a}return o}function Mo(r,n){let o=jo(n),i=Yr(r,o),e=i._[0],t=e?r.indexOf(e):-1,{_:a,...s}=i,c=Eo(s,n);return{command:e,flags:c,restArgs:t>=0?r.slice(t+1):[]}}function kn(r,n={}){let o=jo(n),i=Yr(r,o),{_:e,...t}=i;return{args:Eo(t,n),rawPositionals:e}}function yn(r,n){let o={},i=Object.entries(n);for(let[e,[t,a]]of i.entries())o[t]=a.variadic?r.slice(e):r[e];return o}function Uo(r,n){for(let[o,i]of Object.entries(n)){if(!i.required)continue;let e=r[o];if(Array.isArray(e)?e.length===0:!e)return`Missing required argument: <${o}${i.variadic?"...":""}>`}return null}var In="__exit__";class fr{command;env;prefix;options;constructor(r,n,o,i={}){this.command=r;this.env=n;this.prefix=o;this.options=i}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(r,n){if(n)await this.routeInteractive();else await this.routeDirect(r)}async routeDirect(r){let[n,...o]=r;if(n&&this.command.hasSubcommands()){let i=this.command.getSubcommand(n);if(i){await this.handleSubcommandRoute(i,o);return}if(!n.startsWith("-")){this.handleUnknownSubcommand(n);return}}await this.executeCommand(r)}handleUnknownSubcommand(r){let n=this.command.getSubcommands().map((o)=>o.name);Kr("subcommand",r,n,this.commandPath)}async handleSubcommandRoute(r,n){await new fr(r,this.env,this.commandPath).route(n,!1)}async executeCommand(r){if(this.isHelpRequest(r)){this.printHelp(this.command);return}if(this.command.hasSubcommands()&&!this.command.execute){this.printHelp(this.command);return}if(!this.command.execute)return;let{args:o,rawPositionals:i}=kn(r,this.command.args),e=yn(i,this.command.positionals),t=Uo(e,this.command.positionals);if(t)w.error(t),console.error(`
90
- Run "${this.commandPath} --help" for usage.`),process.exit(1);let a=this.command.prompts&&i.length===0,s=this.buildContext(e,o,a);await this.command.execute(s)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:r}=kn([],this.command.args),n=yn([],this.command.positionals),o=this.buildContext(n,r,!0);await this.command.execute?.(o)}async runSubcommandMenu(){while(!0){let r=await this.promptSubcommandSelectionOrBack();if(r===null)return;if(r===In){this.options.onExit?.();return}let n=this.command.getSubcommand(r);if(n)await this.executeSubcommand(n)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(r){if(r instanceof X){if(this.options.isRoot)this.options.onExit?.();return null}throw r}}async executeSubcommand(r){try{await new fr(r,this.env,this.commandPath).route([],!0)}catch(n){if(n instanceof X)return;if(n instanceof v){if(w.warn(p.yellow(n.message)),n.hint)w.info(p.dim(n.hint));return}throw n}}promptSubcommandSelection(){let{isRoot:r}=this.options,n=r?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:In}:{hint:"Return to previous menu",label:"Back",value:In};return tr({message:r?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,options:[...this.command.getSubcommands().map((o)=>({hint:o.description,label:o.name,value:o.name})),n]})}buildContext(r,n,o){return{...this.env,args:n,interactive:o,positionals:r}}isHelpRequest(r){return r.includes("--help")||r.includes("-h")}printHelp(r){let n=r===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(r,n))}}var ve={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class Ln{commands=new Map;metadata;configManager;help;bin;globalArgs={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Enable interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};constructor(r,n){this.configManager=r,this.metadata={...ve,...n},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Cn({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(r){for(let n of r)n.init?.(),this.commands.set(n.name,n)}async run(r=process.argv.slice(2)){let{command:n,flags:o,restArgs:i}=Mo(r,this.globalArgs);if(o.version&&!n)return console.log(this.help.version());if(o.interactive&&!n)return this.runInteractive();if(!n)return console.log(this.help.global());if(n==="help")return this.printHelpFor(i[0]);await this.runDirect(n,i,!!o.help)}printHelpFor(r){if(!r)return console.log(this.help.global());let n=this.commands.get(r);if(!n)return this.handleUnknownCommand(r);console.log(this.help.command(n))}async runInteractive(){this.showIntro();let r=this.createVirtualRootCommand(),n={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},o=new fr(r,n,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await o.route([],!0)}catch(i){this.handleError(i)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(r)=>this.commands.get(r),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){zr(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(r,n,o){let i=this.commands.get(r);if(!i)return this.handleUnknownCommand(r);let e=n.length>0&&!n[0]?.startsWith("-");if(o&&!e)return console.log(this.help.command(i));try{let t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new fr(i,t,this.bin).route(n,!1)}catch(t){this.handleError(t)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let r=this.metadata.version?` v${this.metadata.version}`:"";qr(`${p.bgCyan(p.black(` ${this.metadata.name}${r} `))}`)}handleUnknownCommand(r){let n=Array.from(this.commands.keys());Kr("command",r,n,this.bin)}handleError(r){if(this.metadata.onError?.(r))return;if(r instanceof X)process.exit(0);if(r instanceof v){if(w.warn(p.yellow(r.message)),r.hint)w.info(p.dim(r.hint));process.exit(0)}if(r instanceof Error)w.error(p.red(r.message)),process.exit(1);console.error(p.red("Error:"),r),process.exit(1)}}class $r{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(r){for(let n of r)n.init?.(),this.subcommands.set(n.name,n)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(r){return this.subcommands.get(r)}getSubcommands(){return Array.from(this.subcommands.values())}}function mr(r){return r}function q(r){return r}import ur from"fs";import Go from"path";class Rn{config;configPath;defaultConfig;constructor(r,n){this.configPath=Go.resolve(r),this.defaultConfig=n,this.config=this.loadConfig()}get(r){return this.config[r]}set(r,n){this.config[r]=n,this.save()}delete(r){delete this.config[r],this.save()}exists(){return ur.existsSync(this.configPath)}getAll(){return wr({},this.config)}save(r){if(r)this.config={...r};this.ensureDirectoryExists();try{ur.writeFileSync(this.configPath,JSON.stringify(this.config,null,2))}catch(n){console.error(`Failed to save config to ${this.configPath}:`,n)}}ensureDirectoryExists(){let r=Go.dirname(this.configPath);if(!ur.existsSync(r))try{ur.mkdirSync(r,{recursive:!0})}catch(n){console.error(`Failed to create config directory at ${r}:`,n)}}loadConfig(){if(!ur.existsSync(this.configPath))return{...this.defaultConfig};try{let r=ur.readFileSync(this.configPath,"utf-8"),n=JSON.parse(r);return wr({...this.defaultConfig},n)}catch{return console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),{...this.defaultConfig}}}}var No="0.7.0";import{join as Ee}from"path";class L extends $r{}import{existsSync as kr}from"fs";import{cp as Ie,link as Le,mkdir as Un,readdir as Zo,readFile as Gn,readlink as Re,rm as Nn,symlink as De,unlink as Qo,writeFile as He}from"fs/promises";import{join as R,resolve as Xr}from"path";var Zr="hydra";var qo=".hydra/config.json",Pr=".hydra/shared",Cr=".hydra/runners",Fr="default",zo={profiles:{}};var $e=new Set(["github.com","www.github.com"]);var Wo=/\.git$/;function sr(r){let n;try{n=new URL(r)}catch{throw Error(`Invalid GitHub URL: ${r}`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw Error(`Invalid GitHub URL (expected http(s)): ${r}`);if(!$e.has(n.hostname))throw Error(`Invalid GitHub URL (host must be github.com): ${r}`);let o=n.pathname.split("/").filter(Boolean);if(o.length===1){let i=o[0]?.replace(Wo,"");if(!i)throw Error(`Invalid GitHub URL: ${r}`);return{kind:"org",org:i}}if(o.length===2){let i=o[0],e=o[1]?.replace(Wo,"");if(!i||!e)throw Error(`Invalid GitHub URL: ${r}`);return{kind:"repo",owner:i,repo:e}}throw Error(`Invalid GitHub URL (expected github.com/<owner>/<repo> or github.com/<org>): ${r}`)}function Qr(r){return r.kind==="repo"?`${r.owner}/${r.repo}`:r.org}import{existsSync as Pe}from"fs";import{readdir as Ce,stat as Fe}from"fs/promises";import{join as ke}from"path";var Dn="_diag",Ao={runner:/^Runner_.+\.log$/,worker:/^Worker_.+\.log$/},Jo=1024,xo=["B","KB","MB","GB"],ye=1;function Ko(r){if(Ao.worker.test(r))return"worker";if(Ao.runner.test(r))return"runner";return null}function Yo(r){return[...r].sort((n,o)=>o.mtime.getTime()-n.mtime.getTime())}async function Hn(r){if(!Pe(r))return[];let n=await Ce(r,{withFileTypes:!0}),o=[];for(let i of n){if(!i.isFile())continue;let e=Ko(i.name);if(!e)continue;let t=ke(r,i.name),a=await Fe(t);o.push({mtime:a.mtime,name:i.name,path:t,size:a.size,type:e})}return Yo(o)}function jn(r,n){let o=r.find((e)=>e.type===n);if(o)return{fallback:!1,file:o};let i=r[0];return i?{fallback:!0,file:i}:null}function En(r,n){if(n<=0)return"";let o=r.endsWith(`
91
- `)?r.slice(0,-1):r;if(o==="")return"";return o.split(`
86
+ `}}}}).prompt();var Di=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),ze=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Ii=["bold","dim","italic","underline","reset"],We={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Ei={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"},Hi={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"},xe={"\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 Kr(r){return(n)=>Di?`${r}${n}${We.reset}`:n}function Ui(r){for(let n=0;n<r.length;n++){let e=r.charCodeAt(n);if(e<32&&e!==27)return!1}return!0}function qe({bright:r=!1,color:n}){let e=Bun.color(n,"ansi"),o=typeof e==="string"&&e.length>0&&Ui(e)?e:Ei[n];if(!o)return"";return r&&o in xe?xe[o]:o}var Ni=ze.reduce((r,n)=>{let e=qe({color:n});if(e)r[n]=Kr(e);let o=qe({bright:!0,color:n});if(o)r[`${n}Bright`]=Kr(o);return r},{}),ji=Ii.reduce((r,n)=>{return r[n]=Kr(We[n]),r},{}),Ai=ze.reduce((r,n)=>{let e=Hi[n];if(e){let o=`bg${n.charAt(0).toUpperCase()}${n.slice(1)}`;r[o]=Kr(e)}return r},{}),m={...Ni,...ji,...Ai};function Zr(r){if(vr(r))throw new O;return r}function Gi(r){return r.map((n)=>n.key?`${m.bold(n.key)} ${m.dim(n.text)}`:m.dim(n.text)).join(m.dim(" \xB7 "))}function Qr(r){v.info(Gi(r))}var Or={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 sr(r){return Qr(Or.confirm),Zr(await je(r))}async function rr(r){return Qr(Or.text),Zr(await Ge(r))}async function cr(r){return Qr(Or.select),Zr(await Me({showInstructions:!1,...r}))}async function fr(r){return Qr(Or.multiselect),Zr(await Ae({showInstructions:!1,...r}))}var C={arg:m.magenta,cmd:m.cyan,default:m.blue,desc:m.white,flag:m.green,header:(r)=>m.bold(m.yellow(r)),hint:m.dim,name:(r)=>m.bold(m.cyan(r)),placeholder:m.magenta};class Nn{metadata;commands;globalArgs;constructor(r,n,e){this.metadata=r;this.commands=n;this.globalArgs=e}version(){return`${C.name(this.metadata.name)} ${C.hint(this.metadata.version??"0.0.0")}`}global(){let r=[],{name:n,bin:e,version:o,description:i}=this.metadata;if(r.push(""),r.push(`${C.name(n)}${o?` ${C.hint(`v${o}`)}`:""}`),i)r.push(C.desc(i));r.push(""),r.push(C.header("Usage:")),r.push(` ${C.cmd(e)} ${C.placeholder("[command]")} ${C.hint("[options]")}`),r.push(""),r.push(C.header("Commands:"));let t=Array.from(this.commands.values()).map((a)=>[` ${C.cmd(a.name)}`,C.desc(a.description)]);return r.push(...this.formatColumns(t)),r.push(""),r.push(C.header("Options:")),r.push(...this.formatArgDefs(this.globalArgs)),r.push(""),r.push(C.hint(`Run "${e} <command> --help" for command-specific options.`)),r.push(""),r.join(`
87
+ `)}command(r,n){let e=[],o=n??this.metadata.bin,i=`${C.cmd(o)} ${C.cmd(r.name)}`;e.push(""),e.push(`${C.name(r.name)} ${C.hint("-")} ${C.desc(r.description)}`),e.push(""),e.push(C.header("Usage:"));let t=this.formatPositionalUsage(r.positionals);if(r.hasSubcommands())e.push(` ${i} ${C.placeholder("<subcommand>")} ${C.hint("[options]")}`);else{let c=[i];if(t)c.push(t);c.push(C.hint("[options]")),e.push(` ${c.join(" ")}`)}if(r.prompts)e.push(` ${i} ${C.hint("- runs interactively")}`);if(e.push(""),r.hasSubcommands()){e.push(C.header("Subcommands:"));let c=r.getSubcommands().map((f)=>[` ${C.cmd(f.name)}`,C.desc(f.description)]);e.push(...this.formatColumns(c)),e.push("")}if(Object.entries(r.positionals).length>0)e.push(C.header("Arguments:")),e.push(...this.formatPositionalDefs(r.positionals)),e.push("");if(Object.entries(r.args).length>0)e.push(C.header("Options:")),e.push(...this.formatArgDefs(r.args)),e.push("");return e.join(`
88
+ `)}formatPositionalUsage(r){return Object.entries(r).map(([n,e])=>{let o=e.variadic?`${n}...`:n;return e.required?C.arg(`<${o}>`):C.arg(`[${o}]`)}).join(" ")}formatPositionalDefs(r){let n=Object.entries(r).map(([e,o])=>{let i=o.variadic?`${e}...`:e,t=C.desc(o.description??""),a=o.required?"":C.hint(" (optional)");return[` ${C.arg(i)}`,`${t}${a}`]});return this.formatColumns(n)}formatArgDefs(r){let n=[];for(let[e,o]of Object.entries(r)){let t=`${o.alias?`${C.flag(`-${o.alias}`)}, `:" "}${C.flag(`--${e}`)}`,a=C.desc(o.description??""),s=o.default!==void 0?C.hint(` (default: ${C.default(this.formatDefault(o))})`):"";n.push([` ${t}`,`${a}${s}`])}return this.formatColumns(n)}formatDefault(r){if(r.type==="string")return`"${r.default}"`;return String(r.default)}formatColumns(r){if(r.length===0)return[];let n=Math.max(...r.map(([o])=>this.stripAnsi(o).length)),e=2;return r.map(([o,i])=>{let t=n-this.stripAnsi(o).length+e;return`${o}${" ".repeat(t)}${i}`})}stripAnsi(r){return r.replace(/\x1b\[[0-9;]*m/g,"")}}var nr=new Uint32Array(65536),xi=(r,n)=>{let e=r.length,o=n.length,i=1<<e-1,t=-1,a=0,s=e,c=e;while(c--)nr[r.charCodeAt(c)]|=1<<c;for(c=0;c<o;c++){let f=nr[n.charCodeAt(c)],d=f|a;if(f|=(f&t)+t^t,a|=~(f|t),t&=f,a&i)s++;if(t&i)s--;a=a<<1|1,t=t<<1|~(d|a),a&=d}c=e;while(c--)nr[r.charCodeAt(c)]=0;return s},qi=(r,n)=>{let e=n.length,o=r.length,i=[],t=[],a=Math.ceil(e/32),s=Math.ceil(o/32);for(let l=0;l<a;l++)t[l]=-1,i[l]=0;let c=0;for(;c<s-1;c++){let l=0,b=-1,F=c*32,I=Math.min(32,o)+F;for(let y=F;y<I;y++)nr[r.charCodeAt(y)]|=1<<y;for(let y=0;y<e;y++){let A=nr[n.charCodeAt(y)],E=t[y/32|0]>>>y&1,P=i[y/32|0]>>>y&1,j=A|l,H=((A|P)&b)+b^b|A|P,L=l|~(H|b),N=b&H;if(L>>>31^E)t[y/32|0]^=1<<y;if(N>>>31^P)i[y/32|0]^=1<<y;L=L<<1|E,N=N<<1|P,b=N|~(j|L),l=L&j}for(let y=F;y<I;y++)nr[r.charCodeAt(y)]=0}let f=0,d=-1,g=c*32,p=Math.min(32,o-g)+g;for(let l=g;l<p;l++)nr[r.charCodeAt(l)]|=1<<l;let h=o;for(let l=0;l<e;l++){let b=nr[n.charCodeAt(l)],F=t[l/32|0]>>>l&1,I=i[l/32|0]>>>l&1,y=b|f,A=((b|I)&d)+d^d|b|I,E=f|~(A|d),P=d&A;if(h+=E>>>o-1&1,h-=P>>>o-1&1,E>>>31^F)t[l/32|0]^=1<<l;if(P>>>31^I)i[l/32|0]^=1<<l;E=E<<1|F,P=P<<1|I,d=P|~(y|E),f=E&y}for(let l=g;l<p;l++)nr[r.charCodeAt(l)]=0;return h},zi=(r,n)=>{if(r.length<n.length){let e=n;n=r,r=e}if(n.length===0)return r.length;if(r.length<=32)return xi(r,n);return qi(r,n)},Je=(r,n)=>{let e=1/0,o=0;for(let i=0;i<n.length;i++){let t=zi(r,n[i]);if(t<e)e=t,o=i}return n[o]};function Xr(r,n,e,o){let i=Je(n,e);if(console.error(m.red(`Unknown ${r}: ${n}`)),i)console.error(m.yellow(`Did you mean "${i}"?`));console.error(`
89
+ Run "${o} --help" for usage.`),process.exit(1)}function yr(r,n){let e=(i)=>i&&typeof i==="object";if(!e(r)||!e(n))return n;let o={...r};for(let i of Object.keys(n)){let t=o[i],a=n[i];if(Array.isArray(t)&&Array.isArray(a))o[i]=[...a];else if(e(t)&&e(a))o[i]=yr(t,a);else o[i]=a}return o}function jn(r){return r==null?[]:Array.isArray(r)?r:[r]}function Wi(r,n,e,o){var i,t=r[n],a=~o.string.indexOf(n)?e==null||e===!0?"":String(e):typeof e==="boolean"?e:~o.boolean.indexOf(n)?e==="false"?!1:e==="true"||(r._.push((i=+e,i*0===0)?i:e),!!e):(i=+e,i*0===0)?i:e;r[n]=t==null?a:Array.isArray(t)?t.concat(a):[t,a]}function Vr(r,n){r=r||[],n=n||{};var e,o,i,t,a,s={_:[]},c=0,f=0,d=0,g=r.length;let p=n.alias!==void 0,h=n.unknown!==void 0,l=n.default!==void 0;if(n.alias=n.alias||{},n.string=jn(n.string),n.boolean=jn(n.boolean),p)for(e in n.alias){o=n.alias[e]=jn(n.alias[e]);for(c=0;c<o.length;c++)(n.alias[o[c]]=o.concat(e)).splice(c,1)}for(c=n.boolean.length;c-- >0;){o=n.alias[n.boolean[c]]||[];for(f=o.length;f-- >0;)n.boolean.push(o[f])}for(c=n.string.length;c-- >0;){o=n.alias[n.string[c]]||[];for(f=o.length;f-- >0;)n.string.push(o[f])}if(l){for(e in n.default)if(t=typeof n.default[e],o=n.alias[e]=n.alias[e]||[],n[t]!==void 0){n[t].push(e);for(c=0;c<o.length;c++)n[t].push(o[c])}}let b=h?Object.keys(n.alias):[];for(c=0;c<g;c++){if(i=r[c],i==="--"){s._=s._.concat(r.slice(++c));break}for(f=0;f<i.length;f++)if(i.charCodeAt(f)!==45)break;if(f===0)s._.push(i);else if(i.substring(f,f+3)==="no-"){if(t=i.substring(f+3),h&&!~b.indexOf(t))return n.unknown(i);s[t]=!1}else{for(d=f+1;d<i.length;d++)if(i.charCodeAt(d)===61)break;t=i.substring(f,d),a=i.substring(++d)||(c+1===g||(""+r[c+1]).charCodeAt(0)===45||r[++c]),o=f===2?[t]:t;for(d=0;d<o.length;d++){if(t=o[d],h&&!~b.indexOf(t))return n.unknown("-".repeat(f)+t);Wi(s,t,d+1<o.length||a,n)}}}if(l){for(e in n.default)if(s[e]===void 0)s[e]=n.default[e]}if(p)for(e in s){o=n.alias[e]||[];while(o.length>0)s[o.shift()]=s[e]}return s}function Ji(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Ye(r){let n={alias:{},boolean:[],default:{},string:[]};for(let[e,o]of Object.entries(r)){if(o.type==="boolean")n.boolean.push(e);else n.string.push(e);if(o.alias)n.alias[o.alias]=e;let i=Ji(e);if(i!==e)n.alias[i]=e;if(o.default!==void 0)n.default[e]=o.default}return n}function Ke(r,n){let e={...r};for(let[o,i]of Object.entries(n)){if(i.type!=="number")continue;let t=r[o];if(t===void 0||typeof t==="boolean")continue;let a=Number(t);if(Number.isNaN(a))throw Error(`Invalid number for --${o}: "${t}"`);e[o]=a}return e}function Ze(r,n){let e=Ye(n),o=Vr(r,e),i=o._[0],t=i?r.indexOf(i):-1,{_:a,...s}=o,c=Ke(s,n);return{command:i,flags:c,restArgs:t>=0?r.slice(t+1):[]}}function An(r,n={}){let e=Ye(n),o=Vr(r,e),{_:i,...t}=o;return{args:Ke(t,n),rawPositionals:i}}function Mn(r,n){let e={},o=Object.entries(n);for(let[i,[t,a]]of o.entries())e[t]=a.variadic?r.slice(i):r[i];return e}function Qe(r,n){for(let[e,o]of Object.entries(n)){if(!o.required)continue;let i=r[e];if(Array.isArray(i)?i.length===0:!i)return`Missing required argument: <${e}${o.variadic?"...":""}>`}return null}var Gn="__exit__";class dr{command;env;prefix;options;constructor(r,n,e,o={}){this.command=r;this.env=n;this.prefix=e;this.options=o}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(r,n){if(n)await this.routeInteractive();else await this.routeDirect(r)}async routeDirect(r){let[n,...e]=r;if(n&&this.command.hasSubcommands()){let o=this.command.getSubcommand(n);if(o){await this.handleSubcommandRoute(o,e);return}if(!n.startsWith("-")){this.handleUnknownSubcommand(n);return}}await this.executeCommand(r)}handleUnknownSubcommand(r){let n=this.command.getSubcommands().map((e)=>e.name);Xr("subcommand",r,n,this.commandPath)}async handleSubcommandRoute(r,n){await new dr(r,this.env,this.commandPath).route(n,!1)}async executeCommand(r){if(this.isHelpRequest(r)){this.printHelp(this.command);return}if(this.command.hasSubcommands()&&!this.command.execute){this.printHelp(this.command);return}if(!this.command.execute)return;let{args:e,rawPositionals:o}=An(r,this.command.args),i=Mn(o,this.command.positionals),t=Qe(i,this.command.positionals);if(t)v.error(t),console.error(`
90
+ Run "${this.commandPath} --help" for usage.`),process.exit(1);let a=this.command.prompts&&o.length===0,s=this.buildContext(i,e,a);await this.command.execute(s)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:r}=An([],this.command.args),n=Mn([],this.command.positionals),e=this.buildContext(n,r,!0);await this.command.execute?.(e)}async runSubcommandMenu(){while(!0){let r=await this.promptSubcommandSelectionOrBack();if(r===null)return;if(r===Gn){this.options.onExit?.();return}let n=this.command.getSubcommand(r);if(n)await this.executeSubcommand(n)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(r){if(r instanceof O){if(this.options.isRoot)this.options.onExit?.();return null}throw r}}async executeSubcommand(r){try{await new dr(r,this.env,this.commandPath).route([],!0)}catch(n){if(n instanceof O)return;if(n instanceof w){if(v.warn(m.yellow(n.message)),n.hint)v.info(m.dim(n.hint));return}throw n}}promptSubcommandSelection(){let{isRoot:r}=this.options,n=r?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:Gn}:{hint:"Return to previous menu",label:"Back",value:Gn};return cr({message:r?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,options:[...this.command.getSubcommands().map((e)=>({hint:e.description,label:e.name,value:e.name})),n]})}buildContext(r,n,e){return{...this.env,args:n,interactive:e,positionals:r}}isHelpRequest(r){return r.includes("--help")||r.includes("-h")}printHelp(r){let n=r===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(r,n))}}var Yi={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class xn{commands=new Map;metadata;configManager;help;bin;globalArgs={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Enable interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};constructor(r,n){this.configManager=r,this.metadata={...Yi,...n},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Nn({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(r){for(let n of r)n.init?.(),this.commands.set(n.name,n)}async run(r=process.argv.slice(2)){let{command:n,flags:e,restArgs:o}=Ze(r,this.globalArgs);if(e.version&&!n)return console.log(this.help.version());if(e.interactive&&!n)return this.runInteractive();if(!n)return console.log(this.help.global());if(n==="help")return this.printHelpFor(o[0]);await this.runDirect(n,o,!!e.help)}printHelpFor(r){if(!r)return console.log(this.help.global());let n=this.commands.get(r);if(!n)return this.handleUnknownCommand(r);console.log(this.help.command(n))}async runInteractive(){this.showIntro();let r=this.createVirtualRootCommand(),n={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},e=new dr(r,n,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await e.route([],!0)}catch(o){this.handleError(o)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(r)=>this.commands.get(r),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){Yr(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(r,n,e){let o=this.commands.get(r);if(!o)return this.handleUnknownCommand(r);let i=n.length>0&&!n[0]?.startsWith("-");if(e&&!i)return console.log(this.help.command(o));try{let t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new dr(o,t,this.bin).route(n,!1)}catch(t){this.handleError(t)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let r=this.metadata.version?` v${this.metadata.version}`:"";Jr(`${m.bgCyan(m.black(` ${this.metadata.name}${r} `))}`)}handleUnknownCommand(r){let n=Array.from(this.commands.keys());Xr("command",r,n,this.bin)}handleError(r){if(this.metadata.onError?.(r))return;if(r instanceof O)process.exit(0);if(r instanceof w){if(v.warn(m.yellow(r.message)),r.hint)v.info(m.dim(r.hint));process.exit(0)}if(r instanceof Error)v.error(m.red(r.message)),process.exit(1);console.error(m.red("Error:"),r),process.exit(1)}}class Pr{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(r){for(let n of r)n.init?.(),this.subcommands.set(n.name,n)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(r){return this.subcommands.get(r)}getSubcommands(){return Array.from(this.subcommands.values())}}function tr(r){return r}function G(r){return r}import gr from"fs";import Oe from"path";class qn{config;configPath;defaultConfig;constructor(r,n){this.configPath=Oe.resolve(r),this.defaultConfig=n,this.config=this.loadConfig()}get(r){return this.config[r]}set(r,n){this.config[r]=n,this.save()}delete(r){delete this.config[r],this.save()}exists(){return gr.existsSync(this.configPath)}getAll(){return yr({},this.config)}save(r){if(r)this.config={...r};this.ensureDirectoryExists();try{gr.writeFileSync(this.configPath,JSON.stringify(this.config,null,2))}catch(n){console.error(`Failed to save config to ${this.configPath}:`,n)}}ensureDirectoryExists(){let r=Oe.dirname(this.configPath);if(!gr.existsSync(r))try{gr.mkdirSync(r,{recursive:!0})}catch(n){console.error(`Failed to create config directory at ${r}:`,n)}}loadConfig(){if(!gr.existsSync(this.configPath))return{...this.defaultConfig};try{let r=gr.readFileSync(this.configPath,"utf-8"),n=JSON.parse(r);return yr({...this.defaultConfig},n)}catch{return console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),{...this.defaultConfig}}}}var Xe="0.9.0";class R extends Pr{}import{existsSync as Dr}from"fs";import{cp as Bi,link as _i,mkdir as Jn,readdir as ao,readFile as Yn,readlink as Ti,rm as Kn,symlink as rt,unlink as so,writeFile as nt}from"fs/promises";import{join as D,resolve as Tr}from"path";var Sr="hydra";var Ve=".hydra/config.json",ur=".hydra/shared",Fr=".hydra/runners",kr="default",Se={profiles:{}},Be=!1,_e=24,Te=7,ro=["logs","shared"];var Zi=new Set(["github.com","www.github.com"]);var no=/\.git$/;function pr(r){let n;try{n=new URL(r)}catch{throw Error(`Invalid GitHub URL: ${r}`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw Error(`Invalid GitHub URL (expected http(s)): ${r}`);if(!Zi.has(n.hostname))throw Error(`Invalid GitHub URL (host must be github.com): ${r}`);let e=n.pathname.split("/").filter(Boolean);if(e.length===1){let o=e[0]?.replace(no,"");if(!o)throw Error(`Invalid GitHub URL: ${r}`);return{kind:"org",org:o}}if(e.length===2){let o=e[0],i=e[1]?.replace(no,"");if(!o||!i)throw Error(`Invalid GitHub URL: ${r}`);return{kind:"repo",owner:o,repo:i}}throw Error(`Invalid GitHub URL (expected github.com/<owner>/<repo> or github.com/<org>): ${r}`)}function Br(r){return r.kind==="repo"?`${r.owner}/${r.repo}`:r.org}import{existsSync as Qi}from"fs";import{readdir as Oi,stat as Xi}from"fs/promises";import{join as Vi}from"path";var Rr="_diag",eo={runner:/^Runner_.+\.log$/,worker:/^Worker_.+\.log$/},oo=1024,io=["B","KB","MB","GB"],Si=1;function to(r){if(eo.worker.test(r))return"worker";if(eo.runner.test(r))return"runner";return null}function _r(r){return[...r].sort((n,e)=>e.mtime.getTime()-n.mtime.getTime())}async function Lr(r){if(!Qi(r))return[];let n=await Oi(r,{withFileTypes:!0}),e=[];for(let o of n){if(!o.isFile())continue;let i=to(o.name);if(!i)continue;let t=Vi(r,o.name),a=await Xi(t);e.push({mtime:a.mtime,name:o.name,path:t,size:a.size,type:i})}return _r(e)}function zn(r,n){let e=r.find((i)=>i.type===n);if(e)return{fallback:!1,file:e};let o=r[0];return o?{fallback:!0,file:o}:null}function Wn(r,n){if(n<=0)return"";let e=r.endsWith(`
91
+ `)?r.slice(0,-1):r;if(e==="")return"";return e.split(`
92
92
  `).slice(-n).join(`
93
- `)}function Mn(r){let n=r,o=0;while(n>=Jo&&o<xo.length-1)n/=Jo,o++;return`${o===0?String(n):n.toFixed(ye)} ${xo[o]??"B"}`}var Xo="actions/runner",je={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},Vo=["bin"],Oo=["externals"];class Vr{profile;sharedPath=null;constructor(r){this.profile=r}async download(){let r=je[this.profile.os],n=await this.getLatestVersion(),o=R(Pr,"github",n);if(kr(o))return this.sharedPath=o,{path:o,version:n};await Un(o,{recursive:!0});let i=`actions-runner-${r}-${n}.tar.gz`,e=R(o,i),t=`https://github.com/${Xo}/releases/download/v${n}/${i}`;return await Bun.$`curl -sL -o ${e} ${t}`,await Bun.$`tar xzf ${e} -C ${o}`,await Qo(e),this.sharedPath=o,{path:o,version:n}}async create(r){let n=await this.ensureDownloaded(),o=[];for(let i of r){let e=R(this.profile.directory,i);await this.setupRunnerDir(n,e),await this.registerRunner(e,i),o.push({directory:e,id:i,name:i,status:"registered"})}return o}async remove(r){for(let n of r){let o=R(this.profile.directory,n);if(!kr(R(o,".runner")))continue;let i=await this.fetchRemovalToken(o);await Bun.$`bash ./config.sh remove --token ${i}`.cwd(o).quiet().nothrow()}}async start(r){for(let n of r){let o=R(this.profile.directory,n),i=await this.readPidFile(o);if(i&&this.isProcessRunning(i))continue;let e=Bun.spawn(["bash","./run.sh"],{cwd:Xr(o),stderr:"pipe",stdout:"pipe"});e.unref(),await this.writePidFile(o,e.pid)}}async stop(r){for(let n of r){let o=R(this.profile.directory,n);if(!await this.readPidFile(o))continue;let e=Xr(o);await Bun.$`pkill -f ${e}`.quiet().nothrow(),await this.removePidFile(o)}}async list(){let r=this.profile.directory;if(!kr(r))return[];let n=await Zo(r,{withFileTypes:!0}),o=[];for(let i of n){if(!i.isDirectory())continue;let e=R(r,i.name);o.push(await this.getRunnerStatus(e,i.name))}return o}async currentVersion(r){let n=R(this.profile.directory,r);return this.detectVersion(n)}async logFiles(r){return Hn(R(this.profile.directory,r,Dn))}async update(r){let n=await this.ensureDownloaded();for(let o of r){let i=R(this.profile.directory,o);await this.removeRunnerBinaries(i),await this.setupRunnerDir(n,i)}}async getRunnerStatus(r,n){let o=await this.readRunnerName(r),i=await this.readPidFile(r),e=i!==null&&this.isProcessRunning(i),t="unknown";if(e)t="running";else if(kr(R(r,".runner")))t="registered";return{directory:r,id:n,name:o,pid:e?i:void 0,status:t}}async ensureDownloaded(){if(this.sharedPath)return this.sharedPath;let{path:r}=await this.download();return r}async setupRunnerDir(r,n){await Un(n,{recursive:!0});for(let o of Vo)await this.hardLinkDir(R(r,o),R(n,o));for(let o of Oo){let i=Xr(r,o),e=R(n,o);if(!kr(e))await De(i,e)}for(let o of["*.sh","*.sh.template"]){let i=await Array.fromAsync(new Bun.Glob(o).scan(r));for(let e of i)await Ie(R(r,e),R(n,e))}}async registerRunner(r,n){let o=await this.fetchRegistrationToken(),i=["--url",this.profile.url,"--token",o,"--name",n,"--unattended"];if(this.profile.labels)i.push("--labels",this.profile.labels);if(this.profile.runnerGroup)i.push("--runnergroup",this.profile.runnerGroup);await Bun.$`bash ./config.sh ${i}`.cwd(r).quiet()}async fetchRegistrationToken(){return this.fetchRunnerToken(sr(this.profile.url),"registration-token")}async fetchRemovalToken(r){let n=await Gn(R(r,".runner"),"utf-8"),i=JSON.parse(this.stripBom(n)).gitHubUrl;if(!i)throw Error("Cannot determine GitHub URL from runner config");return this.fetchRunnerToken(sr(i),"remove-token")}async fetchRunnerToken(r,n){let o=r.kind==="repo"?`repos/${r.owner}/${r.repo}/actions/runners/${n}`:`orgs/${r.org}/actions/runners/${n}`,i=r.kind==="repo"?"gh needs admin access to the repository":"gh needs the admin:org scope",e=await Bun.$`gh api ${o} --method POST --jq .token`.quiet().nothrow();if(e.exitCode!==0){let a=e.stderr.toString().trim();throw Error(`gh api ${o} failed for ${Qr(r)} (${i})${a?`: ${a}`:""}`)}let t=e.stdout.toString().trim();if(!t)throw Error(`Failed to fetch ${n} for ${Qr(r)}`);return t}async getLatestVersion(){return(await Bun.$`gh api repos/${Xo}/releases/latest --jq .tag_name`.quiet()).stdout.toString().trim().replace(/^v/,"")}pidFilePath(r){return Xr(r,".pid")}async writePidFile(r,n){await He(this.pidFilePath(r),String(n))}async readPidFile(r){try{let n=await Gn(this.pidFilePath(r),"utf-8");return Number.parseInt(n.trim(),10)}catch{return null}}async removePidFile(r){try{await Qo(this.pidFilePath(r))}catch{}}async readRunnerName(r){try{let n=await Gn(R(r,".runner"),"utf-8");return JSON.parse(this.stripBom(n)).agentName??"unknown"}catch{return"unknown"}}async hardLinkDir(r,n){await Un(n,{recursive:!0});let o=await Zo(r,{withFileTypes:!0});for(let i of o){let e=R(r,i.name),t=R(n,i.name);if(i.isDirectory())await this.hardLinkDir(e,t);else await Le(e,t)}}async detectVersion(r){try{return(await Re(R(r,"externals"))).match(/github\/([^/]+)/)?.[1]??null}catch{return null}}async removeRunnerBinaries(r){for(let n of Vo)await Nn(R(r,n),{force:!0,recursive:!0});for(let n of Oo)await Nn(R(r,n),{force:!0});for(let n of["*.sh","*.sh.template"]){let o=await Array.fromAsync(new Bun.Glob(n).scan(r));for(let i of o)await Nn(R(r,i),{force:!0})}}stripBom(r){return r.replace(/^\uFEFF/,"")}isProcessRunning(r){try{return process.kill(r,0),!0}catch{return!1}}}function z(r){switch(r.provider){case"github":return new Vr(r);default:throw Error(`Runner provider "${r.provider}" is not yet implemented`)}}function pr(r,n){if(r.length===0)return n;for(let o of r)if(!n.includes(o))throw new v(`Runner "${o}" not found`);return r}function A(r,n){let o=r.get("profiles");if(Object.keys(o).length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let i=n??r.get("defaultProfile")??Fr,e=o[i];if(!e)throw new v(`Profile "${i}" not found`);return{name:i,profile:e}}async function Q(r){let n=r.get("profiles"),o=Object.keys(n);if(o.length===0)throw new v("No profiles configured","Run hydra init to set up a profile");if(o.length===1)return o[0];return tr({message:"Select profile",options:o.map((i)=>({label:i,value:i,hint:n[i]?.url}))})}var Me=q({profile:{description:"Profile name"},count:{description:"Number of runners to create (overrides profile)"}});class Or extends L{name="create";description="Create and register runners";positionals=Me;async execute(r){let{name:n,profile:o}=r.interactive?A(r.config,await Q(r.config)):A(r.config,r.positionals.profile),i=r.interactive?await this.promptCount(o.numberOfMachines):r.positionals.count?Number.parseInt(r.positionals.count,10):o.numberOfMachines;if(!i||i<1)throw new v("Runner count must be at least 1");let e=z(o),t=K();t.start("Downloading runner binary...");let{version:a}=await e.download();t.stop(`Runner v${a} ready`);let s=r.config.get("runners")??[],c=s.filter((d)=>d.profile===n),f=i-c.length;if(f<=0){w.warn(`Already have ${c.length} runner(s) for profile "${n}". Nothing to create.`);return}let l=new Set(s.map((d)=>d.id)),g=1;for(let d=0;d<f;){let b=`${o.name}-${g++}`;if(l.has(b))continue;d++,t.start(`Registering ${b}...`),await e.create([b]),t.stop(`${p.green("+")} ${b}`),s.push({createdAt:new Date().toISOString(),directory:Ee(o.directory,b),id:b,name:b,profile:n,provider:o.provider,url:o.url})}r.config.set("runners",s);let h=n===r.config.get("defaultProfile")?"":` ${n}`;w.info(`${p.green("Created")} ${f} runner(s) for "${n}". Run ${p.green(`hydra start${h}`)} to start them.`)}async promptCount(r){let n=await rr({initialValue:String(r),message:"Number of runners to create",validate:(o)=>{let i=Number.parseInt(o??"",10);if(Number.isNaN(i)||i<1)return"Must be a positive number";return}});return Number.parseInt(n,10)}}import{existsSync as So}from"fs";import{mkdir as Bo}from"fs/promises";var Ue=q({url:{description:"GitHub repository or organization URL"}}),Ge=mr({force:{alias:"f",default:!1,description:"Overwrite existing config",type:"boolean"},labels:{alias:"l",description:"Comma-separated runner labels",type:"string"},name:{alias:"n",description:"Base name for runners",type:"string"},profile:{alias:"p",description:"Profile name",type:"string"},runners:{alias:"c",description:"Number of runners to create",type:"number"}});class Sr extends L{name="init";description="Initialize Hydra runner manager";positionals=Ue;args=Ge;prompts=!0;async execute(r){let n=r.interactive?await this.promptProfileName(r):r.args.profile??Fr,o=!r.config.exists();if(!o&&r.config.get("profiles")[n]&&!r.args.force){if(!r.interactive)throw new v(`Profile "${n}" already exists. Use --force to overwrite.`);if(!await vr({initialValue:!1,message:`Profile "${n}" already exists. Overwrite?`}))return}await this.ensureDirectories();let e=r.interactive?await this.runInitForm():this.buildProfileFromArgs(r),t=o?{}:{...r.config.get("profiles")};if(t[n]=e,r.config.set("profiles",t),!r.config.get("defaultProfile"))r.config.set("defaultProfile",n);cr([`${p.dim("Profile:")} ${n}`,`${p.dim("URL:")} ${e.url}`,`${p.dim("Runners:")} ${e.numberOfMachines}`,`${p.dim("Name:")} ${e.name}`,e.labels?`${p.dim("Labels:")} ${e.labels}`:"","",`Run ${p.green(`${Zr} create${n!==r.config.get("defaultProfile")?` ${n}`:""}`)} to provision runners.`].filter(Boolean).join(`
94
- `),p.green(o?"Hydra initialized":`Profile "${n}" added`))}async promptProfileName(r){return rr({initialValue:r.args.profile??Fr,message:"Profile name"})}async ensureDirectories(){if(!So(Pr))await Bo(Pr,{recursive:!0});if(!So(Cr))await Bo(Cr,{recursive:!0})}async runInitForm(){let r=await Nr({url:()=>rr({message:"GitHub repository or organization URL",placeholder:"https://github.com/owner/repo",validate:(n)=>{if(!n)return"URL is required";try{sr(n)}catch{return"Must be a GitHub repository or organization URL (https://github.com/<owner>/<repo> or https://github.com/<org>)"}return}}),name:()=>rr({initialValue:"runner",message:"Base name for runners",placeholder:"runner"}),runners:()=>rr({initialValue:"1",message:"Number of runners",placeholder:"1",validate:(n)=>{if(!n)return"Must be a positive number";let o=Number.parseInt(n,10);if(Number.isNaN(o)||o<1)return"Must be a positive number";return}}),labels:()=>rr({message:"Additional labels (comma-separated, optional)",placeholder:"self-hosted,macOS,ARM64"})},{onCancel:()=>{throw new X}});return{directory:Cr,labels:r.labels||void 0,name:r.name,numberOfMachines:Number.parseInt(r.runners,10)||1,os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:r.url}}buildProfileFromArgs(r){if(!r.positionals.url)throw new v("URL is required","Usage: hydra init <url>");return this.validateUrl(r.positionals.url),this.validateRunnerCount(r.args.runners),{directory:Cr,labels:r.args.labels,name:r.args.name??"runner",numberOfMachines:r.args.runners??1,os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:r.positionals.url}}validateUrl(r){try{sr(r)}catch(n){throw new v(n instanceof Error?n.message:`Invalid GitHub URL: ${r}`,"Expected https://github.com/<owner>/<repo> or https://github.com/<org>")}}validateRunnerCount(r){if(r!==void 0&&r<1)throw new v("Runner count must be at least 1")}detectOs(){let r=process.platform;if(r==="darwin")return"osx";if(r==="win32")return"windows";return"linux"}}import{existsSync as Ne}from"fs";import{readFile as qe}from"fs/promises";var ze=100,We={runner:"runner daemon log",worker:"job log"},Ae=mr({lines:{alias:"n",default:ze,description:"Number of lines to tail",type:"number"},list:{alias:"l",default:!1,description:"List available log files instead of printing content",type:"boolean"},open:{alias:"o",default:!1,description:"Open the log file in $EDITOR instead of printing",type:"boolean"},runner:{alias:"r",default:!1,description:"Show the runner daemon log instead of the latest job log",type:"boolean"}}),Je=q({id:{description:"Runner ID"}});class Br extends L{name="logs";description="Inspect logs of the latest jobs";args=Ae;positionals=Je;async execute(r){let n=r.config.get("runners")??[];if(n.length===0)throw new v("No runners found","Run hydra create to provision runners");let o=await this.resolveEntry(r,n),i=r.config.get("profiles")[o.profile];if(!i)throw new v(`Profile "${o.profile}" not found for runner "${o.id}"`,"Run hydra init to set it up");if(!Ne(o.directory))throw new v(`Runner directory not found: ${o.directory}`,"Run hydra create to provision this runner");let t=await z(i).logFiles(o.id);if(t.length===0)this.noLogs(o.id);if(r.args.list){this.printList(o,t);return}let a=this.selectFile(r,o,t);if(r.args.open){await this.openFile(a);return}await this.printTail(o,a,r.args.lines)}async resolveEntry(r,n){let o=r.positionals.id;if(o){let e=n.find((t)=>t.id===o);if(!e)throw new v(`Runner "${o}" not found`,`Known runners: ${n.map((t)=>t.id).join(", ")}`);return e}if(r.interactive)return tr({message:"Select runner",options:n.map((e)=>({hint:e.profile,label:e.name,value:e}))});let i=n[0];if(n.length===1&&i)return i;throw new v("Multiple runners found",`Pass a runner id: hydra logs <id> (${n.map((e)=>e.id).join(", ")})`)}selectFile(r,n,o){if(r.args.runner){let e=o.find((t)=>t.type==="runner");if(!e)throw new v(`No runner daemon logs found for "${n.id}"`,"Start the runner first: hydra start");return e}let i=jn(o,"worker");if(!i)this.noLogs(n.id);if(i.fallback)w.warn(p.yellow("No job (Worker) logs yet; showing the runner daemon log instead"));return i.file}noLogs(r){throw new v(`No logs found for runner "${r}"`,"Logs appear once the runner has started; run hydra start")}printList(r,n){let o=[`${p.bold(r.name)} ${p.dim(r.directory)}`];for(let i of n){let e=i.type==="worker"?p.green("worker"):p.blue("runner");o.push(` ${e} ${i.name} ${p.dim(`${i.mtime.toISOString()} \xB7 ${Mn(i.size)}`)}`)}w.info(o.join(`
95
- `))}async printTail(r,n,o){let i=await qe(n.path,"utf-8"),e=[`${p.bold(r.name)} ${p.dim(We[n.type])}`,p.dim(n.path),p.dim(`Last modified: ${n.mtime.toISOString()}`)];w.info(e.join(`
96
- `)),console.log(En(i,o))}async openFile(r){let n=(process.env.EDITOR??"").split(" ").filter(Boolean),o=n[0];if(o){await Bun.spawn([o,...n.slice(1),r.path],{stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited;return}if(process.platform==="darwin"){await Bun.$`open ${r.path}`.quiet();return}throw new v("No editor configured","Set $EDITOR to open log files")}}var xe=q({name:{description:"Profile name to set as default"}});class qn extends L{name="default";description="Set the default profile";positionals=xe;async execute(r){let n=r.interactive?await Q(r.config):r.positionals.name;if(!n)throw new v("Profile name is required","Usage: hydra profile default <name>");let{name:o}=A(r.config,n);if(r.config.get("defaultProfile")===o){w.info(`"${o}" is already the default profile.`);return}r.config.set("defaultProfile",o),w.info(`${p.green("Default profile set to")} "${o}".`)}}class zn extends L{name="list";description="List all profiles";async execute(r){let n=r.config.get("profiles"),o=Object.keys(n);if(o.length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let i=r.config.get("runners")??[],e=r.config.get("defaultProfile");for(let t of o){let a=n[t],c=await z(a).list(),f=i.filter((b)=>b.profile===t),l=new Set(c.filter((b)=>b.status==="running").map((b)=>b.id)),g=f.filter((b)=>l.has(b.id)).length,u=t===e,h=[`${p.dim("URL:")} ${a.url}`,`${p.dim("Provider:")} ${a.provider}`,`${p.dim("OS:")} ${a.os}`,`${p.dim("Name:")} ${a.name}`,`${p.dim("Runners:")} ${f.length}/${a.numberOfMachines} created, ${p.green(`${g} running`)}`];if(a.labels)h.push(`${p.dim("Labels:")} ${a.labels}`);let d=u?`${t} ${p.dim("(default)")}`:t;cr(h.join(`
97
- `),d)}w.info(p.dim(`${o.length} profile(s)`))}}import{rm as Ke}from"fs/promises";import{join as Ye}from"path";var Ze=q({name:{description:"Profile name to remove"}});class Wn extends L{name="remove";description="Remove a profile";positionals=Ze;async execute(r){let n=r.interactive?await Q(r.config):r.positionals.name;if(!n)throw new v("Profile name is required","Usage: hydra profile remove <name>");let{profile:o}=A(r.config,n),i=r.config.get("runners")??[],e=i.filter((c)=>c.profile===n);if(e.length>0){if(!await vr({initialValue:!0,message:`This will stop and remove ${e.length} runner(s). Continue?`}))return;await this.removeRunners(o,e.map((l)=>l.id));let f=i.filter((l)=>l.profile!==n);r.config.set("runners",f)}let{[n]:t,...a}=r.config.get("profiles");if(r.config.set("profiles",a),r.config.get("defaultProfile")===n){let c=Object.keys(a);r.config.set("defaultProfile",c[0])}w.info(`${p.green("Removed")} profile "${n}".`)}async removeRunners(r,n){let o=z(r),i=K();for(let e of n)i.start(`Stopping and removing ${e}...`),await o.stop([e]),await o.remove([e]),await Ke(Ye(r.directory,e),{force:!0,recursive:!0}),i.stop(`${p.red("-")} ${e}`)}}class _r extends L{name="profile";description="Manage profiles";init(){this.registerSubcommands([new zn,new Wn,new qn])}}import{rm as Qe}from"fs/promises";import{join as Xe}from"path";var Ve=q({profile:{description:"Profile name"},ids:{description:"Runner IDs (omit to target all)",variadic:!0}});class Tr extends L{name="remove";description="Deregister and remove runners";positionals=Ve;async execute(r){let{name:n,profile:o}=r.interactive?A(r.config,await Q(r.config)):A(r.config,r.positionals.profile),i=r.config.get("runners")??[],e=i.filter((f)=>f.profile===n);if(e.length===0)throw new v(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=r.interactive?await this.promptRunnerSelection(e.map((f)=>f.id)):pr(r.positionals.ids??[],e.map((f)=>f.id)),a=z(o),s=K();for(let f of t)s.start(`Stopping and removing ${f}...`),await a.stop([f]),await a.remove([f]),await Qe(Xe(o.directory,f),{force:!0,recursive:!0}),s.stop(`${p.red("-")} ${f}`);let c=i.filter((f)=>!t.includes(f.id));r.config.set("runners",c),w.info(`${p.green("Removed")} ${t.length} runner(s).`)}async promptRunnerSelection(r){return ar({message:"Select runners to remove",options:r.map((n)=>({label:n,value:n})),required:!0})}}var Oe=q({profile:{description:"Profile name"},ids:{description:"Runner IDs (omit to target all)",variadic:!0}});class rn extends L{name="start";description="Start runners";positionals=Oe;async execute(r){let{name:n,profile:o}=r.interactive?A(r.config,await Q(r.config)):A(r.config,r.positionals.profile),e=(r.config.get("runners")??[]).filter((u)=>u.profile===n);if(e.length===0)throw new v(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=z(o),a=K();a.start("Fetching runner status...");let s=await t.list();a.stop("Runner status fetched");let c=new Set(s.filter((u)=>u.status==="running").map((u)=>u.id)),f=e.map((u)=>u.id).filter((u)=>!c.has(u)),l=r.interactive?await this.promptRunnerSelection(f):pr(r.positionals.ids??[],e.map((u)=>u.id)),g=0;for(let u of l){if(c.has(u)){a.start(""),a.stop(`${p.dim("\u25CF")} ${u} ${p.dim("already running")}`);continue}a.start(`Starting ${u}...`),await t.start([u]),a.stop(`${p.green("\u25B6")} ${u}`),g++}w.info(`${p.green("Started")} ${g} runner(s).`)}async promptRunnerSelection(r){if(r.length===0)throw new v("All runners are already running");return ar({message:"Select runners to start",options:r.map((n)=>({label:n,value:n})),required:!0})}}var Se={registered:p.yellow,running:p.green,stopped:p.red,unknown:p.dim};class nn extends L{name="status";description="Show runner status across all profiles";async execute(r){let n=r.config.get("profiles"),o=Object.keys(n);if(o.length===0)throw new v("No profiles configured","Run hydra init to set up a profile");let i=r.config.get("runners")??[],e=0,t=0,a=[];for(let s of o){let c=n[s],l=await z(c).list();if(a.length>0)a.push("");a.push(`${p.bold(s)} ${p.dim(c.url)}`);let g=new Set(i.filter((h)=>h.profile===s).map((h)=>h.id)),u=l.filter((h)=>g.has(h.id)).sort((h,d)=>h.name.localeCompare(d.name,void 0,{numeric:!0}));this.formatRunners(u,a),e+=u.length,t+=u.filter((h)=>h.status==="running").length}a.push(""),a.push(p.dim(`${e} runner(s) total, ${t} running`)),w.info(a.join(`
98
- `))}formatRunners(r,n){if(r.length===0){n.push(p.dim(" No runners."));return}for(let o of r){let i=Se[o.status]??p.dim,e=o.pid?p.dim(` (pid: ${o.pid})`):"";n.push(` ${i("\u25CF")} ${o.name} ${i(o.status)}${e}`)}}}var Be=q({profile:{description:"Profile name"},ids:{description:"Runner IDs (omit to target all)",variadic:!0}});class on extends L{name="stop";description="Stop runners";positionals=Be;async execute(r){let{name:n,profile:o}=r.interactive?A(r.config,await Q(r.config)):A(r.config,r.positionals.profile),e=(r.config.get("runners")??[]).filter((u)=>u.profile===n);if(e.length===0)throw new v(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=z(o),a=K();a.start("Fetching runner status...");let s=await t.list();a.stop("Runner status fetched");let c=new Set(s.filter((u)=>u.status==="running").map((u)=>u.id)),f=e.map((u)=>u.id).filter((u)=>c.has(u)),l=r.interactive?await this.promptRunnerSelection(f):pr(r.positionals.ids??[],e.map((u)=>u.id)),g=0;for(let u of l){if(!c.has(u)){a.start(""),a.stop(`${p.dim("\u25CF")} ${u} ${p.dim("not running")}`);continue}a.start(`Stopping ${u}...`),await t.stop([u]),a.stop(`${p.red("\u25A0")} ${u}`),g++}w.info(`${p.green("Stopped")} ${g} runner(s).`)}async promptRunnerSelection(r){if(r.length===0)throw new v("No runners are currently running");return ar({message:"Select runners to stop",options:r.map((n)=>({label:n,value:n})),required:!0})}}class en extends L{name="update";description="Update runners to the latest version";async execute(r){let n=r.config.get("profiles"),o=r.config.get("runners")??[];if(o.length===0)throw new v("No runners found","Run hydra create to provision runners");let i=K(),e=Map.groupBy(o,(c)=>c.profile),t=null,a="",s=!1;for(let[c,f]of e){let l=n[c],g=f[0];if(!l||!g)continue;let u=z(l);if(!s){if(s=!0,i.start("Checking for updates..."),a=(await u.download()).version,t=await u.currentVersion(g.id),i.stop(`Current: v${t??"unknown"} | Latest: v${a}`),t===a){w.info(`Already on latest version ${p.dim(`(v${a})`)}`);return}}let h=await u.list(),d=new Set(h.filter((b)=>b.status==="running").map((b)=>b.id));for(let b of f){let k=d.has(b.id);if(i.start(`Updating ${b.id}...`),k)await u.stop([b.id]);if(await u.update([b.id]),k)await u.start([b.id]);let D=k?` ${p.dim("(restarted)")}`:"";i.stop(`${p.green("\u2713")} ${b.id}${D}`)}}w.info(`${p.green("Updated")} ${o.length} runner(s) from v${t} to v${a}`)}}class _o extends Ln{constructor(){super(new Rn(qo,zo),{bin:Zr,clearOnStart:!0,exitLabel:"Exit",goodbyeMessage:"Heads down.",name:"HYDRA",promptMessage:"What do you need?",version:No})}init(){this.registerCommands([new Sr,new Or,new rn,new on,new nn,new Br,new Tr,new en,new _r])}}var _e=new _o;_e.run();
93
+ `)}function mr(r){let n=r,e=0;while(n>=oo&&e<io.length-1)n/=oo,e++;return`${e===0?String(n):n.toFixed(Si)} ${io[e]??"B"}`}var co="actions/runner",et={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},fo=["bin"],uo=["externals"];class rn{profile;sharedPath=null;constructor(r){this.profile=r}async download(){let r=et[this.profile.os],n=await this.getLatestVersion(),e=D(ur,"github",n);if(Dr(e))return this.sharedPath=e,{path:e,version:n};await Jn(e,{recursive:!0});let o=`actions-runner-${r}-${n}.tar.gz`,i=D(e,o),t=`https://github.com/${co}/releases/download/v${n}/${o}`;return await Bun.$`curl -sL -o ${i} ${t}`,await Bun.$`tar xzf ${i} -C ${e}`,await so(i),this.sharedPath=e,{path:e,version:n}}async create(r){let n=await this.ensureDownloaded(),e=[];for(let o of r){let i=D(this.profile.directory,o);await this.setupRunnerDir(n,i),await this.registerRunner(i,o),e.push({directory:i,id:o,name:o,status:"registered"})}return e}async remove(r){for(let n of r){let e=D(this.profile.directory,n);if(!Dr(D(e,".runner")))continue;let o=await this.fetchRemovalToken(e);await Bun.$`bash ./config.sh remove --token ${o}`.cwd(e).quiet().nothrow()}}async start(r){for(let n of r){let e=D(this.profile.directory,n),o=await this.readPidFile(e);if(o&&this.isProcessRunning(o))continue;let i=Bun.spawn(["bash","./run.sh"],{cwd:Tr(e),stderr:"pipe",stdout:"pipe"});i.unref(),await this.writePidFile(e,i.pid)}}async stop(r){for(let n of r){let e=D(this.profile.directory,n);if(!await this.readPidFile(e))continue;let i=Tr(e);await Bun.$`pkill -f ${i}`.quiet().nothrow(),await this.removePidFile(e)}}async list(){let r=this.profile.directory;if(!Dr(r))return[];let n=await ao(r,{withFileTypes:!0}),e=[];for(let o of n){if(!o.isDirectory())continue;let i=D(r,o.name);e.push(await this.getRunnerStatus(i,o.name))}return e}async currentVersion(r){let n=D(this.profile.directory,r);return this.detectVersion(n)}async logFiles(r){return Lr(D(this.profile.directory,r,Rr))}async update(r){let n=await this.ensureDownloaded();for(let e of r){let o=D(this.profile.directory,e);await this.removeRunnerBinaries(o),await this.setupRunnerDir(n,o)}}async getRunnerStatus(r,n){let e=await this.readRunnerName(r),o=await this.readPidFile(r),i=o!==null&&this.isProcessRunning(o),t="unknown";if(i)t="running";else if(Dr(D(r,".runner")))t="registered";return{directory:r,id:n,name:e,pid:i?o:void 0,status:t}}async ensureDownloaded(){if(this.sharedPath)return this.sharedPath;let{path:r}=await this.download();return r}async setupRunnerDir(r,n){await Jn(n,{recursive:!0});for(let e of fo)await this.hardLinkDir(D(r,e),D(n,e));for(let e of uo){let o=Tr(r,e),i=D(n,e);if(!Dr(i))await rt(o,i)}for(let e of["*.sh","*.sh.template"]){let o=await Array.fromAsync(new Bun.Glob(e).scan(r));for(let i of o)await Bi(D(r,i),D(n,i))}}async registerRunner(r,n){let e=await this.fetchRegistrationToken(),o=["--url",this.profile.url,"--token",e,"--name",n,"--unattended"];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(r).quiet()}async fetchRegistrationToken(){return this.fetchRunnerToken(pr(this.profile.url),"registration-token")}async fetchRemovalToken(r){let n=await Yn(D(r,".runner"),"utf-8"),o=JSON.parse(this.stripBom(n)).gitHubUrl;if(!o)throw Error("Cannot determine GitHub URL from runner config");return this.fetchRunnerToken(pr(o),"remove-token")}async fetchRunnerToken(r,n){let e=r.kind==="repo"?`repos/${r.owner}/${r.repo}/actions/runners/${n}`:`orgs/${r.org}/actions/runners/${n}`,o=r.kind==="repo"?"gh needs admin access to the repository":"gh needs the admin:org scope",i=await Bun.$`gh api ${e} --method POST --jq .token`.quiet().nothrow();if(i.exitCode!==0){let a=i.stderr.toString().trim();throw Error(`gh api ${e} failed for ${Br(r)} (${o})${a?`: ${a}`:""}`)}let t=i.stdout.toString().trim();if(!t)throw Error(`Failed to fetch ${n} for ${Br(r)}`);return t}async getLatestVersion(){return(await Bun.$`gh api repos/${co}/releases/latest --jq .tag_name`.quiet()).stdout.toString().trim().replace(/^v/,"")}pidFilePath(r){return Tr(r,".pid")}async writePidFile(r,n){await nt(this.pidFilePath(r),String(n))}async readPidFile(r){try{let n=await Yn(this.pidFilePath(r),"utf-8");return Number.parseInt(n.trim(),10)}catch{return null}}async removePidFile(r){try{await so(this.pidFilePath(r))}catch{}}async readRunnerName(r){try{let n=await Yn(D(r,".runner"),"utf-8");return JSON.parse(this.stripBom(n)).agentName??"unknown"}catch{return"unknown"}}async hardLinkDir(r,n){await Jn(n,{recursive:!0});let e=await ao(r,{withFileTypes:!0});for(let o of e){let i=D(r,o.name),t=D(n,o.name);if(o.isDirectory())await this.hardLinkDir(i,t);else await _i(i,t)}}async detectVersion(r){try{return(await Ti(D(r,"externals"))).match(/github\/([^/]+)/)?.[1]??null}catch{return null}}async removeRunnerBinaries(r){for(let n of fo)await Kn(D(r,n),{force:!0,recursive:!0});for(let n of uo)await Kn(D(r,n),{force:!0});for(let n of["*.sh","*.sh.template"]){let e=await Array.fromAsync(new Bun.Glob(n).scan(r));for(let o of e)await Kn(D(r,o),{force:!0})}}stripBom(r){return r.replace(/^\uFEFF/,"")}isProcessRunning(r){try{return process.kill(r,0),!0}catch{return!1}}}import{existsSync as Qn}from"fs";import{readdir as On,readFile as ot,readlink as it,rm as Xn,stat as tt}from"fs/promises";import{join as ar}from"path";var po="_work",at="externals",st=".pid",ct="github",ft=/github\/([^/]+)/,ut=["runner","worker"],pt=24,mo=3600000,Zn=10;function nn(r){return{auto:r?.auto??Be,intervalHours:r?.intervalHours??_e,lastRun:r?.lastRun,olderThanDays:r?.olderThanDays??Te,targets:r?.targets??ro}}function lo(r,n){return r-n*pt*mo}function Vn(r,n){if(!r.lastRun)return!0;let e=Date.parse(r.lastRun);if(Number.isNaN(e))return!0;return n-e>=r.intervalHours*mo}function go(r,n){let e=_r(r),o=new Set;for(let i of ut){let t=e.find((a)=>a.type===i);if(t)o.add(t.path)}return e.filter((i)=>!o.has(i.path)&&i.mtime.getTime()<n)}function ho(r){return[...r].sort(ht)[0]??null}function bo(r,n){let e=ho(r),o=new Set(n);return r.filter((i)=>i!==e&&!o.has(i))}function vo(r){return r.match(ft)?.[1]??null}function en(r){return Object.values(r).reduce((n,e)=>n+e.freedBytes,0)}async function wo(r){try{let n=await ot(ar(r,st),"utf-8"),e=Number.parseInt(n.trim(),Zn);if(Number.isNaN(e))return!1;return process.kill(e,0),!0}catch{return!1}}async function on(r){if(!Qn(r))return 0;let n=await On(r,{withFileTypes:!0}),e=0;for(let o of n){if(o.isSymbolicLink())continue;let i=ar(r,o.name);if(o.isDirectory()){e+=await on(i);continue}if(o.isFile()){let t=await tt(i);e+=t.size}}return e}async function tn(r){let n=lo(r.now,r.olderThanDays),e={};for(let o of r.targets)switch(o){case"logs":e.logs=await mt(r.entries,n,r.dryRun);break;case"work":e.work=await lt(r.entries,r.dryRun);break;case"shared":e.shared=await dt(r.entries,r.dryRun,r.sharedDir);break}return e}async function mt(r,n,e){let o={freedBytes:0,removed:0,skipped:[]};for(let i of r){let t=await Lr(ar(i.directory,Rr));for(let a of go(t,n)){if(!e)await Xn(a.path,{force:!0});o.removed++,o.freedBytes+=a.size}}return o}async function lt(r,n){let e={freedBytes:0,removed:0,skipped:[]};for(let o of r){if(await wo(o.directory)){e.skipped.push(o.id);continue}let i=ar(o.directory,po);if(!Qn(i))continue;let t=await On(i);if(t.length===0)continue;if(e.freedBytes+=await on(i),e.removed+=t.length,n)continue;for(let a of t)await Xn(ar(i,a),{force:!0,recursive:!0})}return e}async function dt(r,n,e){let o={freedBytes:0,removed:0,skipped:[]},i=e??ar(ur,ct);if(!Qn(i))return o;let a=(await On(i,{withFileTypes:!0})).filter((c)=>c.isDirectory()).map((c)=>c.name),s=await gt(r);for(let c of bo(a,s)){let f=ar(i,c);if(o.freedBytes+=await on(f),o.removed++,!n)await Xn(f,{force:!0,recursive:!0})}return o}async function gt(r){let n=[];for(let e of r)try{let o=await it(ar(e.directory,at)),i=vo(o);if(i)n.push(i)}catch{}return n}function ht(r,n){let e=r.split(".").map((t)=>Number.parseInt(t,Zn)),o=n.split(".").map((t)=>Number.parseInt(t,Zn)),i=Math.max(e.length,o.length);for(let t=0;t<i;t++){let a=e[t]??0,s=o[t]??0,c=Number.isNaN(a)?0:a,f=Number.isNaN(s)?0:s;if(c!==f)return f-c}return 0}function x(r){switch(r.provider){case"github":return new rn(r);default:throw Error(`Runner provider "${r.provider}" is not yet implemented`)}}var Co=0,bt={logs:"file(s)",shared:"version(s)",work:"item(s)"},vt=tr({days:{alias:"d",default:Co,description:"Prune logs older than this many days (default from config)",type:"number"},dryRun:{alias:"n",default:!1,description:"List what would be deleted without deleting",type:"boolean"},logs:{alias:"l",default:!1,description:"Prune old _diag log files",type:"boolean"},shared:{alias:"s",default:!1,description:"Remove unused shared runner versions",type:"boolean"},work:{alias:"w",default:!1,description:"Delete _work contents of stopped runners",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class an extends R{name="cleanup";description="Free disk space used by logs, job workspaces, and old runner versions";args=vt;async execute(r){let n=r.config.get("profiles");if(Object.keys(n).length===0)throw new w("No profiles configured","Run hydra init to set up a profile");let e=nn(r.config.get("cleanup")),o=this.explicitTargets(r),i=o.length>0?o:e.targets,t=r.args.days>Co?r.args.days:e.olderThanDays;if(i.includes("work")&&!r.args.dryRun&&!r.args.yes&&r.interactive){if(!await sr({message:"Delete _work contents (checkouts and caches) of stopped runners?"}))i=i.filter((c)=>c!=="work")}let a=await tn({dryRun:r.args.dryRun,entries:r.config.get("runners")??[],now:Date.now(),olderThanDays:t,targets:i});if(this.printReport(a,r.args.dryRun),r.args.dryRun)return;r.config.set("cleanup",{...r.config.get("cleanup"),lastRun:new Date().toISOString()})}explicitTargets(r){let n=[];if(r.args.logs)n.push("logs");if(r.args.work)n.push("work");if(r.args.shared)n.push("shared");return n}printReport(r,n){let e=[];for(let[t,a]of Object.entries(r)){if(!a)continue;let s=bt[t],c=mr(a.freedBytes),f=n?`would remove ${a.removed} ${s}, ${c}`:`removed ${a.removed} ${s}, freed ${c}`;if(e.push(`${m.bold(t)}: ${a.removed>0?f:m.dim("nothing to do")}`),a.skipped.length>0)e.push(m.dim(` skipped running runner(s): ${a.skipped.join(", ")}`))}if(e.length===0){v.info(m.dim("Nothing to clean."));return}let o=en(r),i=n?"Would free":"Freed";e.push(m.dim(`${i} ${mr(o)} total`)),v.info(e.join(`
94
+ `))}}async function Ir(r){try{let n=nn(r.config.get("cleanup"));if(!n.auto)return;if(!Vn(n,Date.now()))return;let e=await tn({dryRun:!1,entries:r.config.get("runners")??[],now:Date.now(),olderThanDays:n.olderThanDays,targets:n.targets});r.config.set("cleanup",{...r.config.get("cleanup"),lastRun:new Date().toISOString()});let o=en(e);if(o>0)v.info(m.dim(`Auto cleanup freed ${mr(o)}`))}catch(n){let e=n instanceof Error?n.message:String(n);v.warn(m.yellow(`Auto cleanup failed: ${e}`))}}import{join as wt}from"path";function hr(r,n){if(r.length===0)return n;for(let e of r)if(!n.includes(e))throw new w(`Runner "${e}" not found`);return r}function z(r,n){let e=r.get("profiles");if(Object.keys(e).length===0)throw new w("No profiles configured","Run hydra init to set up a profile");let o=n??r.get("defaultProfile")??kr,i=e[o];if(!i)throw new w(`Profile "${o}" not found`);return{name:o,profile:i}}async function Q(r){let n=r.get("profiles"),e=Object.keys(n);if(e.length===0)throw new w("No profiles configured","Run hydra init to set up a profile");if(e.length===1)return e[0];return cr({message:"Select profile",options:e.map((o)=>({label:o,value:o,hint:n[o]?.url}))})}var Ct=G({profile:{description:"Profile name"},count:{description:"Number of runners to create (overrides profile)"}});class sn extends R{name="create";description="Create and register runners";positionals=Ct;async execute(r){let{name:n,profile:e}=r.interactive?z(r.config,await Q(r.config)):z(r.config,r.positionals.profile),o=r.interactive?await this.promptCount(e.numberOfMachines):r.positionals.count?Number.parseInt(r.positionals.count,10):e.numberOfMachines;if(!o||o<1)throw new w("Runner count must be at least 1");let i=x(e),t=Y();t.start("Downloading runner binary...");let{version:a}=await i.download();t.stop(`Runner v${a} ready`);let s=r.config.get("runners")??[],c=s.filter((l)=>l.profile===n),f=o-c.length;if(f<=0){v.warn(`Already have ${c.length} runner(s) for profile "${n}". Nothing to create.`);return}let d=new Set(s.map((l)=>l.id)),g=1;for(let l=0;l<f;){let b=`${e.name}-${g++}`;if(d.has(b))continue;l++,t.start(`Registering ${b}...`),await i.create([b]),t.stop(`${m.green("+")} ${b}`),s.push({createdAt:new Date().toISOString(),directory:wt(e.directory,b),id:b,name:b,profile:n,provider:e.provider,url:e.url})}r.config.set("runners",s);let h=n===r.config.get("defaultProfile")?"":` ${n}`;v.info(`${m.green("Created")} ${f} runner(s) for "${n}". Run ${m.green(`hydra start${h}`)} to start them.`)}async promptCount(r){let n=await rr({initialValue:String(r),message:"Number of runners to create",validate:(e)=>{let o=Number.parseInt(e??"",10);if(Number.isNaN(o)||o<1)return"Must be a positive number";return}});return Number.parseInt(n,10)}}import{existsSync as $o}from"fs";import{mkdir as yo}from"fs/promises";var $t=G({url:{description:"GitHub repository or organization URL"}}),yt=tr({force:{alias:"f",default:!1,description:"Overwrite existing config",type:"boolean"},labels:{alias:"l",description:"Comma-separated runner labels",type:"string"},name:{alias:"n",description:"Base name for runners",type:"string"},profile:{alias:"p",description:"Profile name",type:"string"},runners:{alias:"c",description:"Number of runners to create",type:"number"}});class cn extends R{name="init";description="Initialize Hydra runner manager";positionals=$t;args=yt;prompts=!0;async execute(r){let n=r.interactive?await this.promptProfileName(r):r.args.profile??kr,e=!r.config.exists();if(!e&&r.config.get("profiles")[n]&&!r.args.force){if(!r.interactive)throw new w(`Profile "${n}" already exists. Use --force to overwrite.`);if(!await sr({initialValue:!1,message:`Profile "${n}" already exists. Overwrite?`}))return}await this.ensureDirectories();let i=r.interactive?await this.runInitForm():this.buildProfileFromArgs(r),t=e?{}:{...r.config.get("profiles")};if(t[n]=i,r.config.set("profiles",t),!r.config.get("defaultProfile"))r.config.set("defaultProfile",n);lr([`${m.dim("Profile:")} ${n}`,`${m.dim("URL:")} ${i.url}`,`${m.dim("Runners:")} ${i.numberOfMachines}`,`${m.dim("Name:")} ${i.name}`,i.labels?`${m.dim("Labels:")} ${i.labels}`:"","",`Run ${m.green(`${Sr} create${n!==r.config.get("defaultProfile")?` ${n}`:""}`)} to provision runners.`].filter(Boolean).join(`
95
+ `),m.green(e?"Hydra initialized":`Profile "${n}" added`))}async promptProfileName(r){return rr({initialValue:r.args.profile??kr,message:"Profile name"})}async ensureDirectories(){if(!$o(ur))await yo(ur,{recursive:!0});if(!$o(Fr))await yo(Fr,{recursive:!0})}async runInitForm(){let r=await Wr({url:()=>rr({message:"GitHub repository or organization URL",placeholder:"https://github.com/owner/repo",validate:(n)=>{if(!n)return"URL is required";try{pr(n)}catch{return"Must be a GitHub repository or organization URL (https://github.com/<owner>/<repo> or https://github.com/<org>)"}return}}),name:()=>rr({initialValue:"runner",message:"Base name for runners",placeholder:"runner"}),runners:()=>rr({initialValue:"1",message:"Number of runners",placeholder:"1",validate:(n)=>{if(!n)return"Must be a positive number";let e=Number.parseInt(n,10);if(Number.isNaN(e)||e<1)return"Must be a positive number";return}}),labels:()=>rr({message:"Additional labels (comma-separated, optional)",placeholder:"self-hosted,macOS,ARM64"})},{onCancel:()=>{throw new O}});return{directory:Fr,labels:r.labels||void 0,name:r.name,numberOfMachines:Number.parseInt(r.runners,10)||1,os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:r.url}}buildProfileFromArgs(r){if(!r.positionals.url)throw new w("URL is required","Usage: hydra init <url>");return this.validateUrl(r.positionals.url),this.validateRunnerCount(r.args.runners),{directory:Fr,labels:r.args.labels,name:r.args.name??"runner",numberOfMachines:r.args.runners??1,os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:r.positionals.url}}validateUrl(r){try{pr(r)}catch(n){throw new w(n instanceof Error?n.message:`Invalid GitHub URL: ${r}`,"Expected https://github.com/<owner>/<repo> or https://github.com/<org>")}}validateRunnerCount(r){if(r!==void 0&&r<1)throw new w("Runner count must be at least 1")}detectOs(){let r=process.platform;if(r==="darwin")return"osx";if(r==="win32")return"windows";return"linux"}}import{existsSync as Pt}from"fs";import{readFile as Ft}from"fs/promises";var kt=100,Rt={runner:"runner daemon log",worker:"job log"},Lt=tr({lines:{alias:"n",default:kt,description:"Number of lines to tail",type:"number"},list:{alias:"l",default:!1,description:"List available log files instead of printing content",type:"boolean"},open:{alias:"o",default:!1,description:"Open the log file in $EDITOR instead of printing",type:"boolean"},runner:{alias:"r",default:!1,description:"Show the runner daemon log instead of the latest job log",type:"boolean"}}),Dt=G({id:{description:"Runner ID"}});class fn extends R{name="logs";description="Inspect logs of the latest jobs";args=Lt;positionals=Dt;async execute(r){let n=r.config.get("runners")??[];if(n.length===0)throw new w("No runners found","Run hydra create to provision runners");let e=await this.resolveEntry(r,n),o=r.config.get("profiles")[e.profile];if(!o)throw new w(`Profile "${e.profile}" not found for runner "${e.id}"`,"Run hydra init to set it up");if(!Pt(e.directory))throw new w(`Runner directory not found: ${e.directory}`,"Run hydra create to provision this runner");let t=await x(o).logFiles(e.id);if(t.length===0)this.noLogs(e.id);if(r.args.list){this.printList(e,t);return}let a=this.selectFile(r,e,t);if(r.args.open){await this.openFile(a);return}await this.printTail(e,a,r.args.lines)}async resolveEntry(r,n){let e=r.positionals.id;if(e){let i=n.find((t)=>t.id===e);if(!i)throw new w(`Runner "${e}" not found`,`Known runners: ${n.map((t)=>t.id).join(", ")}`);return i}if(r.interactive)return cr({message:"Select runner",options:n.map((i)=>({hint:i.profile,label:i.name,value:i}))});let o=n[0];if(n.length===1&&o)return o;throw new w("Multiple runners found",`Pass a runner id: hydra logs <id> (${n.map((i)=>i.id).join(", ")})`)}selectFile(r,n,e){if(r.args.runner){let i=e.find((t)=>t.type==="runner");if(!i)throw new w(`No runner daemon logs found for "${n.id}"`,"Start the runner first: hydra start");return i}let o=zn(e,"worker");if(!o)this.noLogs(n.id);if(o.fallback)v.warn(m.yellow("No job (Worker) logs yet; showing the runner daemon log instead"));return o.file}noLogs(r){throw new w(`No logs found for runner "${r}"`,"Logs appear once the runner has started; run hydra start")}printList(r,n){let e=[`${m.bold(r.name)} ${m.dim(r.directory)}`];for(let o of n){let i=o.type==="worker"?m.green("worker"):m.blue("runner");e.push(` ${i} ${o.name} ${m.dim(`${o.mtime.toISOString()} \xB7 ${mr(o.size)}`)}`)}v.info(e.join(`
96
+ `))}async printTail(r,n,e){let o=await Ft(n.path,"utf-8"),i=[`${m.bold(r.name)} ${m.dim(Rt[n.type])}`,m.dim(n.path),m.dim(`Last modified: ${n.mtime.toISOString()}`)];v.info(i.join(`
97
+ `)),console.log(Wn(o,e))}async openFile(r){let n=(process.env.EDITOR??"").split(" ").filter(Boolean),e=n[0];if(e){await Bun.spawn([e,...n.slice(1),r.path],{stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited;return}if(process.platform==="darwin"){await Bun.$`open ${r.path}`.quiet();return}throw new w("No editor configured","Set $EDITOR to open log files")}}var It=G({name:{description:"Profile name to set as default"}});class Sn extends R{name="default";description="Set the default profile";positionals=It;async execute(r){let n=r.interactive?await Q(r.config):r.positionals.name;if(!n)throw new w("Profile name is required","Usage: hydra profile default <name>");let{name:e}=z(r.config,n);if(r.config.get("defaultProfile")===e){v.info(`"${e}" is already the default profile.`);return}r.config.set("defaultProfile",e),v.info(`${m.green("Default profile set to")} "${e}".`)}}class Bn extends R{name="list";description="List all profiles";async execute(r){let n=r.config.get("profiles"),e=Object.keys(n);if(e.length===0)throw new w("No profiles configured","Run hydra init to set up a profile");let o=r.config.get("runners")??[],i=r.config.get("defaultProfile");for(let t of e){let a=n[t],c=await x(a).list(),f=o.filter((b)=>b.profile===t),d=new Set(c.filter((b)=>b.status==="running").map((b)=>b.id)),g=f.filter((b)=>d.has(b.id)).length,p=t===i,h=[`${m.dim("URL:")} ${a.url}`,`${m.dim("Provider:")} ${a.provider}`,`${m.dim("OS:")} ${a.os}`,`${m.dim("Name:")} ${a.name}`,`${m.dim("Runners:")} ${f.length}/${a.numberOfMachines} created, ${m.green(`${g} running`)}`];if(a.labels)h.push(`${m.dim("Labels:")} ${a.labels}`);let l=p?`${t} ${m.dim("(default)")}`:t;lr(h.join(`
98
+ `),l)}v.info(m.dim(`${e.length} profile(s)`))}}import{rm as Et}from"fs/promises";import{join as Ht}from"path";var Ut=G({name:{description:"Profile name to remove"}});class _n extends R{name="remove";description="Remove a profile";positionals=Ut;async execute(r){let n=r.interactive?await Q(r.config):r.positionals.name;if(!n)throw new w("Profile name is required","Usage: hydra profile remove <name>");let{profile:e}=z(r.config,n),o=r.config.get("runners")??[],i=o.filter((c)=>c.profile===n);if(i.length>0){if(!await sr({initialValue:!0,message:`This will stop and remove ${i.length} runner(s). Continue?`}))return;await this.removeRunners(e,i.map((d)=>d.id));let f=o.filter((d)=>d.profile!==n);r.config.set("runners",f)}let{[n]:t,...a}=r.config.get("profiles");if(r.config.set("profiles",a),r.config.get("defaultProfile")===n){let c=Object.keys(a);r.config.set("defaultProfile",c[0])}v.info(`${m.green("Removed")} profile "${n}".`)}async removeRunners(r,n){let e=x(r),o=Y();for(let i of n)o.start(`Stopping and removing ${i}...`),await e.stop([i]),await e.remove([i]),await Et(Ht(r.directory,i),{force:!0,recursive:!0}),o.stop(`${m.red("-")} ${i}`)}}class un extends R{name="profile";description="Manage profiles";init(){this.registerSubcommands([new Bn,new _n,new Sn])}}import{rm as Nt}from"fs/promises";import{join as jt}from"path";var At=G({profile:{description:"Profile name"},ids:{description:"Runner IDs (omit to target all)",variadic:!0}});class pn extends R{name="remove";description="Deregister and remove runners";positionals=At;async execute(r){let{name:n,profile:e}=r.interactive?z(r.config,await Q(r.config)):z(r.config,r.positionals.profile),o=r.config.get("runners")??[],i=o.filter((f)=>f.profile===n);if(i.length===0)throw new w(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=r.interactive?await this.promptRunnerSelection(i.map((f)=>f.id)):hr(r.positionals.ids??[],i.map((f)=>f.id)),a=x(e),s=Y();for(let f of t)s.start(`Stopping and removing ${f}...`),await a.stop([f]),await a.remove([f]),await Nt(jt(e.directory,f),{force:!0,recursive:!0}),s.stop(`${m.red("-")} ${f}`);let c=o.filter((f)=>!t.includes(f.id));r.config.set("runners",c),v.info(`${m.green("Removed")} ${t.length} runner(s).`)}async promptRunnerSelection(r){return fr({message:"Select runners to remove",options:r.map((n)=>({label:n,value:n})),required:!0})}}var Mt=G({profile:{description:"Profile name"},ids:{description:"Runner IDs (omit to target all)",variadic:!0}});class mn extends R{name="start";description="Start runners";positionals=Mt;async execute(r){let{name:n,profile:e}=r.interactive?z(r.config,await Q(r.config)):z(r.config,r.positionals.profile),i=(r.config.get("runners")??[]).filter((p)=>p.profile===n);if(i.length===0)throw new w(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=x(e),a=Y();a.start("Fetching runner status...");let s=await t.list();a.stop("Runner status fetched");let c=new Set(s.filter((p)=>p.status==="running").map((p)=>p.id)),f=i.map((p)=>p.id).filter((p)=>!c.has(p)),d=r.interactive?await this.promptRunnerSelection(f):hr(r.positionals.ids??[],i.map((p)=>p.id)),g=0;for(let p of d){if(c.has(p)){a.start(""),a.stop(`${m.dim("\u25CF")} ${p} ${m.dim("already running")}`);continue}a.start(`Starting ${p}...`),await t.start([p]),a.stop(`${m.green("\u25B6")} ${p}`),g++}v.info(`${m.green("Started")} ${g} runner(s).`),await Ir(r)}async promptRunnerSelection(r){if(r.length===0)throw new w("All runners are already running");return fr({message:"Select runners to start",options:r.map((n)=>({label:n,value:n})),required:!0})}}var Gt={registered:m.yellow,running:m.green,stopped:m.red,unknown:m.dim};class ln extends R{name="status";description="Show runner status across all profiles";async execute(r){let n=r.config.get("profiles"),e=Object.keys(n);if(e.length===0)throw new w("No profiles configured","Run hydra init to set up a profile");let o=r.config.get("runners")??[],i=0,t=0,a=[];for(let s of e){let c=n[s],d=await x(c).list();if(a.length>0)a.push("");a.push(`${m.bold(s)} ${m.dim(c.url)}`);let g=new Set(o.filter((h)=>h.profile===s).map((h)=>h.id)),p=d.filter((h)=>g.has(h.id)).sort((h,l)=>h.name.localeCompare(l.name,void 0,{numeric:!0}));this.formatRunners(p,a),i+=p.length,t+=p.filter((h)=>h.status==="running").length}a.push(""),a.push(m.dim(`${i} runner(s) total, ${t} running`)),v.info(a.join(`
99
+ `))}formatRunners(r,n){if(r.length===0){n.push(m.dim(" No runners."));return}for(let e of r){let o=Gt[e.status]??m.dim,i=e.pid?m.dim(` (pid: ${e.pid})`):"";n.push(` ${o("\u25CF")} ${e.name} ${o(e.status)}${i}`)}}}var xt=G({profile:{description:"Profile name"},ids:{description:"Runner IDs (omit to target all)",variadic:!0}});class dn extends R{name="stop";description="Stop runners";positionals=xt;async execute(r){let{name:n,profile:e}=r.interactive?z(r.config,await Q(r.config)):z(r.config,r.positionals.profile),i=(r.config.get("runners")??[]).filter((p)=>p.profile===n);if(i.length===0)throw new w(`No runners found for profile "${n}"`,"Run hydra create to provision runners");let t=x(e),a=Y();a.start("Fetching runner status...");let s=await t.list();a.stop("Runner status fetched");let c=new Set(s.filter((p)=>p.status==="running").map((p)=>p.id)),f=i.map((p)=>p.id).filter((p)=>c.has(p)),d=r.interactive?await this.promptRunnerSelection(f):hr(r.positionals.ids??[],i.map((p)=>p.id)),g=0;for(let p of d){if(!c.has(p)){a.start(""),a.stop(`${m.dim("\u25CF")} ${p} ${m.dim("not running")}`);continue}a.start(`Stopping ${p}...`),await t.stop([p]),a.stop(`${m.red("\u25A0")} ${p}`),g++}v.info(`${m.green("Stopped")} ${g} runner(s).`)}async promptRunnerSelection(r){if(r.length===0)throw new w("No runners are currently running");return fr({message:"Select runners to stop",options:r.map((n)=>({label:n,value:n})),required:!0})}}class gn extends R{name="update";description="Update runners to the latest version";async execute(r){let n=r.config.get("profiles"),e=r.config.get("runners")??[];if(e.length===0)throw new w("No runners found","Run hydra create to provision runners");let o=Y(),i=Map.groupBy(e,(c)=>c.profile),t=null,a="",s=!1;for(let[c,f]of i){let d=n[c],g=f[0];if(!d||!g)continue;let p=x(d);if(!s){if(s=!0,o.start("Checking for updates..."),a=(await p.download()).version,t=await p.currentVersion(g.id),o.stop(`Current: v${t??"unknown"} | Latest: v${a}`),t===a){v.info(`Already on latest version ${m.dim(`(v${a})`)}`),await Ir(r);return}}let h=await p.list(),l=new Set(h.filter((b)=>b.status==="running").map((b)=>b.id));for(let b of f){let F=l.has(b.id);if(o.start(`Updating ${b.id}...`),F)await p.stop([b.id]);if(await p.update([b.id]),F)await p.start([b.id]);let I=F?` ${m.dim("(restarted)")}`:"";o.stop(`${m.green("\u2713")} ${b.id}${I}`)}}v.info(`${m.green("Updated")} ${e.length} runner(s) from v${t} to v${a}`),await Ir(r)}}class Po extends xn{constructor(){super(new qn(Ve,Se),{bin:Sr,clearOnStart:!0,exitLabel:"Exit",goodbyeMessage:"Heads down.",name:"HYDRA",promptMessage:"What do you need?",version:Xe})}init(){this.registerCommands([new cn,new sn,new mn,new dn,new ln,new fn,new an,new pn,new gn,new un])}}var qt=new Po;qt.run();
package/package.json CHANGED
@@ -4,9 +4,6 @@
4
4
  "hydra": "dist/cli.js"
5
5
  },
6
6
  "description": "A tool for spawning multiple local GitHub self-hosted runners",
7
- "dependencies": {
8
- "@r5n/cli-core": "0.2.2"
9
- },
10
7
  "files": [
11
8
  "dist",
12
9
  "schema.json",
@@ -39,5 +36,5 @@
39
36
  },
40
37
  "type": "module",
41
38
  "types": "src/cli.ts",
42
- "version": "0.7.0"
39
+ "version": "0.9.0"
43
40
  }
package/schema.json CHANGED
@@ -3,6 +3,40 @@
3
3
  "$schema": "http://json-schema.org/draft-07/schema#",
4
4
  "additionalProperties": false,
5
5
  "definitions": {
6
+ "cleanup": {
7
+ "additionalProperties": false,
8
+ "properties": {
9
+ "auto": {
10
+ "default": false,
11
+ "description": "Run cleanup automatically after hydra start and hydra update",
12
+ "type": "boolean"
13
+ },
14
+ "intervalHours": {
15
+ "default": 24,
16
+ "description": "Minimum hours between automatic cleanup runs",
17
+ "minimum": 1,
18
+ "type": "integer"
19
+ },
20
+ "lastRun": {
21
+ "description": "ISO timestamp of the last cleanup run; managed by Hydra, do not edit by hand",
22
+ "format": "date-time",
23
+ "type": "string"
24
+ },
25
+ "olderThanDays": {
26
+ "default": 7,
27
+ "description": "Prune log files older than this many days",
28
+ "minimum": 0,
29
+ "type": "integer"
30
+ },
31
+ "targets": {
32
+ "default": ["logs", "shared"],
33
+ "description": "What to clean: _diag log files, _work job workspaces, unused shared runner versions",
34
+ "items": { "enum": ["logs", "work", "shared"], "type": "string" },
35
+ "type": "array"
36
+ }
37
+ },
38
+ "type": "object"
39
+ },
6
40
  "profile": {
7
41
  "additionalProperties": false,
8
42
  "properties": {
@@ -71,6 +105,10 @@
71
105
  "description": "Configuration for Hydra GitHub self-hosted runner manager",
72
106
  "properties": {
73
107
  "$schema": { "description": "JSON Schema reference for IDE support", "type": "string" },
108
+ "cleanup": {
109
+ "$ref": "#/definitions/cleanup",
110
+ "description": "Disk cleanup behavior for hydra cleanup and automatic cleanup"
111
+ },
74
112
  "defaultProfile": { "description": "The default profile to use when no profile is specified", "type": "string" },
75
113
  "profiles": {
76
114
  "additionalProperties": { "$ref": "#/definitions/profile" },