@heygaia/cli 0.1.11 → 0.1.12

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