@heygaia/cli 0.1.9 → 0.1.11

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 +29 -19
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,23 +1,33 @@
1
1
  #!/usr/bin/env node
2
- import{Command as ao}from"commander";import{render as Ur}from"ink";import Xr from"react";import{Box as ye,Text as te}from"ink";import Er from"react";import{ProgressBar as ut,Select as Oe,Spinner as Me}from"@inkjs/ui";import{Box as p,Text as s,useInput as ee}from"ink";import me from"ink-text-input";import{useEffect as Se,useState as M}from"react";import{Box as de,Text as ct}from"ink";var h="#00bbff";import{Box as rr,Text as Be}from"ink";import{jsx as it,jsxs as at}from"react/jsx-runtime";var st=({status:e,step:t})=>t.toLowerCase()==="welcome"?null:at(rr,{width:"100%",borderStyle:"single",borderColor:"gray",paddingX:1,justifyContent:"space-between",children:[at(Be,{color:h,children:[it(Be,{bold:!0,children:"Status:"})," ",t]}),it(Be,{color:"white",dimColor:!0,children:e})]});import{Box as or}from"ink";import nr from"ink-big-text";import ir from"ink-gradient";import{jsx as Ae}from"react/jsx-runtime";var ne=()=>Ae(or,{flexDirection:"column",marginTop:1,marginBottom:1,children:Ae(ir,{colors:[h,"#b0eaff",h],children:Ae(nr,{text:"GAIA",font:"3d"})})});import{jsx as ie,jsxs as xe}from"react/jsx-runtime";var ar=["Welcome","Prerequisites","Repository Setup","Install Tools","Environment Setup","Project Setup","Finished"],lt=["Detect Repo","Prerequisites","Environment Setup","Project Setup","Finished"],sr=({currentStep:e,steps:t})=>{let o=t.indexOf(e);return ie(de,{marginBottom:1,children:t.map((r,n)=>{let a=r===e,c=o>n;return xe(de,{marginRight:2,children:[xe(ct,{color:a?h:c?"green":"gray",children:[c?"\u2713 ":a?"\u25CF ":"\u25CB ",r]}),n<t.length-1&&ie(ct,{color:"gray",children:" \u203A "})]},r)})})},he=({children:e,status:t,step:o,steps:r=ar})=>xe(de,{flexDirection:"column",height:"100%",width:"100%",children:[xe(de,{flexGrow:1,flexDirection:"column",children:[ie(ne,{}),ie(sr,{currentStep:o,steps:r}),ie(de,{flexDirection:"column",flexGrow:1,children:e})]}),ie(st,{status:t,step:o})]});import{Fragment as Ao,jsx as i,jsxs as u}from"react/jsx-runtime";var _e=({label:e,status:t})=>u(p,{children:[i(p,{marginRight:1,children:t==="pending"?i(Me,{type:"dots"}):t==="success"?i(s,{color:h,children:"\u2714"}):t==="error"?i(s,{color:"red",children:"\u2716"}):i(s,{color:"yellow",children:"\u26A0"})}),i(s,{children:e})]}),cr=({onConfirm:e})=>(ee((t,o)=>{o.return&&e()}),u(p,{flexDirection:"column",paddingX:2,borderStyle:"round",borderColor:h,children:[i(s,{bold:!0,children:"Welcome to the Interactive GAIA Setup"}),u(p,{flexDirection:"column",marginTop:1,marginBottom:1,children:[i(s,{children:"This wizard will guide you through the setup process:"}),i(s,{children:" 1. Check Prerequisites (Git, Docker, Mise)"}),i(s,{children:" 2. Clone Repository (from GitHub)"}),i(s,{children:" 3. Install Tools (node, python, uv via mise)"}),i(s,{children:" 4. Configure Env Vars (databases, API keys, etc.)"}),i(s,{children:" 5. Setup Project (install all dependencies)"})]}),i(s,{color:h,children:"Press Enter to start..."})]})),lr=({portResults:e,onAccept:t,onAbort:o})=>{ee((n,a)=>{a.return?t():a.escape&&o()});let r=e.filter(n=>!n.available);return u(p,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:"yellow",children:[i(p,{marginBottom:1,children:i(s,{bold:!0,color:"yellow",children:"Port Conflicts Detected"})}),e.map(n=>u(p,{children:[u(s,{color:n.available?"green":n.alternative?"yellow":"red",children:[n.available?"\u2714":n.alternative?"\u26A0":"\u2716"," "]}),u(s,{children:[n.service," (:",n.port,")"]}),!n.available&&u(s,{color:n.alternative?"gray":"red",children:[" ","- in use",n.usedBy?` by ${n.usedBy}`:"",n.alternative?` \u2192 will use :${n.alternative}`:" \u2014 NO ALTERNATIVE FOUND"]})]},n.port)),u(p,{marginTop:1,flexDirection:"column",children:[r.some(n=>!n.alternative)&&i(p,{borderStyle:"single",borderColor:"red",paddingX:1,marginBottom:1,children:i(s,{color:"red",children:"Some ports have no available alternative. Free them and retry."})}),!r.some(n=>!n.alternative)&&r.some(n=>n.alternative)&&i(s,{color:"gray",children:"Alternative ports will be used for conflicting services."}),i(p,{marginTop:1,children:u(s,{children:[i(s,{color:"green",bold:!0,children:"Enter"})," to continue with alternatives ",i(s,{color:"yellow",bold:!0,children:"Escape"})," to abort"]})})]})]})},ur=({defaultValue:e,onSubmit:t})=>{let[o,r]=M(e);return u(p,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:h,children:[i(s,{children:"Where should we clone the repository?"}),u(p,{children:[i(s,{color:h,children:"\u279C "}),i(me,{value:o,onChange:r,onSubmit:t})]}),u(s,{color:"gray",children:["(Press Enter for default: ",e,")"]})]})},pr=({repoPath:e,onAction:t})=>u(p,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:"yellow",children:[i(p,{marginBottom:1,children:i(s,{bold:!0,color:"yellow",children:"Existing Installation Found"})}),u(s,{children:["Found a GAIA installation at"," ",i(s,{color:"cyan",bold:!0,children:e})]}),i(p,{marginTop:1,children:i(s,{color:"gray",children:"What would you like to do?"})}),i(p,{marginTop:1,children:i(Oe,{options:[{label:"Use existing installation",value:"use_existing"},{label:"Delete and re-clone",value:"delete_reclone"},{label:"Choose a different path",value:"different_path"},{label:"Exit setup",value:"exit"}],onChange:r=>t(r)})})]}),dr=({setupMode:e,portOverrides:t,onConfirm:o})=>{ee((c,d)=>{d.return&&o()});let r=e||"developer",n=t?.[3e3]??3e3,a=t?.[8e3]??8e3;return u(p,{flexDirection:"column",marginTop:2,borderStyle:"round",borderColor:h,padding:1,children:[i(s,{color:h,bold:!0,children:"You are all set!"}),u(p,{marginTop:1,flexDirection:"column",children:[i(s,{bold:!0,children:"To start GAIA, run:"}),i(p,{marginTop:1,padding:1,borderStyle:"single",borderColor:"gray",flexDirection:"column",children:i(s,{color:"cyan",children:"$ gaia start"})}),i(p,{marginTop:1,children:i(s,{color:"gray",dimColor:!0,children:r==="selfhost"?"Runs: docker compose --profile all up -d (background)":"Runs: mise dev (interactive \u2014 keep terminal open)"})})]}),u(p,{marginTop:1,flexDirection:"column",children:[i(s,{bold:!0,children:"Access GAIA at:"}),u(p,{marginLeft:2,flexDirection:"column",children:[u(s,{children:["Web:"," ",u(s,{color:"cyan",bold:!0,children:["http://localhost:",n]})]}),u(s,{children:["API:"," ",u(s,{color:"cyan",bold:!0,children:["http://localhost:",a]})]})]})]}),i(Fe,{}),i(p,{marginTop:1,children:i(s,{dimColor:!0,children:"Press Enter to exit"})})]})},Fe=()=>u(p,{marginTop:1,flexDirection:"column",children:[i(s,{bold:!0,children:"Available commands:"}),u(p,{marginLeft:2,flexDirection:"column",children:[u(s,{children:[u(s,{color:h,bold:!0,children:["gaia start"," "]}),i(s,{color:"gray",children:" Start all services"})]}),u(s,{children:[u(s,{color:h,bold:!0,children:["gaia stop"," "]}),i(s,{color:"gray",children:" Stop all services"})]}),u(s,{children:[i(s,{color:h,bold:!0,children:"gaia status"}),i(s,{color:"gray",children:" Check service health"})]}),u(s,{children:[u(s,{color:h,bold:!0,children:["gaia setup"," "]}),i(s,{color:"gray",children:" Reconfigure environment"})]})]})]}),mr=({phase:e,progress:t,isComplete:o,logs:r,title:n})=>u(p,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:h,children:[i(p,{marginBottom:1,children:i(s,{bold:!0,color:h,children:n||"Installing Dependencies"})}),u(p,{flexDirection:"column",gap:1,children:[i(p,{children:o?u(s,{color:"green",children:["\u2713 ",e]}):i(Me,{label:e||"Preparing..."})}),!o&&t>0&&i(p,{width:50,children:i(ut,{value:t})}),!o&&r&&r.length>0&&i(p,{flexDirection:"column",marginTop:1,borderStyle:"single",borderColor:"gray",paddingX:1,paddingY:0,minHeight:6,children:r.map((a,c)=>i(s,{color:"gray",wrap:"truncate",children:a},c))})]})]});var Le=({onSelect:e})=>u(p,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:h,children:[i(s,{bold:!0,children:"Setup Mode"}),i(p,{marginTop:1,children:i(s,{color:"gray",children:"How do you want to run GAIA?"})}),i(p,{marginTop:1,children:i(Oe,{options:[{label:"Self-Host (Docker)",value:"selfhost"},{label:"Developer Mode (Local)",value:"developer"}],onChange:o=>e(o)})}),u(p,{marginTop:1,flexDirection:"column",children:[i(s,{color:"gray",dimColor:!0,children:"Self-Host: Run everything in Docker containers (recommended for deployment)"}),i(s,{color:"gray",dimColor:!0,children:"Developer: Run backend locally with Docker services (recommended for contributing)"})]})]}),Ne=({onSelect:e})=>u(p,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:h,children:[i(s,{bold:!0,children:"Environment Variables Setup"}),i(p,{marginTop:1,children:i(s,{color:"gray",children:"Choose how you want to configure environment variables:"})}),i(p,{marginTop:1,children:i(Oe,{options:[{label:"Manual Setup (Recommended)",value:"manual"},{label:"Infisical (Advanced)",value:"infisical"}],onChange:o=>e(o)})}),u(p,{marginTop:1,flexDirection:"column",children:[i(s,{color:"gray",dimColor:!0,children:"Manual Setup: Configure variables interactively (recommended for most users)"}),i(s,{color:"gray",dimColor:!0,children:"Infisical: All secrets managed in Infisical dashboard (requires pre-configuration)"})]})]}),Ge=({onSubmit:e})=>{let[t,o]=M({INFISICAL_TOKEN:"",INFISICAL_PROJECT_ID:"",INFISICAL_MACHINE_IDENTITY_CLIENT_ID:"",INFISICAL_MACHINE_IDENTITY_CLIENT_SECRET:""}),[r,n]=M(0),[a,c]=M(null),d=[{key:"INFISICAL_TOKEN",description:"Service token from project settings (st.xxx...)"},{key:"INFISICAL_PROJECT_ID",description:"Found in your Infisical project settings"},{key:"INFISICAL_MACHINE_IDENTITY_CLIENT_ID",description:"From Access Control \u2192 Machine Identities"},{key:"INFISICAL_MACHINE_IDENTITY_CLIENT_SECRET",description:"Generated when creating the machine identity"}];ee((f,y)=>{if(y.tab||y.downArrow)n(g=>g<d.length-1?g+1:g);else if(y.upArrow)n(g=>g>0?g-1:g);else if(y.return){if(r<d.length-1){n(v=>v+1);return}let g=d.filter(v=>!t[v.key].trim());if(g.length>0){c(`Required: ${g.map(b=>b.key).join(", ")}`);let v=d.findIndex(b=>!t[b.key].trim());v>=0&&n(v);return}e(t)}});let m=d[r];return u(p,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:h,children:[i(p,{marginBottom:1,children:i(s,{bold:!0,color:h,children:"Infisical Configuration"})}),i(p,{marginBottom:1,borderStyle:"single",borderColor:"cyan",paddingX:1,children:i(s,{color:"cyan",children:"All environment variables (API keys, auth secrets, etc.) must be configured in your Infisical project. Only Infisical credentials will be stored locally."})}),u(p,{marginBottom:1,flexDirection:"column",children:[i(s,{color:"gray",children:"Configure your Infisical credentials."}),u(s,{color:"gray",dimColor:!0,children:["Visit"," ",i(s,{color:"cyan",underline:!0,children:"app.infisical.com"})," ","to get these values."]})]}),d.map((f,y)=>{let g=f.key.includes("SECRET")||f.key.includes("TOKEN");return u(p,{flexDirection:"column",marginBottom:1,children:[i(p,{children:u(s,{color:y===r?h:"white",children:[y===r?"\u25B8 ":" ",f.key,":"]})}),i(p,{marginLeft:2,children:i(s,{color:"gray",dimColor:!0,children:f.description})}),y===r?i(p,{marginLeft:2,children:i(me,{value:t[f.key],onChange:v=>{o(b=>({...b,[f.key]:v})),c(null)},placeholder:"Enter value...",mask:g?"*":void 0})}):i(p,{marginLeft:2,children:i(s,{color:t[f.key]?"green":"gray",children:t[f.key]?g?`\u2713 ${"*".repeat(8)}`:`\u2713 ${t[f.key]}`:"(not set)"})})]},f.key)}),a&&i(p,{marginTop:1,children:i(s,{color:"red",children:a})}),i(p,{marginTop:1,children:i(s,{color:"gray",dimColor:!0,children:"\u2191\u2193/Tab to navigate \u2022 Enter to confirm"})})]})},qe=({category:e,currentIndex:t,totalGroups:o,onSubmit:r})=>{let[n,a]=M(()=>{let v={};for(let b of e.variables)v[b.name]=b.defaultValue||"";return v}),[c,d]=M(0),[m,f]=M(null);Se(()=>{let v={};for(let b of e.variables)v[b.name]=b.defaultValue||"";a(v),d(0),f(null)},[e.name]),ee((v,b)=>{if(b.tab||b.downArrow)d(l=>l<e.variables.length-1?l+1:l);else if(b.upArrow)d(l=>l>0?l-1:l);else if(b.escape){let l=e.variables.filter(S=>S.required&&!n[S.name]?.trim());if(l.length>0){f(`Required fields cannot be skipped: ${l.map(S=>S.name).join(", ")}`);return}r(n)}});let y=()=>{if(c<e.variables.length-1)d(c+1);else{let v=e.variables.filter(b=>b.required&&!n[b.name]?.trim());if(v.length>0){f(`Required fields are missing: ${v.map(b=>b.name).join(", ")}`);return}f(null),r(n)}},g=e.variables.some(v=>v.required);return u(p,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:m?"red":h,children:[u(p,{justifyContent:"space-between",children:[u(s,{bold:!0,children:["Configure ",e.name]}),u(s,{color:"gray",children:["Group ",t+1," / ",o]})]}),u(p,{marginTop:1,flexDirection:"column",children:[u(p,{children:[u(s,{color:"cyan",bold:!0,children:["Purpose:"," "]}),i(s,{color:"white",children:e.description})]}),e.affectedFeatures&&u(p,{children:[u(s,{color:"cyan",bold:!0,children:["Affects:"," "]}),i(s,{color:"gray",children:e.affectedFeatures})]}),e.docsUrl&&u(p,{marginTop:1,children:[i(s,{color:"green",children:"\u{1F4D6} Docs: "}),i(s,{color:"blue",underline:!0,children:e.docsUrl})]})]}),i(p,{marginTop:1,flexDirection:"column",children:e.variables.map((v,b)=>{let l=b===c,S=!!v.defaultValue;return u(p,{flexDirection:"column",marginBottom:1,children:[u(p,{children:[u(s,{color:l?h:"gray",bold:l,children:[l?"\u279C ":" ",v.name]}),v.required&&u(s,{color:"red",bold:!0,children:[" ","*"]}),S&&!l&&u(s,{color:"gray",dimColor:!0,children:[" ","(default: ",v.defaultValue,")"]})]}),l&&i(p,{marginLeft:2,children:i(me,{value:n[v.name]||"",onChange:x=>{a(C=>({...C,[v.name]:x})),m&&f(null)},onSubmit:y,placeholder:S?`Default: ${v.defaultValue}`:v.required?"Enter a value (required)":"Press Enter to skip"})})]},v.name)})}),m&&i(p,{marginTop:1,children:u(s,{color:"red",bold:!0,children:["\u26A0 ",m]})}),i(p,{marginTop:1,flexDirection:"column",children:u(s,{color:"gray",dimColor:!0,children:["\u21B5 Enter to next field \u2022 Tab/\u2193 move down \u2022 \u2191 move up",!g&&" \u2022 ESC skip group"]})})]})},$e=({alternatives:e,onSubmit:t})=>{let[o,r]=M(new Set),[n,a]=M({}),[c,d]=M(0),[m,f]=M(null);Se(()=>{let x={};for(let C of e)for(let I of C.variables)x[I.name]=I.defaultValue||"";a(x)},[e]);let y=[];for(let x=0;x<e.length;x++)if(y.push({type:"provider",categoryIndex:x}),o.has(x)){let C=e[x];if(C)for(let I=0;I<C.variables.length;I++)y.push({type:"field",categoryIndex:x,fieldIndex:I})}y.push({type:"submit"});let g=y[c],v=g?.type==="field",b=g?.type==="submit";ee((x,C)=>{let I=Math.min(c,y.length-1);if(I!==c){d(I);return}if(v)C.upArrow?d(w=>Math.max(0,w-1)):(C.downArrow||C.tab)&&d(w=>Math.min(y.length-1,w+1));else if(b)C.upArrow?d(w=>Math.max(0,w-1)):(C.return||x===" ")&&S();else if(C.upArrow)d(w=>Math.max(0,w-1));else if(C.downArrow||C.tab)d(w=>Math.min(y.length-1,w+1));else if((C.return||x===" ")&&g?.type==="provider"){let w=g.categoryIndex;r(Y=>{let k=new Set(Y);return k.has(w)?k.delete(w):k.add(w),k}),m&&f(null)}});let l=()=>{m&&f(null),d(x=>Math.min(y.length-1,x+1))},S=()=>{let x=[],C={};for(let I of o){let w=e[I];if(!w)continue;if(w.variables.some(k=>n[k.name]?.trim())){x.push(w.name);for(let k of w.variables){let ge=n[k.name];ge&&(C[k.name]=ge)}}}if(x.length===0){o.size===0?f("Enable at least one provider (press Space or Enter)"):f("Enter a value for at least one field");return}t(x,C)};return u(p,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:m?"red":h,children:[u(p,{justifyContent:"space-between",children:[i(s,{bold:!0,children:"Configure AI Provider"}),i(s,{color:"yellow",children:"* At least one required"})]}),i(p,{marginTop:1,children:i(s,{color:"gray",children:"Enable and configure at least one AI provider below:"})}),i(p,{marginTop:1,flexDirection:"column",children:e.map((x,C)=>{let I=o.has(C),w=y.findIndex(k=>k.type==="provider"&&k.categoryIndex===C),Y=c===w;return u(p,{flexDirection:"column",marginBottom:1,children:[u(p,{children:[i(s,{color:Y?h:void 0,bold:Y,children:Y?"\u279C ":" "}),i(s,{color:I?"green":"gray",children:I?"[\u2714]":"[ ]"}),u(s,{color:I?h:"gray",bold:I,children:[" ",x.name]}),x.description&&u(s,{color:"gray",dimColor:!0,children:[" ","- ",x.description]})]}),Y&&x.docsUrl&&u(p,{marginLeft:6,children:[i(s,{color:"yellow",children:"\u{1F4D6} "}),i(s,{color:"blue",underline:!0,children:x.docsUrl})]}),I&&i(p,{marginLeft:4,flexDirection:"column",marginTop:1,children:x.variables.map((k,ge)=>{let er=y.findIndex(pe=>pe.type==="field"&&pe.categoryIndex===C&&pe.fieldIndex===ge),oe=c===er,nt=!!k.defaultValue,ke=n[k.name]||"";return u(p,{flexDirection:"column",marginBottom:1,children:[u(p,{children:[u(s,{color:oe?h:"gray",bold:oe,children:[oe?" \u279C ":" ",k.name]}),!oe&&ke&&i(s,{color:"green",children:" \u2713"}),!oe&&!ke&&nt&&u(s,{color:"gray",dimColor:!0,children:[" ","(default: ",k.defaultValue,")"]})]}),oe&&i(p,{marginLeft:4,children:i(me,{value:ke,onChange:pe=>{a(tr=>({...tr,[k.name]:pe})),m&&f(null)},onSubmit:l,placeholder:nt?`Default: ${k.defaultValue}`:"Enter value..."})})]},k.name)})})]},x.name)})}),m&&i(p,{marginTop:1,children:u(s,{color:"red",bold:!0,children:["\u26A0 ",m]})}),u(p,{marginTop:1,children:[i(s,{color:b?h:void 0,bold:b,children:b?"\u279C ":" "}),i(p,{borderStyle:"round",borderColor:b?h:"gray",paddingX:2,children:i(s,{color:b?h:"gray",bold:b,children:"Continue \u2192"})})]}),i(p,{marginTop:1,children:i(s,{color:"gray",dimColor:!0,children:"\u2191/\u2193 navigate \u2022 Space/Enter toggle/select \u2022 Tab skip field"})})]})},je=({currentVar:e,currentIndex:t,totalCount:o,onSubmit:r,onSkip:n})=>{let[a,c]=M(e.defaultValue||""),[d,m]=M(null);Se(()=>{c(e.defaultValue||""),m(null)},[e.name]),ee((g,v)=>{if(v.escape){if(e.required&&!a.trim()){m("This field is required and cannot be skipped");return}n()}});let f=g=>{if(e.required&&!g.trim()){m("This field is required");return}m(null),r(g)},y=!!e.defaultValue;return u(p,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:d?"red":h,children:[u(p,{justifyContent:"space-between",children:[i(s,{bold:!0,children:"Configure Environment Variables"}),u(s,{color:"gray",children:[t+1," / ",o]})]}),u(p,{marginTop:1,flexDirection:"column",children:[u(p,{children:[i(s,{color:h,bold:!0,children:e.name}),e.required?u(s,{color:"red",bold:!0,children:[" ","* required"]}):u(s,{color:"gray",dimColor:!0,children:[" ","(optional)"]})]}),u(p,{marginTop:1,children:[u(s,{color:"cyan",bold:!0,children:["Category:"," "]}),i(s,{color:"white",children:e.category})]}),u(p,{children:[u(s,{color:"cyan",bold:!0,children:["Purpose:"," "]}),i(s,{color:"white",children:e.description})]}),e.affectedFeatures&&u(p,{children:[u(s,{color:"cyan",bold:!0,children:["Affects:"," "]}),i(s,{color:"gray",children:e.affectedFeatures})]}),e.docsUrl&&u(p,{marginTop:1,children:[i(s,{color:"green",children:"\u{1F4D6} Docs: "}),i(s,{color:"blue",underline:!0,children:e.docsUrl})]}),y&&u(p,{marginTop:1,children:[u(s,{color:"green",bold:!0,children:["Default:"," "]}),i(s,{color:"white",children:e.defaultValue})]})]}),u(p,{marginTop:1,children:[i(s,{color:h,children:"\u279C "}),i(me,{value:a,onChange:g=>{c(g),d&&m(null)},onSubmit:f,placeholder:y?"Press Enter to use default":e.required?"Enter a value (required)":"Press Enter to skip"})]}),d&&i(p,{marginTop:1,children:u(s,{color:"red",bold:!0,children:["\u26A0 ",d]})}),i(p,{marginTop:1,flexDirection:"column",children:e.required?i(s,{color:"yellow",dimColor:!0,children:"\u21B5 Enter to confirm (required field)"}):y?i(s,{color:"green",dimColor:!0,children:"\u21B5 Enter to use default \u2022 ESC to skip"}):i(s,{color:"gray",dimColor:!0,children:"\u21B5 Enter to confirm \u2022 ESC to skip"})})]})},pt=({store:e})=>{let[t,o]=M(e.currentState);return Se(()=>{let r=()=>o({...e.currentState});return e.on("change",r),()=>{e.off("change",r)}},[e]),u(he,{status:t.status,step:t.step,children:[t.step==="Welcome"&&t.inputRequest?.id==="welcome"&&i(cr,{onConfirm:()=>e.submitInput(!0)}),t.step==="Prerequisites"&&t.data.checks&&u(p,{flexDirection:"column",borderStyle:"round",paddingX:1,borderColor:h,children:[i(s,{bold:!0,children:"System Checks"}),u(p,{flexDirection:"column",marginTop:1,children:[i(_e,{label:"Git",status:t.data.checks.git}),i(_e,{label:"Docker",status:t.data.checks.docker}),i(_e,{label:"Mise",status:t.data.checks.mise})]})]}),t.inputRequest?.id==="port_conflicts"&&t.data.portConflicts&&i(lr,{portResults:t.data.portConflicts,onAccept:()=>e.submitInput("accept"),onAbort:()=>e.submitInput("abort")}),t.inputRequest?.id==="repo_path"&&i(ur,{defaultValue:t.inputRequest.meta.default,onSubmit:r=>e.submitInput(r)}),t.inputRequest?.id==="existing_repo"&&t.data.existingRepoPath&&i(pr,{repoPath:t.data.existingRepoPath,onAction:r=>e.submitInput(r)}),t.step==="Repository Setup"&&!t.inputRequest&&u(p,{flexDirection:"column",borderStyle:"round",padding:1,borderColor:h,children:[i(s,{bold:!0,children:"Cloning Repository"}),u(p,{marginTop:1,flexDirection:"column",children:[i(ut,{value:t.data.repoProgress||0}),t.data.repoPhase&&i(p,{marginTop:1,children:i(s,{color:"gray",children:t.data.repoPhase})})]})]}),t.inputRequest?.id==="setup_mode"&&i(Le,{onSelect:r=>e.submitInput(r)}),t.inputRequest?.id==="env_method"&&i(Ne,{onSelect:r=>e.submitInput(r)}),t.inputRequest?.id==="env_infisical"&&i(Ge,{onSubmit:r=>e.submitInput(r)}),t.step==="Environment Setup"&&t.inputRequest?.id==="env_var"&&t.data.currentEnvVar&&i(je,{categories:t.data.envCategories||[],currentVar:t.data.currentEnvVar,currentIndex:t.data.envVarIndex||0,totalCount:t.data.envVarTotal||0,onSubmit:r=>e.submitInput(r),onSkip:()=>e.submitInput("")}),t.step==="Environment Setup"&&t.inputRequest?.id==="env_group"&&t.data.currentEnvGroup&&i(qe,{category:t.data.currentEnvGroup,currentIndex:t.data.envGroupIndex||0,totalGroups:t.data.envGroupTotal||0,onSubmit:r=>e.submitInput(r)}),t.step==="Environment Setup"&&t.inputRequest?.id==="env_alternatives"&&t.data.alternativeGroups&&i($e,{alternatives:t.data.alternativeGroups,onSubmit:(r,n)=>e.submitInput({selectedGroups:r,values:n})}),t.step==="Environment Setup"&&!t.inputRequest&&u(p,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:h,children:[i(s,{bold:!0,children:"Environment Setup"}),i(p,{marginTop:1,children:i(Me,{label:t.status||"Configuring environment..."})})]}),t.step==="Finished"&&i(dr,{setupMode:t.data.setupMode,portOverrides:t.data.portOverrides,onConfirm:()=>e.submitInput("exit")}),(t.step==="Install Tools"||t.step==="Project Setup")&&i(mr,{title:t.step==="Install Tools"?"Installing Tools":"Project Setup",phase:t.data.dependencyPhase||"",progress:t.data.dependencyProgress||0,isComplete:t.step==="Install Tools"?t.data.toolComplete||!1:t.data.dependencyComplete||!1,logs:t.data.dependencyLogs||[]}),t.error&&i(p,{borderStyle:"single",borderColor:"red",padding:1,marginTop:2,children:u(s,{color:"red",children:["Error: ",t.error.message]})})]})};import{Spinner as fr}from"@inkjs/ui";import{Box as q,Text as O,useInput as gr}from"ink";import{useEffect as xr,useState as hr}from"react";import{jsx as G,jsxs as B}from"react/jsx-runtime";var dt=({store:e,command:t})=>{let[o,r]=hr(e.currentState);xr(()=>{let a=()=>r({...e.currentState});return e.on("change",a),()=>{e.off("change",a)}},[e]),gr((a,c)=>{(c.return||c.escape)&&(o.data.started||o.data.stopped||o.error)&&e.submitInput("exit")});let n=t==="start";return B(q,{flexDirection:"column",width:"100%",children:[G(ne,{}),(o.step==="Starting"||o.step==="Stopping")&&B(q,{flexDirection:"column",marginTop:1,paddingX:2,borderStyle:"round",borderColor:h,children:[G(fr,{label:o.status||"Working..."}),o.data.repoPath&&G(q,{marginTop:1,children:B(O,{color:"gray",children:["Repository: ",o.data.repoPath]})}),o.data.setupMode&&G(q,{children:B(O,{color:"gray",children:["Mode: ",o.data.setupMode]})})]}),o.step==="Running"&&o.data.started&&B(q,{flexDirection:"column",marginTop:1,paddingX:2,paddingY:1,borderStyle:"round",borderColor:"green",children:[B(O,{color:"green",bold:!0,children:["\u2713"," GAIA is running!"]}),o.data.setupMode!=="developer"&&B(q,{marginTop:1,flexDirection:"column",children:[B(O,{children:["Web:"," ",B(O,{color:"cyan",bold:!0,children:["http://localhost:",o.data.webPort||3e3]})]}),B(O,{children:["API:"," ",B(O,{color:"cyan",bold:!0,children:["http://localhost:",o.data.apiPort||8e3]})]})]}),o.data.setupMode==="developer"&&B(q,{marginTop:1,flexDirection:"column",children:[G(O,{color:"gray",children:"Dev servers started in background."}),B(O,{color:"gray",children:["Logs: ",G(O,{color:h,children:"dev-start.log"})," in your repo root."]}),B(O,{color:"gray",children:["Run ",G(O,{color:h,children:"gaia stop"})," to shut down."]})]}),G(q,{marginTop:1,children:G(O,{dimColor:!0,children:"Press Enter to exit"})})]}),o.step==="Stopped"&&o.data.stopped&&B(q,{flexDirection:"column",marginTop:1,paddingX:2,paddingY:1,borderStyle:"round",borderColor:h,children:[B(O,{color:h,bold:!0,children:["\u2713"," All GAIA services stopped."]}),G(q,{marginTop:1,children:G(O,{dimColor:!0,children:"Press Enter to exit"})})]}),o.error&&B(q,{borderStyle:"single",borderColor:"red",padding:1,marginTop:2,children:[B(O,{color:"red",children:["Error: ",o.error.message]}),G(q,{marginTop:1,children:G(O,{dimColor:!0,children:"Press Enter to exit"})})]})]})};import{ProgressBar as Sr,Spinner as ve}from"@inkjs/ui";import{Box as P,Text as E,useInput as mt}from"ink";import{useEffect as vr,useState as yr}from"react";import{jsx as T,jsxs as R}from"react/jsx-runtime";var ft=({store:e})=>{let[t,o]=yr(e.currentState);return vr(()=>{let r=()=>o({...e.currentState});return e.on("change",r),()=>{e.off("change",r)}},[e]),R(he,{status:t.status,step:t.step,steps:lt,children:[t.step==="Detect Repo"&&R(P,{flexDirection:"column",paddingX:2,borderStyle:"round",borderColor:h,children:[T(E,{bold:!0,children:"Detecting GAIA Repository"}),T(P,{marginTop:1,children:T(ve,{label:"Searching for repository..."})}),t.data.repoPath&&T(P,{marginTop:1,children:R(E,{color:"green",children:["Found: ",t.data.repoPath]})})]}),t.step==="Prerequisites"&&t.data.checks&&R(P,{flexDirection:"column",borderStyle:"round",paddingX:1,borderColor:h,children:[T(E,{bold:!0,children:"System Checks"}),R(P,{flexDirection:"column",marginTop:1,children:[T(He,{label:"Git",status:t.data.checks.git}),T(He,{label:"Docker",status:t.data.checks.docker}),T(He,{label:"Mise",status:t.data.checks.mise})]})]}),t.inputRequest?.id==="port_conflicts"&&t.data.portConflicts&&T(Tr,{portResults:t.data.portConflicts,onAccept:()=>e.submitInput("accept"),onAbort:()=>e.submitInput("abort")}),t.inputRequest?.id==="setup_mode"&&T(Le,{onSelect:r=>e.submitInput(r)}),t.inputRequest?.id==="env_method"&&T(Ne,{onSelect:r=>e.submitInput(r)}),t.inputRequest?.id==="env_infisical"&&T(Ge,{onSubmit:r=>e.submitInput(r)}),t.step==="Environment Setup"&&t.inputRequest?.id==="env_var"&&t.data.currentEnvVar&&T(je,{categories:t.data.envCategories||[],currentVar:t.data.currentEnvVar,currentIndex:t.data.envVarIndex||0,totalCount:t.data.envVarTotal||0,onSubmit:r=>e.submitInput(r),onSkip:()=>e.submitInput("")}),t.step==="Environment Setup"&&t.inputRequest?.id==="env_group"&&t.data.currentEnvGroup&&T(qe,{category:t.data.currentEnvGroup,currentIndex:t.data.envGroupIndex||0,totalGroups:t.data.envGroupTotal||0,onSubmit:r=>e.submitInput(r)}),t.step==="Environment Setup"&&t.inputRequest?.id==="env_alternatives"&&t.data.alternativeGroups&&T($e,{alternatives:t.data.alternativeGroups,onSubmit:(r,n)=>e.submitInput({selectedGroups:r,values:n})}),t.step==="Environment Setup"&&!t.inputRequest&&R(P,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:h,children:[T(E,{bold:!0,children:"Environment Setup"}),T(P,{marginTop:1,children:T(ve,{label:t.status||"Configuring environment..."})})]}),t.step==="Project Setup"&&R(P,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:h,children:[T(P,{marginBottom:1,children:T(E,{bold:!0,color:h,children:"Project Setup"})}),R(P,{flexDirection:"column",gap:1,children:[T(P,{children:t.data.dependencyComplete?R(E,{color:"green",children:["\u2713"," ",t.data.dependencyPhase]}):T(ve,{label:t.data.dependencyPhase||"Preparing..."})}),!t.data.dependencyComplete&&t.data.dependencyProgress>0&&T(P,{width:50,children:T(Sr,{value:t.data.dependencyProgress})}),!t.data.dependencyComplete&&t.data.dependencyLogs?.length>0&&T(P,{flexDirection:"column",marginTop:1,borderStyle:"single",borderColor:"gray",paddingX:1,minHeight:6,children:t.data.dependencyLogs.map((r,n)=>T(E,{color:"gray",wrap:"truncate",children:r},n))})]})]}),t.step==="Finished"&&T(br,{setupMode:t.data.setupMode,portOverrides:t.data.portOverrides,onConfirm:()=>e.submitInput("exit")}),t.error&&T(P,{borderStyle:"single",borderColor:"red",padding:1,marginTop:2,children:R(E,{color:"red",children:["Error: ",t.error.message]})})]})},He=({label:e,status:t})=>R(P,{children:[T(P,{marginRight:1,children:t==="pending"?T(ve,{type:"dots"}):t==="success"?T(E,{color:h,children:"\u2714"}):t==="error"?T(E,{color:"red",children:"\u2716"}):T(E,{color:"yellow",children:"\u26A0"})}),T(E,{children:e})]}),Tr=({portResults:e,onAccept:t,onAbort:o})=>(mt((r,n)=>{n.return?t():n.escape&&o()}),R(P,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:"yellow",children:[T(E,{bold:!0,color:"yellow",children:"Port Conflicts Detected"}),e.map(r=>R(P,{children:[R(E,{color:r.available?"green":"red",children:[r.available?"\u2714":"\u2716"," "]}),R(E,{children:[r.service," (:",r.port,")"]}),!r.available&&R(E,{color:"gray",children:[" ","- in use",r.usedBy?` by ${r.usedBy}`:"",r.alternative?` (alt: :${r.alternative})`:""]})]},r.port)),T(P,{marginTop:1,children:R(E,{children:[T(E,{color:"green",bold:!0,children:"Enter"})," continue ",T(E,{color:"yellow",bold:!0,children:"Escape"})," abort"]})})]})),br=({setupMode:e,portOverrides:t,onConfirm:o})=>{mt((c,d)=>{d.return&&o()});let r=e||"developer",n=t?.[3e3]??3e3,a=t?.[8e3]??8e3;return R(P,{flexDirection:"column",marginTop:2,borderStyle:"round",borderColor:h,padding:1,children:[T(E,{color:h,bold:!0,children:"Setup Complete!"}),R(P,{marginTop:1,flexDirection:"column",children:[T(E,{bold:!0,children:"To start GAIA, run:"}),T(P,{marginTop:1,padding:1,borderStyle:"single",borderColor:"gray",flexDirection:"column",children:T(E,{color:"cyan",children:"$ gaia start"})}),T(P,{marginTop:1,children:T(E,{color:"gray",dimColor:!0,children:r==="selfhost"?"Runs: docker compose --profile all up -d (background)":"Runs: mise dev (interactive \u2014 keep terminal open)"})})]}),R(P,{marginTop:1,flexDirection:"column",children:[T(E,{bold:!0,children:"Access GAIA at:"}),R(P,{marginLeft:2,flexDirection:"column",children:[R(E,{children:["Web:"," ",R(E,{color:"cyan",bold:!0,children:["http://localhost:",n]})]}),R(E,{children:["API:"," ",R(E,{color:"cyan",bold:!0,children:["http://localhost:",a]})]})]})]}),T(Fe,{}),T(P,{marginTop:1,children:T(E,{dimColor:!0,children:"Press Enter to exit"})})]})};import{Spinner as Cr}from"@inkjs/ui";import{Box as A,Text as _,useInput as Ir}from"ink";import{useEffect as gt,useState as xt}from"react";import{jsx as D,jsxs as F}from"react/jsx-runtime";var ht=({store:e})=>{let[t,o]=xt(e.currentState),[r,n]=xt(!1);return gt(()=>{let a=()=>o({...e.currentState});return e.on("change",a),()=>{e.off("change",a)}},[e]),gt(()=>{t.step==="Results"&&n(!1)},[t.step]),Ir((a,c)=>{(c.return||c.escape)&&t.step==="Results"&&e.submitInput("exit"),a==="r"&&t.step==="Results"&&t.data.refreshable&&!r&&(n(!0),e.submitInput("refresh"))}),F(A,{flexDirection:"column",width:"100%",children:[D(ne,{}),t.step==="Checking"&&D(A,{marginTop:1,children:D(Cr,{label:t.data.services?"Refreshing service health...":"Checking service health..."})}),t.step==="Results"&&t.data.services&&F(A,{flexDirection:"column",children:[F(A,{flexDirection:"column",borderStyle:"round",borderColor:h,paddingX:2,paddingY:1,children:[D(_,{bold:!0,color:h,children:"GAIA Service Status"}),F(A,{marginTop:1,flexDirection:"column",children:[F(A,{children:[D(A,{width:22,children:D(_,{bold:!0,children:"Service"})}),D(A,{width:10,children:D(_,{bold:!0,children:"Status"})}),D(A,{width:10,children:D(_,{bold:!0,children:"Latency"})})]}),D(_,{color:"gray",children:"\u2500".repeat(42)}),t.data.services.map(a=>F(A,{children:[D(A,{width:22,children:F(_,{children:[a.name," (:",a.port,")"]})}),D(A,{width:10,children:D(_,{color:a.status==="up"?"green":"red",bold:!0,children:a.status==="up"?"\u2713 UP":"\u2717 DOWN"})}),D(A,{width:10,children:D(_,{color:"gray",children:a.latency?`${a.latency}ms`:"--"})})]},a.name))]})]}),t.data.docker&&F(A,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,marginTop:1,children:[D(_,{bold:!0,children:"Docker Containers"}),F(_,{color:"gray",children:["Docker:"," ",t.data.docker.running?D(_,{color:"green",children:"Running"}):D(_,{color:"red",children:"Not running"})]}),t.data.docker.containers?.length>0&&D(A,{marginTop:1,flexDirection:"column",children:t.data.docker.containers.map(a=>F(A,{children:[F(_,{color:a.status==="running"?"green":"red",children:[a.status==="running"?"\u2713":"\u2717"," "]}),D(_,{children:a.name}),a.health&&F(_,{color:"gray",children:[" (",a.health,")"]})]},a.name))})]}),D(A,{marginTop:1,children:F(_,{dimColor:!0,children:["Press Enter or Escape to exit \xB7 Press"," ",D(_,{color:h,children:"r"})," to refresh"]})})]}),t.error&&D(A,{borderStyle:"single",borderColor:"red",padding:1,marginTop:2,children:F(_,{color:"red",children:["Error: ",t.error.message]})})]})};import{jsx as $,jsxs as fe}from"react/jsx-runtime";var wr=["init","setup","status","start","stop"],We=class extends Er.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}render(){return this.state.error?fe(ye,{flexDirection:"column",padding:1,children:[$(te,{color:"red",bold:!0,children:"An unexpected error occurred:"}),$(te,{color:"red",children:this.state.error.message}),this.state.error.stack&&$(ye,{marginTop:1,children:$(te,{color:"gray",dimColor:!0,children:this.state.error.stack})})]}):this.props.children}},Pr=({store:e,command:t})=>{switch(t){case"init":return $(pt,{store:e});case"setup":return $(ft,{store:e});case"status":return $(ht,{store:e});case"start":case"stop":return $(dt,{store:e,command:t});default:return fe(ye,{flexDirection:"column",padding:1,children:[fe(te,{color:"red",children:["Unknown command: ",t]}),fe(ye,{marginTop:1,flexDirection:"column",children:[$(te,{bold:!0,children:"Available commands:"}),wr.map(o=>fe(te,{children:[" ",$(te,{color:"cyan",children:o})]},o))]})]})}},W=({store:e,command:t})=>$(We,{children:$(Pr,{store:e,command:t})});import{EventEmitter as Rr}from"events";var Dr=150,Ve=class extends Rr{state={step:"init",status:"",error:null,data:{},inputRequest:null};inputResolver=null;emitTimer=null;emitPending=!1;get currentState(){return this.state}scheduleEmit(){this.emitPending=!0,this.emitTimer||(this.emitTimer=setTimeout(()=>{this.emitTimer=null,this.emitPending&&(this.emitPending=!1,this.emit("change",this.state))},Dr))}emitNow(){this.emitTimer&&(clearTimeout(this.emitTimer),this.emitTimer=null),this.emitPending=!1,this.emit("change",this.state)}setStep(t){this.state.step=t,this.emitNow()}setStatus(t){this.state.status=t,this.scheduleEmit()}setError(t){this.state.error=t,t!==null&&this.inputResolver&&(this.inputResolver(null),this.inputResolver=null,this.state.inputRequest=null),this.emitNow()}updateData(t,o){this.state.data={...this.state.data,[t]:o},this.scheduleEmit()}waitForInput(t,o){return this.state.inputRequest={id:t,meta:o},this.emitNow(),new Promise(r=>{this.inputResolver=r})}submitInput(t){this.inputResolver&&(this.inputResolver(t),this.inputResolver=null,this.state.inputRequest=null,this.emitNow())}},V=()=>new Ve;import*as z from"fs";import*as Gt from"os";import*as re from"path";import*as K from"fs";import*as St from"os";import*as Qe from"path";var Ue=Qe.join(St.homedir(),".gaia"),Xe=Qe.join(Ue,"config.json");function kr(){K.existsSync(Ue)||K.mkdirSync(Ue,{recursive:!0})}function Ye(){try{if(!K.existsSync(Xe))return null;let e=K.readFileSync(Xe,"utf-8");return JSON.parse(e)}catch{return null}}function Te(e){kr(),K.writeFileSync(Xe,`${JSON.stringify(e,null,2)}
3
- `)}function Ke(e){let o={...Ye()??{version:"0.1.8",setupComplete:!1,setupMethod:"manual",repoPath:"",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},...e,updatedAt:new Date().toISOString()};Te(o)}import*as _t from"path";import*as se from"node:fs";import*as ae from"node:path";import{execa as vt}from"execa";var Je={selfhost:{MONGO_DB:"mongodb://mongo:27017/gaia",REDIS_URL:"redis://redis:6379",POSTGRES_URL:"postgresql://postgres:postgres@postgres:5432/langgraph",CHROMADB_HOST:"chromadb",CHROMADB_PORT:"8000",RABBITMQ_URL:"amqp://guest:guest@rabbitmq:5672/"},developer:{MONGO_DB:"mongodb://localhost:27017/gaia",REDIS_URL:"redis://localhost:6379",POSTGRES_URL:"postgresql://postgres:postgres@localhost:5432/postgres",CHROMADB_HOST:"localhost",CHROMADB_PORT:"8080",RABBITMQ_URL:"amqp://guest:guest@localhost:5672/"}},yt={selfhost:{HOST:"http://localhost:8000",FRONTEND_URL:"http://localhost:3000",GAIA_BACKEND_URL:"http://gaia-backend:80",SETUP_MODE:"selfhost"},developer:{HOST:"http://localhost:8000",FRONTEND_URL:"http://localhost:3000",GAIA_BACKEND_URL:"http://host.docker.internal:8000",SETUP_MODE:"developer"}};function ze(e,t){return Je[t][e]??yt[t][e]}async function Tt(e){let t=ae.join(e,"apps/api/scripts/dump_config_schema.py"),o=ae.join(e,"apps/api/app/config/settings_validator.py"),r=ae.join(e,"apps/api/app/config/settings.py");if(!se.existsSync(t))throw new Error("dump_config_schema.py not found in apps/api/scripts");try{try{let{stdout:n}=await vt("python3",[t,o,r],{cwd:e});return JSON.parse(n)}catch{let{stdout:n}=await vt("python",[t,o,r],{cwd:e});return JSON.parse(n)}}catch(n){throw new Error(`Failed to parse settings schema: ${n.message}. Ensure python is installed.`)}}function bt(e){let t=ae.join(e,"apps","web",".env.local"),o=se.existsSync(t)?t:ae.join(e,"apps","web",".env");if(!se.existsSync(o))return[];let r=se.readFileSync(o,"utf-8"),n=[],a="General";for(let c of r.split(`
4
- `)){let d=c.trim();if(d.startsWith("#")&&!d.startsWith("#=")){let g=d.replace(/^#+\s*/,"").trim();g&&!g.startsWith("These are")&&(a=g);continue}if(!d||d.startsWith("#"))continue;let m=d.indexOf("=");if(m===-1)continue;let f=d.substring(0,m).trim(),y=d.substring(m+1).trim();n.push({name:f,value:y,category:a})}return n}function Ct(e,t){return{NEXT_PUBLIC_API_BASE_URL:`http://localhost:${t?.[8e3]??8e3}/api/v1/`}}function It(e,t,o){let r=o==="selfhost"?new Set(Object.keys(Je.selfhost)):new Set;for(let[n,a]of Object.entries(t)){let c=Number(n),d=Number(a);for(let[m,f]of Object.entries(e)){if(r.has(m))continue;if(f===String(c)){e[m]=String(d);continue}let y=new RegExp(`:${c}(?=[/\\s]|$)`,"g");e[m]=f.replaceAll(y,`:${d}`)}}}function Et(e,t){return e.map(o=>({...o,variables:o.variables.map(r=>{let n=ze(r.name,t);return{...r,defaultValue:n||r.defaultValue}})}))}function Ze(){return Object.keys(Je.selfhost)}function wt(e){return{...yt[e]}}import*as L from"fs";import*as ce from"path";function et(e){L.existsSync(e)&&L.copyFileSync(e,`${e}.bak`)}function Rt(e,t){let o=ce.join(e,".env");et(o);let r=["# GAIA Environment Configuration","# Generated by GAIA CLI",`# Created: ${new Date().toISOString()}`,""],n=["MONGO","REDIS","POSTGRES","CHROMADB","RABBITMQ","WORKOS","GOOGLE","OPENAI","INFISICAL","LANGSMITH","DISCORD","SLACK","TELEGRAM","CLOUDINARY","COMPOSIO","FIRECRAWL","LIVEKIT","DEEPGRAM","ELEVENLABS","RESEND","SENTRY","POSTHOG","MEM0","E2B","DODO","NEXT_PUBLIC","GAIA"];function a(d){for(let f of n)if(d===f||d.startsWith(`${f}_`))return f;let m=d.split("_");return m.length===1?"Core":m[0]||"Core"}let c=new Map;for(let[d,m]of Object.entries(t)){let f=a(d);c.has(f)||c.set(f,[]);let g=/[\s#"'\\]/.test(m)||m===""?`"${m.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:m;c.get(f).push(`${d}=${g}`)}for(let[d,m]of c.entries())r.push(`# ${d} Configuration`),r.push(...m),r.push("");L.writeFileSync(o,r.join(`
5
- `),"utf-8")}function Dt(e,t,o){let r=ce.join(e,"apps","web",".env.local");et(r);let n=bt(e),a=Ct(t,o),c=["# GAIA Web App Environment Configuration","# Generated by GAIA CLI",`# Created: ${new Date().toISOString()}`,""],d=new Map;for(let m of n){d.has(m.category)||d.set(m.category,[]);let f=a[m.name]??m.value;d.get(m.category).push({name:m.name,value:f})}if(n.length===0){c.push("# Core URLs");for(let[m,f]of Object.entries(a))c.push(`${m}=${f}`);c.push("")}else for(let[m,f]of d.entries()){c.push(`# ${m}`);for(let{name:y,value:g}of f)c.push(`${y}=${g}`);c.push("")}L.writeFileSync(r,c.join(`
6
- `),"utf-8")}var kt={8e3:"API_HOST_PORT",5432:"POSTGRES_HOST_PORT",6379:"REDIS_HOST_PORT",27017:"MONGO_HOST_PORT",5672:"RABBITMQ_HOST_PORT",8080:"CHROMADB_HOST_PORT",8083:"MONGO_EXPRESS_HOST_PORT",3e3:"WEB_HOST_PORT"};function Bt(e,t,o){let r=ce.join(e,"infra","docker",".env");et(r);let n=["# Docker Compose environment overrides","# Generated by GAIA CLI",`# Created: ${new Date().toISOString()}`,""];for(let[a,c]of Object.entries(t)){let d=Number(a),m=kt[d];m&&n.push(`${m}=${c}`)}if(o==="selfhost"){let a=t[8e3]??8e3;n.push(""),n.push("# Web build args"),n.push(`NEXT_PUBLIC_API_BASE_URL=http://localhost:${a}/api/v1/`)}n.push(""),L.writeFileSync(r,n.join(`
7
- `),"utf-8")}function le(e){let t={};for(let[o,r]of Object.entries(e)){let n=Number(o),a=kt[n];a&&(t[a]=String(r))}return t}function At(e){let t=ce.join(e,"infra","docker","docker-compose.yml");if(!L.existsSync(t))return;let o=L.readFileSync(t,"utf-8"),r=[{varName:"API_HOST_PORT",hostPort:8e3,containerPort:80},{varName:"CHROMADB_HOST_PORT",hostPort:8080,containerPort:8e3},{varName:"POSTGRES_HOST_PORT",hostPort:5432,containerPort:5432},{varName:"REDIS_HOST_PORT",hostPort:6379,containerPort:6379},{varName:"MONGO_HOST_PORT",hostPort:27017,containerPort:27017},{varName:"RABBITMQ_HOST_PORT",hostPort:5672,containerPort:5672},{varName:"MONGO_EXPRESS_HOST_PORT",hostPort:8083,containerPort:8081},{varName:"WEB_HOST_PORT",hostPort:3e3,containerPort:3e3}],n=!1;for(let{varName:a,hostPort:c,containerPort:d}of r){let m=`"${c}:${d}"`,f=`"\${${a}:-${c}}:${d}"`;o.includes(m)&&(o=o.replace(m,f),n=!0)}n&&L.writeFileSync(t,o,"utf-8")}var Pt={API_HOST_PORT:8e3,POSTGRES_HOST_PORT:5432,REDIS_HOST_PORT:6379,MONGO_HOST_PORT:27017,RABBITMQ_HOST_PORT:5672,CHROMADB_HOST_PORT:8080,MONGO_EXPRESS_HOST_PORT:8083,WEB_HOST_PORT:3e3};function ue(e){let t=ce.join(e,"infra","docker",".env"),o={};if(!L.existsSync(t))return o;let r=L.readFileSync(t,"utf-8");for(let n of r.split(`
8
- `)){let a=n.trim();if(a&&!a.startsWith("#")){let[c,...d]=a.split("=");if(c&&Pt[c]){let m=Number(d.join("=").trim());!Number.isNaN(m)&&m>0&&(o[Pt[c]]=m)}}}return o}var _r=e=>new Promise(t=>setTimeout(t,e));async function be(e,t,o){e.setStep("Environment Setup"),e.setStatus("Configuring environment...");let r=await e.waitForInput("setup_mode");e.updateData("setupMode",r),e.setStatus("Configuring environment variables...");let n=await e.waitForInput("env_method");e.updateData("envMethod",n);let a={};a.ENV="development";let c=Ze();for(let m of c){let f=ze(m,r);f&&(a[m]=f)}let d=wt(r);for(let[m,f]of Object.entries(d))a[m]=f;if(n==="infisical")await Or(e,a),e.setStatus("Infisical credentials saved. Ensure your Infisical project contains all required variables.");else try{await Mr(e,t,a,r)}catch(m){e.setError(m);return}o&&It(a,o,r);try{await Fr(e,t,a,r,o)}catch(m){e.setError(m);return}await _r(1e3)}async function Or(e,t){e.setStatus("Configuring Infisical...");let o=await e.waitForInput("env_infisical");t.INFISICAL_PROJECT_ID=o.INFISICAL_PROJECT_ID,t.INFISICAL_MACHINE_IDENTITY_CLIENT_ID=o.INFISICAL_MACHINE_IDENTITY_CLIENT_ID,t.INFISICAL_MACHINE_IDENTITY_CLIENT_SECRET=o.INFISICAL_MACHINE_IDENTITY_CLIENT_SECRET}async function Mr(e,t,o,r){e.setStatus("Parsing environment variables...");let n;try{n=await Tt(t),n=Et(n,r)}catch(l){throw r==="selfhost"?new Error(`Manual environment setup requires Python to parse config schema.
2
+ import{Command as Ro}from"commander";import{render as fo}from"ink";import go from"react";import{Box as _e,Text as le}from"ink";import qr from"react";import{ProgressBar as Tt,Select as Xe,Spinner as Ue}from"@inkjs/ui";import{Box as f,Text as u,useInput as ce}from"ink";import Te from"ink-text-input";import{useEffect as Be,useState as H}from"react";import{Box as De,Text as Re}from"ink";var T="#00bbff";import{Box as Sr,Text as xr}from"ink";import{jsx as yt}from"react/jsx-runtime";var vt=({status:e,step:t})=>t.toLowerCase()==="welcome"?null:yt(Sr,{width:"100%",paddingX:1,marginTop:1,children:yt(xr,{color:"gray",dimColor:!0,children:e})});import{Box as yr}from"ink";import vr from"ink-big-text";import br from"ink-gradient";import{jsx as We}from"react/jsx-runtime";var pe=()=>We(yr,{flexDirection:"column",marginTop:1,marginBottom:1,children:We(br,{colors:[T,"#b0eaff",T],children:We(vr,{text:"GAIA",font:"3d"})})});import{jsx as de,jsxs as be}from"react/jsx-runtime";var Tr=["Welcome","Prerequisites","Setup Mode","Repository Setup","Environment Setup","Install Tools","Project Setup","Installing CLI","Finished"],bt=["Detect Repo","Prerequisites","Environment Setup","Project Setup","Finished"],Ir=({currentStep:e,steps:t})=>{let o=t.indexOf(e),r=t.length,n=o+1;return be(De,{marginBottom:1,gap:1,children:[o>0&&be(Re,{color:"green",children:["\u2713 ",o]}),be(Re,{color:"gray",children:[n,"/",r]}),de(Re,{color:"gray",children:"\xB7"}),de(Re,{color:T,bold:!0,children:e})]})},ke=({children:e,status:t,step:o,steps:r=Tr})=>be(De,{flexDirection:"column",height:"100%",width:"100%",children:[be(De,{flexGrow:1,flexDirection:"column",children:[de(pe,{}),de(Ir,{currentStep:o,steps:r}),de(De,{flexDirection:"column",flexGrow:1,children:e})]}),de(vt,{status:t,step:o})]});import{Spinner as Cr}from"@inkjs/ui";import{Box as oe,Text as U,useInput as Er}from"ink";import{jsx as $,jsxs as se}from"react/jsx-runtime";var ne=({label:e,status:t})=>se(oe,{children:[$(oe,{marginRight:1,children:t==="pending"?$(Cr,{type:"dots"}):t==="success"?$(U,{color:"green",children:"\u2714"}):t==="error"?$(U,{color:"red",children:"\u2716"}):$(U,{color:"yellow",children:"\u26A0"})}),$(U,{children:e})]}),Ae=({portResults:e,onAccept:t,onAbort:o})=>{Er((n,s)=>{s.return?t():s.escape&&o()});let r=e.filter(n=>!n.available);return se(oe,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:"yellow",children:[$(oe,{marginBottom:1,children:$(U,{bold:!0,color:"yellow",children:"Port Conflicts Detected"})}),e.map(n=>se(oe,{children:[se(U,{color:n.available?"green":n.alternative?"yellow":"red",children:[n.available?"\u2714":n.alternative?"\u26A0":"\u2716"," "]}),se(U,{children:[n.service," (:",n.port,")"]}),!n.available&&se(U,{color:n.alternative?"gray":"red",children:[" ","- in use",n.usedBy?` by ${n.usedBy}`:"",n.alternative?` \u2192 will use :${n.alternative}`:" \u2014 NO ALTERNATIVE FOUND"]})]},n.port)),r.some(n=>!n.alternative)&&$(oe,{marginTop:1,children:$(U,{color:"red",children:"Some ports have no available alternative. Free them and retry."})}),!r.some(n=>!n.alternative)&&r.some(n=>n.alternative)&&$(oe,{marginTop:1,children:$(U,{color:"gray",children:"Alternative ports will be used for conflicting services."})}),$(oe,{marginTop:1,children:se(U,{dimColor:!0,children:[$(U,{bold:!0,children:"Enter"})," continue \xB7 ",$(U,{bold:!0,children:"ESC"})," abort"]})})]})};import{Fragment as on,jsx as i,jsxs as g}from"react/jsx-runtime";var Pr=({onConfirm:e})=>(ce((t,o)=>{o.return&&e()}),g(f,{flexDirection:"column",paddingX:2,borderStyle:"round",borderColor:T,children:[i(u,{bold:!0,children:"Welcome to GAIA Setup"}),g(f,{flexDirection:"column",marginTop:1,marginBottom:1,children:[i(u,{children:"This wizard will guide you through the setup process:"}),i(u,{children:" 1. Check prerequisites and choose setup mode"}),i(u,{children:" 2. Clone repository"}),i(u,{children:" 3. Configure environment variables"}),i(u,{children:" 4. Install tools and dependencies"})]}),i(u,{dimColor:!0,children:"~5-15 min depending on network speed"}),i(f,{marginTop:1,children:g(u,{color:T,children:[i(u,{bold:!0,children:"Enter"})," to start"]})})]})),wr=({defaultValue:e,onSubmit:t})=>{let[o,r]=H(e);return g(f,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:T,children:[i(u,{children:"Clone repository to:"}),i(u,{color:"gray",dimColor:!0,children:"Press Enter for default, or type a custom path"}),g(f,{marginTop:1,children:[i(u,{color:T,children:"\u2192 "}),i(Te,{value:o,onChange:r,onSubmit:t})]})]})},Rr=({repoPath:e,onAction:t})=>g(f,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:"yellow",children:[i(f,{marginBottom:1,children:i(u,{bold:!0,color:"yellow",children:"Existing Installation Found"})}),g(u,{children:["Found a GAIA installation at"," ",i(u,{color:"cyan",bold:!0,children:e})]}),i(f,{marginTop:1,children:i(u,{color:"gray",children:"What would you like to do?"})}),i(f,{marginTop:1,children:i(Xe,{options:[{label:"Use existing installation",value:"use_existing"},{label:"Delete and re-clone",value:"delete_reclone"},{label:"Choose a different path",value:"different_path"},{label:"Exit setup",value:"exit"}],onChange:r=>t(r)})})]}),Dr=({setupMode:e,portOverrides:t,onConfirm:o})=>{ce((s,l)=>{l.return&&o()});let r=t?.[3e3]??3e3,n=t?.[8e3]??8e3;return e==="selfhost"?g(f,{flexDirection:"column",marginTop:2,borderStyle:"round",borderColor:"green",padding:1,children:[i(u,{bold:!0,color:"green",children:"GAIA is Running!"}),i(f,{marginTop:1,children:i(u,{color:"green",children:"\u2713 All services started"})}),g(f,{marginTop:1,flexDirection:"column",children:[g(u,{children:["Web:"," ",g(u,{color:"cyan",bold:!0,children:["http://localhost:",r]})]}),g(u,{children:["API:"," ",g(u,{color:"cyan",bold:!0,children:["http://localhost:",n]})]})]}),i(f,{marginTop:1,children:i(u,{color:"gray",children:"gaia stop \xB7 gaia status \xB7 gaia setup"})}),i(f,{marginTop:1,children:g(u,{dimColor:!0,children:[i(u,{bold:!0,children:"Enter"})," to exit"]})})]}):g(f,{flexDirection:"column",marginTop:2,borderStyle:"round",borderColor:T,padding:1,children:[i(u,{color:T,bold:!0,children:"You're all set!"}),g(f,{marginTop:1,children:[i(u,{bold:!0,children:"Run: "}),i(u,{color:"cyan",children:"$ gaia start"})]}),g(f,{marginTop:1,flexDirection:"column",children:[g(u,{children:["Web:"," ",g(u,{color:"cyan",bold:!0,children:["http://localhost:",r]})]}),g(u,{children:["API:"," ",g(u,{color:"cyan",bold:!0,children:["http://localhost:",n]})]})]}),i(f,{marginTop:1,children:i(u,{color:"gray",children:"gaia stop \xB7 gaia status \xB7 gaia setup"})}),i(f,{marginTop:1,children:g(u,{dimColor:!0,children:[i(u,{bold:!0,children:"Enter"})," to exit"]})})]})},kr=({phase:e,progress:t,isComplete:o,logs:r,title:n})=>g(f,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:T,children:[i(f,{marginBottom:1,children:i(u,{bold:!0,color:T,children:n||"Installing Dependencies"})}),g(f,{flexDirection:"column",gap:1,children:[i(f,{children:o?g(u,{color:"green",children:["\u2713 ",e]}):i(Ue,{label:e||"Preparing..."})}),!o&&t>0&&i(f,{width:50,children:i(Tt,{value:t})}),!o&&r&&r.length>0&&i(f,{flexDirection:"column",marginTop:1,marginLeft:1,children:r.map((s,l)=>i(u,{color:"gray",wrap:"truncate",children:s},l))})]})]});var Qe=({onSelect:e})=>g(f,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:T,children:[i(u,{bold:!0,children:"Setup Mode"}),i(f,{marginTop:1,children:i(u,{color:"gray",children:"How do you want to run GAIA?"})}),i(f,{marginTop:1,children:i(Xe,{options:[{label:"Self-Host \u2014 run everything in Docker",value:"selfhost"},{label:"Developer \u2014 local dev with hot reload",value:"developer"}],onChange:o=>e(o)})})]}),Ye=({onSelect:e})=>g(f,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:T,children:[i(u,{bold:!0,children:"Environment Variables Setup"}),i(f,{marginTop:1,children:i(u,{color:"gray",children:"Choose how you want to configure environment variables:"})}),i(f,{marginTop:1,children:i(Xe,{options:[{label:"Manual Setup (Recommended)",value:"manual"},{label:"Infisical (Advanced)",value:"infisical"}],onChange:o=>e(o)})}),g(f,{marginTop:1,flexDirection:"column",children:[i(u,{color:"gray",dimColor:!0,children:"Manual Setup: Configure variables interactively (recommended for most users)"}),i(u,{color:"gray",dimColor:!0,children:"Infisical: All secrets managed in Infisical dashboard (requires pre-configuration)"})]})]}),Ke=({onSubmit:e})=>{let[t,o]=H({INFISICAL_TOKEN:"",INFISICAL_PROJECT_ID:"",INFISICAL_MACHINE_IDENTITY_CLIENT_ID:"",INFISICAL_MACHINE_IDENTITY_CLIENT_SECRET:""}),[r,n]=H(0),[s,l]=H(null),a=[{key:"INFISICAL_TOKEN",description:"Service token from project settings (st.xxx...)"},{key:"INFISICAL_PROJECT_ID",description:"Found in your Infisical project settings"},{key:"INFISICAL_MACHINE_IDENTITY_CLIENT_ID",description:"From Access Control \u2192 Machine Identities"},{key:"INFISICAL_MACHINE_IDENTITY_CLIENT_SECRET",description:"Generated when creating the machine identity"}];ce((d,x)=>{if(x.tab||x.downArrow)n(b=>b<a.length-1?b+1:b);else if(x.upArrow)n(b=>b>0?b-1:b);else if(x.return){if(r<a.length-1){n(v=>v+1);return}let b=a.filter(v=>!t[v.key].trim());if(b.length>0){l(`Required: ${b.map(S=>S.key).join(", ")}`);let v=a.findIndex(S=>!t[S.key].trim());v>=0&&n(v);return}e(t)}});let c=a[r];return g(f,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:T,children:[i(f,{marginBottom:1,children:i(u,{bold:!0,color:T,children:"Infisical Configuration"})}),i(f,{marginBottom:1,children:i(u,{color:"gray",children:"All secrets managed in your Infisical project. Only credentials stored locally."})}),g(f,{marginBottom:1,flexDirection:"column",children:[i(u,{color:"gray",children:"Configure your Infisical credentials."}),g(u,{color:"gray",dimColor:!0,children:["Visit"," ",i(u,{color:"cyan",underline:!0,children:"app.infisical.com"})," ","to get these values."]})]}),a.map((d,x)=>{let b=d.key.includes("SECRET")||d.key.includes("TOKEN");return g(f,{flexDirection:"column",marginBottom:1,children:[i(f,{children:g(u,{color:x===r?T:"white",children:[x===r?"\u25B8 ":" ",d.key,":"]})}),i(f,{marginLeft:2,children:i(u,{color:"gray",dimColor:!0,children:d.description})}),x===r?i(f,{marginLeft:2,children:i(Te,{value:t[d.key],onChange:v=>{o(S=>({...S,[d.key]:v})),l(null)},placeholder:"Enter value...",mask:b?"*":void 0})}):i(f,{marginLeft:2,children:i(u,{color:t[d.key]?"green":"gray",children:t[d.key]?b?`\u2713 ${"*".repeat(8)}`:`\u2713 ${t[d.key]}`:"(not set)"})})]},d.key)}),s&&i(f,{marginTop:1,children:i(u,{color:"red",children:s})}),i(f,{marginTop:1,children:g(u,{dimColor:!0,children:[i(u,{bold:!0,children:"Enter"})," confirm \xB7 ",i(u,{bold:!0,children:"\u2191\u2193"})," navigate"]})})]})},Je=({category:e,currentIndex:t,totalGroups:o,onSubmit:r})=>{let[n,s]=H(()=>{let v={};for(let S of e.variables)v[S.name]=S.defaultValue||"";return v}),[l,a]=H(0),[c,d]=H(null);Be(()=>{let v={};for(let S of e.variables)v[S.name]=S.defaultValue||"";s(v),a(0),d(null)},[e.name]),ce((v,S)=>{if(S.tab||S.downArrow)a(m=>m<e.variables.length-1?m+1:m);else if(S.upArrow)a(m=>m>0?m-1:m);else if(S.escape){let m=e.variables.filter(p=>p.required&&!n[p.name]?.trim());if(m.length>0){d(`Required fields cannot be skipped: ${m.map(p=>p.name).join(", ")}`);return}r(n)}});let x=()=>{if(l<e.variables.length-1)a(l+1);else{let v=e.variables.filter(S=>S.required&&!n[S.name]?.trim());if(v.length>0){d(`Required fields are missing: ${v.map(S=>S.name).join(", ")}`);return}d(null),r(n)}},b=e.variables.some(v=>v.required);return g(f,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:c?"red":T,children:[g(f,{justifyContent:"space-between",children:[g(u,{bold:!0,children:["Configure ",e.name]}),g(u,{color:"gray",children:["Group ",t+1," / ",o]})]}),i(f,{marginTop:1,children:i(u,{color:"gray",children:e.description})}),i(f,{marginTop:1,flexDirection:"column",children:e.variables.map((v,S)=>{let m=S===l,p=!!v.defaultValue;return g(f,{flexDirection:"column",marginBottom:1,children:[g(f,{children:[g(u,{color:m?T:"gray",bold:m,children:[m?"\u279C ":" ",v.name]}),v.required&&g(u,{color:"red",bold:!0,children:[" ","*"]}),p&&!m&&g(u,{color:"gray",dimColor:!0,children:[" ","(default: ",v.defaultValue,")"]})]}),m&&i(f,{marginLeft:2,children:i(Te,{value:n[v.name]||"",onChange:h=>{s(y=>({...y,[v.name]:h})),c&&d(null)},onSubmit:x,placeholder:p?`Default: ${v.defaultValue}`:v.required?"Enter a value (required)":"Press Enter to skip"})})]},v.name)})}),c&&i(f,{marginTop:1,children:g(u,{color:"red",bold:!0,children:["\u26A0 ",c]})}),i(f,{marginTop:1,children:g(u,{dimColor:!0,children:[i(u,{bold:!0,children:"Enter"})," next \xB7 ",i(u,{bold:!0,children:"\u2191\u2193"})," navigate",!b&&g(u,{children:[" ","\xB7 ",i(u,{bold:!0,children:"ESC"})," skip"]})]})})]})},ze=({alternatives:e,onSubmit:t})=>{let[o,r]=H(new Set),[n,s]=H({}),[l,a]=H(0),[c,d]=H(null);Be(()=>{let h={};for(let y of e)for(let I of y.variables)h[I.name]=I.defaultValue||"";s(h)},[e]);let x=[];for(let h=0;h<e.length;h++)if(x.push({type:"provider",categoryIndex:h}),o.has(h)){let y=e[h];if(y)for(let I=0;I<y.variables.length;I++)x.push({type:"field",categoryIndex:h,fieldIndex:I})}x.push({type:"submit"});let b=x[l],v=b?.type==="field",S=b?.type==="submit";ce((h,y)=>{let I=Math.min(l,x.length-1);if(I!==l){a(I);return}if(v)y.upArrow?a(E=>Math.max(0,E-1)):(y.downArrow||y.tab)&&a(E=>Math.min(x.length-1,E+1));else if(S)y.upArrow?a(E=>Math.max(0,E-1)):(y.return||h===" ")&&p();else if(y.upArrow)a(E=>Math.max(0,E-1));else if(y.downArrow||y.tab)a(E=>Math.min(x.length-1,E+1));else if((y.return||h===" ")&&b?.type==="provider"){let E=b.categoryIndex;r(M=>{let k=new Set(M);return k.has(E)?k.delete(E):k.add(E),k}),c&&d(null)}});let m=()=>{c&&d(null),a(h=>Math.min(x.length-1,h+1))},p=()=>{let h=[],y={};for(let I of o){let E=e[I];if(!E)continue;if(E.variables.some(k=>n[k.name]?.trim())){h.push(E.name);for(let k of E.variables){let we=n[k.name];we&&(y[k.name]=we)}}}if(h.length===0){o.size===0?d("Enable at least one provider (press Space or Enter)"):d("Enter a value for at least one field");return}t(h,y)};return g(f,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:c?"red":T,children:[g(f,{justifyContent:"space-between",children:[i(u,{bold:!0,children:"Configure AI Provider"}),i(u,{color:"yellow",children:"* At least one required"})]}),i(f,{marginTop:1,children:i(u,{color:"gray",children:"Enable and configure at least one AI provider below:"})}),i(f,{marginTop:1,flexDirection:"column",children:e.map((h,y)=>{let I=o.has(y),E=x.findIndex(k=>k.type==="provider"&&k.categoryIndex===y),M=l===E;return g(f,{flexDirection:"column",marginBottom:1,children:[g(f,{children:[i(u,{color:M?T:void 0,bold:M,children:M?"\u279C ":" "}),i(u,{color:I?"green":"gray",children:I?"[\u2714]":"[ ]"}),g(u,{color:I?T:"gray",bold:I,children:[" ",h.name]}),h.description&&g(u,{color:"gray",dimColor:!0,children:[" ","- ",h.description]})]}),M&&h.docsUrl&&g(f,{marginLeft:6,children:[i(u,{color:"yellow",children:"\u{1F4D6} "}),i(u,{color:"blue",underline:!0,children:h.docsUrl})]}),I&&i(f,{marginLeft:4,flexDirection:"column",marginTop:1,children:h.variables.map((k,we)=>{let gr=x.findIndex(ve=>ve.type==="field"&&ve.categoryIndex===y&&ve.fieldIndex===we),ue=l===gr,xt=!!k.defaultValue,Ve=n[k.name]||"";return g(f,{flexDirection:"column",marginBottom:1,children:[g(f,{children:[g(u,{color:ue?T:"gray",bold:ue,children:[ue?" \u279C ":" ",k.name]}),!ue&&Ve&&i(u,{color:"green",children:" \u2713"}),!ue&&!Ve&&xt&&g(u,{color:"gray",dimColor:!0,children:[" ","(default: ",k.defaultValue,")"]})]}),ue&&i(f,{marginLeft:4,children:i(Te,{value:Ve,onChange:ve=>{s(hr=>({...hr,[k.name]:ve})),c&&d(null)},onSubmit:m,placeholder:xt?`Default: ${k.defaultValue}`:"Enter value..."})})]},k.name)})})]},h.name)})}),c&&i(f,{marginTop:1,children:g(u,{color:"red",bold:!0,children:["\u26A0 ",c]})}),g(f,{marginTop:1,children:[i(u,{color:S?T:void 0,bold:S,children:S?"\u279C ":" "}),i(f,{borderStyle:"round",borderColor:S?T:"gray",paddingX:2,children:i(u,{color:S?T:"gray",bold:S,children:"Continue \u2192"})})]}),i(f,{marginTop:1,children:i(u,{color:"gray",dimColor:!0,children:"\u2191/\u2193 navigate \u2022 Space/Enter toggle/select \u2022 Tab skip field"})})]})},Ze=({currentVar:e,currentIndex:t,totalCount:o,onSubmit:r,onSkip:n})=>{let[s,l]=H(e.defaultValue||""),[a,c]=H(null);Be(()=>{l(e.defaultValue||""),c(null)},[e.name]),ce((b,v)=>{if(v.escape){if(e.required&&!s.trim()){c("This field is required and cannot be skipped");return}n()}});let d=b=>{if(e.required&&!b.trim()){c("This field is required");return}c(null),r(b)},x=!!e.defaultValue;return g(f,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:a?"red":T,children:[g(f,{justifyContent:"space-between",children:[g(f,{children:[i(u,{color:T,bold:!0,children:e.name}),e.required?i(u,{color:"red",children:" *"}):g(u,{color:"gray",dimColor:!0,children:[" ","optional"]})]}),g(u,{color:"gray",children:[t+1,"/",o]})]}),i(f,{marginLeft:1,children:i(u,{color:"gray",children:e.description})}),g(f,{marginTop:1,children:[i(u,{color:T,children:"\u2192 "}),i(Te,{value:s,onChange:b=>{l(b),a&&c(null)},onSubmit:d,placeholder:x?`Default: ${e.defaultValue}`:e.required?"required":"skip with Enter"})]}),a&&i(f,{marginTop:1,children:i(u,{color:"red",children:a})}),i(f,{marginTop:1,children:g(u,{dimColor:!0,children:[i(u,{bold:!0,children:"Enter"})," confirm",!e.required&&g(u,{children:[" ","\xB7 ",i(u,{bold:!0,children:"ESC"})," skip"]})]})})]})},It=({store:e})=>{let[t,o]=H(e.currentState);return Be(()=>{let r=()=>o({...e.currentState});return e.on("change",r),()=>{e.off("change",r)}},[e]),ce((r,n)=>{(n.return||n.escape)&&t.error&&e.submitInput("exit")}),g(ke,{status:t.status,step:t.step,children:[t.step==="Welcome"&&t.inputRequest?.id==="welcome"&&i(Pr,{onConfirm:()=>e.submitInput(!0)}),t.step==="Prerequisites"&&t.data.checks&&g(f,{flexDirection:"column",borderStyle:"round",paddingX:1,borderColor:T,children:[i(u,{bold:!0,children:"System Checks"}),g(f,{flexDirection:"column",marginTop:1,children:[i(ne,{label:"Git",status:t.data.checks.git}),i(ne,{label:"Docker",status:t.data.checks.docker}),i(ne,{label:"Mise",status:t.data.checks.mise})]})]}),t.inputRequest?.id==="port_conflicts"&&t.data.portConflicts&&i(Ae,{portResults:t.data.portConflicts,onAccept:()=>e.submitInput("accept"),onAbort:()=>e.submitInput("abort")}),t.inputRequest?.id==="repo_path"&&i(wr,{defaultValue:t.inputRequest.meta.default,onSubmit:r=>e.submitInput(r)}),t.inputRequest?.id==="existing_repo"&&t.data.existingRepoPath&&i(Rr,{repoPath:t.data.existingRepoPath,onAction:r=>e.submitInput(r)}),t.step==="Repository Setup"&&!t.inputRequest&&g(f,{flexDirection:"column",borderStyle:"round",padding:1,borderColor:T,children:[i(u,{bold:!0,children:"Cloning Repository"}),g(f,{marginTop:1,flexDirection:"column",children:[i(Tt,{value:t.data.repoProgress||0}),t.data.repoPhase&&i(f,{marginTop:1,children:i(u,{color:"gray",children:t.data.repoPhase})})]})]}),t.inputRequest?.id==="setup_mode"&&i(Qe,{onSelect:r=>e.submitInput(r)}),t.inputRequest?.id==="env_method"&&i(Ye,{onSelect:r=>e.submitInput(r)}),t.inputRequest?.id==="env_infisical"&&i(Ke,{onSubmit:r=>e.submitInput(r)}),t.step==="Environment Setup"&&t.inputRequest?.id==="env_var"&&t.data.currentEnvVar&&i(Ze,{categories:t.data.envCategories||[],currentVar:t.data.currentEnvVar,currentIndex:t.data.envVarIndex||0,totalCount:t.data.envVarTotal||0,onSubmit:r=>e.submitInput(r),onSkip:()=>e.submitInput("")}),t.step==="Environment Setup"&&t.inputRequest?.id==="env_group"&&t.data.currentEnvGroup&&i(Je,{category:t.data.currentEnvGroup,currentIndex:t.data.envGroupIndex||0,totalGroups:t.data.envGroupTotal||0,onSubmit:r=>e.submitInput(r)}),t.step==="Environment Setup"&&t.inputRequest?.id==="env_alternatives"&&t.data.alternativeGroups&&i(ze,{alternatives:t.data.alternativeGroups,onSubmit:(r,n)=>e.submitInput({selectedGroups:r,values:n})}),t.step==="Environment Setup"&&!t.inputRequest&&g(f,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:T,children:[i(u,{bold:!0,children:"Environment Setup"}),i(f,{marginTop:1,children:i(Ue,{label:t.status||"Configuring environment..."})})]}),t.step==="Finished"&&i(Dr,{setupMode:t.data.setupMode,portOverrides:t.data.portOverrides,onConfirm:()=>e.submitInput("exit")}),(t.step==="Install Tools"||t.step==="Project Setup")&&i(kr,{title:t.step==="Install Tools"?"Installing Tools":"Project Setup",phase:t.data.dependencyPhase||"",progress:t.data.dependencyProgress||0,isComplete:t.step==="Install Tools"?t.data.toolComplete||!1:t.data.dependencyComplete||!1,logs:t.data.dependencyLogs||[]}),t.step==="Installing CLI"&&g(f,{flexDirection:"column",borderStyle:"round",padding:1,borderColor:T,children:[i(u,{bold:!0,color:T,children:"Installing CLI"}),i(f,{marginTop:1,children:i(Ue,{label:t.status||"Installing gaia CLI globally..."})})]}),t.error&&g(f,{flexDirection:"column",borderStyle:"single",borderColor:"red",padding:1,marginTop:2,children:[g(u,{color:"red",children:["Error: ",t.error.message]}),i(f,{marginTop:1,children:g(u,{dimColor:!0,children:[i(u,{bold:!0,children:"Enter"})," to exit"]})})]})]})};import{Spinner as Ar}from"@inkjs/ui";import{Box as q,Text as R,useInput as Br}from"ink";import{useEffect as _r,useState as Or}from"react";import{jsx as j,jsxs as P}from"react/jsx-runtime";var Ct=({store:e})=>{let[t,o]=Or(e.currentState);return _r(()=>{let r=()=>o({...e.currentState});return e.on("change",r),()=>{e.off("change",r)}},[e]),Br((r,n)=>{(n.return||n.escape)&&(t.data.started||t.data.stopped||t.error)&&e.submitInput("exit")}),P(q,{flexDirection:"column",width:"100%",children:[j(pe,{}),(t.step==="Starting"||t.step==="Stopping")&&P(q,{flexDirection:"column",marginTop:1,paddingX:2,borderStyle:"round",borderColor:T,children:[j(Ar,{label:t.status||"Working..."}),t.data.repoPath&&j(q,{marginTop:1,children:P(R,{color:"gray",children:["Repository: ",t.data.repoPath]})}),t.data.setupMode&&j(q,{children:P(R,{color:"gray",children:["Mode: ",t.data.setupMode]})}),t.data.dockerLogs&&t.data.dockerLogs.length>0&&j(q,{flexDirection:"column",marginTop:1,marginLeft:1,children:t.data.dockerLogs.map((r,n)=>j(R,{color:"gray",wrap:"truncate",children:r},n))})]}),t.step==="Running"&&t.data.started&&P(q,{flexDirection:"column",marginTop:1,paddingX:2,paddingY:1,borderStyle:"round",borderColor:"green",children:[P(R,{color:"green",bold:!0,children:["\u2713"," GAIA is running!"]}),t.data.setupMode!=="developer"&&P(q,{marginTop:1,flexDirection:"column",children:[P(R,{children:["Web:"," ",P(R,{color:"cyan",bold:!0,children:["http://localhost:",t.data.webPort||3e3]})]}),P(R,{children:["API:"," ",P(R,{color:"cyan",bold:!0,children:["http://localhost:",t.data.apiPort||8e3]})]})]}),t.data.setupMode==="developer"&&P(q,{marginTop:1,flexDirection:"column",children:[P(q,{flexDirection:"column",children:[P(R,{children:["Web:"," ",P(R,{color:"cyan",bold:!0,children:["http://localhost:",t.data.webPort||3e3]})]}),P(R,{children:["API:"," ",P(R,{color:"cyan",bold:!0,children:["http://localhost:",t.data.apiPort||8e3]})]})]}),P(q,{marginTop:1,flexDirection:"column",children:[j(R,{color:"gray",children:"Dev servers started in background."}),P(R,{color:"gray",children:["Logs: ",j(R,{color:T,children:"dev-start.log"})," in your repo root."]}),P(R,{color:"gray",children:["Run ",j(R,{color:T,children:"gaia stop"})," to shut down."]})]})]}),j(q,{marginTop:1,children:P(R,{dimColor:!0,children:[j(R,{bold:!0,children:"Enter"})," to exit"]})})]}),t.step==="Stopped"&&t.data.stopped&&P(q,{flexDirection:"column",marginTop:1,paddingX:2,paddingY:1,borderStyle:"round",borderColor:T,children:[P(R,{color:T,bold:!0,children:["\u2713"," All GAIA services stopped."]}),j(q,{marginTop:1,children:P(R,{dimColor:!0,children:[j(R,{bold:!0,children:"Enter"})," to exit"]})})]}),t.error&&P(q,{borderStyle:"single",borderColor:"red",padding:1,marginTop:2,children:[P(R,{color:"red",children:["Error: ",t.error.message]}),j(q,{marginTop:1,children:P(R,{dimColor:!0,children:[j(R,{bold:!0,children:"Enter"})," to exit"]})})]})]})};import{ProgressBar as Lr,Spinner as et}from"@inkjs/ui";import{Box as A,Text as _,useInput as Et}from"ink";import{useEffect as Mr,useState as Fr}from"react";import{jsx as C,jsxs as B}from"react/jsx-runtime";var Pt=({store:e})=>{let[t,o]=Fr(e.currentState);return Mr(()=>{let r=()=>o({...e.currentState});return e.on("change",r),()=>{e.off("change",r)}},[e]),Et((r,n)=>{(n.return||n.escape)&&t.error&&e.submitInput("exit")}),B(ke,{status:t.status,step:t.step,steps:bt,children:[t.step==="Detect Repo"&&B(A,{flexDirection:"column",paddingX:2,borderStyle:"round",borderColor:T,children:[C(_,{bold:!0,children:"Detecting GAIA Repository"}),C(A,{marginTop:1,children:C(et,{label:"Searching for repository..."})}),t.data.repoPath&&C(A,{marginTop:1,children:B(_,{color:"green",children:["Found: ",t.data.repoPath]})})]}),t.step==="Prerequisites"&&t.data.checks&&B(A,{flexDirection:"column",borderStyle:"round",paddingX:1,borderColor:T,children:[C(_,{bold:!0,children:"System Checks"}),B(A,{flexDirection:"column",marginTop:1,children:[C(ne,{label:"Git",status:t.data.checks.git}),C(ne,{label:"Docker",status:t.data.checks.docker}),C(ne,{label:"Mise",status:t.data.checks.mise})]})]}),t.inputRequest?.id==="port_conflicts"&&t.data.portConflicts&&C(Ae,{portResults:t.data.portConflicts,onAccept:()=>e.submitInput("accept"),onAbort:()=>e.submitInput("abort")}),t.inputRequest?.id==="setup_mode"&&C(Qe,{onSelect:r=>e.submitInput(r)}),t.inputRequest?.id==="env_method"&&C(Ye,{onSelect:r=>e.submitInput(r)}),t.inputRequest?.id==="env_infisical"&&C(Ke,{onSubmit:r=>e.submitInput(r)}),t.step==="Environment Setup"&&t.inputRequest?.id==="env_var"&&t.data.currentEnvVar&&C(Ze,{categories:t.data.envCategories||[],currentVar:t.data.currentEnvVar,currentIndex:t.data.envVarIndex||0,totalCount:t.data.envVarTotal||0,onSubmit:r=>e.submitInput(r),onSkip:()=>e.submitInput("")}),t.step==="Environment Setup"&&t.inputRequest?.id==="env_group"&&t.data.currentEnvGroup&&C(Je,{category:t.data.currentEnvGroup,currentIndex:t.data.envGroupIndex||0,totalGroups:t.data.envGroupTotal||0,onSubmit:r=>e.submitInput(r)}),t.step==="Environment Setup"&&t.inputRequest?.id==="env_alternatives"&&t.data.alternativeGroups&&C(ze,{alternatives:t.data.alternativeGroups,onSubmit:(r,n)=>e.submitInput({selectedGroups:r,values:n})}),t.step==="Environment Setup"&&!t.inputRequest&&B(A,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:T,children:[C(_,{bold:!0,children:"Environment Setup"}),C(A,{marginTop:1,children:C(et,{label:t.status||"Configuring environment..."})})]}),t.step==="Project Setup"&&B(A,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"round",borderColor:T,children:[C(A,{marginBottom:1,children:C(_,{bold:!0,color:T,children:"Project Setup"})}),B(A,{flexDirection:"column",gap:1,children:[C(A,{children:t.data.dependencyComplete?B(_,{color:"green",children:["\u2713"," ",t.data.dependencyPhase]}):C(et,{label:t.data.dependencyPhase||"Preparing..."})}),!t.data.dependencyComplete&&t.data.dependencyProgress>0&&C(A,{width:50,children:C(Lr,{value:t.data.dependencyProgress})}),!t.data.dependencyComplete&&t.data.dependencyLogs?.length>0&&C(A,{flexDirection:"column",marginTop:1,marginLeft:1,children:t.data.dependencyLogs.map((r,n)=>C(_,{color:"gray",wrap:"truncate",children:r},n))})]})]}),t.step==="Finished"&&C(Nr,{setupMode:t.data.setupMode,portOverrides:t.data.portOverrides,onConfirm:()=>e.submitInput("exit")}),t.error&&B(A,{flexDirection:"column",borderStyle:"single",borderColor:"red",padding:1,marginTop:2,children:[B(_,{color:"red",children:["Error: ",t.error.message]}),C(A,{marginTop:1,children:B(_,{dimColor:!0,children:[C(_,{bold:!0,children:"Enter"})," to exit"]})})]})]})},Nr=({portOverrides:e,onConfirm:t})=>{Et((n,s)=>{s.return&&t()});let o=e?.[3e3]??3e3,r=e?.[8e3]??8e3;return B(A,{flexDirection:"column",marginTop:2,borderStyle:"round",borderColor:T,padding:1,children:[C(_,{color:T,bold:!0,children:"Setup Complete!"}),B(A,{marginTop:1,children:[C(_,{bold:!0,children:"Run: "}),C(_,{color:"cyan",children:"$ gaia start"})]}),B(A,{marginTop:1,flexDirection:"column",children:[B(_,{children:["Web:"," ",B(_,{color:"cyan",bold:!0,children:["http://localhost:",o]})]}),B(_,{children:["API:"," ",B(_,{color:"cyan",bold:!0,children:["http://localhost:",r]})]})]}),C(A,{marginTop:1,children:C(_,{color:"gray",children:"gaia stop \xB7 gaia status \xB7 gaia setup"})}),C(A,{marginTop:1,children:B(_,{dimColor:!0,children:[C(_,{bold:!0,children:"Enter"})," to exit"]})})]})};import{Spinner as Gr}from"@inkjs/ui";import{Box as O,Text as D,useInput as $r}from"ink";import{useEffect as wt,useState as tt}from"react";import{jsx as w,jsxs as N}from"react/jsx-runtime";var Rt=({store:e})=>{let[t,o]=tt(e.currentState),[r,n]=tt(!1),[s,l]=tt(null);return wt(()=>{let a=()=>o({...e.currentState});return e.on("change",a),()=>{e.off("change",a)}},[e]),wt(()=>{t.step==="Results"&&(n(!1),l(new Date().toLocaleTimeString()))},[t.step]),$r((a,c)=>{(c.return||c.escape)&&t.step==="Results"&&e.submitInput("exit"),a==="r"&&t.step==="Results"&&t.data.refreshable&&!r&&(n(!0),e.submitInput("refresh"))}),N(O,{flexDirection:"column",width:"100%",children:[w(pe,{}),t.step==="Checking"&&w(O,{marginTop:1,children:w(Gr,{label:t.data.services?"Refreshing service health...":"Checking service health..."})}),t.step==="Results"&&t.data.services&&N(O,{flexDirection:"column",children:[N(O,{flexDirection:"column",borderStyle:"round",borderColor:T,paddingX:2,paddingY:1,children:[N(O,{justifyContent:"space-between",children:[w(D,{bold:!0,color:T,children:"GAIA Service Status"}),s&&N(D,{color:"gray",dimColor:!0,children:["checked ",s," \xB7 ",w(D,{bold:!0,children:"r"})," refresh"]})]}),N(O,{marginTop:1,flexDirection:"column",children:[N(O,{children:[w(O,{width:22,children:w(D,{bold:!0,children:"Service"})}),w(O,{width:10,children:w(D,{bold:!0,children:"Status"})}),w(O,{width:10,children:w(D,{bold:!0,children:"Latency"})})]}),w(D,{color:"gray",children:"\u2500".repeat(42)}),[...t.data.services].sort((a,c)=>a.status==="down"&&c.status!=="down"?-1:a.status!=="down"&&c.status==="down"?1:a.name.localeCompare(c.name)).map(a=>N(O,{children:[w(O,{width:22,children:N(D,{children:[a.name," (:",a.port,")"]})}),w(O,{width:10,children:w(D,{color:a.status==="up"?"green":"red",bold:!0,children:a.status==="up"?"\u2713 UP":"\u2717 DOWN"})}),w(O,{width:10,children:w(D,{color:"gray",children:a.latency?`${a.latency}ms`:"--"})})]},a.name))]})]}),t.data.docker&&N(O,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,marginTop:1,children:[w(D,{bold:!0,children:"Docker Containers"}),N(D,{color:"gray",children:["Docker:"," ",t.data.docker.running?w(D,{color:"green",children:"Running"}):w(D,{color:"red",children:"Not running"})]}),t.data.docker.containers?.length>0&&w(O,{marginTop:1,flexDirection:"column",children:t.data.docker.containers.map(a=>N(O,{children:[N(D,{color:a.status==="running"?"green":"red",children:[a.status==="running"?"\u2713":"\u2717"," "]}),w(D,{children:a.name}),a.health&&N(D,{color:"gray",children:[" (",a.health,")"]})]},a.name))})]}),w(O,{marginTop:1,children:N(D,{dimColor:!0,children:[w(D,{bold:!0,children:"Enter"})," exit \xB7 ",w(D,{bold:!0,children:"r"})," refresh"]})})]}),t.error&&w(O,{borderStyle:"single",borderColor:"red",padding:1,marginTop:2,children:N(D,{color:"red",children:["Error: ",t.error.message]})})]})};import{jsx as Y,jsxs as Ie}from"react/jsx-runtime";var jr=["init","setup","status","start","stop"],rt=class extends qr.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}render(){return this.state.error?Ie(_e,{flexDirection:"column",padding:1,children:[Y(le,{color:"red",bold:!0,children:"An unexpected error occurred:"}),Y(le,{color:"red",children:this.state.error.message}),this.state.error.stack&&Y(_e,{marginTop:1,children:Y(le,{color:"gray",dimColor:!0,children:this.state.error.stack})})]}):this.props.children}},Hr=({store:e,command:t})=>{switch(t){case"init":return Y(It,{store:e});case"setup":return Y(Pt,{store:e});case"status":return Y(Rt,{store:e});case"start":case"stop":return Y(Ct,{store:e,command:t});default:return Ie(_e,{flexDirection:"column",padding:1,children:[Ie(le,{color:"red",children:["Unknown command: ",t]}),Ie(_e,{marginTop:1,flexDirection:"column",children:[Y(le,{bold:!0,children:"Available commands:"}),jr.map(o=>Ie(le,{children:[" ",Y(le,{color:"cyan",children:o})]},o))]})]})}},K=({store:e,command:t})=>Y(rt,{children:Y(Hr,{store:e,command:t})});import{EventEmitter as Vr}from"events";var Wr=150,ot=class extends Vr{state={step:"init",status:"",error:null,data:{},inputRequest:null};inputResolver=null;emitTimer=null;emitPending=!1;get currentState(){return this.state}scheduleEmit(){this.emitPending=!0,this.emitTimer||(this.emitTimer=setTimeout(()=>{this.emitTimer=null,this.emitPending&&(this.emitPending=!1,this.emit("change",this.state))},Wr))}emitNow(){this.emitTimer&&(clearTimeout(this.emitTimer),this.emitTimer=null),this.emitPending=!1,this.emit("change",this.state)}setStep(t){this.state.step=t,this.emitNow()}setStatus(t){this.state.status=t,this.scheduleEmit()}setError(t){this.state.error=t,t!==null&&this.inputResolver&&(this.inputResolver(null),this.inputResolver=null,this.state.inputRequest=null),this.emitNow()}updateData(t,o){this.state.data={...this.state.data,[t]:o},this.scheduleEmit()}waitForInput(t,o){return this.state.inputRequest={id:t,meta:o},this.emitNow(),new Promise(r=>{this.inputResolver=r})}submitInput(t){this.inputResolver&&(this.inputResolver(t),this.inputResolver=null,this.state.inputRequest=null,this.emitNow())}},J=()=>new ot;import*as re from"fs";import*as er from"os";import*as ie from"path";import*as ee from"fs";import*as Dt from"os";import*as at from"path";var nt=at.join(Dt.homedir(),".gaia"),it=at.join(nt,"config.json"),st="0.1.10";function Ur(){ee.existsSync(nt)||ee.mkdirSync(nt,{recursive:!0})}function ct(){try{if(!ee.existsSync(it))return null;let e=ee.readFileSync(it,"utf-8");return JSON.parse(e)}catch{return null}}function Oe(e){Ur(),ee.writeFileSync(it,`${JSON.stringify(e,null,2)}
3
+ `)}function Ce(e){let o={...ct()??{version:st,setupComplete:!1,setupMethod:"manual",repoPath:"",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},...e,updatedAt:new Date().toISOString()};Oe(o)}import*as Vt from"path";import*as fe from"node:fs";import*as me from"node:path";import{execa as kt}from"execa";var lt={selfhost:{MONGO_DB:"mongodb://mongo:27017/gaia",REDIS_URL:"redis://redis:6379",POSTGRES_URL:"postgresql://postgres:postgres@postgres:5432/langgraph",CHROMADB_HOST:"chromadb",CHROMADB_PORT:"8000",RABBITMQ_URL:"amqp://guest:guest@rabbitmq:5672/"},developer:{MONGO_DB:"mongodb://localhost:27017/gaia",REDIS_URL:"redis://localhost:6379",POSTGRES_URL:"postgresql://postgres:postgres@localhost:5432/postgres",CHROMADB_HOST:"localhost",CHROMADB_PORT:"8080",RABBITMQ_URL:"amqp://guest:guest@localhost:5672/"}},At={selfhost:{HOST:"http://localhost:8000",FRONTEND_URL:"http://localhost:3000",GAIA_BACKEND_URL:"http://gaia-backend:80",SETUP_MODE:"selfhost"},developer:{HOST:"http://localhost:8000",FRONTEND_URL:"http://localhost:3000",GAIA_BACKEND_URL:"http://host.docker.internal:8000",SETUP_MODE:"developer"}};function ut(e,t){return lt[t][e]??At[t][e]}async function Bt(e){let t=me.join(e,"apps/api/scripts/dump_config_schema.py"),o=me.join(e,"apps/api/app/config/settings_validator.py"),r=me.join(e,"apps/api/app/config/settings.py");if(!fe.existsSync(t))throw new Error("dump_config_schema.py not found in apps/api/scripts");try{try{let{stdout:n}=await kt("python3",[t,o,r],{cwd:e});return JSON.parse(n)}catch{let{stdout:n}=await kt("python",[t,o,r],{cwd:e});return JSON.parse(n)}}catch(n){throw new Error(`Failed to parse settings schema: ${n.message}. Ensure python is installed.`)}}function _t(e){let t=me.join(e,"apps","web",".env.local"),o=fe.existsSync(t)?t:me.join(e,"apps","web",".env");if(!fe.existsSync(o))return[];let r=fe.readFileSync(o,"utf-8"),n=[],s="General";for(let l of r.split(`
4
+ `)){let a=l.trim();if(a.startsWith("#")&&!a.startsWith("#=")){let b=a.replace(/^#+\s*/,"").trim();b&&!b.startsWith("These are")&&(s=b);continue}if(!a||a.startsWith("#"))continue;let c=a.indexOf("=");if(c===-1)continue;let d=a.substring(0,c).trim(),x=a.substring(c+1).trim();n.push({name:d,value:x,category:s})}return n}function Ot(e,t){return{NEXT_PUBLIC_API_BASE_URL:`http://localhost:${t?.[8e3]??8e3}/api/v1/`}}function Lt(e,t,o){let r=o==="selfhost"?new Set(Object.keys(lt.selfhost)):new Set;for(let[n,s]of Object.entries(t)){let l=Number(n),a=Number(s);for(let[c,d]of Object.entries(e)){if(r.has(c))continue;if(d===String(l)){e[c]=String(a);continue}let x=new RegExp(`:${l}(?=[/\\s]|$)`,"g");e[c]=d.replaceAll(x,`:${a}`)}}}function Mt(e,t){return e.map(o=>({...o,variables:o.variables.map(r=>{let n=ut(r.name,t);return{...r,defaultValue:n||r.defaultValue}})}))}function pt(){return Object.keys(lt.selfhost)}function Ft(e){return{...At[e]}}import*as V from"fs";import*as ge from"path";function dt(e){V.existsSync(e)&&V.copyFileSync(e,`${e}.bak`)}function Gt(e,t){let o=ge.join(e,".env");dt(o);let r=["# GAIA Environment Configuration","# Generated by GAIA CLI",`# Created: ${new Date().toISOString()}`,""],n=["MONGO","REDIS","POSTGRES","CHROMADB","RABBITMQ","WORKOS","GOOGLE","OPENAI","INFISICAL","LANGSMITH","DISCORD","SLACK","TELEGRAM","CLOUDINARY","COMPOSIO","FIRECRAWL","LIVEKIT","DEEPGRAM","ELEVENLABS","RESEND","SENTRY","POSTHOG","MEM0","E2B","DODO","NEXT_PUBLIC","GAIA"];function s(a){for(let d of n)if(a===d||a.startsWith(`${d}_`))return d;let c=a.split("_");return c.length===1?"Core":c[0]||"Core"}let l=new Map;for(let[a,c]of Object.entries(t)){let d=s(a);l.has(d)||l.set(d,[]);let b=/[\s#"'\\]/.test(c)||c===""?`"${c.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:c;l.get(d).push(`${a}=${b}`)}for(let[a,c]of l.entries())r.push(`# ${a} Configuration`),r.push(...c),r.push("");V.writeFileSync(o,r.join(`
5
+ `),"utf-8")}function $t(e,t,o){let r=ge.join(e,"apps","web",".env.local");dt(r);let n=_t(e),s=Ot(t,o),l=["# GAIA Web App Environment Configuration","# Generated by GAIA CLI",`# Created: ${new Date().toISOString()}`,""],a=new Map;for(let c of n){a.has(c.category)||a.set(c.category,[]);let d=s[c.name]??c.value;a.get(c.category).push({name:c.name,value:d})}if(n.length===0){l.push("# Core URLs");for(let[c,d]of Object.entries(s))l.push(`${c}=${d}`);l.push("")}else for(let[c,d]of a.entries()){l.push(`# ${c}`);for(let{name:x,value:b}of d)l.push(`${x}=${b}`);l.push("")}V.writeFileSync(r,l.join(`
6
+ `),"utf-8")}var qt={8e3:"API_HOST_PORT",5432:"POSTGRES_HOST_PORT",6379:"REDIS_HOST_PORT",27017:"MONGO_HOST_PORT",5672:"RABBITMQ_HOST_PORT",8080:"CHROMADB_HOST_PORT",8083:"MONGO_EXPRESS_HOST_PORT",3e3:"WEB_HOST_PORT"};function jt(e,t,o){let r=ge.join(e,"infra","docker",".env");dt(r);let n=["# Docker Compose environment overrides","# Generated by GAIA CLI",`# Created: ${new Date().toISOString()}`,""];for(let[s,l]of Object.entries(t)){let a=Number(s),c=qt[a];c&&n.push(`${c}=${l}`)}if(o==="selfhost"){let s=t[8e3]??8e3;n.push(""),n.push("# Web build args"),n.push(`NEXT_PUBLIC_API_BASE_URL=http://localhost:${s}/api/v1/`)}n.push(""),V.writeFileSync(r,n.join(`
7
+ `),"utf-8")}function he(e){let t={};for(let[o,r]of Object.entries(e)){let n=Number(o),s=qt[n];s&&(t[s]=String(r))}return t}function Ht(e){let t=ge.join(e,"infra","docker","docker-compose.yml");if(!V.existsSync(t))return;let o=V.readFileSync(t,"utf-8"),r=[{varName:"API_HOST_PORT",hostPort:8e3,containerPort:80},{varName:"CHROMADB_HOST_PORT",hostPort:8080,containerPort:8e3},{varName:"POSTGRES_HOST_PORT",hostPort:5432,containerPort:5432},{varName:"REDIS_HOST_PORT",hostPort:6379,containerPort:6379},{varName:"MONGO_HOST_PORT",hostPort:27017,containerPort:27017},{varName:"RABBITMQ_HOST_PORT",hostPort:5672,containerPort:5672},{varName:"MONGO_EXPRESS_HOST_PORT",hostPort:8083,containerPort:8081},{varName:"WEB_HOST_PORT",hostPort:3e3,containerPort:3e3}],n=!1;for(let{varName:s,hostPort:l,containerPort:a}of r){let c=`"${l}:${a}"`,d=`"\${${s}:-${l}}:${a}"`;o.includes(c)&&(o=o.replaceAll(c,d),n=!0)}n&&V.writeFileSync(t,o,"utf-8")}var Nt={API_HOST_PORT:8e3,POSTGRES_HOST_PORT:5432,REDIS_HOST_PORT:6379,MONGO_HOST_PORT:27017,RABBITMQ_HOST_PORT:5672,CHROMADB_HOST_PORT:8080,MONGO_EXPRESS_HOST_PORT:8083,WEB_HOST_PORT:3e3};function Se(e){let t=ge.join(e,"infra","docker",".env"),o={};if(!V.existsSync(t))return o;let r=V.readFileSync(t,"utf-8");for(let n of r.split(`
8
+ `)){let s=n.trim();if(s&&!s.startsWith("#")){let[l,...a]=s.split("=");if(l&&Nt[l]){let c=a.join("=").trim().replace(/^["']|["']$/g,""),d=Number(c);!Number.isNaN(d)&&d>0&&(o[Nt[l]]=d)}}}return o}var Yr=e=>new Promise(t=>setTimeout(t,e));async function Le(e){e.setStep("Setup Mode"),e.setStatus("Choose how to run GAIA...");let t=await e.waitForInput("setup_mode");return e.updateData("setupMode",t),t}async function Me(e,t,o,r){e.setStep("Environment Setup"),e.setStatus("Configuring environment..."),e.updateData("setupMode",o),e.setStatus("Configuring environment variables...");let n=await e.waitForInput("env_method");e.updateData("envMethod",n);let s={};s.ENV="development";let l=pt();for(let c of l){let d=ut(c,o);d&&(s[c]=d)}let a=Ft(o);for(let[c,d]of Object.entries(a))s[c]=d;if(n==="infisical")await Kr(e,s),e.setStatus("Infisical credentials saved. Ensure your Infisical project contains all required variables.");else try{await Jr(e,t,s,o)}catch(c){e.setError(c);return}r&&Lt(s,r,o);try{await zr(e,t,s,o,r)}catch(c){e.setError(c);return}await Yr(1e3)}async function Kr(e,t){e.setStatus("Configuring Infisical...");let o=await e.waitForInput("env_infisical");t.INFISICAL_TOKEN=o.INFISICAL_TOKEN,t.INFISICAL_PROJECT_ID=o.INFISICAL_PROJECT_ID,t.INFISICAL_MACHINE_IDENTITY_CLIENT_ID=o.INFISICAL_MACHINE_IDENTITY_CLIENT_ID,t.INFISICAL_MACHINE_IDENTITY_CLIENT_SECRET=o.INFISICAL_MACHINE_IDENTITY_CLIENT_SECRET}async function Jr(e,t,o,r){e.setStatus("Parsing environment variables...");let n;try{n=await Bt(t),n=Mt(n,r)}catch(m){throw r==="selfhost"?new Error(`Manual environment setup requires Python to parse config schema.
9
9
  For self-host mode, we recommend using Infisical for secret management.
10
10
  Alternatively, install Python 3.11+ and try again.
11
11
 
12
- Original error: ${l.message}`):new Error(`Failed to parse settings: ${l.message}`)}let a=new Set,c=[],d=new Set;for(let l of n)if(l.alternativeGroup&&!d.has(l.name)){let S=n.find(x=>x.name===l.alternativeGroup);S&&(c.push([l,S]),a.add(l.name),a.add(S.name),d.add(l.name),d.add(S.name))}let m=n.filter(l=>l.variables.length===1&&!a.has(l.name)),f=n.filter(l=>l.variables.length>1&&!a.has(l.name));for(let l of c){e.updateData("alternativeGroups",l),e.setStatus("Choose an AI provider...");let S=await e.waitForInput("env_alternatives");for(let[x,C]of Object.entries(S.values))C&&(o[x]=C)}let y=Ze(),v=[...m.flatMap(l=>l.variables).filter(l=>!y.includes(l.name))].sort((l,S)=>l.required&&!S.required?-1:!l.required&&S.required?1:0);e.updateData("envVarTotal",v.length);for(let l=0;l<v.length;l++){let S=v[l];if(!S)continue;e.updateData("currentEnvVar",S),e.updateData("envVarIndex",l),e.setStatus(`Configuring ${S.name}...`);let x=await e.waitForInput("env_var",{varName:S.name});(x||S.required||S.defaultValue)&&(o[S.name]=x||S.defaultValue||"")}let b=[...f].filter(l=>!l.variables.every(S=>y.includes(S.name))).sort((l,S)=>{let x=l.variables.some(I=>I.required),C=S.variables.some(I=>I.required);return x&&!C?-1:!x&&C?1:0});e.updateData("envGroupTotal",b.length);for(let l=0;l<b.length;l++){let S=b[l];if(!S)continue;e.updateData("currentEnvGroup",S),e.updateData("envGroupIndex",l),e.setStatus(`Configuring ${S.name}...`);let x=await e.waitForInput("env_group",{groupName:S.name});for(let[C,I]of Object.entries(x)){let w=S.variables.find(Y=>Y.name===C);(I||w?.required||w?.defaultValue)&&(o[C]=I||w?.defaultValue||"")}}}async function Fr(e,t,o,r,n){e.setStatus("Writing API environment file...");try{let c=_t.join(t,"apps","api");Rt(c,o),e.setStatus("API environment variables configured!")}catch(c){throw new Error(`Failed to write API .env file: ${c.message}`)}e.setStatus("Writing web environment file...");try{Dt(t,r,n),e.setStatus("Web environment variables configured!")}catch(c){throw new Error(`Failed to write web .env file: ${c.message}`)}let a=n&&Object.keys(n).length>0;if(a||r==="selfhost"){e.setStatus("Writing Docker Compose environment...");try{a&&At(t),Bt(t,n??{},r),e.setStatus("Docker Compose environment configured!")}catch(c){throw new Error(`Failed to write Docker Compose .env: ${c.message}`)}}}import{execa as Lr}from"execa";import Ce from"fs";import Nr from"simple-git";async function Ot(e,t,o){if(Ce.existsSync(e)){let r=`${e}/.git`;if(!Ce.existsSync(r))throw new Error(`Directory ${e} exists but is not a git repository`);await Nr().cwd(e).pull(),o(100,"Already exists, pulled latest")}else try{let r=Lr("git",["clone","--progress",t,e]);r.stderr?.on("data",n=>{let a=n.toString();a.includes("Counting objects")?o(5,"Counting objects"):a.includes("Compressing objects")&&o(10,"Compressing objects");let c=a.match(/Receiving objects:\s+(\d+)%\s+\((\d+)\/(\d+)\)/);if(c?.[1]){let m=Math.min(100,parseInt(c[1],10)),f=c[2],y=c[3];o(10+Math.floor(m*.5),`Receiving objects: ${f}/${y}`)}let d=a.match(/Resolving deltas:\s+(\d+)%\s+\((\d+)\/(\d+)\)/);if(d?.[1]){let m=Math.min(100,parseInt(d[1],10)),f=d[2],y=d[3];o(60+Math.floor(m*.4),`Resolving deltas: ${f}/${y}`)}}),await r,o(100,"Clone complete")}catch(r){throw Ce.existsSync(e)&&Ce.rmSync(e,{recursive:!0,force:!0}),r}}import{execa as J}from"execa";var U={git:"https://git-scm.com/downloads",docker:"https://docs.docker.com/get-docker/",mise:"https://mise.jdx.dev/getting-started.html"},qr={8e3:"API Server",5432:"PostgreSQL",6379:"Redis",27017:"MongoDB",5672:"RabbitMQ",3e3:"Web Frontend",8080:"ChromaDB",8083:"Mongo Express"};async function Ie(){try{return await J("git",["--version"]),"success"}catch{return"error"}}async function Ee(){let e=!1,t=!1,o;try{await J("docker",["--version"]),e=!0}catch{return{name:"Docker",installUrl:U.docker,installed:!1,working:!1,errorMessage:"Docker is not installed"}}try{await J("docker",["info"],{timeout:5e3}),t=!0}catch{o="Docker is installed but the daemon is not running. Please start Docker Desktop or the Docker daemon."}return{name:"Docker",installUrl:U.docker,installed:e,working:t,errorMessage:o}}async function we(){try{return await J("mise",["--version"]),"success"}catch{return"missing"}}async function Pe(){if((await import("node:os")).platform()==="win32")try{return await J("powershell",["-Command","irm https://mise.jdx.dev/install.ps1 | iex"]),!0}catch{return!1}try{return await J("sh",["-c","curl https://mise.jdx.dev/install.sh | sh"]),!0}catch{return!1}}async function Re(e){let t=await import("node:net"),o=[],r=n=>new Promise(a=>{let c=t.createServer();c.once("error",()=>a(!1)),c.once("listening",()=>{c.close(()=>a(!0))}),c.listen(n)});for(let n of e){let a=qr[n]||`Port ${n}`;if(await r(n))o.push({port:n,service:a,available:!0});else{let d=await $r(n),m=await jr(n+1,n+100,r);o.push({port:n,service:a,available:!1,usedBy:d,alternative:m||void 0})}}return o}async function $r(e){if((await import("node:os")).platform()==="win32"){try{let{stdout:r}=await J("netstat",["-ano","-p","TCP"]),n=r.trim().split(`
13
- `);for(let a of n)if(a.includes(`:${e}`)&&a.includes("LISTENING")){let c=a.trim().split(/\s+/),d=c[c.length-1];if(d)try{let{stdout:m}=await J("tasklist",["/FI",`PID eq ${d}`,"/FO","CSV","/NH"]);return m.trim().split(",")[0]?.replace(/"/g,"")||`PID ${d}`}catch{return`PID ${d}`}}}catch{}return}try{let{stdout:r}=await J("lsof",["-i",`:${e}`,"-sTCP:LISTEN","-P","-n"]),n=r.trim().split(`
14
- `);if(n.length>1)return n[1]?.split(/\s+/)?.[0]||void 0}catch{}}async function jr(e,t,o){for(let r=e;r<=t;r++)if(await o(r))return r;return null}import*as j from"fs";import*as H from"path";var Hr=e=>new Promise(t=>setTimeout(t,e)),Wr="dev-start.log";function Ft(e){let t=H.join(e,".env");return j.existsSync(t)?["--env-file",".env"]:[]}async function Lt(e,t,o,r){if(t==="selfhost"){o?.("Starting all services in Docker (selfhost mode)...");let n=H.join(e,"infra/docker"),a=Ft(n),c=r&&Object.keys(r).length>0?le(r):void 0;await N("docker",["compose","-f","docker-compose.selfhost.yml",...a,"up","-d","--build","--remove-orphans"],n,void 0,void 0,c),o?.("All services started in Docker!")}else{o?.("Starting development servers...");let{spawn:n}=await import("child_process"),a=H.join(e,Wr),c=j.openSync(a,"a"),d;try{d=n("mise",["dev"],{cwd:e,stdio:["ignore",c,c],detached:!0,shell:!0}),d.unref()}finally{j.closeSync(c)}if(await Hr(1500),d.pid!=null)try{process.kill(d.pid,0)}catch{throw new Error(`Development servers crashed on startup. Check logs at: ${a}`)}o?.(`Development servers started! Logs: ${a}`)}}async function Nt(e,t,o){let r=H.join(e,"infra/docker"),n=await tt(e);t?.("Stopping Docker services...");try{let a=Ft(r),c=n==="selfhost"?["compose","-f","docker-compose.selfhost.yml",...a,"down"]:["compose",...a,"down"];await N("docker",c,r)}catch{}if(n!=="selfhost"){t?.("Stopping local processes...");try{let a=o?.[8e3]??8e3,c=o?.[3e3]??3e3;if(process.platform==="win32")for(let d of[a,c])try{await N("powershell",["-Command",`Get-NetTCPConnection -LocalPort ${d} -ErrorAction SilentlyContinue | ForEach-Object { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue }`],e)}catch{}else for(let d of[a,c])try{await N("sh",["-c",`lsof -ti :${d} -sTCP:LISTEN | xargs kill 2>/dev/null || true`],e)}catch{}}catch{}}t?.("All services stopped.")}async function tt(e){let t=H.join(e,"apps","api",".env");if(!j.existsSync(t))return null;let o=j.readFileSync(t,"utf-8"),r=o.match(/^SETUP_MODE=(.+)$/m);if(r?.[1]){let n=r[1].trim().replace(/^["']|["']$/g,"");if(n==="selfhost"||n==="developer")return n}return o.includes("mongodb://mongo:")?"selfhost":(o.includes("mongodb://localhost:"),"developer")}async function N(e,t,o,r,n,a){let{spawn:c}=await import("child_process");return new Promise((d,m)=>{let f=c(e,t,{cwd:o,stdio:["ignore","pipe","pipe"],shell:!0,env:a?{...process.env,...a}:void 0}),y="",g=0;f.stdout?.on("data",v=>{let b=v.toString();y+=b,n?.(b),g=Math.min(g+5,95),r?.(g)}),f.stderr?.on("data",v=>{let b=v.toString();y+=b,n?.(b),g=Math.min(g+5,95),r?.(g)}),f.on("close",v=>{v===0?(r?.(100),d()):m(new Error(`Command failed with code ${v}: ${y.slice(-500)}`))}),f.on("error",v=>{m(v)})})}function X(e){let t=e||process.cwd();for(;t!==H.dirname(t);){if(j.existsSync(H.join(t,"apps/api/app/config/settings_validator.py")))return t;t=H.dirname(t)}let o=Ye();return o?.repoPath&&j.existsSync(H.join(o.repoPath,"apps/api/app/config/settings_validator.py"))?o.repoPath:null}var Vr=process.env.GAIA_CLI_DEV==="true",Q=e=>new Promise(t=>setTimeout(t,e));async function qt(e){e.setStep("Welcome"),e.setStatus("Waiting for user input..."),await e.waitForInput("welcome");let t=l=>{let S=e.currentState.data.dependencyLogs||[],x=l.split(`
15
- `).filter(I=>I.trim()!==""),C=[...S,...x].slice(-20);e.updateData("dependencyLogs",C)};e.setStep("Prerequisites"),e.setStatus("Checking system requirements..."),e.updateData("checks",{git:"pending",docker:"pending",mise:"pending"}),await Q(800),e.setStatus("Checking Git...");let o=await Ie();e.updateData("checks",{...e.currentState.data.checks,git:o}),e.setStatus("Checking Docker...");let r=await Ee(),n=r.working?"success":"error";e.updateData("checks",{...e.currentState.data.checks,docker:n}),r.working||e.updateData("dockerError",r.errorMessage),e.setStatus("Checking Mise...");let a=await we();e.updateData("checks",{...e.currentState.data.checks,mise:a}),a==="missing"&&(e.setStatus("Installing Mise..."),a=await Pe()?"success":"error",e.updateData("checks",{...e.currentState.data.checks,mise:a}));let c=[];if(o==="error"&&c.push({name:"Git"}),n==="error"&&c.push({name:"Docker",message:r.errorMessage}),c.length>0){let l=[];l.push("Prerequisites failed:");for(let S of c)l.push(` \u2022 ${S.name}: ${S.message||"Not installed or not working"}`);l.push(`
16
- Installation guides:`),o==="error"&&l.push(` \u2022 Git: ${U.git}`),n==="error"&&(r.installed?l.push(" \u2022 Docker: Start Docker Desktop or run 'sudo systemctl start docker'"):l.push(` \u2022 Docker: ${U.docker}`)),e.setError(new Error(l.join(`
17
- `)));return}e.setStatus("Checking Ports...");let m=await Re([8e3,5432,6379,27017,5672,3e3,8080,8083]),f={},y=m.filter(l=>!l.available);if(y.length>0){let l=y.filter(x=>!x.alternative);if(l.length>0){e.setError(new Error(`Cannot find free alternative ports for: ${l.map(x=>`${x.port} (${x.service})`).join(", ")}. Free these ports and try again.`));return}if(e.updateData("portConflicts",m),await e.waitForInput("port_conflicts")==="abort"){e.setError(new Error("Port conflicts not resolved. Please free the ports and try again."));return}for(let x of m)!x.available&&x.alternative&&(f[x.port]=x.alternative)}e.updateData("portOverrides",f),e.setStatus("Prerequisites check complete!"),await Q(1e3);let g="";if(Vr){if(g=X()||"",!g){e.setError(new Error("DEV_MODE: Could not find workspace root. Run from within the gaia repo."));return}e.setStep("Repository Setup"),e.setStatus("[DEV MODE] Using current workspace..."),await Q(500),e.setStatus("Repository ready!")}else{e.setStep("Repository Setup");let l=re.join(Gt.homedir(),"gaia"),S=!0;for(g=l;;){if(g=await e.waitForInput("repo_path",{default:l}),re.isAbsolute(g)||(g=re.resolve(g)),z.existsSync(g)){if(!z.statSync(g).isDirectory()){e.setError(new Error(`Path ${g} exists and is not a directory.`)),await Q(2e3),e.setError(null);continue}if(z.existsSync(re.join(g,"apps/api/app/config/settings_validator.py"))){e.updateData("existingRepoPath",g);let w=await e.waitForInput("existing_repo");if(w==="use_existing"){S=!1;break}else if(w==="delete_reclone"){e.setStatus("Removing existing installation..."),z.rmSync(g,{recursive:!0,force:!0});break}else{if(w==="different_path")continue;e.setError(new Error("Setup cancelled by user."));return}}if(z.readdirSync(g).length>0){e.setError(new Error(`Directory ${g} is not empty and is not a GAIA installation. Please choose another path.`)),await Q(2e3),e.setError(null);continue}}break}if(S){e.setStep("Repository Setup"),e.setStatus("Preparing repository..."),e.updateData("repoProgress",0),e.updateData("repoPhase","");try{await Ot(g,"https://github.com/theexperiencecompany/gaia.git",(x,C)=>{e.updateData("repoProgress",x),C?(e.updateData("repoPhase",C),e.setStatus(`${C}...`)):e.setStatus(`Cloning repository to ${g}... ${x}%`)}),e.setStatus("Repository ready!")}catch(x){e.setError(x);return}}else e.setStatus("Using existing repository!")}if(await Q(1e3),await be(e,g,f),e.currentState.error)return;if(e.currentState.data.setupMode==="selfhost"){let l=e.currentState.data.envMethod||"manual";Te({version:"0.1.8",setupComplete:!0,setupMethod:l,repoPath:g,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}),e.setStep("Installing CLI"),e.setStatus("Installing gaia CLI globally...");try{await N("npm",["install","-g","@heygaia/cli"],g),e.setStatus("CLI installed globally!")}catch{}await Q(500),e.setStep("Finished"),e.setStatus("Setup complete! Run 'gaia start' to build and start all services in Docker."),await e.waitForInput("exit");return}if(a==="error"){e.setError(new Error(`Developer mode requires Mise but it failed to install.
18
- \u2022 Mise: ${U.mise}`));return}e.setStep("Install Tools"),e.setStatus("Installing toolchain..."),e.updateData("dependencyPhase","Initializing mise..."),e.updateData("dependencyProgress",0),e.updateData("dependencyLogs",[]);try{e.updateData("dependencyPhase","Trusting mise configuration..."),await N("mise",["trust"],g,void 0,t),e.updateData("dependencyProgress",50),e.updateData("dependencyPhase","Installing tools (node, python, uv, nx)..."),await N("mise",["install"],g,l=>{e.updateData("dependencyProgress",50+l*.5)},t),e.updateData("dependencyProgress",100),e.updateData("toolComplete",!0)}catch(l){e.setError(new Error(`Failed to install tools: ${l.message}`));return}await Q(1e3),e.setStep("Project Setup"),e.updateData("dependencyPhase","Setting up project..."),e.updateData("dependencyProgress",0),e.updateData("dependencyComplete",!1),e.updateData("repoPath",g),e.updateData("dependencyLogs",[]);try{e.updateData("dependencyProgress",0),e.updateData("dependencyPhase","Running mise setup (all dependencies)...");let l=Object.keys(f).length>0?le(f):void 0;await N("mise",["setup"],g,S=>{e.updateData("dependencyProgress",S)},t,l),e.updateData("dependencyProgress",100),e.updateData("dependencyPhase","Setup complete!"),e.updateData("dependencyComplete",!0)}catch(l){e.setError(new Error(`Failed to setup project: ${l.message}`));return}await Q(1e3);let b=e.currentState.data.envMethod||"manual";Te({version:"0.1.8",setupComplete:!0,setupMethod:b,repoPath:g,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}),e.setStep("Installing CLI"),e.setStatus("Installing gaia CLI globally...");try{await N("npm",["install","-g","@heygaia/cli"],g),e.setStatus("CLI installed globally!")}catch{}await Q(500),e.setStep("Finished"),e.setStatus("Setup complete!"),await e.waitForInput("exit")}async function $t(){let e=V(),{unmount:t}=Ur(Xr.createElement(W,{store:e,command:"init"}));try{await qt(e)}catch(o){e.setError(o)}e.currentState.error&&await e.waitForInput("exit"),t(),process.exit(e.currentState.error?1:0)}import{render as Qr}from"ink";import Yr from"react";var De=e=>new Promise(t=>setTimeout(t,e));async function jt(e){e.setStep("Detect Repo"),e.setStatus("Looking for GAIA repository...");let t=X();if(!t){e.setError(new Error("Could not find GAIA repository. Run this command from within a cloned gaia repo, or use 'gaia init' to set up from scratch."));return}e.updateData("repoPath",t),e.setStatus(`Found repository at ${t}`),await De(1e3),e.setStep("Prerequisites"),e.setStatus("Checking system requirements..."),e.updateData("checks",{git:"pending",docker:"pending",mise:"pending"}),await De(500);let o=await Ie();e.updateData("checks",{...e.currentState.data.checks,git:o});let r=await Ee(),n=r.working?"success":"error";e.updateData("checks",{...e.currentState.data.checks,docker:n}),r.working||e.updateData("dockerError",r.errorMessage);let a=await we();e.updateData("checks",{...e.currentState.data.checks,mise:a}),a==="missing"&&(e.setStatus("Installing Mise..."),a=await Pe()?"success":"error",e.updateData("checks",{...e.currentState.data.checks,mise:a}));let c=[];if(o==="error"&&c.push({name:"Git"}),n==="error"&&c.push({name:"Docker",message:r.errorMessage}),c.length>0){let l=[];l.push("Prerequisites failed:");for(let S of c)l.push(` \u2022 ${S.name}: ${S.message||"Not installed or not working"}`);l.push(`
19
- Installation guides:`),o==="error"&&l.push(` \u2022 Git: ${U.git}`),n==="error"&&(r.installed?l.push(" \u2022 Docker: Start Docker Desktop or run 'sudo systemctl start docker'"):l.push(` \u2022 Docker: ${U.docker}`)),e.setError(new Error(l.join(`
20
- `)));return}e.setStatus("Checking Ports...");let m=await Re([8e3,5432,6379,27017,5672,3e3,8080,8083]),f={},y=m.filter(l=>!l.available);if(y.length>0){let l=y.filter(x=>!x.alternative);if(l.length>0){e.setError(new Error(`Cannot find free alternative ports for: ${l.map(x=>`${x.port} (${x.service})`).join(", ")}. Free these ports and try again.`));return}if(e.updateData("portConflicts",m),await e.waitForInput("port_conflicts")==="abort"){e.setError(new Error("Port conflicts not resolved. Please free the ports and try again."));return}for(let x of m)!x.available&&x.alternative&&(f[x.port]=x.alternative)}if(e.updateData("portOverrides",f),e.setStatus("Prerequisites check complete!"),await De(1e3),await be(e,t,f),e.currentState.error)return;if(e.currentState.data.setupMode==="selfhost"){let l=e.currentState.data.envMethod||"manual";Ke({setupComplete:!0,setupMethod:l,repoPath:t}),e.setStep("Finished"),e.setStatus("Setup complete! Run 'gaia start' to build and start all services in Docker."),await e.waitForInput("exit");return}if(a==="error"){e.setError(new Error(`Developer mode requires Mise but it failed to install.
21
- \u2022 Mise: ${U.mise}`));return}e.setStep("Project Setup"),e.updateData("dependencyPhase","Setting up project..."),e.updateData("dependencyProgress",0),e.updateData("dependencyComplete",!1),e.updateData("dependencyLogs",[]);let v=l=>{let S=e.currentState.data.dependencyLogs||[],x=l.split(`
22
- `).filter(I=>I.trim()!==""),C=[...S,...x].slice(-20);e.updateData("dependencyLogs",C)};try{e.updateData("dependencyPhase","Trusting mise configuration..."),await N("mise",["trust"],t,void 0,v),e.updateData("dependencyProgress",20),e.updateData("dependencyPhase","Installing tools..."),await N("mise",["install"],t,S=>{e.updateData("dependencyProgress",20+S*.3)},v),e.updateData("dependencyPhase","Running mise setup...");let l=Object.keys(f).length>0?le(f):void 0;await N("mise",["setup"],t,S=>{e.updateData("dependencyProgress",50+S*.5)},v,l),e.updateData("dependencyProgress",100),e.updateData("dependencyPhase","Setup complete!"),e.updateData("dependencyComplete",!0)}catch(l){e.setError(new Error(`Failed to setup project: ${l.message}`));return}await De(1e3);let b=e.currentState.data.envMethod||"manual";Ke({setupComplete:!0,setupMethod:b,repoPath:t}),e.setStep("Finished"),e.setStatus("Setup complete!"),await e.waitForInput("exit")}async function Ht(){let e=V(),{unmount:t}=Qr(Yr.createElement(W,{store:e,command:"setup"}));try{await jt(e)}catch(o){e.setError(o)}e.currentState.error&&await e.waitForInput("exit"),t(),process.exit(e.currentState.error?1:0)}import{render as Kr}from"ink";import Jr from"react";async function Wt(e){e.setStep("Starting"),e.setStatus("Locating GAIA repository...");let t=X();if(!t){e.setError(new Error("Could not find GAIA repository. Run from within a cloned gaia repo."));return}e.updateData("repoPath",t);let o=await tt(t);if(!o){e.setError(new Error("No .env file found. Run 'gaia setup' first to configure the environment."));return}let r=ue(t),n=r[3e3]??3e3,a=r[8e3]??8e3;e.updateData("setupMode",o),e.updateData("webPort",n),e.updateData("apiPort",a),e.setStatus(`Starting GAIA in ${o} mode...`);try{await Lt(t,o,c=>{e.setStatus(c)},r),e.setStep("Running"),e.setStatus("GAIA is running!"),e.updateData("started",!0)}catch(c){e.setError(new Error(`Failed to start services: ${c.message}`));return}await e.waitForInput("exit")}async function Vt(){let e=V(),{unmount:t}=Kr(Jr.createElement(W,{store:e,command:"start"}));await new Promise(o=>setTimeout(o,50));try{await Wt(e)}catch(o){e.setError(o)}e.currentState.error&&await e.waitForInput("exit"),t(),process.exit(e.currentState.error?1:0)}import{render as ro}from"ink";import oo from"react";import{execa as ot}from"execa";var rt=["gaia-backend","gaia-web","chromadb","postgres","redis","mongo","rabbitmq","arq_worker"];async function Ut(){try{let{stdout:e}=await ot("docker",["inspect","--format","{{.Name}}|{{.State.Status}}|{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}",...rt]),t=new Map;for(let o of e.trim().split(`
23
- `)){if(!o)continue;let[r,n,a]=o.split("|"),c=r?.replace(/^\//,"")??"";t.set(c,{name:c,status:n==="running"?"running":"stopped",health:a!=="none"?a:void 0})}return rt.map(o=>t.get(o)??{name:o,status:"not_found"})}catch{let e=rt.map(async t=>{try{let{stdout:o}=await ot("docker",["inspect","--format","{{.State.Status}}|{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}",t]),[r,n]=o.trim().split("|");return{name:t,status:r==="running"?"running":"stopped",health:n!=="none"?n:void 0}}catch{return{name:t,status:"not_found"}}});return Promise.all(e)}}async function Xt(){try{return await ot("docker",["info"]),!0}catch{return!1}}var zr=[{name:"API",port:8e3,type:"http",path:"/health"},{name:"Web",port:3e3,type:"http",path:"/"},{name:"PostgreSQL",port:5432,type:"tcp"},{name:"Redis",port:6379,type:"tcp"},{name:"MongoDB",port:27017,type:"tcp"},{name:"RabbitMQ",port:5672,type:"tcp"},{name:"ChromaDB",port:8080,type:"tcp"}];async function Qt(e){let o=zr.map(r=>({...r,port:e?.[r.port]??r.port})).map(r=>r.type==="http"?Zr(r.name,r.port,r.path):eo(r.name,r.port));return Promise.all(o)}async function Zr(e,t,o){let r=Date.now();try{let n=await fetch(`http://localhost:${t}${o}`,{signal:AbortSignal.timeout(5e3)}),a=Date.now()-r;return{name:e,port:t,status:"up",latency:a,details:n.ok?`HTTP ${n.status}`:`HTTP ${n.status} (error)`}}catch{return{name:e,port:t,status:"down",details:"Connection failed"}}}async function eo(e,t){let o=await import("node:net"),r=Date.now();return new Promise(n=>{let a=new o.Socket;a.setTimeout(3e3),a.on("connect",()=>{let c=Date.now()-r;a.destroy(),n({name:e,port:t,status:"up",latency:c})}),a.on("timeout",()=>{a.destroy(),n({name:e,port:t,status:"down"})}),a.on("error",()=>{a.destroy(),n({name:e,port:t,status:"down"})}),a.connect(t,"localhost")})}async function Yt(){return await Xt()?{running:!0,containers:await Ut()}:{running:!1,containers:[]}}async function to(e){e.setStep("Checking"),e.setStatus("Checking service health..."),e.updateData("refreshable",!1);let t=X(),o=t?ue(t):void 0,[r,n]=await Promise.all([Qt(o),Yt()]);e.updateData("services",r),e.updateData("docker",n);let a=r.filter(d=>d.status==="up").length,c=r.length;e.setStep("Results"),e.setStatus(`${a}/${c} services running`),e.updateData("refreshable",!0)}async function Kt(e){for(;await to(e),await e.waitForInput("exit_or_refresh")==="refresh";);}async function Jt(){let e=V(),{unmount:t}=ro(oo.createElement(W,{store:e,command:"status"}));await new Promise(o=>setTimeout(o,50));try{await Kt(e)}catch(o){e.setError(o)}e.currentState.error&&await e.waitForInput("exit"),t(),process.exit(e.currentState.error?1:0)}import{render as no}from"ink";import io from"react";async function zt(e){e.setStep("Stopping"),e.setStatus("Locating GAIA repository...");let t=X();if(!t){e.setError(new Error("Could not find GAIA repository. Run from within a cloned gaia repo."));return}e.updateData("repoPath",t);let o=ue(t);try{await Nt(t,r=>{e.setStatus(r)},o),e.setStep("Stopped"),e.setStatus("All services stopped."),e.updateData("stopped",!0)}catch(r){e.setError(new Error(`Failed to stop services: ${r.message}`));return}await e.waitForInput("exit")}async function Zt(){let e=V(),{unmount:t}=no(io.createElement(W,{store:e,command:"stop"}));await new Promise(o=>setTimeout(o,50));try{await zt(e)}catch(o){e.setError(o)}e.currentState.error&&await e.waitForInput("exit"),t(),process.exit(e.currentState.error?1:0)}var Z=new ao;Z.name("gaia").description("CLI tool for setting up and managing GAIA").version("0.1.0");Z.command("init").description("Full setup from scratch (clone, configure, start)").action(async()=>{await $t()});Z.command("setup").description("Configure an existing GAIA repository").action(async()=>{await Ht()});Z.command("status").description("Check health of all GAIA services").action(async()=>{await Jt()});Z.command("start").description("Start GAIA services").action(async()=>{await Vt()});Z.command("stop").description("Stop all GAIA services").action(async()=>{await Zt()});process.argv.slice(2).length||(Z.outputHelp(),process.exit(0));Z.parse();
12
+ Original error: ${m.message}`):new Error(`Failed to parse settings: ${m.message}`)}let s=new Set,l=[],a=new Set;for(let m of n)if(m.alternativeGroup&&!a.has(m.name)){let p=n.find(h=>h.name===m.alternativeGroup);p&&(l.push([m,p]),s.add(m.name),s.add(p.name),a.add(m.name),a.add(p.name))}let c=n.filter(m=>m.variables.length===1&&!s.has(m.name)),d=n.filter(m=>m.variables.length>1&&!s.has(m.name));for(let m of l){e.updateData("alternativeGroups",m),e.setStatus("Choose an AI provider...");let p=await e.waitForInput("env_alternatives");for(let[h,y]of Object.entries(p.values))y&&(o[h]=y)}let x=pt(),v=[...c.flatMap(m=>m.variables).filter(m=>!x.includes(m.name))].sort((m,p)=>m.required&&!p.required?-1:!m.required&&p.required?1:0);e.updateData("envVarTotal",v.length);for(let m=0;m<v.length;m++){let p=v[m];if(!p)continue;e.updateData("currentEnvVar",p),e.updateData("envVarIndex",m),e.setStatus(`Configuring ${p.name}...`);let h=await e.waitForInput("env_var",{varName:p.name});(h||p.required||p.defaultValue)&&(o[p.name]=h||p.defaultValue||"")}let S=[...d].filter(m=>!m.variables.every(p=>x.includes(p.name))).sort((m,p)=>{let h=m.variables.some(I=>I.required),y=p.variables.some(I=>I.required);return h&&!y?-1:!h&&y?1:0});e.updateData("envGroupTotal",S.length);for(let m=0;m<S.length;m++){let p=S[m];if(!p)continue;e.updateData("currentEnvGroup",p),e.updateData("envGroupIndex",m),e.setStatus(`Configuring ${p.name}...`);let h=await e.waitForInput("env_group",{groupName:p.name});for(let[y,I]of Object.entries(h)){let E=p.variables.find(M=>M.name===y);(I||E?.required||E?.defaultValue)&&(o[y]=I||E?.defaultValue||"")}}}async function zr(e,t,o,r,n){e.setStatus("Writing API environment file...");try{let l=Vt.join(t,"apps","api");Gt(l,o),e.setStatus("API environment variables configured!")}catch(l){throw new Error(`Failed to write API .env file: ${l.message}`)}e.setStatus("Writing web environment file...");try{$t(t,r,n),e.setStatus("Web environment variables configured!")}catch(l){throw new Error(`Failed to write web .env file: ${l.message}`)}let s=n&&Object.keys(n).length>0;if(s||r==="selfhost"){e.setStatus("Writing Docker Compose environment...");try{s&&Ht(t),jt(t,n??{},r),e.setStatus("Docker Compose environment configured!")}catch(l){throw new Error(`Failed to write Docker Compose .env: ${l.message}`)}}}import{execa as Zr}from"execa";import Fe from"fs";import eo from"simple-git";async function Wt(e,t,o,r){if(Fe.existsSync(e)){let n=`${e}/.git`;if(!Fe.existsSync(n))throw new Error(`Directory ${e} exists but is not a git repository`);await eo().cwd(e).pull(),o(100,"Already exists, pulled latest")}else try{let n=["clone","--progress"];r&&n.push("--branch",r),n.push(t,e);let s=Zr("git",n);s.stderr?.on("data",l=>{let a=l.toString();a.includes("Counting objects")?o(5,"Counting objects"):a.includes("Compressing objects")&&o(10,"Compressing objects");let c=a.match(/Receiving objects:\s+(\d+)%\s+\((\d+)\/(\d+)\)/);if(c?.[1]){let x=Math.min(100,parseInt(c[1],10)),b=c[2],v=c[3];o(10+Math.floor(x*.5),`Receiving objects: ${b}/${v}`)}let d=a.match(/Resolving deltas:\s+(\d+)%\s+\((\d+)\/(\d+)\)/);if(d?.[1]){let x=Math.min(100,parseInt(d[1],10)),b=d[2],v=d[3];o(60+Math.floor(x*.4),`Resolving deltas: ${b}/${v}`)}}),await s,o(100,"Clone complete")}catch(n){throw Fe.existsSync(e)&&Fe.rmSync(e,{recursive:!0,force:!0}),n}}import{execSync as mt}from"child_process";import*as L from"fs";import*as Ne from"os";import*as G from"path";var Ee=process.platform==="win32";function Pe(e){try{return mt(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function Ut(){let e=Pe("npm config get prefix");return e?Ee?e:G.join(e,"bin"):null}function Xt(){let e=Pe("pnpm bin -g");if(e&&L.existsSync(e))return e;let t=Pe("pnpm root -g");if(t){let o=G.join(G.dirname(t),"bin");if(L.existsSync(o))return o}return null}function Qt(){let e=G.join(Ne.homedir(),".bun","bin");return L.existsSync(e)?e:null}function Yt(){let e=Pe("yarn global bin");return e&&L.existsSync(e)?e:null}function ro(){let e=Ee?"gaia.cmd":"gaia";for(let t of[Ut,Xt,Qt,Yt]){let o=t();if(o&&L.existsSync(G.join(o,e)))return o}if(Ee)for(let t of[Ut,Xt,Qt,Yt]){let o=t();if(o&&L.existsSync(G.join(o,"gaia")))return o}return null}function oo(){try{return mt(Ee?"where gaia":"command -v gaia",{stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function no(){let e=process.env.SHELL||"",t=Ne.homedir();if(e.includes("zsh"))return G.join(t,".zshrc");if(e.includes("bash")){let o=G.join(t,".bashrc"),r=G.join(t,".bash_profile");return L.existsSync(o)?o:r}return e.includes("fish")?G.join(t,".config","fish","config.fish"):null}function io(e,t){try{if((L.existsSync(t)?L.readFileSync(t,"utf-8"):"").includes(e))return!0;let n=t.includes("fish")?`
13
+ set -gx PATH "${e}" $PATH # Added by GAIA CLI
14
+ `:`
15
+ export PATH="${e}:$PATH" # Added by GAIA CLI
16
+ `;return L.appendFileSync(t,n),!0}catch{return!1}}function ao(e){try{let t=Pe(`powershell -Command "[Environment]::GetEnvironmentVariable('Path', 'User')"`);if(t&&t.includes(e))return!0;mt(`setx PATH "${e};${t||""}"`,{stdio:["pipe","pipe","pipe"]});let o=G.join(Ne.homedir(),"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),r=G.dirname(o);return L.existsSync(r)||L.mkdirSync(r,{recursive:!0}),(L.existsSync(o)?L.readFileSync(o,"utf-8"):"").includes(e)||L.appendFileSync(o,`
17
+ $env:Path = "${e};" + $env:Path # Added by GAIA CLI
18
+ `),!0}catch{return!1}}async function ft(){if(oo())return{success:!0,message:"gaia command is ready.",inPath:!0,pathAdded:!1};let e=ro();if(!e)return{success:!1,message:"Could not find gaia binary. Run manually: npm install -g @heygaia/cli",inPath:!1,pathAdded:!1};if(Ee)return ao(e)?{success:!0,message:"Added to PATH. Restart your terminal for the 'gaia' command to be available.",inPath:!1,pathAdded:!0}:{success:!1,message:`Add to your PATH manually: setx PATH "${e};%PATH%"`,inPath:!1,pathAdded:!1};let t=no();if(!t)return{success:!1,message:`Add to your PATH: export PATH="${e}:$PATH"`,inPath:!1,pathAdded:!1};if(io(e,t)){let r=G.basename(t);return{success:!0,message:`Added to PATH via ~/${r}. Restart terminal or run: source ~/${r}`,inPath:!1,pathAdded:!0}}return{success:!1,message:`Could not write to ${t}. Add manually: export PATH="${e}:$PATH"`,inPath:!1,pathAdded:!1}}import{execa as te}from"execa";var X={git:"https://git-scm.com/downloads",docker:"https://docs.docker.com/get-docker/",mise:"https://mise.jdx.dev/getting-started.html"},so={8e3:"API Server",5432:"PostgreSQL",6379:"Redis",27017:"MongoDB",5672:"RabbitMQ",3e3:"Web Frontend",8080:"ChromaDB",8083:"Mongo Express"};async function Ge(){try{return await te("git",["--version"]),"success"}catch{return"error"}}async function xe(){let e=!1,t=!1,o;try{await te("docker",["--version"]),e=!0}catch{return{name:"Docker",installUrl:X.docker,installed:!1,working:!1,errorMessage:"Docker is not installed"}}try{await te("docker",["info"],{timeout:5e3}),t=!0}catch{o="Docker is installed but the daemon is not running. Please start Docker Desktop or the Docker daemon."}return{name:"Docker",installUrl:X.docker,installed:e,working:t,errorMessage:o}}async function ye(){try{return await te("mise",["--version"]),"success"}catch{return"missing"}}async function $e(){if((await import("node:os")).platform()==="win32")try{return await te("powershell",["-Command","irm https://mise.jdx.dev/install.ps1 | iex"]),!0}catch{return!1}try{return await te("sh",["-c","curl https://mise.jdx.dev/install.sh | sh"]),!0}catch{return!1}}async function qe(e){let t=await import("node:net"),o=[],r=n=>new Promise(s=>{let l=t.createServer();l.once("error",()=>s(!1)),l.once("listening",()=>{l.close(()=>s(!0))}),l.listen(n)});for(let n of e){let s=so[n]||`Port ${n}`;if(await r(n))o.push({port:n,service:s,available:!0});else{let a=await co(n),c=await lo(n+1,n+100,r);o.push({port:n,service:s,available:!1,usedBy:a,alternative:c||void 0})}}return o}async function co(e){if((await import("node:os")).platform()==="win32"){try{let{stdout:r}=await te("netstat",["-ano","-p","TCP"]),n=r.trim().split(`
19
+ `);for(let s of n)if(s.includes(`:${e}`)&&s.includes("LISTENING")){let l=s.trim().split(/\s+/),a=l[l.length-1];if(a)try{let{stdout:c}=await te("tasklist",["/FI",`PID eq ${a}`,"/FO","CSV","/NH"]);return c.trim().split(",")[0]?.replace(/"/g,"")||`PID ${a}`}catch{return`PID ${a}`}}}catch{}return}try{let{stdout:r}=await te("lsof",["-i",`:${e}`,"-sTCP:LISTEN","-P","-n"]),n=r.trim().split(`
20
+ `);if(n.length>1)return n[1]?.split(/\s+/)?.[0]||void 0}catch{}}async function lo(e,t,o){for(let r=e;r<=t;r++)if(await o(r))return r;return null}import*as F from"fs";import*as Q from"path";var uo=e=>new Promise(t=>setTimeout(t,e)),po="dev-start.log";var Jt=".gaia-dev.pid";function zt(e){let t=Q.join(e,".env");return F.existsSync(t)?["--env-file",".env"]:[]}async function je(e,t,o,r,n,s){if(t==="selfhost"){let l=s?.build??!1,a=s?.pull??!1;o?.(l?"Building and starting all services in Docker...":"Starting all services in Docker (selfhost mode)...");let c=Q.join(e,"infra/docker"),d=zt(c),x=r&&Object.keys(r).length>0?he(r):void 0,b=["compose","-f","docker-compose.selfhost.yml",...d,"up","-d","--remove-orphans"];l&&b.push("--build"),a&&b.push("--pull","always");let v=l?900*1e3:300*1e3;await W("docker",b,c,void 0,n,x,v),o?.("All services started in Docker!")}else{o?.("Starting development servers...");let{spawn:l}=await import("child_process"),a=Q.join(e,po),c=Q.join(e,Jt),d=F.openSync(a,"w"),x;try{x=l("mise",["dev"],{cwd:e,stdio:["ignore",d,d],detached:!0,shell:!0}),x.unref()}finally{F.closeSync(d)}if(x.pid!=null&&F.writeFileSync(c,String(x.pid),"utf-8"),await uo(1500),x.pid!=null)try{process.kill(x.pid,0)}catch{throw new Error(`Development servers crashed on startup. Check logs at: ${a}`)}o?.(`Development servers started! Logs: ${a}`)}}async function Zt(e,t,o){let r=Q.join(e,"infra/docker"),n=await gt(e);t?.("Stopping Docker services...");try{let s=zt(r),l=n==="selfhost"?["compose","-f","docker-compose.selfhost.yml",...s,"down"]:["compose",...s,"down"];await W("docker",l,r)}catch{}if(n!=="selfhost"){t?.("Stopping local processes...");let s=Q.join(e,Jt),l=!1;if(F.existsSync(s)){try{let a=Number.parseInt(F.readFileSync(s,"utf-8").trim(),10);if(!Number.isNaN(a)&&a>0)try{process.kill(-a,"SIGTERM"),l=!0}catch{}}catch{}try{F.unlinkSync(s)}catch{}}if(!l)try{let a=o?.[8e3]??8e3,c=o?.[3e3]??3e3;if(process.platform==="win32")for(let d of[a,c])try{await W("powershell",["-Command",`Get-NetTCPConnection -LocalPort ${d} -ErrorAction SilentlyContinue | ForEach-Object { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue }`],e)}catch{}else for(let d of[a,c])try{await W("sh",["-c",`lsof -ti :${d} -sTCP:LISTEN | xargs kill 2>/dev/null || true`],e)}catch{}}catch{}}t?.("All services stopped.")}async function gt(e){let t=Q.join(e,"apps","api",".env");if(!F.existsSync(t))return null;let o=F.readFileSync(t,"utf-8"),r=o.match(/^SETUP_MODE=(.+)$/m);if(r?.[1]){let n=r[1].trim().replace(/^["']|["']$/g,"");if(n==="selfhost"||n==="developer")return n}return o.includes("mongodb://mongo:")?"selfhost":(o.includes("mongodb://localhost:"),"developer")}async function W(e,t,o,r,n,s,l){let{spawn:a}=await import("child_process");return new Promise((c,d)=>{let x=a(e,t,{cwd:o,stdio:["ignore","pipe","pipe"],shell:!0,env:s?{...process.env,...s}:void 0}),b="",v=0,S=!1,m;l&&(m=setTimeout(()=>{S=!0,x.kill("SIGTERM"),d(new Error(`Command timed out after ${Math.round(l/6e4)}m. Check \`docker compose logs\` to debug.`))},l)),x.stdout?.on("data",p=>{let h=p.toString();b+=h,n?.(h),v=Math.min(v+5,95),r?.(v)}),x.stderr?.on("data",p=>{let h=p.toString();b+=h,n?.(h),v=Math.min(v+5,95),r?.(v)}),x.on("close",p=>{m&&clearTimeout(m),!S&&(p===0?(r?.(100),c()):d(new Error(`Command failed with code ${p}: ${b.slice(-500)}`)))}),x.on("error",p=>{m&&clearTimeout(m),!S&&d(p)})})}function z(e){let t=e||process.cwd();for(;t!==Q.dirname(t);){if(F.existsSync(Q.join(t,"apps/api/app/config/settings_validator.py")))return t;t=Q.dirname(t)}let o=ct();if(o?.repoPath){if(F.existsSync(Q.join(o.repoPath,"apps/api/app/config/settings_validator.py")))return o.repoPath;console.warn(`Warning: Saved repo path "${o.repoPath}" is no longer a valid GAIA installation. Resetting config.`),Ce({repoPath:"",setupComplete:!1})}return null}var mo=process.env.GAIA_CLI_DEV==="true",Z=e=>new Promise(t=>setTimeout(t,e));async function tr(e,t){e.setStep("Welcome"),e.setStatus("Waiting for user input..."),await e.waitForInput("welcome");let o=p=>{let h=e.currentState.data.dependencyLogs||[],y=p.split(`
21
+ `).filter(E=>E.trim()!==""),I=[...h,...y].slice(-20);e.updateData("dependencyLogs",I)};e.setStep("Prerequisites"),e.setStatus("Checking system requirements..."),e.updateData("checks",{git:"pending",docker:"pending",mise:"pending"}),await Z(800),e.setStatus("Checking Git...");let r=await Ge();e.updateData("checks",{...e.currentState.data.checks,git:r}),e.setStatus("Checking Docker...");let n=await xe(),s=n.working?"success":"error";e.updateData("checks",{...e.currentState.data.checks,docker:s}),n.working||e.updateData("dockerError",n.errorMessage),e.setStatus("Checking Mise...");let l=await ye();e.updateData("checks",{...e.currentState.data.checks,mise:l}),l==="missing"&&(e.setStatus("Installing Mise..."),l=await $e()?"success":"error",e.updateData("checks",{...e.currentState.data.checks,mise:l}));let a=[];if(r==="error"&&a.push({name:"Git"}),s==="error"&&a.push({name:"Docker",message:n.errorMessage}),a.length>0){let p=[];p.push("Prerequisites failed:");for(let h of a)p.push(` \u2022 ${h.name}: ${h.message||"Not installed or not working"}`);p.push(`
22
+ Installation guides:`),r==="error"&&p.push(` \u2022 Git: ${X.git}`),s==="error"&&(n.installed?p.push(" \u2022 Docker: Start Docker Desktop or run 'sudo systemctl start docker'"):p.push(` \u2022 Docker: ${X.docker}`)),e.setError(new Error(p.join(`
23
+ `)));return}e.setStatus("Checking Ports...");let d=await qe([8e3,5432,6379,27017,5672,3e3,8080,8083]),x={},b=d.filter(p=>!p.available);if(b.length>0){let p=b.filter(y=>!y.alternative);if(p.length>0){e.setError(new Error(`Cannot find free alternative ports for: ${p.map(y=>`${y.port} (${y.service})`).join(", ")}. Free these ports and try again.`));return}if(e.updateData("portConflicts",d),await e.waitForInput("port_conflicts")==="abort"){e.setError(new Error("Port conflicts not resolved. Please free the ports and try again."));return}for(let y of d)!y.available&&y.alternative&&(x[y.port]=y.alternative)}e.updateData("portOverrides",x),e.setStatus("Prerequisites check complete!"),await Z(1e3);let v=await Le(e),S="";if(mo){if(S=z()||"",!S){e.setError(new Error("DEV_MODE: Could not find workspace root. Run from within the gaia repo."));return}e.setStep("Repository Setup"),e.setStatus("[DEV MODE] Using current workspace..."),await Z(500),e.setStatus("Repository ready!")}else{e.setStep("Repository Setup");let p=v==="selfhost"?ie.join(er.homedir(),"gaia"):ie.resolve("gaia"),h=!0;for(S=p;;){if(S=await e.waitForInput("repo_path",{default:p}),ie.isAbsolute(S)||(S=ie.resolve(S)),re.existsSync(S)){if(!re.statSync(S).isDirectory()){e.setError(new Error(`Path ${S} exists and is not a directory.`)),await Z(2e3),e.setError(null);continue}if(re.existsSync(ie.join(S,"apps/api/app/config/settings_validator.py"))){e.updateData("existingRepoPath",S);let M=await e.waitForInput("existing_repo");if(M==="use_existing"){h=!1;break}else if(M==="delete_reclone"){e.setStatus("Removing existing installation..."),re.rmSync(S,{recursive:!0,force:!0});break}else{if(M==="different_path")continue;e.setError(new Error("Setup cancelled by user."));return}}if(re.readdirSync(S).length>0){e.setError(new Error(`Directory ${S} is not empty and is not a GAIA installation. Please choose another path.`)),await Z(2e3),e.setError(null);continue}}break}if(h){e.setStep("Repository Setup"),e.setStatus("Preparing repository..."),e.updateData("repoProgress",0),e.updateData("repoPhase","");try{await Wt(S,"https://github.com/theexperiencecompany/gaia.git",(y,I)=>{e.updateData("repoProgress",y),I?(e.updateData("repoPhase",I),e.setStatus(`${I}...`)):e.setStatus(`Cloning repository to ${S}... ${y}%`)},t),e.setStatus("Repository ready!")}catch(y){e.setError(y);return}}else e.setStatus("Using existing repository!")}if(await Z(1e3),await Me(e,S,v,x),e.currentState.error)return;if(v==="selfhost"){e.setStep("Installing CLI"),e.setStatus("Installing gaia CLI globally...");try{await W("npm",["install","-g","@heygaia/cli"],S),e.setStatus("Verifying PATH...");let y=await ft();y.inPath?e.setStatus("CLI installed! gaia command is ready."):(y.pathAdded,e.setStatus(y.message))}catch{e.setStatus("CLI install failed. Install manually: npm install -g @heygaia/cli")}await Z(500),e.setStep("Project Setup"),e.setStatus("Building and starting all services in Docker..."),e.updateData("dependencyPhase","Building and starting Docker services..."),e.updateData("dependencyProgress",0),e.updateData("dependencyLogs",[]),e.updateData("dependencyComplete",!1);let p=y=>{let I=y.split(`
24
+ `).map(M=>M.replace(/\x1b\[[0-9;]*m/g,"").trim()).filter(M=>M.length>0);if(I.length===0)return;let E=e.currentState.data.dependencyLogs||[];e.updateData("dependencyLogs",[...E,...I].slice(-50))};try{await je(S,"selfhost",y=>e.setStatus(y),x,p,{build:!0})}catch(y){e.setError(new Error(`Failed to start services: ${y.message}`));return}e.updateData("dependencyProgress",100),e.updateData("dependencyComplete",!0);let h=e.currentState.data.envMethod||"manual";Oe({version:st,setupComplete:!0,setupMethod:h,repoPath:S,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}),e.updateData("setupMode",v),e.setStep("Finished"),e.setStatus("Setup complete! GAIA is running."),await e.waitForInput("exit");return}if(l==="error"){e.setError(new Error(`Developer mode requires Mise but it failed to install.
25
+ \u2022 Mise: ${X.mise}`));return}e.setStep("Install Tools"),e.setStatus("Installing toolchain..."),e.updateData("dependencyPhase","Initializing mise..."),e.updateData("dependencyProgress",0),e.updateData("dependencyLogs",[]);try{e.updateData("dependencyPhase","Trusting mise configuration..."),await W("mise",["trust"],S,void 0,o),e.updateData("dependencyProgress",50),e.updateData("dependencyPhase","Installing tools (node, python, uv, nx)..."),await W("mise",["install"],S,p=>{e.updateData("dependencyProgress",50+p*.5)},o),e.updateData("dependencyProgress",100),e.updateData("toolComplete",!0)}catch(p){e.setError(new Error(`Failed to install tools: ${p.message}`));return}await Z(1e3),e.setStep("Project Setup"),e.updateData("dependencyPhase","Setting up project..."),e.updateData("dependencyProgress",0),e.updateData("dependencyComplete",!1),e.updateData("repoPath",S),e.updateData("dependencyLogs",[]);try{e.updateData("dependencyProgress",0),e.updateData("dependencyPhase","Running mise setup (all dependencies)...");let p=Object.keys(x).length>0?he(x):void 0;await W("mise",["setup"],S,h=>{e.updateData("dependencyProgress",h)},o,p),e.updateData("dependencyProgress",100),e.updateData("dependencyPhase","Setup complete!"),e.updateData("dependencyComplete",!0)}catch(p){e.setError(new Error(`Failed to setup project: ${p.message}`));return}await Z(1e3);let m=e.currentState.data.envMethod||"manual";Oe({version:"0.1.8",setupComplete:!0,setupMethod:m,repoPath:S,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}),e.setStep("Installing CLI"),e.setStatus("Installing gaia CLI globally...");try{await W("npm",["install","-g","@heygaia/cli"],S),e.setStatus("Verifying PATH...");let p=await ft();p.inPath?e.setStatus("CLI installed! gaia command is ready."):(p.pathAdded,e.setStatus(p.message))}catch{e.setStatus("CLI install failed. Install manually: npm install -g @heygaia/cli")}await Z(500),e.setStep("Finished"),e.setStatus("Setup complete!"),await e.waitForInput("exit")}async function rr(e={}){let t=J(),{unmount:o}=fo(go.createElement(K,{store:t,command:"init"}));try{await tr(t,e.branch)}catch(r){t.setError(r)}t.currentState.error&&await t.waitForInput("exit"),o(),process.exit(t.currentState.error?1:0)}import{render as ho}from"ink";import So from"react";var He=e=>new Promise(t=>setTimeout(t,e));async function or(e){e.setStep("Detect Repo"),e.setStatus("Looking for GAIA repository...");let t=z();if(!t){e.setError(new Error("Could not find GAIA repository. Run this command from within a cloned gaia repo, or use 'gaia init' to set up from scratch."));return}e.updateData("repoPath",t),e.setStatus(`Found repository at ${t}`),await He(1e3),e.setStep("Prerequisites"),e.setStatus("Checking system requirements..."),e.updateData("checks",{git:"pending",docker:"pending",mise:"pending"}),await He(500);let o=await Ge();e.updateData("checks",{...e.currentState.data.checks,git:o});let r=await xe(),n=r.working?"success":"error";e.updateData("checks",{...e.currentState.data.checks,docker:n}),r.working||e.updateData("dockerError",r.errorMessage);let s=await ye();e.updateData("checks",{...e.currentState.data.checks,mise:s}),s==="missing"&&(e.setStatus("Installing Mise..."),s=await $e()?"success":"error",e.updateData("checks",{...e.currentState.data.checks,mise:s}));let l=[];if(o==="error"&&l.push({name:"Git"}),n==="error"&&l.push({name:"Docker",message:r.errorMessage}),l.length>0){let m=[];m.push("Prerequisites failed:");for(let p of l)m.push(` \u2022 ${p.name}: ${p.message||"Not installed or not working"}`);m.push(`
26
+ Installation guides:`),o==="error"&&m.push(` \u2022 Git: ${X.git}`),n==="error"&&(r.installed?m.push(" \u2022 Docker: Start Docker Desktop or run 'sudo systemctl start docker'"):m.push(` \u2022 Docker: ${X.docker}`)),e.setError(new Error(m.join(`
27
+ `)));return}e.setStatus("Checking Ports...");let c=await qe([8e3,5432,6379,27017,5672,3e3,8080,8083]),d={},x=c.filter(m=>!m.available);if(x.length>0){let m=x.filter(h=>!h.alternative);if(m.length>0){e.setError(new Error(`Cannot find free alternative ports for: ${m.map(h=>`${h.port} (${h.service})`).join(", ")}. Free these ports and try again.`));return}if(e.updateData("portConflicts",c),await e.waitForInput("port_conflicts")==="abort"){e.setError(new Error("Port conflicts not resolved. Please free the ports and try again."));return}for(let h of c)!h.available&&h.alternative&&(d[h.port]=h.alternative)}e.updateData("portOverrides",d),e.setStatus("Prerequisites check complete!"),await He(1e3);let b=await Le(e);if(await Me(e,t,b,d),e.currentState.error)return;if(b==="selfhost"){let m=e.currentState.data.envMethod||"manual";Ce({setupComplete:!0,setupMethod:m,repoPath:t}),e.setStep("Finished"),e.setStatus("Setup complete! Run 'gaia start' to build and start all services in Docker."),await e.waitForInput("exit");return}if(s==="error"){e.setError(new Error(`Developer mode requires Mise but it failed to install.
28
+ \u2022 Mise: ${X.mise}`));return}e.setStep("Project Setup"),e.updateData("dependencyPhase","Setting up project..."),e.updateData("dependencyProgress",0),e.updateData("dependencyComplete",!1),e.updateData("dependencyLogs",[]);let v=m=>{let p=e.currentState.data.dependencyLogs||[],h=m.split(`
29
+ `).filter(I=>I.trim()!==""),y=[...p,...h].slice(-20);e.updateData("dependencyLogs",y)};try{e.updateData("dependencyPhase","Trusting mise configuration..."),await W("mise",["trust"],t,void 0,v),e.updateData("dependencyProgress",20),e.updateData("dependencyPhase","Installing tools..."),await W("mise",["install"],t,p=>{e.updateData("dependencyProgress",20+p*.3)},v),e.updateData("dependencyPhase","Running mise setup...");let m=Object.keys(d).length>0?he(d):void 0;await W("mise",["setup"],t,p=>{e.updateData("dependencyProgress",50+p*.5)},v,m),e.updateData("dependencyProgress",100),e.updateData("dependencyPhase","Setup complete!"),e.updateData("dependencyComplete",!0)}catch(m){e.setError(new Error(`Failed to setup project: ${m.message}`));return}await He(1e3);let S=e.currentState.data.envMethod||"manual";Ce({setupComplete:!0,setupMethod:S,repoPath:t}),e.setStep("Finished"),e.setStatus("Setup complete!"),await e.waitForInput("exit")}async function nr(){let e=J(),{unmount:t}=ho(So.createElement(K,{store:e,command:"setup"}));try{await or(e)}catch(o){e.setError(o)}e.currentState.error&&await e.waitForInput("exit"),t(),process.exit(e.currentState.error?1:0)}import{render as xo}from"ink";import yo from"react";async function ir(e,t){e.setStep("Starting"),e.setStatus("Locating GAIA repository...");let o=z();if(!o){e.setError(new Error("Could not find GAIA repository. Run from within a cloned gaia repo."));return}e.updateData("repoPath",o);let r=await gt(o);if(!r){e.setError(new Error("No .env file found. Run 'gaia init' for fresh setup, or 'gaia setup' to configure an existing repo."));return}if(r==="selfhost"){e.setStatus("Checking Docker...");let c=await xe();if(!c.working){e.setError(new Error(c.errorMessage||`Docker is not running. Please start Docker and try again.
30
+ ${X.docker}`));return}}else{e.setStatus("Checking Mise...");let c=await ye();if(c==="missing"||c==="error"){e.setError(new Error(`Developer mode requires Mise but it is not installed.
31
+ Install: ${X.mise}`));return}}let n=Se(o),s=n[3e3]??3e3,l=n[8e3]??8e3;e.updateData("setupMode",r),e.updateData("webPort",s),e.updateData("apiPort",l),e.updateData("dockerLogs",[]),e.setStatus(`Starting GAIA in ${r} mode...`);let a=c=>{let d=c.split(`
32
+ `).map(b=>b.replace(/\x1b\[[0-9;]*m/g,"").trim()).filter(b=>b.length>0);if(d.length===0)return;let x=e.currentState.data.dockerLogs||[];e.updateData("dockerLogs",[...x,...d].slice(-50))};try{await je(o,r,c=>{e.setStatus(c)},n,a,t),e.setStep("Running"),e.setStatus("GAIA is running!"),e.updateData("started",!0)}catch(c){e.setError(new Error(`Failed to start services: ${c.message}`));return}await e.waitForInput("exit")}async function ar(e){let t=J(),{unmount:o}=xo(yo.createElement(K,{store:t,command:"start"}));await new Promise(r=>setTimeout(r,50));try{await ir(t,e)}catch(r){t.setError(r)}t.currentState.error&&await t.waitForInput("exit"),o(),process.exit(t.currentState.error?1:0)}import{render as Co}from"ink";import Eo from"react";import{execa as St}from"execa";var ht=["gaia-backend","gaia-web","chromadb","postgres","redis","mongo","rabbitmq","arq_worker"];async function sr(){try{let{stdout:e}=await St("docker",["inspect","--format","{{.Name}}|{{.State.Status}}|{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}",...ht]),t=new Map;for(let o of e.trim().split(`
33
+ `)){if(!o)continue;let[r,n,s]=o.split("|"),l=r?.replace(/^\//,"")??"";t.set(l,{name:l,status:n==="running"?"running":"stopped",health:s!=="none"?s:void 0})}return ht.map(o=>t.get(o)??{name:o,status:"not_found"})}catch{let e=ht.map(async t=>{try{let{stdout:o}=await St("docker",["inspect","--format","{{.State.Status}}|{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}",t]),[r,n]=o.trim().split("|");return{name:t,status:r==="running"?"running":"stopped",health:n!=="none"?n:void 0}}catch{return{name:t,status:"not_found"}}});return Promise.all(e)}}async function cr(){try{return await St("docker",["info"]),!0}catch{return!1}}var vo=[{name:"API",port:8e3,type:"http",path:"/health"},{name:"Web",port:3e3,type:"http",path:"/"},{name:"PostgreSQL",port:5432,type:"tcp"},{name:"Redis",port:6379,type:"tcp"},{name:"MongoDB",port:27017,type:"tcp"},{name:"RabbitMQ",port:5672,type:"tcp"},{name:"ChromaDB",port:8080,type:"tcp"}];async function lr(e){let o=vo.map(r=>({...r,port:e?.[r.port]??r.port})).map(r=>r.type==="http"?bo(r.name,r.port,r.path):To(r.name,r.port));return Promise.all(o)}async function bo(e,t,o){let r=Date.now();try{let n=await fetch(`http://localhost:${t}${o}`,{signal:AbortSignal.timeout(5e3)}),s=Date.now()-r;return{name:e,port:t,status:n.ok?"up":"down",latency:s,details:n.ok?`HTTP ${n.status}`:`HTTP ${n.status} (error)`}}catch{return{name:e,port:t,status:"down",details:"Connection failed"}}}async function To(e,t){let o=await import("node:net"),r=Date.now();return new Promise(n=>{let s=new o.Socket;s.setTimeout(3e3),s.on("connect",()=>{let l=Date.now()-r;s.destroy(),n({name:e,port:t,status:"up",latency:l})}),s.on("timeout",()=>{s.destroy(),n({name:e,port:t,status:"down"})}),s.on("error",()=>{s.destroy(),n({name:e,port:t,status:"down"})}),s.connect(t,"localhost")})}async function ur(){return await cr()?{running:!0,containers:await sr()}:{running:!1,containers:[]}}async function Io(e){e.setStep("Checking"),e.setStatus("Checking service health..."),e.updateData("refreshable",!1);let t=z(),o=t?Se(t):void 0,[r,n]=await Promise.all([lr(o),ur()]);e.updateData("services",r),e.updateData("docker",n);let s=r.filter(a=>a.status==="up").length,l=r.length;e.setStep("Results"),e.setStatus(`${s}/${l} services running`),e.updateData("refreshable",!0)}async function pr(e){for(;await Io(e),await e.waitForInput("exit_or_refresh")==="refresh";);}async function dr(){let e=J(),{unmount:t}=Co(Eo.createElement(K,{store:e,command:"status"}));await new Promise(o=>setTimeout(o,50));try{await pr(e)}catch(o){e.setError(o)}e.currentState.error&&await e.waitForInput("exit"),t(),process.exit(e.currentState.error?1:0)}import{render as Po}from"ink";import wo from"react";async function mr(e){e.setStep("Stopping"),e.setStatus("Locating GAIA repository...");let t=z();if(!t){e.setError(new Error("Could not find GAIA repository. Run from within a cloned gaia repo."));return}e.updateData("repoPath",t);let o=Se(t);try{await Zt(t,r=>{e.setStatus(r)},o),e.setStep("Stopped"),e.setStatus("All services stopped."),e.updateData("stopped",!0)}catch(r){e.setError(new Error(`Failed to stop services: ${r.message}`));return}await e.waitForInput("exit")}async function fr(){let e=J(),{unmount:t}=Po(wo.createElement(K,{store:e,command:"stop"}));await new Promise(o=>setTimeout(o,50));try{await mr(e)}catch(o){e.setError(o)}e.currentState.error&&await e.waitForInput("exit"),t(),process.exit(e.currentState.error?1:0)}var ae=new Ro;ae.name("gaia").description("CLI tool for setting up and managing GAIA").version("0.1.0");ae.command("init").description("Full setup from scratch (clone, configure, start)").option("--branch <branch>","Git branch to clone").action(async e=>{await rr({branch:e.branch})});ae.command("setup").description("Configure an existing GAIA repository").action(async()=>{await nr()});ae.command("status").description("Check health of all GAIA services").action(async()=>{await dr()});ae.command("start").description("Start GAIA services").option("-b, --build","Rebuild Docker images before starting").option("--pull","Pull latest base images before starting").action(async e=>{await ar({build:e.build,pull:e.pull})});ae.command("stop").description("Stop all GAIA services").action(async()=>{await fr()});process.argv.slice(2).length||(ae.outputHelp(),process.exit(0));ae.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heygaia/cli",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "description": "CLI tool for setting up and managing GAIA",
5
5
  "type": "module",
6
6
  "bin": {