gibil 0.1.5 → 0.1.6

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