gibil 0.1.5 → 0.1.7
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 +2 -2
- package/dist/index.js +20 -20
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
<p align="center"><strong>Full servers. Forged in seconds. Gone when done.</strong></p>
|
|
8
8
|
|
|
9
9
|
<p align="center">
|
|
10
|
-
<img src="https://img.shields.io/badge/version-0.1.
|
|
11
|
-
<img src="https://img.shields.io/badge/tests-
|
|
10
|
+
<img src="https://img.shields.io/badge/version-0.1.6-blue" alt="Version 0.1.6" />
|
|
11
|
+
<img src="https://img.shields.io/badge/tests-116%20passing-brightgreen" alt="Tests: 116 passing" />
|
|
12
12
|
<img src="https://img.shields.io/badge/typescript-%3E5.0-3178C6" alt="TypeScript" />
|
|
13
13
|
<img src="https://img.shields.io/badge/node-%3E%3D20-339933" alt="Node >= 20" />
|
|
14
14
|
<img src="https://img.shields.io/badge/license-proprietary-red" alt="License: Proprietary" />
|
package/dist/index.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
${
|
|
4
|
-
${
|
|
5
|
-
${
|
|
6
|
-
${
|
|
7
|
-
${
|
|
8
|
-
${
|
|
9
|
-
|
|
2
|
+
var ft=Object.defineProperty;var _e=(t,e)=>()=>(t&&(e=t(t=0)),e);var mt=(t,e)=>{for(var n in e)ft(t,n,{get:e[n],enumerable:!0})};import{homedir as wt}from"os";import{join as U}from"path";var G,w,R=_e(()=>{"use strict";G=U(wt(),".gibil"),w={root:G,instances:U(G,"instances"),keys:U(G,"keys"),instanceFile:t=>U(G,"instances",`${t}.json`),keyDir:t=>U(G,"keys",t),privateKey:t=>U(G,"keys",t,"id_ed25519"),publicKey:t=>U(G,"keys",t,"id_ed25519.pub")}});var be={};mt(be,{clearApiKey:()=>ye,fetchUsage:()=>$e,getApiKey:()=>A,getApiUrl:()=>It,getApiUrlFromConfig:()=>oe,getHetznerToken:()=>ve,getServerDefaults:()=>Et,saveApiKey:()=>X,saveHetznerToken:()=>Q,saveServerDefaults:()=>we,trackUsage:()=>W,verifyApiKey:()=>M});import{readFile as $t,writeFile as bt,mkdir as xt}from"fs/promises";import{existsSync as St}from"fs";import{join as kt}from"path";async function L(){if(!St(he))return{};let t=await $t(he,"utf-8");return JSON.parse(t)}async function ie(t){await xt(w.root,{recursive:!0,mode:448}),await bt(he,JSON.stringify(t,null,2),{mode:384})}async function X(t){let e=await L();e.api_key=t,await ie(e)}async function A(){return process.env.GIBIL_API_KEY?process.env.GIBIL_API_KEY:(await L()).api_key??null}async function ye(){let t=await L();delete t.api_key,await ie(t)}function It(){return process.env.GIBIL_API_URL??He}async function oe(){return process.env.GIBIL_API_URL?process.env.GIBIL_API_URL:(await L()).api_url??He}async function Q(t){let e=await L();e.hetzner_token=t,await ie(e)}async function ve(){return process.env.HETZNER_API_TOKEN?process.env.HETZNER_API_TOKEN:(await L()).hetzner_token??null}async function we(t,e){let n=await L();n.default_server_type=t,n.default_location=e,await ie(n)}async function Et(){let t=await L();return{serverType:t.default_server_type??"cax11",location:t.default_location??"fsn1"}}async function M(t){let e=await oe(),n=await fetch(`${e}/auth-verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t})});if(n.status===401)throw new Error("Invalid API key. Get one at https://gibil.dev");if(!n.ok){let s=await n.text();throw new Error(`API error (${n.status}): ${s}`)}return await n.json()}async function W(t,e,n,s){let i=await oe(),c=await fetch(`${i}/usage-track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,instance_name:n,server_type:s})});if(c.status===429)throw new Error("Plan limit reached. Upgrade at https://gibil.dev/pricing");if(!c.ok){let r=await c.text();throw new Error(`Usage tracking failed (${c.status}): ${r}`)}}async function $e(t){let e=await oe(),n=await fetch(`${e}/usage-get`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok){let s=await n.text();throw new Error(`Failed to fetch usage (${n.status}): ${s}`)}return await n.json()}var he,He,D=_e(()=>{"use strict";R();he=kt(w.root,"config.json"),He="https://zopdxjruwktjyjunitrv.supabase.co/functions/v1"});import{Command as pn}from"commander";import{readFileSync as dn}from"fs";import{fileURLToPath as gn}from"url";import{dirname as fn,join as mn}from"path";import J from"picocolors";var N=t=>J.red(t),ht=t=>J.yellow(t),z=t=>J.green(t),yt=t=>J.red(t),p=t=>J.dim(t),y=t=>J.bold(t),I="\u{1F98E}";var H=z("\u2713"),Z=yt("\u2716"),Te=ht("\u26A0"),re="\u{12248}",Ae=`
|
|
3
|
+
${N(" /\\")}
|
|
4
|
+
${N(" / \\")}
|
|
5
|
+
${N(" / \u{1F525} \\")}
|
|
6
|
+
${N(" / \\")}
|
|
7
|
+
${p(" ~~~~~~~~")}
|
|
8
|
+
${y(" g i b i l")} ${p(re)}
|
|
9
|
+
`,Pe=`${I} ${y("gibil")} ${p(re)}`,Ce=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],V=class{timer=null;frame=0;text;constructor(e){this.text=e}start(){return process.stderr.isTTY?(this.timer=setInterval(()=>{let e=N(Ce[this.frame%Ce.length]);process.stderr.write(`\r ${e} ${this.text}`),this.frame++},80),this):(process.stderr.write(` ${this.text}
|
|
10
10
|
`),this)}update(e){this.text=e,process.stderr.isTTY||process.stderr.write(` ${e}
|
|
11
|
-
`)}succeed(e){this.stop(),process.stderr.write(`\r ${
|
|
12
|
-
`)}fail(e){this.stop(),process.stderr.write(`\r ${
|
|
13
|
-
`)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,process.stderr.isTTY&&process.stderr.write("\r\x1B[K"))}};function
|
|
14
|
-
`)}function
|
|
15
|
-
`)}function Et(t){let e=[];if(t.startsWith("node:")){let n=t.split(":")[1]??"20";e.push("# Install Node.js"),e.push(`curl -fsSL https://deb.nodesource.com/setup_${n}.x | bash - > /dev/null 2>&1`),e.push("apt-get install -y -qq nodejs > /dev/null 2>&1"),e.push("npm install -g pnpm@latest > /dev/null 2>&1"),e.push("")}else if(t.startsWith("python:")){let n=t.split(":")[1]??"3.12";e.push("# Install Python"),e.push(`apt-get install -y -qq python${n} python3-pip python3-venv > /dev/null 2>&1`),e.push("")}else if(t.startsWith("go:")){let n=t.split(":")[1]??"1.22";e.push("# Install Go"),e.push('GO_ARCH=$(uname -m | sed "s/x86_64/amd64/" | sed "s/aarch64/arm64/")'),e.push(`wget -q https://go.dev/dl/go${n}.linux-\${GO_ARCH}.tar.gz -O /tmp/go.tar.gz`),e.push("tar -C /usr/local -xzf /tmp/go.tar.gz"),e.push("export PATH=$PATH:/usr/local/go/bin"),e.push('echo "export PATH=\\$PATH:/usr/local/go/bin" >> /root/.bashrc'),e.push("")}else e.push("# Install Node.js (default)"),e.push("curl -fsSL https://deb.nodesource.com/setup_20.x | bash - > /dev/null 2>&1"),e.push("apt-get install -y -qq nodejs > /dev/null 2>&1"),e.push("npm install -g pnpm@latest > /dev/null 2>&1"),e.push("");return e}function At(){return["# Install Docker","curl -fsSL https://get.docker.com | sh > /dev/null 2>&1","systemctl enable docker --now"]}function _t(t){let e=[];e.push(`# Start service: ${t.name.replace(/[^a-zA-Z0-9_-]/g,"")}`);let i=`docker run -d --name ${t.name.replace(/[^a-zA-Z0-9_-]/g,"")}`;if(t.port&&(i+=` -p ${t.port}:${t.port}`),t.env)for(let[r,a]of Object.entries(t.env))i+=` -e ${r}=${S(a)}`;return i+=` ${t.image}`,e.push(i),e.push(""),e}function S(t){return`'${t.replace(/'/g,"'\\''")}'`}import{readFile as Pt}from"fs/promises";import{existsSync as _e,statSync as Tt}from"fs";import{join as jt}from"path";import{parse as Te}from"yaml";var Ht=".gibil.yml";async function ue(t){let e;if(_e(t)&&Tt(t).isFile()?e=t:e=jt(t,Ht),!_e(e))return null;let n=await Pt(e,"utf-8"),i=Te(n);return He(i)}function je(t){let e=Te(t);return He(e)}function He(t){if(!t||typeof t!="object")throw new Error("Invalid .gibil.yml: must be a YAML object");let e=t,n={};return typeof e.name=="string"&&(n.name=e.name),typeof e.image=="string"&&(n.image=e.image),typeof e.server_type=="string"&&(n.server_type=e.server_type),typeof e.location=="string"&&(n.location=e.location),Array.isArray(e.services)&&(n.services=e.services.map(i=>{let r=i;if(typeof r.name!="string"||typeof r.image!="string")throw new Error("Each service must have a 'name' and 'image' field");return{name:r.name,image:r.image,port:typeof r.port=="number"?r.port:void 0,env:Pe(r.env,`service "${r.name}"`)}})),Array.isArray(e.tasks)&&(n.tasks=e.tasks.map(i=>{let r=i;if(typeof r.name!="string"||typeof r.command!="string")throw new Error("Each task must have a 'name' and 'command' field");return{name:r.name,command:r.command}})),e.env!==void 0&&(n.env=Pe(e.env,"top-level")),n}function Pe(t,e){if(t==null)return;if(typeof t!="object"||Array.isArray(t))throw new Error(`env in ${e} must be a key-value object`);let n={};for(let[i,r]of Object.entries(t))if(typeof r=="string")n[i]=r;else if(typeof r=="number"||typeof r=="boolean")n[i]=String(r);else throw new Error(`env.${i} in ${e} must be a string, number, or boolean \u2014 got ${typeof r}`);return Object.keys(n).length>0?n:void 0}M();import{readFile as Ot,writeFile as Nt,mkdir as Oe,rm as Rt,readdir as Kt}from"fs/promises";import{existsSync as Ne}from"fs";import{join as pe}from"path";var ge=class{instancesDir;keysDir;constructor(e){let n=e??y.root;this.instancesDir=pe(n,"instances"),this.keysDir=pe(n,"keys")}async ensureDirectories(){await Oe(this.instancesDir,{recursive:!0,mode:448}),await Oe(this.keysDir,{recursive:!0,mode:448})}instanceFile(e){return pe(this.instancesDir,`${e}.json`)}async save(e){await this.ensureDirectories(),await Nt(this.instanceFile(e.name),JSON.stringify(e,null,2),{mode:384})}async load(e){let n=this.instanceFile(e);if(!Ne(n))return null;let i=await Ot(n,"utf-8");return JSON.parse(i)}async loadOrThrow(e){let n=await this.load(e);if(!n)throw new Error(`Instance "${e}" not found. Run "gibil list" to see active instances.`);return n}async loadActiveOrThrow(e){let n=await this.loadOrThrow(e);if(new Date>new Date(n.expiresAt))throw new Error(`Instance "${e}" has expired (TTL was ${n.ttlMinutes}m). Run "gibil destroy ${e}" to clean up.`);return n}async delete(e){let n=this.instanceFile(e);Ne(n)&&await Rt(n)}async list(){await this.ensureDirectories();let e=await Kt(this.instancesDir),n=[];for(let i of e){if(!i.endsWith(".json"))continue;let r=i.replace(".json",""),a=await this.load(r);a&&n.push(a)}return n}},W=new ge;var ee=t=>W.save(t);var Re=t=>W.loadOrThrow(t),E=t=>W.loadActiveOrThrow(t),Ke=t=>W.delete(t),te=()=>W.list();import{randomBytes as Mt}from"crypto";function Me(t=6){return Mt(Math.ceil(t/2)).toString("hex").slice(0,t)}function Le(){return`gibil-${Me()}`}function ze(){return`fleet-${Me(8)}`}M();var Lt=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}$/;function Ge(t){if(!Lt.test(t))throw new Error(`Invalid instance name "${t}". Names must be 1-63 chars, start with alphanumeric, and contain only [a-zA-Z0-9_-].`);return t}function de(t,e){let n=parseInt(t,10);if(isNaN(n)||n<=0)throw new Error(`${e} must be a positive integer, got "${t}"`);return n}L();import{execSync as ne}from"child_process";import{readFileSync as zt}from"fs";function Gt(){try{let t=ne("git config user.name",{encoding:"utf-8"}).trim(),e=ne("git config user.email",{encoding:"utf-8"}).trim();if(!t||!e)return;let n;try{if(ne("git config gpg.format",{encoding:"utf-8"}).trim()==="ssh"){let r=ne("git config user.signingkey",{encoding:"utf-8"}).trim();if(r)try{n=zt(r,"utf-8").trim()}catch{(r.startsWith("ssh-")||r.startsWith("key::"))&&(n=r.replace(/^key::/,""))}}}catch{}return{name:t,email:e,signingKey:n}}catch{return}}async function De(t,e,n){o.step("Generating SSH keys...");let i=await Ce(e),r;try{o.step("Uploading SSH key..."),r=await t.createSSHKey(`gibil-${e}`,i.publicKey);let a=Gt(),s=Ae({repo:n.repo,config:n.config??void 0,ttlMinutes:n.ttlMinutes,githubToken:process.env.GITHUB_TOKEN,gitIdentity:a});o.step("Creating server...");let c=await t.createServer(e,r.id,s,n.config?.server_type??n.serverType,n.config?.location??n.location);o.step("Waiting for server...");let p=(await t.waitForReady(c.id)).public_net.ipv4.ip,f=new Date,v={name:e,serverId:c.id,ip:p,sshKeyId:r.id,keyPath:y.privateKey(e),status:"running",createdAt:f.toISOString(),ttlMinutes:n.ttlMinutes,expiresAt:new Date(f.getTime()+n.ttlMinutes*6e4).toISOString(),repo:n.repo,fleetId:n.fleetId,gitIdentity:a};return await ee(v),o.step(`Waiting for SSH on ${p}...`),await Ee(e,p),v}catch(a){if(o.error(`Failed to create instance "${e}", cleaning up...`),await Q(e).catch(s=>o.warn(`Could not clean up SSH keys: ${s instanceof Error?s.message:String(s)}`)),r){let s=r.id;await t.deleteSSHKey(s).catch(c=>o.warn(`Could not delete Hetzner SSH key ${s}: ${c instanceof Error?c.message:String(c)}`))}throw a}}function Fe(t){let e=Math.max(0,Math.floor((new Date(t.expiresAt).getTime()-Date.now())/1e3));return{name:t.name,ip:t.ip,ssh:`ssh -i ${t.keyPath} -o StrictHostKeyChecking=no root@${t.ip}`,status:t.status,ttl_remaining:e,created_at:t.createdAt,fleet_id:t.fleetId}}async function Dt(t){let e=t.match(/github\.com\/([^/]+)\/([^/.]+)/);if(!e)return o.debug(`Cannot fetch config from non-GitHub repo: ${t}`),null;let[,n,i]=e,r=`https://raw.githubusercontent.com/${n}/${i}/HEAD/.gibil.yml`;o.debug(`Fetching config from ${r}`);try{let a=await fetch(r,{signal:AbortSignal.timeout(1e4)});if(!a.ok)return o.debug(`No .gibil.yml found in repo (${a.status})`),null;let s=await a.text();return je(s)}catch{return o.debug("Failed to fetch repo config, continuing without it"),null}}function Ue(t){t.command("create").description("Spin up one or more ephemeral dev machines").option("-n, --name <name>","Instance name").option("-f, --fleet <count>","Number of instances to create in parallel").option("-r, --repo <git-url>","Git repository to clone on startup").option("--json","Output instance info as JSON").option("--ttl <minutes>","Auto-destroy after N minutes","60").option("-c, --config <path>","Path to .gibil.yml config").option("--server-type <type>","Hetzner server type (e.g. cpx11, cpx21)").option("--location <loc>","Hetzner location (e.g. fsn1, nbg1)").option("-q, --quiet","Suppress non-essential output").action(async e=>{e.json&&m(!0);let n=de(e.ttl??"60","TTL");if(n>10080)throw new Error("TTL cannot exceed 7 days (10080 minutes).");let i=de(e.fleet??"1","Fleet count");if(i>20)throw new Error("Fleet size cannot exceed 20. Contact support for higher limits.");e.name&&Ge(e.name);let r=null;e.config?r=await ue(e.config):e.repo?r=await Dt(e.repo):r=await ue(process.cwd());let a=await C();if(a){o.info("Verifying API key...");let c=await H(a);o.info(` Authenticated as ${c.user.email} (${c.user.plan})`)}let s=await z.create();if(i===1){let c=e.name??Le(),l=Date.now(),p=o.spin(`Forging "${c}"...`),f=await De(s,c,{repo:e.repo,ttlMinutes:n,config:r,serverType:e.serverType,location:e.location}),v=((Date.now()-l)/1e3).toFixed(1);p.succeed(h.createReady(c,v)),a&&await F(a,"create",f.name,e.serverType).catch(d=>o.debug(`Usage tracking failed: ${d instanceof Error?d.message:String(d)}`)),e.json?o.json(Fe(f)):(o.info(""),o.info(ve("Server ready",[`${u("Name:")} ${g(f.name)}`,`${u("IP:")} ${f.ip}`,`${u("TTL:")} ${n} minutes`,`${u("SSH:")} ${g(`gibil ssh ${f.name}`)}`])),o.info(""))}else{let c=ze(),l=e.name??"gibil",p=Date.now(),f=o.spin(`Forging fleet "${c}" \u2014 ${i} servers...`),v=Array.from({length:i},(w,I)=>`${l}-${I+1}-${c.slice(6)}`),d=await Promise.allSettled(v.map(w=>De(s,w,{repo:e.repo,ttlMinutes:n,config:r,serverType:e.serverType,location:e.location,fleetId:c}))),$=[],A=[];for(let w=0;w<d.length;w++){let I=d[w];I.status==="fulfilled"?$.push(I.value):A.push(`${v[w]}: ${I.reason instanceof Error?I.reason.message:String(I.reason)}`)}let O=((Date.now()-p)/1e3).toFixed(1);if(f.succeed(h.fleetReady($.length,i)+` ${u(`(${O}s)`)}`),a&&await Promise.all($.map(w=>F(a,"create",w.name,e.serverType).catch(I=>o.debug(`Usage tracking failed for ${w.name}: ${I instanceof Error?I.message:String(I)}`)))),e.json)o.json({fleet_id:c,instances:$.map(Fe),errors:A});else{o.info("");for(let w of $)o.info(` ${_} ${g(w.name)} ${u("\u2192")} ${w.ip}`);for(let w of A)o.info(` ${q} ${w}`);o.info("")}}})}import{spawn as Ft}from"child_process";function Be(t){t.command("ssh <name>").description("SSH into a running ephemeral machine").action(async e=>{let n=await E(e),i=["-A","-i",n.keyPath,"-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR",`root@${n.ip}`];Ft("ssh",i,{stdio:"inherit"}).on("exit",a=>{process.exit(a??0)})})}function qe(t){t.command("run <name> <command...>").description("Execute a command on a running instance").option("--json","Output result as JSON").action(async(e,n,i)=>{i.json&&m(!0);let r=await E(e),a=n.join(" ");o.info(`Running on "${e}" (${r.ip}): ${a}`);let s=await P({instanceName:e,ip:r.ip,command:a,stream:!i.json});i.json?o.json({instance:e,command:a,stdout:s.stdout,stderr:s.stderr,exit_code:s.exitCode}):s.exitCode!==0&&o.error(`Command exited with code ${s.exitCode}`),process.exit(s.exitCode??1)})}L();async function Je(t,e){let n=await Re(e);o.info(`Destroying instance "${e}" (server ${n.serverId})...`);try{await t.destroyServer(n.serverId)}catch(r){o.warn(`Could not delete server ${n.serverId}: ${r instanceof Error?r.message:String(r)}`)}try{await t.deleteSSHKey(n.sshKeyId)}catch(r){o.warn(`Could not delete SSH key ${n.sshKeyId}: ${r instanceof Error?r.message:String(r)}`)}await Q(e),await Ke(e);let i=await C();i&&await F(i,"destroy",e).catch(r=>o.warn(`Usage tracking failed (billing may be inaccurate): ${r instanceof Error?r.message:String(r)}`)),o.info(` ${_} ${h.destroySingle(e)}`)}function Ve(t){t.command("destroy [name]").description("Destroy a running ephemeral machine").option("-a, --all","Destroy all gibil instances").option("--json","Output result as JSON").action(async(e,n)=>{if(n.json&&m(!0),n.all){let i=await te();if(i.length===0){n.json?o.json({destroyed:[],failed:[]}):o.info(h.noInstances);return}let r=await z.create();o.info(`Destroying ${i.length} instance(s)...`);let a=await Promise.allSettled(i.map(l=>Je(r,l.name))),s=[],c=[];for(let l=0;l<a.length;l++)if(a[l].status==="fulfilled")s.push(i[l].name);else{let p=a[l].reason;c.push(`${i[l].name}: ${p instanceof Error?p.message:String(p)}`)}n.json?o.json({destroyed:s,failed:c}):c.length===0?o.info(`
|
|
16
|
-
${
|
|
17
|
-
${
|
|
18
|
-
${
|
|
19
|
-
`)||"(no output)"}],isError:
|
|
20
|
-
${
|
|
11
|
+
`)}succeed(e){this.stop(),process.stderr.write(`\r ${H} ${e??this.text}
|
|
12
|
+
`)}fail(e){this.stop(),process.stderr.write(`\r ${Z} ${e??this.text}
|
|
13
|
+
`)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,process.stderr.isTTY&&process.stderr.write("\r\x1B[K"))}};function je(t,e){let n=Math.max(t.length+4,...e.map(a=>fe(a).length+4)),s=`${p("\u256D")}${p("\u2500".repeat(n))}${p("\u256E")}`,i=`${p("\u2570")}${p("\u2500".repeat(n))}${p("\u256F")}`,c=`${p("\u2502")} ${I} ${y(t)}${" ".repeat(n-fe(t).length-4)}${p("\u2502")}`,r=`${p("\u251C")}${p("\u2500".repeat(n))}${p("\u2524")}`,l=e.map(a=>{let u=n-fe(a).length-2;return`${p("\u2502")} ${a}${" ".repeat(Math.max(0,u))}${p("\u2502")}`});return[s,c,r,...l,i].join(`
|
|
14
|
+
`)}function fe(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}var x={welcome:`${I} Your first fire. Welcome to Gibil.`,noInstances:`${I} No fires burning. Gibil sleeps.`,destroyAll:`${I} All fires extinguished. Gibil moves on.`,destroySingle:t=>`${I} "${t}" \u2014 fire out.`,authSuccess:`${I} Logged in. The forge is yours.`,authLogout:`${I} Logged out. The forge cools.`,createReady:(t,e)=>`${I} "${t}" forged ${p(`(${e}s)`)}`,fleetReady:(t,e)=>`${I} Fleet forged \u2014 ${t}/${e} fires lit.`,ttlWarning:(t,e)=>`${I} ${t} \u2014 flame is low (${e}m remaining)`,initComplete:`${I} The forge is ready. Run ${y("gibil create")} to light your first fire.`,setupNeeded:`${I} No forge configured. Run ${y("gibil init")} to get started.`};var vt="info",me=!1,Oe={debug:0,info:1,warn:2,error:3,silent:4};function $(t){me=t}function K(t){return me&&t!=="error"?!1:Oe[t]>=Oe[vt]}var o={debug(t,...e){K("debug")&&console.debug(`${p("[debug]")} ${t}`,...e)},info(t,...e){K("info")&&console.log(t,...e)},warn(t,...e){K("warn")&&console.warn(`${Te} ${t}`,...e)},error(t,...e){K("error")&&console.error(`${Z} ${t}`,...e)},success(t){K("info")&&console.log(`${H} ${t}`)},step(t){K("info")&&console.log(` ${p("\u203A")} ${t}`)},flame(t){K("info")&&console.log(t)},detail(t,e){K("info")&&console.log(` ${p(t+":")} ${e}`)},spin(t){return me?new V(t):new V(t).start()},json(t){console.log(JSON.stringify(t,null,2))}};var _t="https://api.hetzner.cloud/v1",P=class t{token;constructor(e){this.token=e}static async create(e){let{getHetznerToken:n}=await Promise.resolve().then(()=>(D(),be)),s=e??await n();if(!s)throw new Error("HETZNER_API_TOKEN is required. Run 'gibil init' or set it in your environment.");return new t(s)}async request(e,n,s){let i=`${_t}${n}`;o.debug(`${e} ${i}`);let c=await fetch(i,{method:e,headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0});if(!c.ok){let r=await c.text(),l;try{l=JSON.parse(r).error?.message??r}catch{l=r}throw new Error(`Hetzner API error (${c.status}): ${l}`)}return c.status===204?{}:await c.json()}async createServer(e,n,s,i,c){if(!i||!c){let{getServerDefaults:u}=await Promise.resolve().then(()=>(D(),be)),f=await u();i=i??f.serverType,c=c??f.location}if(i.startsWith("cax")&&!["fsn1","nbg1"].includes(c))throw new Error(`ARM server type "${i}" is not available in "${c}". Use --location fsn1 or --location nbg1, or switch to an x86 type (cpx11, cpx21, etc.).`);let a={name:e,server_type:i,image:"ubuntu-24.04",ssh_keys:[n],labels:{gibil:"true","gibil-name":e},location:c};o.debug(`createServer payload: ${JSON.stringify({name:e,server_type:i,image:"ubuntu-24.04",location:c})}`),s&&(a.user_data=s);try{return(await this.request("POST","/servers",a)).server}catch(u){let f=`(server_type=${i}, location=${c}). Try a different --server-type or --location.`;throw u instanceof Error?new Error(`${u.message} ${f}`):u}}async destroyServer(e){await this.request("DELETE",`/servers/${e}`)}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}async listServers(e="gibil=true"){return(await this.request("GET",`/servers?label_selector=${encodeURIComponent(e)}&per_page=50`)).servers}async waitForReady(e,n=12e4){let s=Date.now(),i=3e3;for(;Date.now()-s<n;){let c=await this.getServer(e);if(c.status==="running"&&c.public_net.ipv4.ip!=="0.0.0.0")return c;o.debug(`Server ${e} status: ${c.status}, waiting...`),await new Promise(r=>setTimeout(r,i))}throw new Error(`Server ${e} did not become ready within ${n/1e3}s`)}async createSSHKey(e,n){return(await this.request("POST","/ssh_keys",{name:e,public_key:n})).ssh_key}async deleteSSHKey(e){await this.request("DELETE",`/ssh_keys/${e}`)}};R();import{mkdir as Ct,rm as Ne,readFile as Tt,chmod as At}from"fs/promises";import{existsSync as Ke}from"fs";import{execFile as Pt}from"child_process";import{promisify as jt}from"util";var Ot=jt(Pt);async function se(t){let e=w.keyDir(t);Ke(e)&&await Ne(e,{recursive:!0}),await Ct(e,{recursive:!0});let n=w.privateKey(t),s=w.publicKey(t);await Ot("ssh-keygen",["-t","ed25519","-f",n,"-N","","-C",`gibil-${t}`]),await At(n,384);let i=await Tt(s,"utf-8");return{privateKeyPath:n,publicKeyPath:s,publicKey:i.trim()}}async function Y(t){let e=w.keyDir(t);Ke(e)&&await Ne(e,{recursive:!0})}R();import{Client as Ht}from"ssh2";import{readFile as Nt}from"fs/promises";async function C(t){let{instanceName:e,ip:n,command:s,stream:i=!1,timeoutMs:c=3e4}=t,r=await Nt(w.privateKey(e),"utf-8");return new Promise((l,a)=>{let u=new Ht,f="",g="";u.on("ready",()=>{o.debug(`SSH connected to ${n}`),u.exec(s,(d,m)=>{if(d)return u.end(),a(d);m.on("data",v=>{let S=v.toString();f+=S,i&&process.stdout.write(S)}),m.stderr.on("data",v=>{let S=v.toString();g+=S,i&&process.stderr.write(S)}),m.on("close",v=>{u.end(),l({stdout:f,stderr:g,exitCode:v??0})})})}).on("error",d=>{let m="";d.code==="ECONNREFUSED"?m=" (instance may have been destroyed or is still booting)":d.code==="EHOSTUNREACH"?m=" (IP unreachable \u2014 instance may not be running)":d.code==="ETIMEDOUT"&&(m=" (connection timed out \u2014 check if instance is running with 'gibil list')"),a(new Error(`SSH connection to ${n} failed: ${d.message}${m}`))}).connect({host:n,port:22,username:"root",privateKey:r,readyTimeout:c,hostVerifier:()=>!0,agent:process.env.SSH_AUTH_SOCK,agentForward:!0})})}async function ae(t,e,n=12e4){let s=Date.now(),i=5e3;for(;Date.now()-s<n;)try{await C({instanceName:t,ip:e,command:"echo ready",timeoutMs:1e4});return}catch{o.debug(`SSH not ready on ${e}, retrying...`),await new Promise(c=>setTimeout(c,i))}throw new Error(`SSH did not become available on ${e} within ${n/1e3}s`)}function ce(t){let{repo:e,config:n,ttlMinutes:s,githubToken:i,gitIdentity:c}=t,r=["#!/bin/bash","set -euo pipefail","","# \u2500\u2500 Gibil cloud-init \u2500\u2500","export HOME=/root","export DEBIAN_FRONTEND=noninteractive"];i&&r.push(`export GITHUB_TOKEN=${T(i)}`),r.push("","# Base packages","apt-get update -qq","apt-get install -y -qq git curl wget build-essential unzip > /dev/null 2>&1","","# Install GitHub CLI","if ! type gh > /dev/null 2>&1; then"," curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg 2>/dev/null"," chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg"," ARCH=$(dpkg --print-architecture)",' echo "deb [arch=${ARCH} signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" > /etc/apt/sources.list.d/github-cli.list'," apt-get update -qq && apt-get install -y -qq gh > /dev/null 2>&1","fi","");let l=n?.image??"node:20";if(r.push(...Kt(l)),n?.services&&n.services.length>0){r.push(...Rt()),r.push("");for(let a of n.services)r.push(...Lt(a))}if(n?.env){r.push("# Environment variables");for(let[a,u]of Object.entries(n.env))r.push(`export ${a}=${T(u)}`),r.push(`echo 'export ${a}=${T(u)}' >> /root/.bashrc`);r.push("")}if(r.push("# Configure git"),c?(r.push(`git config --global user.email ${T(c.email)}`),r.push(`git config --global user.name ${T(c.name)}`),c.signingKey&&(r.push("git config --global gpg.format ssh"),r.push(`git config --global user.signingkey ${T("key::"+c.signingKey)}`),r.push("git config --global commit.gpgsign true"),r.push("git config --global tag.gpgsign true"),r.push("mkdir -p /root/.ssh"),r.push(`echo ${T(c.email+" "+c.signingKey)} > /root/.ssh/allowed_signers`),r.push("git config --global gpg.ssh.allowedSignersFile /root/.ssh/allowed_signers"))):(r.push("git config --global user.email 'gibil@bot.dev'"),r.push("git config --global user.name 'Gibil Bot'")),r.push(""),e){let a=e.match(/github\.com\/([^/]+\/[^/.]+)/);r.push("# Clone repository"),r.push("cd /root"),a?(r.push('if [ -n "${GITHUB_TOKEN:-}" ]; then'),r.push(` CLONE_URL="https://x-access-token:\${GITHUB_TOKEN}@github.com/${a[1]}.git"`),r.push("else"),r.push(` CLONE_URL=${T(e)}`),r.push("fi"),r.push('timeout 300 git clone "$CLONE_URL" /root/project || { echo "Git clone failed or timed out"; exit 1; }')):r.push(`timeout 300 git clone ${T(e)} /root/project || { echo "Git clone failed or timed out"; exit 1; }`),r.push("cd /root/project"),r.push(""),r.push('if [ -n "${GITHUB_TOKEN:-}" ]; then'),r.push(' echo "${GITHUB_TOKEN}" | gh auth login --with-token 2>/dev/null || true'),a&&r.push(` git -C /root/project remote set-url origin "https://x-access-token:\${GITHUB_TOKEN}@github.com/${a[1]}.git"`),r.push("fi"),r.push("")}if(s&&s>0&&(r.push("# Auto-destroy after TTL"),r.push(`echo "shutdown -h now" | at now + ${s} minutes 2>/dev/null || true`),r.push(`(sleep ${s*60} && shutdown -h now) &`),r.push("")),r.push("# Clean up cloud-init secrets"),r.push("rm -f /var/lib/cloud/instance/user-data.txt"),r.push(""),r.push("# Signal that infrastructure is ready"),r.push("touch /root/.gibil-ready"),r.push('echo "Gibil infrastructure ready"'),r.push(""),e&&n?.tasks&&n.tasks.length>0){r.push("# Run project tasks"),r.push("cd /root/project");for(let a of n.tasks)r.push(`echo '\u25B6 Running task: '${T(a.name)}`),r.push(`if ! ${a.command}; then`),r.push(` echo '\u2717 Task failed: '${T(a.name)}`),r.push(" touch /root/.gibil-tasks-failed"),r.push("fi");r.push(""),r.push("# Signal tasks complete"),r.push("if [ ! -f /root/.gibil-tasks-failed ]; then"),r.push(" touch /root/.gibil-tasks-done"),r.push(' echo "Gibil tasks complete"'),r.push("else"),r.push(' echo "Gibil tasks finished with errors"'),r.push("fi")}return r.join(`
|
|
15
|
+
`)}function Kt(t){let e=[];if(t.startsWith("node:")){let n=t.split(":")[1]??"20";e.push("# Install Node.js"),e.push(`curl -fsSL https://deb.nodesource.com/setup_${n}.x | bash - > /dev/null 2>&1`),e.push("apt-get install -y -qq nodejs > /dev/null 2>&1"),e.push("npm install -g pnpm@latest > /dev/null 2>&1"),e.push("")}else if(t.startsWith("python:")){let n=t.split(":")[1]??"3.12";e.push("# Install Python"),e.push(`apt-get install -y -qq python${n} python3-pip python3-venv > /dev/null 2>&1`),e.push("")}else if(t.startsWith("go:")){let n=t.split(":")[1]??"1.22";e.push("# Install Go"),e.push('GO_ARCH=$(uname -m | sed "s/x86_64/amd64/" | sed "s/aarch64/arm64/")'),e.push(`wget -q https://go.dev/dl/go${n}.linux-\${GO_ARCH}.tar.gz -O /tmp/go.tar.gz`),e.push("tar -C /usr/local -xzf /tmp/go.tar.gz"),e.push("export PATH=$PATH:/usr/local/go/bin"),e.push('echo "export PATH=\\$PATH:/usr/local/go/bin" >> /root/.bashrc'),e.push("")}else e.push("# Install Node.js (default)"),e.push("curl -fsSL https://deb.nodesource.com/setup_20.x | bash - > /dev/null 2>&1"),e.push("apt-get install -y -qq nodejs > /dev/null 2>&1"),e.push("npm install -g pnpm@latest > /dev/null 2>&1"),e.push("");return e}function Rt(){return["# Install Docker","curl -fsSL https://get.docker.com | sh > /dev/null 2>&1","systemctl enable docker --now"]}function Lt(t){let e=[];e.push(`# Start service: ${t.name.replace(/[^a-zA-Z0-9_-]/g,"")}`);let s=`docker run -d --name ${t.name.replace(/[^a-zA-Z0-9_-]/g,"")}`;if(t.port&&(s+=` -p ${t.port}:${t.port}`),t.env)for(let[i,c]of Object.entries(t.env))s+=` -e ${i}=${T(c)}`;return s+=` ${t.image}`,e.push(s),e.push(""),e}function T(t){return`'${t.replace(/'/g,"'\\''")}'`}import{readFile as Mt}from"fs/promises";import{existsSync as Re,statSync as Dt}from"fs";import{join as zt}from"path";import{parse as Me}from"yaml";var Gt=".gibil.yml";async function le(t){let e;if(Re(t)&&Dt(t).isFile()?e=t:e=zt(t,Gt),!Re(e))return null;let n=await Mt(e,"utf-8"),s=Me(n);return ze(s)}function De(t){let e=Me(t);return ze(e)}function ze(t){if(!t||typeof t!="object")throw new Error("Invalid .gibil.yml: must be a YAML object");let e=t,n={};return typeof e.name=="string"&&(n.name=e.name),typeof e.image=="string"&&(n.image=e.image),typeof e.server_type=="string"&&(n.server_type=e.server_type),typeof e.location=="string"&&(n.location=e.location),Array.isArray(e.services)&&(n.services=e.services.map(s=>{let i=s;if(typeof i.name!="string"||typeof i.image!="string")throw new Error("Each service must have a 'name' and 'image' field");return{name:i.name,image:i.image,port:typeof i.port=="number"?i.port:void 0,env:Le(i.env,`service "${i.name}"`)}})),Array.isArray(e.tasks)&&(n.tasks=e.tasks.map(s=>{let i=s;if(typeof i.name!="string"||typeof i.command!="string")throw new Error("Each task must have a 'name' and 'command' field");return{name:i.name,command:i.command}})),e.env!==void 0&&(n.env=Le(e.env,"top-level")),n}function Le(t,e){if(t==null)return;if(typeof t!="object"||Array.isArray(t))throw new Error(`env in ${e} must be a key-value object`);let n={};for(let[s,i]of Object.entries(t))if(typeof i=="string")n[s]=i;else if(typeof i=="number"||typeof i=="boolean")n[s]=String(i);else throw new Error(`env.${s} in ${e} must be a string, number, or boolean \u2014 got ${typeof i}`);return Object.keys(n).length>0?n:void 0}R();import{readFile as Ut,writeFile as Ft,mkdir as Ge,rm as Bt,readdir as qt}from"fs/promises";import{existsSync as Ue}from"fs";import{join as xe}from"path";var Se=class{instancesDir;keysDir;constructor(e){let n=e??w.root;this.instancesDir=xe(n,"instances"),this.keysDir=xe(n,"keys")}async ensureDirectories(){await Ge(this.instancesDir,{recursive:!0,mode:448}),await Ge(this.keysDir,{recursive:!0,mode:448})}instanceFile(e){return xe(this.instancesDir,`${e}.json`)}async save(e){await this.ensureDirectories(),await Ft(this.instanceFile(e.name),JSON.stringify(e,null,2),{mode:384})}async load(e){let n=this.instanceFile(e);if(!Ue(n))return null;let s=await Ut(n,"utf-8");return JSON.parse(s)}async loadOrThrow(e){let n=await this.load(e);if(!n)throw new Error(`Instance "${e}" not found. Run "gibil list" to see active instances.`);return n}async loadActiveOrThrow(e){let n=await this.loadOrThrow(e);if(new Date>new Date(n.expiresAt))throw new Error(`Instance "${e}" has expired (TTL was ${n.ttlMinutes}m). Run "gibil destroy ${e}" to clean up.`);return n}async delete(e){let n=this.instanceFile(e);Ue(n)&&await Bt(n)}async list(){await this.ensureDirectories();let e=await qt(this.instancesDir),n=[];for(let s of e){if(!s.endsWith(".json"))continue;let i=s.replace(".json",""),c=await this.load(i);c&&n.push(c)}return n}},ee=new Se;var F=t=>ee.save(t);var Fe=t=>ee.loadOrThrow(t),E=t=>ee.loadActiveOrThrow(t),ue=t=>ee.delete(t),B=()=>ee.list();import{randomBytes as Jt}from"crypto";function Be(t=6){return Jt(Math.ceil(t/2)).toString("hex").slice(0,t)}function pe(){return`gibil-${Be()}`}function qe(){return`fleet-${Be(8)}`}R();var Wt=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}$/;function Je(t){if(!Wt.test(t))throw new Error(`Invalid instance name "${t}". Names must be 1-63 chars, start with alphanumeric, and contain only [a-zA-Z0-9_-].`);return t}function te(t,e){let n=parseInt(t,10);if(isNaN(n)||n<=0)throw new Error(`${e} must be a positive integer, got "${t}"`);return n}D();import{execSync as de}from"child_process";import{readFileSync as Yt}from"fs";function Vt(){try{let t=de("git config user.name",{encoding:"utf-8"}).trim(),e=de("git config user.email",{encoding:"utf-8"}).trim();if(!t||!e)return;let n;try{if(de("git config gpg.format",{encoding:"utf-8"}).trim()==="ssh"){let i=de("git config user.signingkey",{encoding:"utf-8"}).trim();if(i)try{n=Yt(i,"utf-8").trim()}catch{(i.startsWith("ssh-")||i.startsWith("key::"))&&(n=i.replace(/^key::/,""))}}}catch{}return{name:t,email:e,signingKey:n}}catch{return}}async function We(t,e,n){o.step("Generating SSH keys...");let s=await se(e),i;try{o.step("Uploading SSH key..."),i=await t.createSSHKey(`gibil-${e}`,s.publicKey),n.repo&&n.repo.includes("github.com")&&!process.env.GITHUB_TOKEN&&o.debug("No GITHUB_TOKEN set \u2014 private repos will fail to clone. Set GITHUB_TOKEN to enable private repo access.");let c=Vt(),r=ce({repo:n.repo,config:n.config??void 0,ttlMinutes:n.ttlMinutes,githubToken:process.env.GITHUB_TOKEN,gitIdentity:c});o.step("Creating server...");let l=await t.createServer(e,i.id,r,n.serverType??n.config?.server_type,n.location??n.config?.location);o.step("Waiting for server...");let u=(await t.waitForReady(l.id)).public_net.ipv4.ip,f=new Date,g={name:e,serverId:l.id,ip:u,sshKeyId:i.id,keyPath:w.privateKey(e),status:"running",createdAt:f.toISOString(),ttlMinutes:n.ttlMinutes,expiresAt:new Date(f.getTime()+n.ttlMinutes*6e4).toISOString(),repo:n.repo,fleetId:n.fleetId,gitIdentity:c};if(await F(g),o.step(`Waiting for SSH on ${u}...`),await ae(e,u),n.repo||n.config){o.step("Waiting for provisioning...");let d=36e4,m=5e3,v=Date.now(),S=!1;for(;Date.now()-v<d;){try{if((await C({instanceName:e,ip:u,command:"test -f /root/.gibil-ready && echo ready || echo waiting",timeoutMs:1e4})).stdout.trim()==="ready"){S=!0;break}}catch{}await new Promise(O=>setTimeout(O,m))}if(!S)try{let O=await C({instanceName:e,ip:u,command:"tail -20 /var/log/cloud-init-output.log 2>/dev/null || echo 'No cloud-init log found'",timeoutMs:1e4});o.warn("Provisioning may have failed. Cloud-init log:"),o.info(O.stdout)}catch{o.warn("Provisioning may have failed \u2014 could not read cloud-init log.")}}return g}catch(c){if(o.error(`Failed to create instance "${e}", cleaning up...`),await Y(e).catch(r=>o.warn(`Could not clean up SSH keys: ${r instanceof Error?r.message:String(r)}`)),i){let r=i.id;await t.deleteSSHKey(r).catch(l=>o.warn(`Could not delete Hetzner SSH key ${r}: ${l instanceof Error?l.message:String(l)}`))}throw c}}function Ye(t){let e=Math.max(0,Math.floor((new Date(t.expiresAt).getTime()-Date.now())/1e3));return{name:t.name,ip:t.ip,ssh:`ssh -i ${t.keyPath} -o StrictHostKeyChecking=no root@${t.ip}`,status:t.status,ttl_remaining:e,created_at:t.createdAt,fleet_id:t.fleetId}}async function Zt(t){let e=t.match(/github\.com\/([^/]+)\/([^/.]+)/);if(!e)return o.debug(`Cannot fetch config from non-GitHub repo: ${t}`),null;let[,n,s]=e,i=`https://raw.githubusercontent.com/${n}/${s}/HEAD/.gibil.yml`;o.debug(`Fetching config from ${i}`);try{let c={};process.env.GITHUB_TOKEN&&(c.Authorization=`token ${process.env.GITHUB_TOKEN}`);let r=await fetch(i,{signal:AbortSignal.timeout(1e4),headers:c});if(!r.ok)return o.debug(`No .gibil.yml found in repo (${r.status})`),null;let l=await r.text();return De(l)}catch{return o.debug("Failed to fetch repo config, continuing without it"),null}}function Ve(t){t.command("create").description("Spin up one or more ephemeral dev machines").option("-n, --name <name>","Instance name").option("-f, --fleet <count>","Number of instances to create in parallel").option("-r, --repo <git-url>","Git repository to clone on startup").option("--json","Output instance info as JSON").option("--ttl <minutes>","Auto-destroy after N minutes","60").option("-c, --config <path>","Path to .gibil.yml config").option("--server-type <type>","Hetzner server type (e.g. cpx11, cpx21)").option("--location <loc>","Hetzner location (e.g. fsn1, nbg1)").option("-q, --quiet","Suppress non-essential output").option("-e, --env <KEY=VALUE...>","Environment variables to set on the server").action(async e=>{e.json&&$(!0);let n=te(e.ttl??"60","TTL");if(n>10080)throw new Error("TTL cannot exceed 7 days (10080 minutes).");let s=te(e.fleet??"1","Fleet count");if(s>20)throw new Error("Fleet size cannot exceed 20. Contact support for higher limits.");e.name&&Je(e.name);let i={};if(e.env)for(let a of e.env){let u=a.indexOf("=");if(u<=0)throw new Error(`Invalid --env format: "${a}". Use KEY=VALUE.`);i[a.slice(0,u)]=a.slice(u+1)}i.GITHUB_TOKEN&&!process.env.GITHUB_TOKEN&&(process.env.GITHUB_TOKEN=i.GITHUB_TOKEN);let c=null;e.config?c=await le(e.config):e.repo?c=await Zt(e.repo)??await le(process.cwd()):c=await le(process.cwd()),Object.keys(i).length>0&&(c||(c={}),c.env={...c.env,...i});let r=await A();if(r){o.info("Verifying API key...");let a=await M(r);o.info(` Authenticated as ${a.user.email} (${a.user.plan})`)}let l=await P.create();if(s===1){let a=e.name??pe(),u=Date.now(),f=o.spin(`Forging "${a}"...`),g=await We(l,a,{repo:e.repo,ttlMinutes:n,config:c,serverType:e.serverType,location:e.location}),d=((Date.now()-u)/1e3).toFixed(1);f.succeed(x.createReady(a,d)),r&&await W(r,"create",g.name,e.serverType).catch(m=>o.debug(`Usage tracking failed: ${m instanceof Error?m.message:String(m)}`)),e.json?o.json(Ye(g)):(o.info(""),o.info(je("Server ready",[`${p("Name:")} ${y(g.name)}`,`${p("IP:")} ${g.ip}`,`${p("TTL:")} ${n} minutes`,`${p("SSH:")} ${y(`gibil ssh ${g.name}`)}`])),o.info(""))}else{let a=qe(),u=e.name??"gibil",f=Date.now(),g=o.spin(`Forging fleet "${a}" \u2014 ${s} servers...`),d=Array.from({length:s},(b,k)=>`${u}-${k+1}-${a.slice(6)}`),m=await Promise.allSettled(d.map(b=>We(l,b,{repo:e.repo,ttlMinutes:n,config:c,serverType:e.serverType,location:e.location,fleetId:a}))),v=[],S=[];for(let b=0;b<m.length;b++){let k=m[b];k.status==="fulfilled"?v.push(k.value):S.push(`${d[b]}: ${k.reason instanceof Error?k.reason.message:String(k.reason)}`)}let O=((Date.now()-f)/1e3).toFixed(1);if(g.succeed(x.fleetReady(v.length,s)+` ${p(`(${O}s)`)}`),r&&await Promise.all(v.map(b=>W(r,"create",b.name,e.serverType).catch(k=>o.debug(`Usage tracking failed for ${b.name}: ${k instanceof Error?k.message:String(k)}`)))),e.json)o.json({fleet_id:a,instances:v.map(Ye),errors:S});else{o.info("");for(let b of v)o.info(` ${H} ${y(b.name)} ${p("\u2192")} ${b.ip}`);for(let b of S)o.info(` ${Z} ${b}`);o.info("")}}})}import{spawn as Xt}from"child_process";function Ze(t){t.command("ssh <name>").description("SSH into a running ephemeral machine").action(async e=>{let n=await E(e),s=["-A","-i",n.keyPath,"-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR",`root@${n.ip}`];Xt("ssh",s,{stdio:"inherit"}).on("exit",c=>{process.exit(c??0)})})}function Xe(t){t.command("run <name> <command...>").description("Execute a command on a running instance").option("--json","Output result as JSON").option("--timeout <seconds>","Command timeout in seconds (default: 30)").action(async(e,n,s)=>{s.json&&$(!0);let i=await E(e),c=n.join(" "),r=s.timeout?te(s.timeout,"Timeout")*1e3:3e4;o.info(`Running on "${e}" (${i.ip}): ${c}`);let l=await C({instanceName:e,ip:i.ip,command:c,stream:!s.json,timeoutMs:r});s.json?o.json({instance:e,command:c,stdout:l.stdout,stderr:l.stderr,exit_code:l.exitCode}):l.exitCode!==0&&o.error(`Command exited with code ${l.exitCode}`),process.exit(l.exitCode??1)})}D();async function Qe(t,e){let n=await Fe(e);o.info(`Destroying instance "${e}" (server ${n.serverId})...`);try{await t.destroyServer(n.serverId)}catch(i){o.warn(`Could not delete server ${n.serverId}: ${i instanceof Error?i.message:String(i)}`)}try{await t.deleteSSHKey(n.sshKeyId)}catch(i){o.warn(`Could not delete SSH key ${n.sshKeyId}: ${i instanceof Error?i.message:String(i)}`)}await Y(e),await ue(e);let s=await A();s&&await W(s,"destroy",e).catch(i=>o.warn(`Usage tracking failed (billing may be inaccurate): ${i instanceof Error?i.message:String(i)}`)),o.info(` ${H} ${x.destroySingle(e)}`)}function et(t){t.command("destroy [name]").description("Destroy a running ephemeral machine").option("-a, --all","Destroy all gibil instances").option("--json","Output result as JSON").action(async(e,n)=>{if(n.json&&$(!0),n.all){let s=await B();if(s.length===0){n.json?o.json({destroyed:[],failed:[]}):o.info(x.noInstances);return}let i=await P.create();o.info(`Destroying ${s.length} instance(s)...`);let c=await Promise.allSettled(s.map(a=>Qe(i,a.name))),r=[],l=[];for(let a=0;a<c.length;a++)if(c[a].status==="fulfilled")r.push(s[a].name);else{let u=c[a].reason;l.push(`${s[a].name}: ${u instanceof Error?u.message:String(u)}`)}n.json?o.json({destroyed:r,failed:l}):l.length===0?o.info(`
|
|
16
|
+
${x.destroyAll}`):o.info(`
|
|
17
|
+
${r.length} destroyed, ${l.length} failed`)}else{e||(o.error('Specify an instance name or use --all. Run "gibil list" to see instances.'),process.exit(1));let s=await P.create();await Qe(s,e),n.json&&o.json({destroyed:[e]})}})}function tt(t){t.command("list").alias("ls").description("List all active gibil instances").option("--json","Output as JSON").action(async e=>{e.json&&$(!0);let n=await B();if(n.length===0){e.json?o.json({instances:[]}):o.info(x.noInstances);return}let s=n.map(i=>{let c=Math.max(0,Math.floor((new Date(i.expiresAt).getTime()-Date.now())/1e3));return{name:i.name,ip:i.ip,ssh:`ssh -i ${i.keyPath} -o StrictHostKeyChecking=no root@${i.ip}`,status:i.status,ttl_remaining:c,created_at:i.createdAt,fleet_id:i.fleetId}});if(e.json){o.json({instances:s});return}o.info(p(`${"NAME".padEnd(30)} ${"IP".padEnd(18)} ${"STATUS".padEnd(12)} ${"TTL".padEnd(10)} ${"AGE".padEnd(10)}`)),o.info(p("\u2500".repeat(80)));for(let i of s){let c=nt(i.ttl_remaining),r=Qt(i.created_at),l=i.name.padEnd(30),a=i.status.padEnd(12),u=c.padEnd(10),f=r.padEnd(10),g=i.status==="running"?z(a):N(a),d=i.ttl_remaining<=300?N(u):u;o.info(`${y(l)} ${i.ip.padEnd(18)} ${g} ${d} ${p(f)}`)}o.info(`
|
|
18
|
+
${p(`${s.length} server(s)`)}`)})}function nt(t){if(t<=0)return"expired";let e=Math.floor(t/60),n=t%60;return e>=60?`${Math.floor(e/60)}h ${e%60}m`:`${e}m ${n}s`}function Qt(t){let e=Date.now()-new Date(t).getTime(),n=Math.floor(e/1e3);return nt(n)}function rt(t){t.command("extend <name>").description("Extend the TTL of a running instance").requiredOption("--ttl <minutes>","New TTL in minutes from now").option("--json","Output result as JSON").action(async(e,n)=>{n.json&&$(!0);let s=await E(e),i=parseInt(n.ttl,10);(isNaN(i)||i<=0)&&(o.error("TTL must be a positive number of minutes"),process.exit(1)),await C({instanceName:e,ip:s.ip,command:["pkill -f 'sleep.*shutdown' || true",`(sleep ${i*60} && shutdown -h now) &`].join(" && ")});let c=new Date(Date.now()+i*6e4).toISOString();s.ttlMinutes=i,s.expiresAt=c,await F(s),n.json?o.json({name:s.name,ttl_minutes:i,expires_at:c}):o.info(`\u2713 Extended "${e}" TTL to ${i} minutes (expires ${c})`)})}import{readFile as en}from"fs/promises";import{randomBytes as tn}from"crypto";function it(t){t.command("exec <name>").description("Upload and run a local script on an instance").requiredOption("-s, --script <path>","Path to local script").option("--json","Output result as JSON").action(async(e,n)=>{n.json&&$(!0);let s=await E(e),i=await en(n.script,"utf-8");o.info(`Uploading and running script "${n.script}" on "${e}"...`);let c=Buffer.from(i).toString("base64"),r=`/tmp/gibil-script-${tn(4).toString("hex")}.sh`,l=await C({instanceName:e,ip:s.ip,command:`echo '${c}' | base64 -d > ${r} && chmod +x ${r} && ${r}; EXIT=$?; rm -f ${r}; exit $EXIT`,stream:!n.json});n.json?o.json({instance:e,script:n.script,stdout:l.stdout,stderr:l.stderr,exit_code:l.exitCode}):l.exitCode!==0&&o.error(`Script exited with code ${l.exitCode}`),process.exit(l.exitCode??1)})}D();import{createInterface as nn}from"readline";function ot(t){let e=nn({input:process.stdin,output:process.stderr});return new Promise(n=>{e.question(t,s=>{e.close(),n(s.trim())})})}function st(t){let e=t.command("auth").description("Manage authentication");e.command("login").description("Log in with your Gibil API key").option("--key <api-key>","API key (or enter interactively)").option("--json","Output result as JSON").action(async n=>{n.json&&$(!0);let s=n.key??process.env.GIBIL_API_KEY;s||(s=await ot("Enter your API key: ")),s||(o.error("No API key provided."),process.exit(1)),s.startsWith("pk_")||(o.error('Invalid key format. API keys start with "pk_".'),process.exit(1)),o.info("Verifying API key...");try{let i=await M(s);await X(s),n.json?o.json({authenticated:!0,email:i.user.email,plan:i.user.plan}):(o.info(x.authSuccess),o.detail("Email",i.user.email),o.detail("Plan",i.user.plan),o.detail("Limits",`${i.limits.max_concurrent} concurrent servers, ${i.limits.remaining_hours}h remaining`))}catch(i){o.error(i instanceof Error?i.message:String(i)),process.exit(1)}}),e.command("setup").description("Configure Hetzner API token (stored in ~/.gibil/config.json)").option("--token <token>","Hetzner API token (or enter interactively)").action(async n=>{let s=n.token;s||(s=await ot("Enter your Hetzner API token: ")),s||(o.error("No token provided."),process.exit(1));try{let c=await(await fetch("https://api.hetzner.cloud/v1/servers",{headers:{Authorization:`Bearer ${s}`}})).json();c.error&&(o.error(`Invalid token: ${c.error.message}`),process.exit(1))}catch{o.error("Could not verify token with Hetzner API."),process.exit(1)}await Q(s),o.success("Hetzner token saved to ~/.gibil/config.json")}),e.command("logout").description("Clear stored API key").action(async()=>{await ye(),o.info(x.authLogout)}),e.command("status").description("Show current authentication status").option("--json","Output result as JSON").action(async n=>{n.json&&$(!0);let s=await A();if(!s){n.json?o.json({authenticated:!1}):o.info(`Not logged in. Run ${y("gibil auth login")} to authenticate.`);return}try{let i=await M(s);n.json?o.json({authenticated:!0,email:i.user.email,plan:i.user.plan,limits:i.limits}):(o.success(`Authenticated as ${i.user.email}`),o.detail("Plan",i.user.plan),o.detail("Concurrent servers",String(i.limits.max_concurrent)),o.detail("Hours remaining",String(i.limits.remaining_hours)))}catch{n.json?o.json({authenticated:!1,error:"Key verification failed"}):o.error(`Stored API key is invalid. Run ${y("gibil auth login")} to re-authenticate.`)}})}D();function at(t){t.command("usage").description("Show current month's usage and plan limits").option("--json","Output as JSON").action(async e=>{e.json&&$(!0);let n=await A();n||(o.error('Not logged in. Run "gibil auth login" first.'),process.exit(1));try{let s=await $e(n);if(e.json)o.json(s);else{let i=Math.round(s.vm_hours_used/s.vm_hours_limit*100);o.info(`Plan: ${s.plan}`),o.info(`VM hours: ${s.vm_hours_used.toFixed(1)} / ${s.vm_hours_limit}h (${i}%)`),o.info(`Active instances: ${s.active_instances} / ${s.max_concurrent}`),i>80&&o.warn("Running low on hours. Upgrade at https://gibil.dev/pricing")}}catch(s){o.error(s instanceof Error?s.message:String(s)),process.exit(1)}})}import{McpServer as rn}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as on}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as h}from"zod";R();async function ne(t,e){if(t)return t;if(e)return E(e);let s=(await B()).filter(i=>new Date<new Date(i.expiresAt));if(s.length===0)throw new Error("No active servers. Use create_server first.");if(s.length===1)return s[0];throw new Error(`Multiple servers running: ${s.map(i=>i.name).join(", ")}. Pass the "server" parameter to specify which one.`)}function q(t,e,n=3e4){return C({instanceName:t.name,ip:t.ip,command:e,stream:!1,timeoutMs:n})}function j(t){return`'${t.replace(/'/g,"'\\''")}'`}async function ct(t){let e=null;if(t&&(e=await E(t),e.gitIdentity)){let{name:r,email:l,signingKey:a}=e.gitIdentity,u=[`git config --global user.name ${j(r)}`,`git config --global user.email ${j(l)}`];a&&u.push("git config --global gpg.format ssh",`git config --global user.signingkey ${j("key::"+a)}`,"git config --global commit.gpgsign true"),q(e,u.join(" && ")).catch(()=>{})}let n=t?`gibil-${t}`:"gibil",s=new rn({name:n,version:"0.2.0"});e||(s.tool("create_server","Forge a new ephemeral server. Returns the server name and IP when ready.",{name:h.string().optional().describe("Server name (auto-generated if omitted)"),repo:h.string().optional().describe("Git repo URL to clone on boot"),ttl:h.number().optional().describe("Auto-destroy after N minutes (default: 60)"),server_type:h.string().optional().describe("Hetzner server type (default: auto-detected)"),location:h.string().optional().describe("Hetzner datacenter (default: auto-detected)"),env:h.record(h.string(),h.string()).optional().describe("Environment variables to set on the server")},async({name:r,repo:l,ttl:a,server_type:u,location:f,env:g})=>{try{let d=r??pe(),m=a??60,v=await P.create(),S=await se(d),O=await v.createSSHKey(`gibil-${d}`,S.publicKey),k=ce({repo:l,config:g?{env:g}:void 0,ttlMinutes:m,githubToken:process.env.GITHUB_TOKEN}),Ie=await v.createServer(d,O.id,k,u,f),ge=(await v.waitForReady(Ie.id)).public_net.ipv4.ip,Ee=new Date,gt={name:d,serverId:Ie.id,ip:ge,sshKeyId:O.id,keyPath:w.privateKey(d),status:"running",createdAt:Ee.toISOString(),ttlMinutes:m,expiresAt:new Date(Ee.getTime()+m*6e4).toISOString(),repo:l};return await F(gt),await ae(d,ge),{content:[{type:"text",text:JSON.stringify({name:d,ip:ge,ttl_minutes:m,status:"running"},null,2)}]}}catch(d){return{content:[{type:"text",text:`Failed to create server: ${d instanceof Error?d.message:String(d)}`}],isError:!0}}}),s.tool("destroy_server","Burn a server. Deletes the server, SSH keys, and local metadata.",{name:h.string().describe("Name of the server to destroy")},async({name:r})=>{try{let l=await E(r),a=await P.create();return await a.destroyServer(l.serverId).catch(()=>{}),await a.deleteSSHKey(l.sshKeyId).catch(()=>{}),await Y(r).catch(()=>{}),await ue(r),{content:[{type:"text",text:`Server "${r}" destroyed.`}]}}catch(l){return{content:[{type:"text",text:`Failed to destroy: ${l instanceof Error?l.message:String(l)}`}],isError:!0}}}),s.tool("list_servers","List all active gibil servers with their names, IPs, and remaining TTL.",{},async()=>{let l=(await B()).map(a=>({name:a.name,ip:a.ip,status:a.status,ttl_remaining_seconds:Math.max(0,Math.floor((new Date(a.expiresAt).getTime()-Date.now())/1e3)),repo:a.repo}));return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}),s.tool("extend_server","Extend a server's TTL. Resets the auto-destroy timer.",{name:h.string().describe("Server name"),ttl:h.number().describe("New TTL in minutes from now")},async({name:r,ttl:l})=>{try{let a=await E(r),u=await q(a,`pkill -f 'sleep.*shutdown' || true && (sleep ${l*60} && shutdown -h now) &`);return u.exitCode!==0?{content:[{type:"text",text:`Failed to extend TTL: ${u.stderr}`}],isError:!0}:(a.ttlMinutes=l,a.expiresAt=new Date(Date.now()+l*6e4).toISOString(),await F(a),{content:[{type:"text",text:`Server "${r}" TTL extended to ${l} minutes.`}]})}catch(a){return{content:[{type:"text",text:`Failed to extend: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}}));let i=h.string().optional().describe("Server name (auto-selects if only one is running)");s.tool("vm_bash","Run a shell command on a remote server. Use for: builds, tests, git, package managers, any shell operation.",{command:h.string().describe("Shell command to execute"),working_dir:h.string().optional().describe("Working directory (default: /root/project)"),timeout_ms:h.number().optional().describe("Timeout in ms (default: 30000)"),server:i},async r=>{let l=await ne(e,r.server),a=r.working_dir??"/root/project",u=await q(l,`cd ${a} 2>/dev/null || cd /root && ${r.command}`,r.timeout_ms??3e4);return{content:[{type:"text",text:[u.stdout,u.stderr].filter(Boolean).join(`
|
|
19
|
+
`)||"(no output)"}],isError:u.exitCode!==0}}),s.tool("vm_read","Read a file from a remote server. Returns the file contents with line numbers.",{path:h.string().describe("Absolute path on the server (e.g. /root/project/src/app.ts)"),offset:h.number().optional().describe("Start at line N (1-based)"),limit:h.number().optional().describe("Max lines to return"),server:i},async r=>{let l=await ne(e,r.server),a=j(r.path),u=`cat -n ${a}`;r.offset&&r.limit?u=`sed -n '${r.offset},${r.offset+r.limit-1}p' ${a} | cat -n`:r.offset?u=`tail -n +${r.offset} ${a} | cat -n`:r.limit&&(u=`head -n ${r.limit} ${a} | cat -n`);let f=await q(l,u);return f.exitCode!==0?{content:[{type:"text",text:`Error: ${f.stderr}`}],isError:!0}:{content:[{type:"text",text:f.stdout}]}}),s.tool("vm_write","Write content to a file on a remote server. Creates parent directories if needed. Overwrites existing files.",{path:h.string().describe("Absolute path on the server"),content:h.string().describe("File content to write"),server:i},async r=>{let l=await ne(e,r.server),a=Buffer.from(r.content).toString("base64"),u=j(r.path),f=`mkdir -p "$(dirname ${u})" && echo '${a}' | base64 -d > ${u}`,g=await q(l,f);return g.exitCode!==0?{content:[{type:"text",text:`Error: ${g.stderr}`}],isError:!0}:{content:[{type:"text",text:`Wrote ${r.path}`}]}}),s.tool("vm_ls","List files and directories on a remote server.",{path:h.string().optional().describe("Directory path (default: /root/project)"),glob:h.string().optional().describe("Glob pattern to filter (e.g. '**/*.ts')"),server:i},async r=>{let l=await ne(e,r.server),a=r.path??"/root/project",u;r.glob?u=`cd ${j(a)} && find . -path './${r.glob}' -type f 2>/dev/null | sort | head -200`:u=`ls -la ${j(a)}`;let f=await q(l,u);return f.exitCode!==0?{content:[{type:"text",text:`Error: ${f.stderr}`}],isError:!0}:{content:[{type:"text",text:f.stdout}]}}),s.tool("vm_grep","Search for a pattern in files on a remote server. Uses ripgrep if available, falls back to grep.",{pattern:h.string().describe("Regex pattern to search for"),path:h.string().optional().describe("Directory or file to search (default: /root/project)"),include:h.string().optional().describe("File glob to include (e.g. '*.ts')"),server:i},async r=>{let l=await ne(e,r.server),a=r.path??"/root/project",u=j(r.pattern),f=j(a),g;if(r.include){let v=j(r.include);g=`cd ${f} && (rg -n --glob ${v} ${u} 2>/dev/null || grep -rn --include=${v} ${u} .) | head -100`}else g=`cd ${f} && (rg -n ${u} 2>/dev/null || grep -rn ${u} .) | head -100`;return{content:[{type:"text",text:(await q(l,g)).stdout||"(no matches)"}]}});let c=new on;await s.connect(c)}function lt(t){t.command("mcp [name]").description("Start an MCP server (used by Claude Code, Cursor, and other agents)").action(async e=>{try{await ct(e)}catch(n){o.error(n instanceof Error?n.message:String(n)),process.exit(1)}})}D();import{createInterface as sn}from"readline";import{execSync as an}from"child_process";import{existsSync as cn}from"fs";import{join as ln}from"path";R();function ke(t){let e=sn({input:process.stdin,output:process.stderr});return new Promise(n=>{e.question(t,s=>{e.close(),n(s.trim())})})}async function un(){let t=!!await ve(),e=!!await A();return{hetzner:t,apiKey:e}}function ut(t){t.command("init").description("Set up gibil \u2014 configure your forge in 60 seconds").option("--force","Reconfigure even if already set up").action(async e=>{console.error(Ae);let n=await un();if(n.hetzner&&!e.force){o.info(`${H} Already configured.`),n.apiKey?(o.detail("Hetzner",z("connected")),o.detail("Gibil API",z("connected"))):(o.detail("Hetzner",z("connected")),o.detail("Gibil API",p("not configured (optional)"))),o.info(""),o.info(` Run ${y("gibil init --force")} to reconfigure.`),o.info(` Run ${y("gibil create")} to forge a server.`);return}o.info(""),o.info(y("Step 1: Hetzner API Token")),o.info(p(" Your servers run on Hetzner Cloud. You need an API token.")),o.info(p(" Get one at: https://console.hetzner.cloud \u2192 API Tokens")),o.info("");let s=await ke(" Hetzner API token: ");s||(o.error("No token provided. Run gibil init again when ready."),process.exit(1));let i=o.spin("Verifying Hetzner token...");try{let d=await(await fetch("https://api.hetzner.cloud/v1/servers",{headers:{Authorization:`Bearer ${s}`}})).json();d.error&&(i.fail(`Invalid token: ${d.error.message}`),process.exit(1)),i.succeed("Hetzner token verified")}catch{i.fail("Could not reach Hetzner API. Check your network."),process.exit(1)}await Q(s);let c=o.spin("Detecting available server types..."),r="cax11",l="fsn1",a=[{type:"cax11",location:"fsn1"},{type:"cpx11",location:"fsn1"}];for(let g of a)try{let m=await(await fetch("https://api.hetzner.cloud/v1/servers",{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({name:"gibil-probe",server_type:g.type,image:"ubuntu-24.04",location:g.location,start_after_create:!1})})).json();if(m.server){await fetch(`https://api.hetzner.cloud/v1/servers/${m.server.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${s}`}}),r=g.type,l=g.location;break}}catch{}await we(r,l),c.succeed(`Default server type: ${r} (${l})`),o.info(""),o.info(y("Step 2: Gibil API Key")+p(" (optional)")),o.info(p(" For usage tracking and plan limits.")),o.info(p(" Skip this if you just want to use your own Hetzner token.")),o.info("");let u=await ke(" Gibil API key (or press Enter to skip): ");if(u)if(!u.startsWith("pk_"))o.warn('API keys start with "pk_". Skipping.');else{let g=o.spin("Verifying API key...");try{let d=await M(u);await X(u),g.succeed(`Logged in as ${d.user.email} (${d.user.plan})`)}catch(d){g.fail(`Could not verify key: ${d instanceof Error?d.message:String(d)}`),o.info(p(" Continuing without Gibil API. You can add it later with: gibil auth login"))}}else o.info(p(" Skipped. You can add it later with: gibil auth login"));if(o.info(""),o.info(x.initComplete),o.info(""),o.info(p(" Quick start:")),o.info(` ${y("gibil create")} ${p("Forge a server")}`),o.info(` ${y("gibil create --repo github.com/you/project")} ${p("Clone a repo on boot")}`),o.info(` ${y("gibil ssh <name>")} ${p("Connect to it")}`),o.info(` ${y("gibil destroy <name>")} ${p("Burn it down")}`),o.info(""),(await ke(" Install the gibil agent skill? (Y/n): ")).toLowerCase()!=="n"){let g=o.spin("Installing gibil skill...");try{an("npx -y skills add https://github.com/AlexikM/gibil-skills --skill gibil -y -g",{stdio:"pipe",timeout:3e4}),g.succeed("Gibil skill installed for your AI agents")}catch{g.fail("Could not install skill automatically"),o.info(p(" Install manually: npx skills add https://github.com/AlexikM/gibil-skills --skill gibil"))}}else o.info(p(" Skipped. Install later: npx skills add https://github.com/AlexikM/gibil-skills --skill gibil"))})}async function pt(){if(process.env.HETZNER_API_TOKEN)return!1;let t=ln(w.root,"config.json");return!cn(t)}try{await import("dotenv/config")}catch{}var hn=fn(gn(import.meta.url)),dt={version:"0.0.0"};for(let t of["../package.json","../../package.json"])try{dt=JSON.parse(dn(mn(hn,t),"utf-8"));break}catch{}var _=new pn;_.name("gibil").description("Ephemeral dev compute for humans and AI agents").version(`${dt.version} ${re}`,"-v, --version").addHelpText("before",`
|
|
20
|
+
${Pe}
|
|
21
21
|
`).addHelpText("after",`
|
|
22
|
-
${
|
|
23
|
-
`);
|
|
22
|
+
${p("Docs:")} https://gibil.dev/docs
|
|
23
|
+
`);ut(_);Ve(_);Ze(_);Xe(_);et(_);tt(_);rt(_);it(_);st(_);at(_);lt(_);async function yn(){let t=process.argv.slice(2);!(t.length===0||t.includes("init")||t.includes("auth")||t.includes("--help")||t.includes("-h")||t.includes("--version")||t.includes("-v")||t.includes("-V")||t.includes("mcp")||t.includes("ssh")||t.includes("run")||t.includes("exec")||t.includes("list")||t.includes("ls"))&&await pt()&&(o.info(""),o.info(x.setupNeeded),o.info(""),process.exit(1));try{await _.parseAsync(process.argv)}catch(n){n instanceof Error&&o.error(n.message),process.exit(1)}}yn();
|