bostrat-node 1.7.5 → 1.7.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.js +62 -62
  2. package/dist/index.js +166 -166
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
1
- var mn=Object.defineProperty;var _=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Ae=(e,t)=>{for(var n in t)mn(e,n,{get:t[n],enumerable:!0})};import pe from"node:fs";import ke from"node:path";import hn from"node:os";function ce(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,r;try{r=new URL(n)}catch{return t}let o={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return o?(r.protocol=o,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function fe(e){let t;try{t=pe.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
2
- `)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!s)continue;let i=s[2].trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),n[s[1]]=i}return n}function Qe(e,t=process.env){let n=fe(e);for(let[r,o]of Object.entries(n))r in t||(t[r]=o);return n}function et(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
3
- `).map(o=>o?`# ${o}`:"#"));for(let[o,s]of Object.entries(t))s==null||s===""||r.push(`${o}=${s}`);pe.mkdirSync(ke.dirname(e),{recursive:!0}),pe.writeFileSync(e,r.join(`
1
+ var wn=Object.defineProperty;var S=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Ae=(e,t)=>{for(var n in t)wn(e,n,{get:t[n],enumerable:!0})};import pe from"node:fs";import Oe from"node:path";import yn from"node:os";function ce(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,r;try{r=new URL(n)}catch{return t}let o={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return o?(r.protocol=o,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function me(e){let t;try{t=pe.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
2
+ `)){let o=r.trim();if(!o||o.startsWith("#"))continue;let a=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!a)continue;let i=a[2].trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),n[a[1]]=i}return n}function tt(e,t=process.env){let n=me(e);for(let[r,o]of Object.entries(n))r in t||(t[r]=o);return n}function nt(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
3
+ `).map(o=>o?`# ${o}`:"#"));for(let[o,a]of Object.entries(t))a==null||a===""||r.push(`${o}=${a}`);pe.mkdirSync(Oe.dirname(e),{recursive:!0}),pe.writeFileSync(e,r.join(`
4
4
  `)+`
5
- `,{mode:384}),pe.chmodSync(e,384)}function tt(e=process.platform){return e==="darwin"?{BOSTRAT_TMUX_BIN:"/opt/homebrew/bin/tmux",BOSTRAT_TMUX_SOCKET:`/tmp/tmux-${process.getuid?.()??501}/bostrat`,BOSTRAT_CHROMIUM_BIN:"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"}:{}}var Oe,ne,ve=_(()=>{Oe=process.env.BOSTRAT_STATE_DIR||ke.join(process.env.HOME||hn.tmpdir(),".bostrat"),ne=()=>ke.join(Oe,"node.env")});var Ee=_(()=>{});var nt=_(()=>{Ee()});var rt=_(()=>{});var ot=_(()=>{});import $e from"node:path";import{execFile as yn}from"node:child_process";import{promisify as gn}from"node:util";var Eo,st,Tn,$o,Ro,at=_(()=>{Eo=gn(yn),st=process.env.HOME||"/home/globo",Tn=$e.join(process.env.BOSTRAT_STATE_DIR||$e.join(st,".bostrat"),"repos"),$o=[...(process.env.BOSTRAT_REPOS_ROOT||$e.join(st,"Documents")).split(","),Tn].map(e=>e.trim()).filter(Boolean),Ro=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});import it from"node:path";import bn from"node:os";import{execFile as _n}from"node:child_process";import{promisify as Sn}from"node:util";var Fo,xn,Bo,Lo,Uo,Re=_(()=>{at();Fo=Sn(_n),xn=process.env.BOSTRAT_STATE_DIR||it.join(process.env.HOME||bn.tmpdir(),".bostrat"),Bo=it.join(xn,"repos"),Lo=5*6e4,Uo=10*6e4});var ct=_(()=>{Re()});import kn from"node:os";import On from"node:path";import{execFile as vn}from"node:child_process";import{promisify as En}from"node:util";var Zo,Qo,es,lt=_(()=>{ct();Zo=En(vn),Qo=process.env.BOSTRAT_STATE_DIR||On.join(process.env.HOME||kn.tmpdir(),".bostrat"),es=25*1024});var ut=_(()=>{});var as,dt=_(()=>{Re();ut();as=60*6e4});var pt=_(()=>{dt()});import $n from"node:os";import ft from"node:path";var Rn,gs,Ts,Ie=_(()=>{Ne();Rn=process.env.BOSTRAT_DEBUG_DIR||ft.join($n.homedir(),".bostrat","debug"),gs=ft.join(Rn,"handoff.jsonl"),Ts=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as Nn}from"node:child_process";import{promisify as Pn}from"node:util";import Mn from"node:fs";function wt(e){return`/tmp/tmux-${e}/default`}function Dn({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=wt(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function Me(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Fn(e,{loginShell:t});return r===yt?!0:r===Pe?!1:n}async function Fn(e,{loginShell:t=!1,timeoutMs:n=Cn}={}){if(!e)return Pe;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await jn(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),yt}catch(s){return s?.killed||s?.signal?ht:s?.code===1||s?.code===127?Pe:ht}}var jn,Bs,mt,Ls,Us,Hs,yt,Pe,ht,Cn,me,Ks,Ws,zs,Ys,qs,Ne=_(()=>{nt();rt();ot();lt();pt();Ie();Ee();jn=Pn(Nn),Bs=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";mt=typeof process.getuid=="function"?process.getuid():0,Ls=Dn({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Mn.existsSync(wt(mt))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:mt}),Us=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Hs=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions";yt="present",Pe="absent",ht="unknown",Cn=5e3;me={claude:"npm install -g @anthropic-ai/claude-code",codex:"npm install -g @openai/codex","cursor-agent":"curl https://cursor.com/install -fsS | bash",gh:"apt install gh (Debian: enable cli.github.com/packages) / brew install gh \u2014 see https://github.com/cli/cli#installation"},Ks=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Ws=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,zs=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Ys=Number(process.env.BOSTRAT_BOX_COLS)||120,qs=Number(process.env.BOSTRAT_BOX_ROWS)||40});var xt={};Ae(xt,{NODE_IMAGE:()=>De,commandPlan:()=>bt,flyToml:()=>Tt,flyWizard:()=>Yn,parseFlyFlags:()=>_t,stageConfig:()=>St});import je from"node:fs";import X from"node:path";import Bn from"node:os";import Ln from"node:readline/promises";import{execFile as Un}from"node:child_process";import{createRequire as Hn}from"node:module";import{randomUUID as Kn}from"node:crypto";function Tt({app:e,region:t,nodeName:n=e,planeUrl:r=gt,image:o=De}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
5
+ `,{mode:384}),pe.chmodSync(e,384)}function rt(e=process.platform){return e==="darwin"?{BOSTRAT_TMUX_BIN:"/opt/homebrew/bin/tmux",BOSTRAT_TMUX_SOCKET:`/tmp/tmux-${process.getuid?.()??501}/bostrat`,BOSTRAT_CHROMIUM_BIN:"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"}:{}}var Ee,ne,$e=S(()=>{Ee=process.env.BOSTRAT_STATE_DIR||Oe.join(process.env.HOME||yn.tmpdir(),".bostrat"),ne=()=>Oe.join(Ee,"node.env")});var Re=S(()=>{});var ot=S(()=>{Re()});var st=S(()=>{});var at=S(()=>{});import Ne from"node:path";import{execFile as Tn}from"node:child_process";import{promisify as bn}from"node:util";var Ro,it,_n,No,Io,ct=S(()=>{Ro=bn(Tn),it=process.env.HOME||"/home/globo",_n=Ne.join(process.env.BOSTRAT_STATE_DIR||Ne.join(it,".bostrat"),"repos"),No=[...(process.env.BOSTRAT_REPOS_ROOT||Ne.join(it,"Documents")).split(","),_n].map(e=>e.trim()).filter(Boolean),Io=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});import lt from"node:path";import Sn from"node:os";import{execFile as xn}from"node:child_process";import{promisify as kn}from"node:util";var Lo,vn,Uo,Ho,Ko,Ie=S(()=>{ct();Lo=kn(xn),vn=process.env.BOSTRAT_STATE_DIR||lt.join(process.env.HOME||Sn.tmpdir(),".bostrat"),Uo=lt.join(vn,"repos"),Ho=5*6e4,Ko=10*6e4});var ut=S(()=>{Ie()});import On from"node:os";import En from"node:path";import{execFile as $n}from"node:child_process";import{promisify as Rn}from"node:util";var es,ts,ns,rs,os,ss,dt=S(()=>{ut();es=Rn($n),ts=process.env.BOSTRAT_STATE_DIR||En.join(process.env.HOME||On.tmpdir(),".bostrat"),ns=25*1024,rs=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,os=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,ss=Promise.resolve()});var ft=S(()=>{});var ds,pt=S(()=>{Ie();ft();ds=60*6e4});var mt=S(()=>{pt()});import Nn from"node:os";import ht from"node:path";var In,xs,ks,Pe=S(()=>{Me();In=process.env.BOSTRAT_DEBUG_DIR||ht.join(Nn.homedir(),".bostrat","debug"),xs=ht.join(In,"handoff.jsonl"),ks=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as Mn}from"node:child_process";import{promisify as jn}from"node:util";import Dn from"node:fs";function gt(e){return`/tmp/tmux-${e}/default`}function Fn({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=gt(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function De(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Ln(e,{loginShell:t});return r===Tt?!0:r===je?!1:n}async function Ln(e,{loginShell:t=!1,timeoutMs:n=Bn}={}){if(!e)return je;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await Cn(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),Tt}catch(a){return a?.killed||a?.signal?yt:a?.code===1||a?.code===127?je:yt}}var Cn,Ws,wt,zs,Ys,qs,Tt,je,yt,Bn,he,Gs,Vs,Js,Xs,Zs,Me=S(()=>{ot();st();at();dt();mt();Pe();Re();Cn=jn(Mn),Ws=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";wt=typeof process.getuid=="function"?process.getuid():0,zs=Fn({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Dn.existsSync(gt(wt))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:wt}),Ys=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",qs=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions";Tt="present",je="absent",yt="unknown",Bn=5e3;he={claude:"npm install -g @anthropic-ai/claude-code",codex:"npm install -g @openai/codex","cursor-agent":"curl https://cursor.com/install -fsS | bash",gh:"apt install gh (Debian: enable cli.github.com/packages) / brew install gh \u2014 see https://github.com/cli/cli#installation"},Gs=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Vs=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Js=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Xs=Number(process.env.BOSTRAT_BOX_COLS)||120,Zs=Number(process.env.BOSTRAT_BOX_ROWS)||40});var vt={};Ae(vt,{NODE_IMAGE:()=>Fe,commandPlan:()=>St,flyToml:()=>_t,flyWizard:()=>Gn,parseFlyFlags:()=>xt,stageConfig:()=>kt});import Ce from"node:fs";import Z from"node:path";import Un from"node:os";import Hn from"node:readline/promises";import{execFile as Kn}from"node:child_process";import{createRequire as Wn}from"node:module";import{randomUUID as zn}from"node:crypto";function _t({app:e,region:t,nodeName:n=e,planeUrl:r=bt,image:o=Fe}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
6
6
  # Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
7
7
  # No [http_service] and none should be added: the node dials OUT to the plane;
8
8
  # nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
@@ -42,72 +42,72 @@ swap_size_mb = 1024
42
42
  # Scale later with: fly scale memory 4096 -a ${e}
43
43
  size = "shared-cpu-2x"
44
44
  memory = "2gb"
45
- `}function bt({app:e,org:t,region:n,sizeGb:r,token:o,owner:s,dir:i}){let d=[`BOSTRAT_PLANE_TOKEN=${o}`,...s?[`BOSTRAT_OWNER=${s}`]:[]];return[{argv:["apps","create",e,"-o",t],display:`fly apps create ${e} -o ${t}`,tolerate:/already|taken|exists/i},{argv:["volumes","create","node_data","-a",e,"-r",n,"-s",String(r),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${r} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted>${s?" BOSTRAT_OWNER=\u2026":""} via stdin`,stdin:d.join(`
45
+ `}function St({app:e,org:t,region:n,sizeGb:r,token:o,owner:a,dir:i}){let d=[`BOSTRAT_PLANE_TOKEN=${o}`,...a?[`BOSTRAT_OWNER=${a}`]:[]];return[{argv:["apps","create",e,"-o",t],display:`fly apps create ${e} -o ${t}`,tolerate:/already|taken|exists/i},{argv:["volumes","create","node_data","-a",e,"-r",n,"-s",String(r),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${r} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted>${a?" BOSTRAT_OWNER=\u2026":""} via stdin`,stdin:d.join(`
46
46
  `)+`
47
- `},{argv:["deploy",i,"-c",X.join(i,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${i} -c ${X.join(i,"fly.toml")} -a ${e} --ha=false`}]}function _t(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--owner":"owner","--image":"image"};for(let r=0;r<e.length;r++){let o=e[r];if(o==="--yes"||o==="-y")t.yes=!0;else if(n[o])t[n[o]]=e[++r]??"";else if(o.startsWith("--")&&o.includes("=")){let[s,...i]=o.split("=");n[s]?t[n[s]]=i.join("="):s==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function St({app:e,dest:t,toml:n}){let r=t||X.join(Bn.homedir(),".bostrat","fly",e);je.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])je.rmSync(X.join(r,o),{recursive:!0,force:!0});return je.writeFileSync(X.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function zn({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await he(["orgs","list","--json"],{exec:n}),s=JSON.parse(o),i=Array.isArray(s)?s.map(d=>d.Slug||d.slug).filter(Boolean):Object.keys(s);if(i.length===1)return t.write(`Org: ${i[0]} (your only org)
48
- `),i[0];if(i.length>1)return await e(`Fly org (${i.join(" / ")})`,i[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function Yn({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:o}={}){let s=_t(e),i=Ln.createInterface({input:t,output:n}),d=async(w,A)=>(await i.question(A?`${w} [${A}]: `:`${w}: `)).trim()||A||"",b=w=>(i.close(),w);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
47
+ `},{argv:["deploy",i,"-c",Z.join(i,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${i} -c ${Z.join(i,"fly.toml")} -a ${e} --ha=false`}]}function xt(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--owner":"owner","--image":"image"};for(let r=0;r<e.length;r++){let o=e[r];if(o==="--yes"||o==="-y")t.yes=!0;else if(n[o])t[n[o]]=e[++r]??"";else if(o.startsWith("--")&&o.includes("=")){let[a,...i]=o.split("=");n[a]?t[n[a]]=i.join("="):a==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function kt({app:e,dest:t,toml:n}){let r=t||Z.join(Un.homedir(),".bostrat","fly",e);Ce.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])Ce.rmSync(Z.join(r,o),{recursive:!0,force:!0});return Ce.writeFileSync(Z.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function qn({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await we(["orgs","list","--json"],{exec:n}),a=JSON.parse(o),i=Array.isArray(a)?a.map(d=>d.Slug||d.slug).filter(Boolean):Object.keys(a);if(i.length===1)return t.write(`Org: ${i[0]} (your only org)
48
+ `),i[0];if(i.length>1)return await e(`Fly org (${i.join(" / ")})`,i[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function Gn({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:o}={}){let a=xt(e),i=Hn.createInterface({input:t,output:n}),d=async(y,N)=>(await i.question(N?`${y} [${N}]: `:`${y}: `)).trim()||N||"",T=y=>(i.close(),y);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
49
49
  bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
50
50
 
51
- `);try{await he(["version"],{exec:r})}catch{return n.write("\u2717 `fly` (flyctl) is not installed or not on PATH.\n install: https://fly.io/docs/flyctl/install/ \u2014 then re-run `bostrat-node fly`\n"),b(1)}try{let{stdout:w}=await he(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${w.trim()}
52
- `)}catch{return n.write("\u2717 not signed in to Fly. Run `fly auth login` (or `fly auth signup`) and re-run `bostrat-node fly`.\n"),b(1)}let f=await zn({ask:d,output:n,exec:r,flag:s.org}),u=s.app||await d("App name",`bostrat-node-${Kn().slice(0,4)}`),T=s.region||await d("Region (see `fly platform regions`)","iad"),m=s.sizeGb||Number(await d("Volume size GB (logins + repos live here)","10"))||10,x=s.name||u,S=s.planeUrl||gt,h=s.token||await d("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!h)return n.write(`\u2717 a node token is required \u2014 mint one in the bostrat setup chat (Connect a node \u2192 Fly), then re-run with it.
53
- `),b(1);let O=s.owner??await d("Owner userId (shown next to the token; empty = infer from token)",""),N=s.image||De,{dir:v}=St({app:u,dest:o,toml:Tt({app:u,region:T,nodeName:x,planeUrl:S,image:N})});n.write(`
54
- wrote ${X.join(v,"fly.toml")} \u2014 deploys the prebuilt node image ${N}
51
+ `);try{await we(["version"],{exec:r})}catch{return n.write("\u2717 `fly` (flyctl) is not installed or not on PATH.\n install: https://fly.io/docs/flyctl/install/ \u2014 then re-run `bostrat-node fly`\n"),T(1)}try{let{stdout:y}=await we(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${y.trim()}
52
+ `)}catch{return n.write("\u2717 not signed in to Fly. Run `fly auth login` (or `fly auth signup`) and re-run `bostrat-node fly`.\n"),T(1)}let p=await qn({ask:d,output:n,exec:r,flag:a.org}),u=a.app||await d("App name",`bostrat-node-${zn().slice(0,4)}`),w=a.region||await d("Region (see `fly platform regions`)","iad"),x=a.sizeGb||Number(await d("Volume size GB (logins + repos live here)","10"))||10,b=a.name||u,m=a.planeUrl||bt,_=a.token||await d("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!_)return n.write(`\u2717 a node token is required \u2014 mint one in the bostrat setup chat (Connect a node \u2192 Fly), then re-run with it.
53
+ `),T(1);let M=a.owner??await d("Owner userId (shown next to the token; empty = infer from token)",""),k=a.image||Fe,{dir:A}=kt({app:u,dest:o,toml:_t({app:u,region:w,nodeName:b,planeUrl:m,image:k})});n.write(`
54
+ wrote ${Z.join(A,"fly.toml")} \u2014 deploys the prebuilt node image ${k}
55
55
  (claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
56
56
 
57
57
  Plan (your flyctl, your org, your bill):
58
- `);let M=bt({app:u,org:f,region:T,sizeGb:m,token:h,owner:O,dir:v});for(let w of M)n.write(` $ ${w.display}
59
- `);if(!s.yes&&(await d(`
58
+ `);let F=St({app:u,org:p,region:w,sizeGb:x,token:_,owner:M,dir:A});for(let y of F)n.write(` $ ${y.display}
59
+ `);if(!a.yes&&(await d(`
60
60
  Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u2014 nothing was created. Re-run any time; the staged context is kept.
61
- `),b(1);for(let w of M){n.write(`
62
- \u2192 ${w.display}
63
- `);try{let{stdout:A,stderr:j}=await he(w.argv,{stdin:w.stdin,exec:r}),Z=`${A||""}${j||""}`.trim();Z&&n.write(Z.split(`
64
- `).map(Q=>` ${Q}`).join(`
61
+ `),T(1);for(let y of F){n.write(`
62
+ \u2192 ${y.display}
63
+ `);try{let{stdout:N,stderr:I}=await we(y.argv,{stdin:y.stdin,exec:r}),j=`${N||""}${I||""}`.trim();j&&n.write(j.split(`
64
+ `).map(K=>` ${K}`).join(`
65
65
  `)+`
66
- `)}catch(A){let j=`${A?.stdout||""}${A?.stderr||""}${A?.message||""}`;if(w.tolerate&&w.tolerate.test(j)){n.write(` (already exists \u2014 continuing)
67
- `);continue}return n.write(`\u2717 failed: ${j.trim().split(`
66
+ `)}catch(N){let I=`${N?.stdout||""}${N?.stderr||""}${N?.message||""}`;if(y.tolerate&&y.tolerate.test(I)){n.write(` (already exists \u2014 continuing)
67
+ `);continue}return n.write(`\u2717 failed: ${I.trim().split(`
68
68
  `).slice(-4).join(`
69
69
  `)}
70
70
  fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
71
- `),b(1)}}return n.write(`
71
+ `),T(1)}}return n.write(`
72
72
  \u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
73
73
  chat: the node step advances on its own within a minute.
74
74
  logs: fly logs -a ${u}
75
- redeploy: fly deploy ${v} -c ${X.join(v,"fly.toml")} -a ${u} --ha=false
75
+ redeploy: fly deploy ${A} -c ${Z.join(A,"fly.toml")} -a ${u} --ha=false
76
76
  Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
77
77
  boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
78
- `),b(0)}var gt,Wn,De,he,At=_(()=>{gt="wss://plane.bostrat.ai/v1/node",Wn=Hn(import.meta.url)("../package.json").version,De=`ghcr.io/globocodes/bostrat-node:${Wn}`;he=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let s=Un("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(i,d,b)=>i?o(Object.assign(i,{stdout:d,stderr:b})):r({stdout:d,stderr:b}));t!=null&&s.stdin?.end(t)})});import qn from"node:fs/promises";import le from"node:path";import Gn from"node:os";import{EventEmitter as Vn}from"node:events";function Xn(e){return e?.cwd?le.join(e.cwd,".bostrat","events"):le.join(kt,"events")}async function Ce(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?le.join(kt,"events"):Xn(e));let o;try{o=await qn.readFile(Jn(n,r),"utf8")}catch{return[]}let s=[];for(let i of o.split(`
79
- `))if(i.trim())try{s.push(JSON.parse(i))}catch{}return s}var ue,kt,Jn,Fe=_(()=>{ue=new Vn;ue.setMaxListeners(0);kt=process.env.BOSTRAT_STATE_DIR||le.join(process.env.HOME||Gn.tmpdir(),".bostrat");Jn=(e,t)=>le.join(e,`${t}.ndjson`)});function Ot(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!Qn.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let r=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(r))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return r}function er(e){let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||r.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=r.map(o=>({...o,fromMs:Ot(o.from,"from",n),toMs:Ot(o.to,"to",n)}))}return t}var Zn,Qn,ia,vt=_(()=>{Zn={"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,note:"GA rates; verified 2026-08-06 via the claude-api skill."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,note:"verified 2026-08-06 via the claude-api skill."}],"claude-sonnet-5":[{from:null,to:"2026-08-31",input:2,output:10,cacheWrite:4,cacheRead:.2,note:"GA introductory pricing ($2/$10); verified 2026-08-06 via the claude-api skill."},{from:"2026-09-01",to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,note:"standard rates resume after the intro window; verified 2026-08-06."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,note:"verified 2026-08-06 via the claude-api skill."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,note:"verified 2026-08-06 via the claude-api skill."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,note:"verified 2026-08-06 via the claude-api skill; 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,note:"verified 2026-07-03; no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:null,input:5,output:30,cacheWrite:6.25,cacheRead:.5,note:"verified 2026-07-18; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-terra":[{from:null,to:null,input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,note:"verified 2026-07-18; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:null,input:1,output:6,cacheWrite:1.25,cacheRead:.1,note:"verified 2026-07-18; cacheWrite = 1.25\xD7 input (30-min TTL)."}]},Qn=/^\d{4}-\d{2}-\d{2}$/;ia=er(Zn)});var Et=_(()=>{vt()});import $t from"node:fs/promises";import Nt from"node:path";import tr from"node:os";function Mt(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function jt(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Dt(e){let t=new Date(Mt(e));return t.setDate(t.getDate()+7),t.getTime()}function Ct(e){let t=new Date(jt(e));return t.setMonth(t.getMonth()+1),t.getTime()}function ar(e=Date.now()){for(let[t,n]of Object.entries(or)){let r=n.startOf(e);if(r!==we[t]){we[t]=r;for(let o of Be.values())o[t]=0;for(let o of Rt)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&Rt.delete(o)}}}function ir(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let o={};for(let s of["weeklyUsd","monthlyUsd"]){let i=r?.[s];if(i==null||i==="")continue;let d=Number(i);if(!Number.isFinite(d)||d<=0)throw new Error(`${n}.${s} must be a positive number or null`);o[s]=d}Object.keys(o).length&&(t[n]=o)}return t}async function Ft(e,{source:t="local",updatedAt:n=Date.now()}={}){re={caps:ir(e),updatedAt:n,source:t};try{await $t.mkdir(Pt,{recursive:!0}),await $t.writeFile(nr(),JSON.stringify(re,null,2))}catch{}return cr()}function cr(e=Date.now()){ar(e);let t=new Set([...Be.keys(),...Object.keys(re?.caps||{})]),n={};for(let r of t){let o=Be.get(r);n[r]={weeklyUsd:It(o?.weekly||0),monthlyUsd:It(o?.monthly||0)}}return{caps:re?.caps||{},configured:!!re,seeded:sr,updatedAt:re?.updatedAt??null,spent:n,windows:{weekly:{start:we.weekly,resetsAt:Dt(e)},monthly:{start:we.monthly,resetsAt:Ct(e)}},warnPct:rr}}var Pt,nr,rr,or,re,sr,we,Be,Rt,It,Bt=_(()=>{Fe();Et();Pt=process.env.BOSTRAT_STATE_DIR||Nt.join(process.env.HOME||tr.tmpdir(),".bostrat"),nr=()=>Nt.join(Pt,"usage-caps.json"),rr=.8;or={weekly:{startOf:Mt,nextStart:Dt,capKey:"weeklyUsd"},monthly:{startOf:jt,nextStart:Ct,capKey:"monthlyUsd"}},re=null,sr=!1,we={weekly:0,monthly:0},Be=new Map,Rt=new Set;It=e=>Math.round(e*1e4)/1e4});var Kt={};Ae(Kt,{detectInstallKind:()=>se,detectProviderAuth:()=>Ht,startPlaneLink:()=>_r,updateCommandFor:()=>He,versionLt:()=>oe});import Ut from"node:fs";import Le from"node:fs/promises";import lr from"node:http";import z from"node:path";import ge from"node:os";import{createRequire as ur}from"node:module";import Ue from"ws";function se({env:e=process.env,pkgDir:t=z.resolve(z.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ut.existsSync}={}){let r=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(r)?r:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(z.join(t,"..",".git"))?"git-checkout":"dev"}function oe(e,t){let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let o=0;o<Math.max(n.length,r.length);o++){let s=(n[o]||0)-(r[o]||0);if(s)return s<0}return!1}function He(e){switch(e){case"npm-global":return"npm install -g bostrat-node && restart the bostrat-node service";case"git-checkout":return"scripts/deploy-pi.sh (or The Bakery \u2192 Deploy to Pi \u2192 bostrat)";case"container":return"Links \u2192 Fly \u2192 Update (or the plane's auto-update while the node sleeps)";default:return"update this node's bostrat-node checkout/install"}}function Ht({home:e=process.env.HOME||ge.homedir(),env:t=process.env}={}){let n=r=>{try{return Ut.statSync(r),!0}catch{return!1}};return{claude:n(z.join(e,".claude",".credentials.json")),codex:n(z.join(t.CODEX_HOME||z.join(e,".codex"),"auth.json"))}}function _r({url:e,token:t,nodeId:n=ge.hostname(),name:r=ge.hostname(),listTracks:o,detectAgents:s=null,onTracksTransferred:i=null,sampleMetrics:d=null,metricsMs:b=Tr,onUpdateAvailable:f=null,installKind:u=se(),selfUrl:T=`http://127.0.0.1:${process.env.PORT||3362}`,log:m=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof o!="function")throw new Error("plane-link: listTracks is required");e=ce(e);let x=T.replace(/^http/,"ws"),S=new Set,h=new Map,O=new Map,N=z.join(dr,"plane-link","cursor.json"),v={},M={},w=new Map,A=null,j=!1,Z=!1,Q=Lt,de=null,ee=null,te=null,H=null,K=null,Se=!1,Ve=0;async function nn(){try{v=JSON.parse(await Le.readFile(N,"utf8"))}catch{v={}}}function rn(){Se=!0,!te&&(te=setTimeout(async()=>{if(te=null,!!Se){Se=!1;try{await Le.mkdir(z.dirname(N),{recursive:!0}),await Le.writeFile(N,JSON.stringify(v))}catch(p){m.error("[plane-link] cursor flush failed:",p?.message||p)}}},wr),te.unref?.())}function E(p){return!A||A.readyState!==Ue.OPEN?!1:(A.send(JSON.stringify(p)),!0)}function xe(p){let l=Date.now();for(let{trackId:a,event:c}of p){let y=w.get(c.id);w.set(c.id,{trackId:a,seq:c.seq,event:c,sentAt:l,tries:(y?.tries??0)+1})}return E({v:$,ch:"events",type:"append",events:p})}function on(p){let l=null;for(let a of w.values())a.trackId===p&&(l==null||a.seq<l)&&(l=a.seq);return l}function sn(p){let l=M[p];if(l==null)return;let a=on(p),c=a==null?l:Math.min(l,a-1);c>(v[p]??0)&&(v[p]=c,rn())}function an(){if(!j)return;let p=Date.now(),l=[...w.values()].filter(a=>a.event&&p-a.sentAt>=gr);if(l.length){l.sort((a,c)=>a.trackId===c.trackId?a.seq-c.seq:a.trackId<c.trackId?-1:1),m.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);for(let a=0;a<l.length;a+=ye){let c=l.slice(a,a+ye).map(y=>({trackId:y.trackId,event:y.event}));if(!xe(c))return}}}async function Xe(){if(!d)return;let p;try{p=await d()}catch(l){m.error("[plane-link] metrics sample failed:",l?.message||l);return}p&&E({v:$,ch:"ctl",type:"metrics",metrics:p})}function cn(){d&&(K&&clearInterval(K),Xe(),K=setInterval(Xe,b),K.unref?.())}async function ln(){let p;try{p=await o()}catch(l){m.error("[plane-link] backfill listTracks failed:",l?.message||l);return}E({v:$,ch:"ctl",type:"tracks",ids:p.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of p){if(!j)return;let a;try{a=await Ce(l)}catch{continue}let c=v[l.id]??0,y=a.filter(g=>g.seq>c&&typeof g.id=="string");for(let g=0;g<y.length;g+=ye){let I=y.slice(g,g+ye).map(D=>({trackId:l.id,event:D}));if(!xe(I))return}}}function Je(p){!j||!p?.trackId||typeof p.id!="string"||xe([{trackId:p.trackId,event:p}])}let ie=new Map;async function un(p){let{reqId:l,method:a,path:c,headers:y={},body:g}=p,I=Object.fromEntries(Object.entries(y).filter(([,L])=>L!=null)),D=new AbortController;ie.set(l,D);try{if(p.host){await dn(p,I,D);return}let L=await fetch(T+c,{method:a,headers:I,body:g?Buffer.from(g,"base64"):void 0,signal:D.signal}),q=Object.fromEntries(L.headers);for(let C of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete q[C];if(q["content-type"]||(q["content-type"]="application/octet-stream"),E({v:$,ch:"control",type:"http_head",reqId:l,status:L.status,headers:q}),L.body){for await(let C of L.body)if(!E({v:$,ch:"control",type:"http_data",reqId:l,data:Buffer.from(C).toString("base64")}))break}E({v:$,ch:"control",type:"http_end",reqId:l,error:null})}finally{ie.delete(l)}}function dn(p,l,a){let{reqId:c,method:y,path:g,body:I}=p,D=new URL(T);return new Promise(L=>{let q=lr.request({host:D.hostname,port:D.port,method:y,path:g,headers:{...l,host:p.host},signal:a.signal},C=>{let{connection:lo,"keep-alive":uo,"transfer-encoding":po,upgrade:fo,...pn}=C.headers;E({v:$,ch:"control",type:"http_head",reqId:c,status:C.statusCode||502,headers:pn}),C.on("data",fn=>{E({v:$,ch:"control",type:"http_data",reqId:c,data:Buffer.from(fn).toString("base64")})||C.destroy()}),C.on("end",()=>{E({v:$,ch:"control",type:"http_end",reqId:c,error:null}),L()}),C.on("error",()=>{E({v:$,ch:"control",type:"http_end",reqId:c,error:"view upstream error"}),L()})});q.on("error",C=>{E({v:$,ch:"control",type:"http_end",reqId:c,error:C?.message||"view request failed"}),L()}),I&&q.write(Buffer.from(I,"base64")),q.end()})}function Ze(){if(Z)return;A=new Ue(e,{headers:{authorization:`Bearer ${t}`}}),A.on("open",async()=>{let l=null;try{l=await s?.()||null}catch{l=null}E({v:$,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:W,installKind:u,providers:Ht(),...l?{agents:l}:{}})}),A.on("message",l=>{let a;try{a=JSON.parse(l)}catch{return}if(a.ch==="ctl"&&a.type==="hello_ok"){j=!0,Q=Lt,de=null,m.log(`[plane-link] connected to plane as ${n}`),a.minNodeVersion&&W&&oe(W,a.minNodeVersion)&&m.error(`[plane-link] this node is bostrat-node ${W}; the plane asks for \u2265${a.minNodeVersion} \u2014 update with: ${He(u)}`);let c=typeof a.latestNodeVersion=="string"?a.latestNodeVersion:null;if(c&&W&&oe(W,c)&&!S.has(c)){S.add(c),m.log(`[plane-link] bostrat-node ${c} is available (this node runs ${W}) \u2014 ${He(u)}`);try{f?.({current:W,latest:c,min:a.minNodeVersion??null,installKind:u,required:!!(a.minNodeVersion&&oe(W,a.minNodeVersion))})}catch(y){m.error(`[plane-link] update notice failed: ${y?.message||y}`)}}H&&clearInterval(H),H=setInterval(()=>{E({v:$,ch:"ctl",type:"ping"}),an()},yr),H.unref?.(),cn(),ln().catch(y=>m.error("[plane-link] backfill failed:",y?.message||y));return}if(a.ch==="ctl"&&a.type==="usage_caps"){Ft(a.caps??{},{source:"plane",updatedAt:a.updatedAt??Date.now()}).then(c=>m.log(`[plane-link] spend caps ${Object.keys(c.caps).length?`updated (${Object.keys(c.caps).join(", ")})`:"cleared"} from plane`)).catch(c=>m.error("[plane-link] spend-caps push rejected:",c?.message||c));return}if(a.ch==="ctl"&&a.type==="transferred"&&Array.isArray(a.tracks)){Promise.resolve().then(()=>i?.(a.tracks)).catch(c=>m.error("[plane-link] transfer notice failed:",c?.message||c));return}if(a.ch==="events"&&a.type==="ack"&&Array.isArray(a.ids)){let c=new Set;for(let y of a.ids){let g=w.get(y);g&&(w.delete(y),(M[g.trackId]??0)<g.seq&&(M[g.trackId]=g.seq),c.add(g.trackId))}for(let y of c)sn(y);return}if(a.ch==="control"&&a.type==="http_open"){un(a).catch(c=>E({v:$,ch:"control",type:"http_end",reqId:a.reqId,error:c?.message||"tunnel error"}));return}if(a.ch==="control"&&a.type==="http_cancel"){ie.get(a.reqId)?.abort();return}if(a.ch==="attach"&&a.type==="open"){let c=new Ue(x+a.path,Array.isArray(a.protocols)?a.protocols:[],a.host?{headers:{host:a.host}}:void 0);h.set(a.streamId,c),O.set(a.streamId,[]),c.on("open",()=>{let g=O.get(a.streamId)||[];O.delete(a.streamId);for(let{buf:I,bin:D}of g)c.send(I,{binary:D})}),c.on("message",(g,I)=>{let D=I?g:Buffer.from(String(g));E({v:$,ch:"attach",type:"data",streamId:a.streamId,data:D.toString("base64"),...I?{bin:!0}:{}})});let y=()=>{O.delete(a.streamId),h.delete(a.streamId)&&E({v:$,ch:"attach",type:"close",streamId:a.streamId})};c.on("close",y),c.on("error",y);return}if(a.ch==="attach"&&a.type==="data"){let c=h.get(a.streamId);if(!c)return;let y=Buffer.from(a.data,"base64"),g=a.bin===!0,I=O.get(a.streamId);I?I.push({buf:y,bin:g}):c.send(y,{binary:g});return}if(a.ch==="attach"&&a.type==="close"){let c=h.get(a.streamId);h.delete(a.streamId),O.delete(a.streamId),c?.close();return}});let p=()=>{j&&m.log("[plane-link] disconnected from plane"),j=!1,H&&(clearInterval(H),H=null),K&&(clearInterval(K),K=null),w.clear(),M={};for(let c of h.values())c.close();h.clear(),O.clear();for(let c of ie.values())c.abort();if(ie.clear(),Z||ee)return;de==null&&(de=Date.now());let l=Date.now()-de<fr,a=l?mr+Math.random()*hr:Q;ee=setTimeout(()=>{ee=null,Ze()},a),ee.unref?.(),l||(Q=Math.min(Q*2,pr))};A.on("close",p),A.on("error",l=>{let a=/Unexpected server response: (\d+)/.exec(l?.message||"")?.[1];(a==="401"||a==="403")&&Date.now()-Ve>=br&&(Ve=Date.now(),m.error(`[plane-link] plane refused this node's credentials (HTTP ${a}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`)),p()})}return ue.on("event",Je),nn().then(Ze),{stop:()=>{Z=!0,ue.off("event",Je),ee&&clearTimeout(ee),te&&clearTimeout(te),H&&clearInterval(H),K&&clearInterval(K),E({v:$,ch:"ctl",type:"bye",reason:"shutdown"}),A?.close()},status:()=>({connected:j,nodeId:n,cursor:{...v},inflight:w.size})}}var W,dr,$,Lt,pr,fr,mr,hr,ye,wr,yr,gr,Tr,br,Ke=_(()=>{Fe();Bt();ve();W=(()=>{try{return ur(import.meta.url)("../package.json").version||null}catch{return null}})(),dr=process.env.BOSTRAT_STATE_DIR||z.join(process.env.HOME||ge.tmpdir(),".bostrat");$=1,Lt=1e3,pr=3e4,fr=6e4,mr=1500,hr=500,ye=100,wr=2e3,yr=25e3,gr=6e4,Tr=6e4,br=6e4});import{execFile as Sr}from"node:child_process";import{promisify as xr}from"node:util";function Wt(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Ma,ja,Da,zt=_(()=>{Ie();Ma=xr(Sr),ja=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Da=Promise.resolve()});var Xt={};Ae(Xt,{ACTIONABLE_KINDS:()=>_e,SELF_UPDATE_DIR:()=>We,createAutoUpdater:()=>Dr,inFlight:()=>Ye,readStatus:()=>ze,selfUpdatePlan:()=>Gt,settleSelfUpdate:()=>jr,startSelfUpdate:()=>Vt,underService:()=>qt,updatePolicy:()=>Rr});import Yt from"node:fs";import G from"node:fs/promises";import Ar from"node:os";import R from"node:path";import{spawn as kr}from"node:child_process";import{createRequire as Or}from"node:module";function Rr({kind:e=se(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:_e.has(e)?e==="git-checkout"||qt(t)?"auto":"prompt":"off"}function qt(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Gt({kind:e,to:t,from:n=Te,statusFile:r=be,logFile:o=R.join(We,"last.log"),port:s=Number(process.env.PORT)||3362,npmPrefix:i=null,serviceName:d=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:b=typeof process.getuid=="function"?process.getuid():0,liveDir:f=process.env.BOSTRAT_LIVE_CHECKOUT||R.resolve(R.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:u=Date.now()}={}){if(!_e.has(e))throw new Error(`self-update: install kind "${e}" is not actionable here`);if(!/^\d+\.\d+\.\d+$/.test(String(t)))throw new Error(`self-update: bad target version "${t}"`);if(n&&!/^\d+\.\d+\.\d+$/.test(String(n)))throw new Error(`self-update: bad current version "${n}"`);let T=(O,N="")=>`write_status ${F(O)} ${N}`,m=process.platform==="darwin"?`launchctl kickstart -k gui/${b}/${d}`:`systemctl --user restart ${F(d)}`,x=`
78
+ `),T(0)}var bt,Yn,Fe,we,At=S(()=>{bt="wss://plane.bostrat.ai/v1/node",Yn=Wn(import.meta.url)("../package.json").version,Fe=`ghcr.io/globocodes/bostrat-node:${Yn}`;we=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let a=Kn("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(i,d,T)=>i?o(Object.assign(i,{stdout:d,stderr:T})):r({stdout:d,stderr:T}));t!=null&&a.stdin?.end(t)})});import Vn from"node:fs/promises";import le from"node:path";import Jn from"node:os";import{EventEmitter as Xn}from"node:events";function Zn(e){return e?.cwd?le.join(e.cwd,".bostrat","events"):le.join(Ot,"events")}async function Be(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?le.join(Ot,"events"):Zn(e));let o;try{o=await Vn.readFile(Qn(n,r),"utf8")}catch{return[]}let a=[];for(let i of o.split(`
79
+ `))if(i.trim())try{a.push(JSON.parse(i))}catch{}return a}var ue,Ot,Qn,Le=S(()=>{ue=new Xn;ue.setMaxListeners(0);Ot=process.env.BOSTRAT_STATE_DIR||le.join(process.env.HOME||Jn.tmpdir(),".bostrat");Qn=(e,t)=>le.join(e,`${t}.ndjson`)});function Et(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!tr.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let r=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(r))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return r}function nr(e){let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||r.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=r.map(o=>({...o,fromMs:Et(o.from,"from",n),toMs:Et(o.to,"to",n)}))}return t}var er,tr,fa,$t=S(()=>{er={"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,note:"GA rates; verified 2026-08-06 via the claude-api skill."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,note:"verified 2026-08-06 via the claude-api skill."}],"claude-sonnet-5":[{from:null,to:"2026-08-31",input:2,output:10,cacheWrite:4,cacheRead:.2,note:"GA introductory pricing ($2/$10); verified 2026-08-06 via the claude-api skill."},{from:"2026-09-01",to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,note:"standard rates resume after the intro window; verified 2026-08-06."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,note:"verified 2026-08-06 via the claude-api skill."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,note:"verified 2026-08-06 via the claude-api skill."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,note:"verified 2026-08-06 via the claude-api skill; 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,note:"verified 2026-07-03; no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:null,input:5,output:30,cacheWrite:6.25,cacheRead:.5,note:"verified 2026-07-18; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-terra":[{from:null,to:null,input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,note:"verified 2026-07-18; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:null,input:1,output:6,cacheWrite:1.25,cacheRead:.1,note:"verified 2026-07-18; cacheWrite = 1.25\xD7 input (30-min TTL)."}]},tr=/^\d{4}-\d{2}-\d{2}$/;fa=nr(er)});var Rt=S(()=>{$t()});import Nt from"node:fs/promises";import Mt from"node:path";import rr from"node:os";function Dt(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Ct(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Ft(e){let t=new Date(Dt(e));return t.setDate(t.getDate()+7),t.getTime()}function Bt(e){let t=new Date(Ct(e));return t.setMonth(t.getMonth()+1),t.getTime()}function cr(e=Date.now()){for(let[t,n]of Object.entries(ar)){let r=n.startOf(e);if(r!==ye[t]){ye[t]=r;for(let o of Ue.values())o[t]=0;for(let o of It)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&It.delete(o)}}}function lr(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let o={};for(let a of["weeklyUsd","monthlyUsd"]){let i=r?.[a];if(i==null||i==="")continue;let d=Number(i);if(!Number.isFinite(d)||d<=0)throw new Error(`${n}.${a} must be a positive number or null`);o[a]=d}Object.keys(o).length&&(t[n]=o)}return t}async function Lt(e,{source:t="local",updatedAt:n=Date.now()}={}){re={caps:lr(e),updatedAt:n,source:t};try{await Nt.mkdir(jt,{recursive:!0}),await Nt.writeFile(or(),JSON.stringify(re,null,2))}catch{}return ur()}function ur(e=Date.now()){cr(e);let t=new Set([...Ue.keys(),...Object.keys(re?.caps||{})]),n={};for(let r of t){let o=Ue.get(r);n[r]={weeklyUsd:Pt(o?.weekly||0),monthlyUsd:Pt(o?.monthly||0)}}return{caps:re?.caps||{},configured:!!re,seeded:ir,updatedAt:re?.updatedAt??null,spent:n,windows:{weekly:{start:ye.weekly,resetsAt:Ft(e)},monthly:{start:ye.monthly,resetsAt:Bt(e)}},warnPct:sr}}var jt,or,sr,ar,re,ir,ye,Ue,It,Pt,Ut=S(()=>{Le();Rt();jt=process.env.BOSTRAT_STATE_DIR||Mt.join(process.env.HOME||rr.tmpdir(),".bostrat"),or=()=>Mt.join(jt,"usage-caps.json"),sr=.8;ar={weekly:{startOf:Dt,nextStart:Ft,capKey:"weeklyUsd"},monthly:{startOf:Ct,nextStart:Bt,capKey:"monthlyUsd"}},re=null,ir=!1,ye={weekly:0,monthly:0},Ue=new Map,It=new Set;Pt=e=>Math.round(e*1e4)/1e4});var zt={};Ae(zt,{detectInstallKind:()=>se,detectProviderAuth:()=>Wt,startPlaneLink:()=>xr,updateCommandFor:()=>We,versionLt:()=>oe});import Kt from"node:fs";import He from"node:fs/promises";import dr from"node:http";import q from"node:path";import Te from"node:os";import{createRequire as fr}from"node:module";import Ke from"ws";function se({env:e=process.env,pkgDir:t=q.resolve(q.dirname(new URL(import.meta.url).pathname),".."),exists:n=Kt.existsSync}={}){let r=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(r)?r:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(q.join(t,"..",".git"))?"git-checkout":"dev"}function oe(e,t){let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let o=0;o<Math.max(n.length,r.length);o++){let a=(n[o]||0)-(r[o]||0);if(a)return a<0}return!1}function We(e){switch(e){case"npm-global":return"npm install -g bostrat-node && restart the bostrat-node service";case"git-checkout":return"scripts/deploy-pi.sh (or The Bakery \u2192 Deploy to Pi \u2192 bostrat)";case"container":return"Links \u2192 Fly \u2192 Update (or the plane's auto-update while the node sleeps)";default:return"update this node's bostrat-node checkout/install"}}function Wt({home:e=process.env.HOME||Te.homedir(),env:t=process.env}={}){let n=r=>{try{return Kt.statSync(r),!0}catch{return!1}};return{claude:n(q.join(e,".claude",".credentials.json")),codex:n(q.join(t.CODEX_HOME||q.join(e,".codex"),"auth.json"))}}function xr({url:e,token:t,nodeId:n=Te.hostname(),name:r=Te.hostname(),listTracks:o,detectAgents:a=null,onTracksTransferred:i=null,sampleMetrics:d=null,metricsMs:T=_r,onUpdateAvailable:p=null,onUpdatePolicy:u=null,updatePolicy:w=null,installKind:x=se(),selfUrl:b=`http://127.0.0.1:${process.env.PORT||3362}`,log:m=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof o!="function")throw new Error("plane-link: listTracks is required");e=ce(e);let _=b.replace(/^http/,"ws"),M=new Set,k=new Map,A=new Map,F=q.join(pr,"plane-link","cursor.json"),y={},N={},I=new Map,j=null,K=!1,xe=!1,de=Ht,fe=null,ee=null,te=null,W=null,z=null,ke=!1,Xe=0;async function on(){try{y=JSON.parse(await He.readFile(F,"utf8"))}catch{y={}}}function sn(){ke=!0,!te&&(te=setTimeout(async()=>{if(te=null,!!ke){ke=!1;try{await He.mkdir(q.dirname(F),{recursive:!0}),await He.writeFile(F,JSON.stringify(y))}catch(f){m.error("[plane-link] cursor flush failed:",f?.message||f)}}},gr),te.unref?.())}function O(f){return!j||j.readyState!==Ke.OPEN?!1:(j.send(JSON.stringify(f)),!0)}function ve(f){let l=Date.now();for(let{trackId:s,event:c}of f){let h=I.get(c.id);I.set(c.id,{trackId:s,seq:c.seq,event:c,sentAt:l,tries:(h?.tries??0)+1})}return O({v:E,ch:"events",type:"append",events:f})}function an(f){let l=null;for(let s of I.values())s.trackId===f&&(l==null||s.seq<l)&&(l=s.seq);return l}function cn(f){let l=N[f];if(l==null)return;let s=an(f),c=s==null?l:Math.min(l,s-1);c>(y[f]??0)&&(y[f]=c,sn())}function ln(){if(!K)return;let f=Date.now(),l=[...I.values()].filter(s=>s.event&&f-s.sentAt>=br);if(l.length){l.sort((s,c)=>s.trackId===c.trackId?s.seq-c.seq:s.trackId<c.trackId?-1:1),m.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);for(let s=0;s<l.length;s+=ge){let c=l.slice(s,s+ge).map(h=>({trackId:h.trackId,event:h.event}));if(!ve(c))return}}}async function Ze(){if(!d)return;let f;try{f=await d()}catch(l){m.error("[plane-link] metrics sample failed:",l?.message||l);return}f&&O({v:E,ch:"ctl",type:"metrics",metrics:f})}function un(){d&&(z&&clearInterval(z),Ze(),z=setInterval(Ze,T),z.unref?.())}async function dn(){let f;try{f=await o()}catch(l){m.error("[plane-link] backfill listTracks failed:",l?.message||l);return}O({v:E,ch:"ctl",type:"tracks",ids:f.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of f){if(!K)return;let s;try{s=await Be(l)}catch{continue}let c=y[l.id]??0,h=s.filter(g=>g.seq>c&&typeof g.id=="string");for(let g=0;g<h.length;g+=ge){let R=h.slice(g,g+ge).map(D=>({trackId:l.id,event:D}));if(!ve(R))return}}}function Qe(f){!K||!f?.trackId||typeof f.id!="string"||ve([{trackId:f.trackId,event:f}])}let ie=new Map;async function fn(f){let{reqId:l,method:s,path:c,headers:h={},body:g}=f,R=Object.fromEntries(Object.entries(h).filter(([,U])=>U!=null)),D=new AbortController;ie.set(l,D);try{if(f.host){await pn(f,R,D);return}let U=await fetch(b+c,{method:s,headers:R,body:g?Buffer.from(g,"base64"):void 0,signal:D.signal}),V=Object.fromEntries(U.headers);for(let C of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete V[C];if(V["content-type"]||(V["content-type"]="application/octet-stream"),O({v:E,ch:"control",type:"http_head",reqId:l,status:U.status,headers:V}),U.body){for await(let C of U.body)if(!O({v:E,ch:"control",type:"http_data",reqId:l,data:Buffer.from(C).toString("base64")}))break}O({v:E,ch:"control",type:"http_end",reqId:l,error:null})}finally{ie.delete(l)}}function pn(f,l,s){let{reqId:c,method:h,path:g,body:R}=f,D=new URL(b);return new Promise(U=>{let V=dr.request({host:D.hostname,port:D.port,method:h,path:g,headers:{...l,host:f.host},signal:s.signal},C=>{let{connection:fo,"keep-alive":po,"transfer-encoding":mo,upgrade:ho,...mn}=C.headers;O({v:E,ch:"control",type:"http_head",reqId:c,status:C.statusCode||502,headers:mn}),C.on("data",hn=>{O({v:E,ch:"control",type:"http_data",reqId:c,data:Buffer.from(hn).toString("base64")})||C.destroy()}),C.on("end",()=>{O({v:E,ch:"control",type:"http_end",reqId:c,error:null}),U()}),C.on("error",()=>{O({v:E,ch:"control",type:"http_end",reqId:c,error:"view upstream error"}),U()})});V.on("error",C=>{O({v:E,ch:"control",type:"http_end",reqId:c,error:C?.message||"view request failed"}),U()}),R&&V.write(Buffer.from(R,"base64")),V.end()})}function et(){if(xe)return;j=new Ke(e,{headers:{authorization:`Bearer ${t}`}}),j.on("open",async()=>{let l=null;try{l=await a?.()||null}catch{l=null}O({v:E,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:Y,installKind:x,...typeof w=="function"?{updatePolicy:w()}:w?{updatePolicy:w}:{},providers:Wt(),...l?{agents:l}:{}})}),j.on("message",l=>{let s;try{s=JSON.parse(l)}catch{return}if(s.ch==="ctl"&&s.type==="hello_ok"){K=!0,de=Ht,fe=null,m.log(`[plane-link] connected to plane as ${n}`),s.minNodeVersion&&Y&&oe(Y,s.minNodeVersion)&&m.error(`[plane-link] this node is bostrat-node ${Y}; the plane asks for \u2265${s.minNodeVersion} \u2014 update with: ${We(x)}`);try{u?.(typeof s.updatePolicy=="string"?s.updatePolicy:null)}catch{}let c=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(c&&Y&&oe(Y,c)&&!M.has(c)){M.add(c),m.log(`[plane-link] bostrat-node ${c} is available (this node runs ${Y}) \u2014 ${We(x)}`);try{p?.({current:Y,latest:c,min:s.minNodeVersion??null,installKind:x,required:!!(s.minNodeVersion&&oe(Y,s.minNodeVersion))})}catch(h){m.error(`[plane-link] update notice failed: ${h?.message||h}`)}}W&&clearInterval(W),W=setInterval(()=>{O({v:E,ch:"ctl",type:"ping"}),ln()},Tr),W.unref?.(),un(),dn().catch(h=>m.error("[plane-link] backfill failed:",h?.message||h));return}if(s.ch==="ctl"&&s.type==="update_policy"){try{u?.(typeof s.mode=="string"?s.mode:null)}catch{}return}if(s.ch==="ctl"&&s.type==="usage_caps"){Lt(s.caps??{},{source:"plane",updatedAt:s.updatedAt??Date.now()}).then(c=>m.log(`[plane-link] spend caps ${Object.keys(c.caps).length?`updated (${Object.keys(c.caps).join(", ")})`:"cleared"} from plane`)).catch(c=>m.error("[plane-link] spend-caps push rejected:",c?.message||c));return}if(s.ch==="ctl"&&s.type==="transferred"&&Array.isArray(s.tracks)){Promise.resolve().then(()=>i?.(s.tracks)).catch(c=>m.error("[plane-link] transfer notice failed:",c?.message||c));return}if(s.ch==="events"&&s.type==="ack"&&Array.isArray(s.ids)){let c=new Set;for(let h of s.ids){let g=I.get(h);g&&(I.delete(h),(N[g.trackId]??0)<g.seq&&(N[g.trackId]=g.seq),c.add(g.trackId))}for(let h of c)cn(h);return}if(s.ch==="control"&&s.type==="http_open"){fn(s).catch(c=>O({v:E,ch:"control",type:"http_end",reqId:s.reqId,error:c?.message||"tunnel error"}));return}if(s.ch==="control"&&s.type==="http_cancel"){ie.get(s.reqId)?.abort();return}if(s.ch==="attach"&&s.type==="open"){let c=new Ke(_+s.path,Array.isArray(s.protocols)?s.protocols:[],s.host?{headers:{host:s.host}}:void 0);k.set(s.streamId,c),A.set(s.streamId,[]),c.on("open",()=>{let g=A.get(s.streamId)||[];A.delete(s.streamId);for(let{buf:R,bin:D}of g)c.send(R,{binary:D})}),c.on("message",(g,R)=>{let D=R?g:Buffer.from(String(g));O({v:E,ch:"attach",type:"data",streamId:s.streamId,data:D.toString("base64"),...R?{bin:!0}:{}})});let h=()=>{A.delete(s.streamId),k.delete(s.streamId)&&O({v:E,ch:"attach",type:"close",streamId:s.streamId})};c.on("close",h),c.on("error",h);return}if(s.ch==="attach"&&s.type==="data"){let c=k.get(s.streamId);if(!c)return;let h=Buffer.from(s.data,"base64"),g=s.bin===!0,R=A.get(s.streamId);R?R.push({buf:h,bin:g}):c.send(h,{binary:g});return}if(s.ch==="attach"&&s.type==="close"){let c=k.get(s.streamId);k.delete(s.streamId),A.delete(s.streamId),c?.close();return}});let f=()=>{K&&m.log("[plane-link] disconnected from plane"),K=!1,W&&(clearInterval(W),W=null),z&&(clearInterval(z),z=null),I.clear(),N={};for(let c of k.values())c.close();k.clear(),A.clear();for(let c of ie.values())c.abort();if(ie.clear(),xe||ee)return;fe==null&&(fe=Date.now());let l=Date.now()-fe<hr,s=l?wr+Math.random()*yr:de;ee=setTimeout(()=>{ee=null,et()},s),ee.unref?.(),l||(de=Math.min(de*2,mr))};j.on("close",f),j.on("error",l=>{let s=/Unexpected server response: (\d+)/.exec(l?.message||"")?.[1];(s==="401"||s==="403")&&Date.now()-Xe>=Sr&&(Xe=Date.now(),m.error(`[plane-link] plane refused this node's credentials (HTTP ${s}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`)),f()})}return ue.on("event",Qe),on().then(et),{stop:()=>{xe=!0,ue.off("event",Qe),ee&&clearTimeout(ee),te&&clearTimeout(te),W&&clearInterval(W),z&&clearInterval(z),O({v:E,ch:"ctl",type:"bye",reason:"shutdown"}),j?.close()},status:()=>({connected:K,nodeId:n,cursor:{...y},inflight:I.size})}}var Y,pr,E,Ht,mr,hr,wr,yr,ge,gr,Tr,br,_r,Sr,ze=S(()=>{Le();Ut();$e();Y=(()=>{try{return fr(import.meta.url)("../package.json").version||null}catch{return null}})(),pr=process.env.BOSTRAT_STATE_DIR||q.join(process.env.HOME||Te.tmpdir(),".bostrat");E=1,Ht=1e3,mr=3e4,hr=6e4,wr=1500,yr=500,ge=100,gr=2e3,Tr=25e3,br=6e4,_r=6e4,Sr=6e4});import{execFile as kr}from"node:child_process";import{promisify as vr}from"node:util";function Yt(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Ba,La,Ua,qt=S(()=>{Pe();Ba=vr(kr),La=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Ua=Promise.resolve()});var Zt={};Ae(Zt,{ACTIONABLE_KINDS:()=>Se,SELF_UPDATE_DIR:()=>Ye,createAutoUpdater:()=>Fr,inFlight:()=>Ge,readStatus:()=>qe,selfUpdatePlan:()=>Jt,settleSelfUpdate:()=>Cr,startSelfUpdate:()=>Xt,underService:()=>Vt,updatePolicy:()=>Ir});import Gt from"node:fs";import J from"node:fs/promises";import Ar from"node:os";import $ from"node:path";import{spawn as Or}from"node:child_process";import{createRequire as Er}from"node:module";function Ir({kind:e=se(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:Se.has(e)?e==="git-checkout"||Vt(t)?"auto":"prompt":"off"}function Vt(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Jt({kind:e,to:t,from:n=be,statusFile:r=_e,logFile:o=$.join(Ye,"last.log"),port:a=Number(process.env.PORT)||3362,npmPrefix:i=null,serviceName:d=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:T=typeof process.getuid=="function"?process.getuid():0,liveDir:p=process.env.BOSTRAT_LIVE_CHECKOUT||$.resolve($.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:u=Date.now()}={}){if(!Se.has(e))throw new Error(`self-update: install kind "${e}" is not actionable here`);if(!/^\d+\.\d+\.\d+$/.test(String(t)))throw new Error(`self-update: bad target version "${t}"`);if(n&&!/^\d+\.\d+\.\d+$/.test(String(n)))throw new Error(`self-update: bad current version "${n}"`);let w=(M,k="")=>`write_status ${B(M)} ${k}`,x=process.platform==="darwin"?`launchctl kickstart -k gui/${T}/${d}`:`systemctl --user restart ${B(d)}`,b=`
80
80
  health() {
81
81
  for i in $(seq 1 45); do
82
82
  sleep 1
83
- if curl -sf -o /dev/null -I "http://127.0.0.1:${s}/"; then return 0; fi
83
+ if curl -sf -o /dev/null -I "http://127.0.0.1:${a}/"; then return 0; fi
84
84
  done
85
85
  return 1
86
- }`,S=`#!/usr/bin/env bash
86
+ }`,m=`#!/usr/bin/env bash
87
87
  # bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
88
88
  # ${n??"?"} \u2192 ${t} (${e}). Status: ${r}
89
89
  set -u
90
- FROM=${F(n??"")}
91
- TO=${F(t)}
92
- STATUS_FILE=${F(r)}
90
+ FROM=${B(n??"")}
91
+ TO=${B(t)}
92
+ STATUS_FILE=${B(r)}
93
93
  STARTED_AT=${Number(u)}
94
94
  write_status() { # <status> [error]
95
95
  local err="\${2:-}"
96
96
  err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
97
97
  printf '{"status":"%s","from":"%s","to":"%s","kind":"%s","startedAt":%s,"updatedAt":%s%s}\\n' \\
98
- "$1" "$FROM" "$TO" ${F(e)} "$STARTED_AT" "$(date +%s000)" \\
98
+ "$1" "$FROM" "$TO" ${B(e)} "$STARTED_AT" "$(date +%s000)" \\
99
99
  "\${err:+,\\"error\\":\\"$err\\"}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
100
100
  }
101
- ${x}
102
- `;if(e==="npm-global"){let O=i?R.join(i,"bin","npm"):"npm",N=v=>`${F(O)} install -g "bostrat-node@${v}" --no-audit --no-fund`;return S+`
103
- ${T("updating",'"" ')}
104
- if ! ${N("$TO")}; then
105
- ${T("failed",'"npm install failed"')}
101
+ ${b}
102
+ `;if(e==="npm-global"){let M=i?$.join(i,"bin","npm"):"npm",k=A=>`${B(M)} install -g "bostrat-node@${A}" --no-audit --no-fund`;return m+`
103
+ ${w("updating",'"" ')}
104
+ if ! ${k("$TO")}; then
105
+ ${w("failed",'"npm install failed"')}
106
106
  exit 1
107
107
  fi
108
- ${T("restarting")}
109
- if ! ${m}; then
110
- ${T("failed",'"service restart failed"')}
108
+ ${w("restarting")}
109
+ if ! ${x}; then
110
+ ${w("failed",'"service restart failed"')}
111
111
  exit 1
112
112
  fi
113
113
  if health; then
@@ -115,52 +115,52 @@ if health; then
115
115
  exit 0
116
116
  fi
117
117
  # \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
118
- ${T("rolling-back",'"agent did not answer on :'+s+' after the update"')}
119
- if [ -n "$FROM" ] && ${N("$FROM")} && ${m} && health; then
120
- ${T("rolled-back",'"agent did not answer on :'+s+' after the update; rolled back"')}
118
+ ${w("rolling-back",'"agent did not answer on :'+a+' after the update"')}
119
+ if [ -n "$FROM" ] && ${k("$FROM")} && ${x} && health; then
120
+ ${w("rolled-back",'"agent did not answer on :'+a+' after the update; rolled back"')}
121
121
  exit 1
122
122
  fi
123
- ${T("failed",'"agent did not answer after the update AND the rollback"')}
123
+ ${w("failed",'"agent did not answer after the update AND the rollback"')}
124
124
  exit 1
125
- `}let h=O=>`( cd ${F(f)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${O}" )`;return S+`
126
- LIVE=${F(f)}
125
+ `}let _=M=>`( cd ${B(p)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${M}" )`;return m+`
126
+ LIVE=${B(p)}
127
127
  TMP_SCRIPT="$(mktemp)"
128
128
  trap 'rm -f "$TMP_SCRIPT"' EXIT
129
129
  # "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
130
130
  # restart \u2192 health in one call): the agent it restarts settles "done" on boot,
131
131
  # and nothing here may write after that boot or the settle would repeat.
132
- ${T("restarting")}
133
- if ${h("$TO")}; then
132
+ ${w("restarting")}
133
+ if ${_("$TO")}; then
134
134
  exit 0
135
135
  fi
136
- ${T("rolling-back",'"deploy-pi.sh v$TO failed"')}
137
- if [ -n "$FROM" ] && ${h("$FROM")}; then
138
- ${T("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
136
+ ${w("rolling-back",'"deploy-pi.sh v$TO failed"')}
137
+ if [ -n "$FROM" ] && ${_("$FROM")}; then
138
+ ${w("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
139
139
  exit 1
140
140
  fi
141
- ${T("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
141
+ ${w("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
142
142
  exit 1
143
- `}async function ze(e=be){try{return JSON.parse(await G.readFile(e,"utf8"))}catch{return null}}async function Vt({to:e,from:t=Te,kind:n=se(),reason:r="manual",statusFile:o=be,spawnImpl:s=kr,now:i=Date.now,npmPrefix:d=void 0,log:b=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!_e.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!oe(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let f=await ze(o);if(Ye(f))return{ok:!1,reason:`an update to ${f.to} is already in flight`,status:f};if(f&&f.to===e&&(f.status==="failed"||f.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${f.status} (${f.error||"no detail"}) \u2014 retried when a newer release exists`,status:f};await G.mkdir(R.dirname(o),{recursive:!0});let u=d!==void 0?d:n==="npm-global"?Wt(await Nr())||R.resolve(R.dirname(process.execPath),".."):null,T=Gt({kind:n,to:e,from:t,statusFile:o,npmPrefix:u,startedAt:i()}),m=R.join(R.dirname(o),`update-${e}.sh`),x=R.join(R.dirname(o),"last.log");await G.writeFile(m,T,{mode:448}),await G.writeFile(o,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,startedAt:i(),updatedAt:i()}));let S=Yt.existsSync("/run/systemd/system")&&await Pr("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",m]]:["setsid",["-f","bash","-c",`exec bash ${F(m)} >> ${F(x)} 2>&1`]];try{s(S[0],S[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(h){return await G.writeFile(o,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,startedAt:i(),updatedAt:i(),error:`could not spawn updater: ${h?.message||h}`})),{ok:!1,reason:`could not spawn updater: ${h?.message||h}`}}return b.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${o}`),{ok:!0,to:e,from:t,kind:n,scriptFile:m,statusFile:o}}async function Nr(){try{return await G.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Pr(e){for(let t of String(process.env.PATH||"").split(R.delimiter))try{return await G.access(R.join(t,e),Yt.constants.X_OK),!0}catch{}return!1}async function jr({statusFile:e=be,current:t=Te,now:n=Date.now,staleMs:r=Mr}={}){let o=await ze(e);if(!o)return null;let s=i=>G.writeFile(e,JSON.stringify(i)).catch(()=>{});if(Ye(o)){if(t&&o.to===t){let i={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await s(i),i}if(n()-Number(o.updatedAt||o.startedAt||0)>r){let i={...o,status:"failed",error:`updater went silent while ${o.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await s(i),i}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let i={...o,announced:!0};return await s(i),i}return null}function Dr({isBusy:e,start:t=Vt,onStuck:n=null,onStarted:r=null,tickMs:o=$r,stuckMs:s=Er,now:i=Date.now,setIntervalImpl:d=setInterval,clearIntervalImpl:b=clearInterval,log:f=console}={}){let u=null,T=()=>{u?.timer&&b(u.timer),u=null},m=async()=>{if(!u)return;let x=!0;try{x=await e()!==!1}catch{x=!0}if(x){if(!u.stuckFired&&i()-u.since>=s){u.stuckFired=!0;try{await n?.({to:u.to,from:u.from,since:u.since})}catch{}}return}let S=u;T();let h=await t({to:S.to,from:S.from,kind:S.kind,reason:"auto"});f.log?.(`[self-update] stasis reached \u2192 ${h.ok?"started":`not started: ${h.reason}`}`);try{await r?.({...S,result:h})}catch{}};return{arm({to:x,from:S=Te,kind:h=se()}){return u?.to===x?!1:(T(),u={to:x,from:S,kind:h,since:i(),stuckFired:!1,timer:d(m,o)},u.timer.unref?.(),!0)},tick:m,cancel:T,get armed(){return u?{to:u.to,from:u.from,kind:u.kind,since:u.since}:null}}}var Te,vr,We,be,Er,$r,_e,F,Ir,Ye,Mr,Jt=_(()=>{Ke();zt();Te=(()=>{try{return Or(import.meta.url)("../package.json").version||null}catch{return null}})(),vr=process.env.BOSTRAT_STATE_DIR||R.join(process.env.HOME||Ar.tmpdir(),".bostrat"),We=R.join(vr,"self-update"),be=R.join(We,"status.json"),Er=1440*6e4,$r=6e4,_e=new Set(["npm-global","git-checkout"]);F=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Ir=new Set(["updating","restarting","rolling-back"]),Ye=e=>!!(e&&Ir.has(e.status));Mr=45*6e4});ve();Ne();import B from"node:fs";import k from"node:path";import ae from"node:os";import{createRequire as qe}from"node:module";import{execFile as Cr,spawn as Fr}from"node:child_process";import{promisify as Br}from"node:util";import Lr from"node:readline/promises";import{randomUUID as Ur}from"node:crypto";import{fileURLToPath as Hr}from"node:url";var V=Br(Cr),Ge=k.dirname(Hr(import.meta.url)),J=k.resolve(Ge,".."),Kr=k.join(Ge,"index.js"),Wr="wss://plane.bostrat.ai/v1/node",Zt=qe(import.meta.url)("../package.json").version,P=(e,t)=>({name:e,level:"pass",detail:t}),Y=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),U=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function zr(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?P("node runtime",`${process.version} at ${process.execPath}`):U("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Yr(e){let t;try{t=B.statSync(e)}catch{return Y("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?Y("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):P("node.env",`${e} (0600)`)}async function qr(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await V(t,["-V"],{timeout:5e3});return P("tmux",`${t} (${n.trim()})`)}catch{return U("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Qt(e,{required:t=!1}={}){if(await Me(e,{loginShell:!0,failOpen:!1}))return P(e,"resolves on the login-shell PATH");let r="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",o=me[e]?`${me[e]}${e==="cursor-agent"?" # installs to ~/.local/bin \u2014 ensure your login shell has it on PATH":""}`:`install ${e} so \`$SHELL -lic 'command -v ${e}'\` finds it`;return t?U(e,r,o):Y(e,r,o)}async function Gr(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await V(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return P("gh (GitHub CLI)",n)}catch{return Y("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",me.gh)}}async function Vr(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Qt(t)));return e.some(t=>t.level==="pass")||e.push(U("agent CLIs","no agent CLI found at all \u2014 a node with nothing to drive","install at least one of claude / codex / cursor-agent")),e}async function Xr(){let e=[...process.platform==="linux"?[["fuser","stopped views can't free their ports (they leak, and the port can't be reused)","apt install psmisc"]]:[],["pgrep","agent-swap can't detect an idle pane shell \u2014 swaps may misfire","apt install procps"],["npm","codex auto-update and `npm run` views are unavailable","install Node.js with npm on the service PATH"]];return Promise.all(e.map(async([t,n,r])=>await Me(t,{failOpen:!1})?P(t,"resolves on the service PATH"):Y(t,`not on the service PATH \u2014 ${n}`,r)))}async function Jr(){try{let t=qe(k.join(J,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let o=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),s=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(s),n()})}),P("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${J} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=qe(k.join(J,"package.json")),r=k.join(k.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");B.existsSync(r)&&!(B.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return U("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function Zr(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";return B.existsSync(t)?P("chromium (mocks)",t):Y("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable`,"install Chromium/Chrome and set BOSTRAT_CHROMIUM_BIN")}function Qr(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?U("claude lane","BOSTRAT_CLAUDE_USE_API_KEY=1 but ANTHROPIC_API_KEY is empty","add the key to node.env or set the flag to 0"):P("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function eo(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return Y("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),o=ce(e.BOSTRAT_PLANE_URL);return await new Promise(s=>{let i=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),d=f=>{clearTimeout(b);try{i.close()}catch{}s(f)},b=setTimeout(()=>d(U("plane link",`no hello_ok within 5s from ${o}`,"check the URL, the token, and the plane's IP gate")),5e3);i.on("open",()=>i.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${Ur().slice(0,8)}`,ephemeral:!0}))),i.on("message",f=>{try{let u=JSON.parse(f);u.type==="hello_ok"?d(P("plane link",`hello_ok in ${Date.now()-r}ms (${o})`)):u.type==="error"&&d(U("plane link",`plane said: ${u.code} ${u.message||""}`,"check the token"))}catch{}}),i.on("error",f=>d(U("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function to(){let e;try{e=JSON.parse(B.readFileSync(k.join(Oe,"content-outbox.json"),"utf8"))}catch{return P("content outbox","empty \u2014 every deliverable has reached the plane")}let t=e.ops?.length||0,n=e.parked?.length||0;if(n){let r=e.parked[0];return U("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?Y("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):P("content outbox",t?`${t} op(s) in flight`:"drained")}function no(e){return e.BOSTRAT_STATE_REMOTE?P("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):Y("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}async function en(e,t={}){let n=[];return n.push(await zr()),n.push(Yr(t.envFile||ne())),n.push(await qr(e)),n.push(...await Vr()),n.push(await Qt("git",{required:!0})),n.push(await Gr()),n.push(...await Xr()),n.push(await Jr()),n.push(Zr(e)),n.push(Qr(e)),n.push(await eo(e,t)),n.push(to()),n.push(no(e)),n}function tn(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let s of e)t(`${n[s.level]} ${s.name}: ${s.detail}`),s.fix&&s.level!=="pass"&&t(` fix: ${s.fix}`);let r=e.filter(s=>s.level==="fail").length,o=e.filter(s=>s.level==="warn").length;return t(r?`
143
+ `}async function qe(e=_e){try{return JSON.parse(await J.readFile(e,"utf8"))}catch{return null}}async function Xt({to:e,from:t=be,kind:n=se(),reason:r="manual",statusFile:o=_e,spawnImpl:a=Or,now:i=Date.now,npmPrefix:d=void 0,log:T=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!Se.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!oe(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let p=await qe(o);if(Ge(p))return{ok:!1,reason:`an update to ${p.to} is already in flight`,status:p};if(p&&p.to===e&&(p.status==="failed"||p.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${p.status} (${p.error||"no detail"}) \u2014 retried when a newer release exists`,status:p};await J.mkdir($.dirname(o),{recursive:!0});let u=d!==void 0?d:n==="npm-global"?Yt(await Mr())||$.resolve($.dirname(process.execPath),".."):null,w=Jt({kind:n,to:e,from:t,statusFile:o,npmPrefix:u,startedAt:i()}),x=$.join($.dirname(o),`update-${e}.sh`),b=$.join($.dirname(o),"last.log");await J.writeFile(x,w,{mode:448}),await J.writeFile(o,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,startedAt:i(),updatedAt:i()}));let m=Gt.existsSync("/run/systemd/system")&&await jr("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",x]]:["setsid",["-f","bash","-c",`exec bash ${B(x)} >> ${B(b)} 2>&1`]];try{a(m[0],m[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(_){return await J.writeFile(o,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,startedAt:i(),updatedAt:i(),error:`could not spawn updater: ${_?.message||_}`})),{ok:!1,reason:`could not spawn updater: ${_?.message||_}`}}return T.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${o}`),{ok:!0,to:e,from:t,kind:n,scriptFile:x,statusFile:o}}async function Mr(){try{return await J.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function jr(e){for(let t of String(process.env.PATH||"").split($.delimiter))try{return await J.access($.join(t,e),Gt.constants.X_OK),!0}catch{}return!1}async function Cr({statusFile:e=_e,current:t=be,now:n=Date.now,staleMs:r=Dr}={}){let o=await qe(e);if(!o)return null;let a=i=>J.writeFile(e,JSON.stringify(i)).catch(()=>{});if(Ge(o)){if(t&&o.to===t){let i={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await a(i),i}if(n()-Number(o.updatedAt||o.startedAt||0)>r){let i={...o,status:"failed",error:`updater went silent while ${o.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await a(i),i}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let i={...o,announced:!0};return await a(i),i}return null}function Fr({isBusy:e,start:t=Xt,onStuck:n=null,onStarted:r=null,tickMs:o=Nr,stuckMs:a=Rr,now:i=Date.now,setIntervalImpl:d=setInterval,clearIntervalImpl:T=clearInterval,log:p=console}={}){let u=null,w=()=>{u?.timer&&T(u.timer),u=null},x=async()=>{if(!u)return;let b=!0;try{b=await e()!==!1}catch{b=!0}if(b){if(!u.stuckFired&&i()-u.since>=a){u.stuckFired=!0;try{await n?.({to:u.to,from:u.from,since:u.since})}catch{}}return}let m=u;w();let _=await t({to:m.to,from:m.from,kind:m.kind,reason:"auto"});p.log?.(`[self-update] stasis reached \u2192 ${_.ok?"started":`not started: ${_.reason}`}`);try{await r?.({...m,result:_})}catch{}};return{arm({to:b,from:m=be,kind:_=se()}){return u?.to===b?!1:(w(),u={to:b,from:m,kind:_,since:i(),stuckFired:!1,timer:d(x,o)},u.timer.unref?.(),!0)},tick:x,cancel:w,get armed(){return u?{to:u.to,from:u.from,kind:u.kind,since:u.since}:null}}}var be,$r,Ye,_e,Rr,Nr,Se,B,Pr,Ge,Dr,Qt=S(()=>{ze();qt();be=(()=>{try{return Er(import.meta.url)("../package.json").version||null}catch{return null}})(),$r=process.env.BOSTRAT_STATE_DIR||$.join(process.env.HOME||Ar.tmpdir(),".bostrat"),Ye=$.join($r,"self-update"),_e=$.join(Ye,"status.json"),Rr=1440*6e4,Nr=6e4,Se=new Set(["npm-global","git-checkout"]);B=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Pr=new Set(["updating","restarting","rolling-back"]),Ge=e=>!!(e&&Pr.has(e.status));Dr=45*6e4});$e();Me();import L from"node:fs";import v from"node:path";import ae from"node:os";import{createRequire as Ve}from"node:module";import{execFile as Br,spawn as Lr}from"node:child_process";import{promisify as Ur}from"node:util";import Hr from"node:readline/promises";import{randomUUID as Kr}from"node:crypto";import{fileURLToPath as Wr}from"node:url";var X=Ur(Br),Je=v.dirname(Wr(import.meta.url)),Q=v.resolve(Je,".."),zr=v.join(Je,"index.js"),Yr="wss://plane.bostrat.ai/v1/node",en=Ve(import.meta.url)("../package.json").version,P=(e,t)=>({name:e,level:"pass",detail:t}),G=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),H=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function qr(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?P("node runtime",`${process.version} at ${process.execPath}`):H("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Gr(e){let t;try{t=L.statSync(e)}catch{return G("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?G("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):P("node.env",`${e} (0600)`)}async function Vr(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await X(t,["-V"],{timeout:5e3});return P("tmux",`${t} (${n.trim()})`)}catch{return H("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function tn(e,{required:t=!1}={}){if(await De(e,{loginShell:!0,failOpen:!1}))return P(e,"resolves on the login-shell PATH");let r="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",o=he[e]?`${he[e]}${e==="cursor-agent"?" # installs to ~/.local/bin \u2014 ensure your login shell has it on PATH":""}`:`install ${e} so \`$SHELL -lic 'command -v ${e}'\` finds it`;return t?H(e,r,o):G(e,r,o)}async function Jr(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await X(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return P("gh (GitHub CLI)",n)}catch{return G("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",he.gh)}}async function Xr(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>tn(t)));return e.some(t=>t.level==="pass")||e.push(H("agent CLIs","no agent CLI found at all \u2014 a node with nothing to drive","install at least one of claude / codex / cursor-agent")),e}async function Zr(){let e=[...process.platform==="linux"?[["fuser","stopped views can't free their ports (they leak, and the port can't be reused)","apt install psmisc"]]:[],["pgrep","agent-swap can't detect an idle pane shell \u2014 swaps may misfire","apt install procps"],["npm","codex auto-update and `npm run` views are unavailable","install Node.js with npm on the service PATH"]];return Promise.all(e.map(async([t,n,r])=>await De(t,{failOpen:!1})?P(t,"resolves on the service PATH"):G(t,`not on the service PATH \u2014 ${n}`,r)))}async function Qr(){try{let t=Ve(v.join(Q,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let o=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),a=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(a),n()})}),P("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${Q} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Ve(v.join(Q,"package.json")),r=v.join(v.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");L.existsSync(r)&&!(L.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return H("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function eo(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";return L.existsSync(t)?P("chromium (mocks)",t):G("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable`,"install Chromium/Chrome and set BOSTRAT_CHROMIUM_BIN")}function to(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?H("claude lane","BOSTRAT_CLAUDE_USE_API_KEY=1 but ANTHROPIC_API_KEY is empty","add the key to node.env or set the flag to 0"):P("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function no(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return G("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),o=ce(e.BOSTRAT_PLANE_URL);return await new Promise(a=>{let i=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),d=p=>{clearTimeout(T);try{i.close()}catch{}a(p)},T=setTimeout(()=>d(H("plane link",`no hello_ok within 5s from ${o}`,"check the URL, the token, and the plane's IP gate")),5e3);i.on("open",()=>i.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${Kr().slice(0,8)}`,ephemeral:!0}))),i.on("message",p=>{try{let u=JSON.parse(p);u.type==="hello_ok"?d(P("plane link",`hello_ok in ${Date.now()-r}ms (${o})`)):u.type==="error"&&d(H("plane link",`plane said: ${u.code} ${u.message||""}`,"check the token"))}catch{}}),i.on("error",p=>d(H("plane link",`${p?.message||p}`,"check the URL, the token, and the plane's IP gate")))})}function ro(){let e;try{e=JSON.parse(L.readFileSync(v.join(Ee,"content-outbox.json"),"utf8"))}catch{return P("content outbox","empty \u2014 every deliverable has reached the plane")}let t=e.ops?.length||0,n=e.parked?.length||0;if(n){let r=e.parked[0];return H("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?G("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):P("content outbox",t?`${t} op(s) in flight`:"drained")}function oo(e){return e.BOSTRAT_STATE_REMOTE?P("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):G("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}async function nn(e,t={}){let n=[];return n.push(await qr()),n.push(Gr(t.envFile||ne())),n.push(await Vr(e)),n.push(...await Xr()),n.push(await tn("git",{required:!0})),n.push(await Jr()),n.push(...await Zr()),n.push(await Qr()),n.push(eo(e)),n.push(to(e)),n.push(await no(e,t)),n.push(ro()),n.push(oo(e)),n}function rn(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let a of e)t(`${n[a.level]} ${a.name}: ${a.detail}`),a.fix&&a.level!=="pass"&&t(` fix: ${a.fix}`);let r=e.filter(a=>a.level==="fail").length,o=e.filter(a=>a.level==="warn").length;return t(r?`
144
144
  FAIL \u2014 ${r} blocking, ${o} warnings`:`
145
- OK \u2014 0 blocking, ${o} warnings`),r===0}async function ro({envFile:e=ne(),input:t=process.stdin,output:n=process.stdout}={}){let r=fe(e),o=Lr.createInterface({input:t,output:n}),s=async(M,w)=>(await o.question(w?`${M} [${w}]: `:`${M}: `)).trim()||w||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
145
+ OK \u2014 0 blocking, ${o} warnings`),r===0}async function so({envFile:e=ne(),input:t=process.stdin,output:n=process.stdout}={}){let r=me(e),o=Hr.createInterface({input:t,output:n}),a=async(F,y)=>(await o.question(y?`${F} [${y}]: `:`${F}: `)).trim()||y||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
146
146
  you type those inside each box, later (box-auth-policy).
147
147
 
148
- `);let i=await s("Plane URL",r.BOSTRAT_PLANE_URL||Wr),d=ce(i);d!==i.trim()&&n.write(` \u2192 using ${d}
149
- `);let b=await s("Node token (minted plane-side; stored 0600)",r.BOSTRAT_PLANE_TOKEN),f=await s("Owner userId (just press Enter \u2014 the plane infers it from your token)",r.BOSTRAT_OWNER||"");f&&!/^user_[A-Za-z0-9]+$/.test(f)&&n.write(` ! that doesn't look like a Clerk userId (user_\u2026) \u2014 leave it empty next time and the plane infers the owner from the token; saved as typed.
150
- `);let u=await s("Node name",r.BOSTRAT_NODE_NAME||ae.hostname().split(".")[0]),T=await s("Repos root",r.BOSTRAT_REPOS_ROOT||k.join(ae.homedir(),"Documents")),m=await s("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),x=(await s("Route NEW claude boxes through a BYO API key? (y/N)",r.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");x&&n.write(`
148
+ `);let i=await a("Plane URL",r.BOSTRAT_PLANE_URL||Yr),d=ce(i);d!==i.trim()&&n.write(` \u2192 using ${d}
149
+ `);let T=await a("Node token (minted plane-side; stored 0600)",r.BOSTRAT_PLANE_TOKEN),p=await a("Owner userId (just press Enter \u2014 the plane infers it from your token)",r.BOSTRAT_OWNER||"");p&&!/^user_[A-Za-z0-9]+$/.test(p)&&n.write(` ! that doesn't look like a Clerk userId (user_\u2026) \u2014 leave it empty next time and the plane infers the owner from the token; saved as typed.
150
+ `);let u=await a("Node name",r.BOSTRAT_NODE_NAME||ae.hostname().split(".")[0]),w=await a("Repos root",r.BOSTRAT_REPOS_ROOT||v.join(ae.homedir(),"Documents")),x=await a("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),b=(await a("Route NEW claude boxes through a BYO API key? (y/N)",r.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");b&&n.write(`
151
151
  BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
152
152
  injected per box, stored 0600 in node.env, never sent to the plane.
153
153
  \u2022 create/copy a key: https://console.anthropic.com/settings/keys
154
154
  \u2022 set a monthly spend limit while you're there \u2014 the key is live.
155
155
 
156
- `);let S=x?await s("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";x&&S&&!/^sk-ant-/.test(S)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
157
- `),o.close();let h={...tt(),...r,BOSTRAT_PLANE_URL:d,BOSTRAT_PLANE_TOKEN:b,BOSTRAT_OWNER:f,BOSTRAT_NODE_NAME:u,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||u,BOSTRAT_REPOS_ROOT:T,BOSTRAT_STATE_REMOTE:m,BOSTRAT_CLAUDE_USE_API_KEY:x?"1":"0",ANTHROPIC_API_KEY:x?S:r.ANTHROPIC_API_KEY};et(e,h,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
156
+ `);let m=b?await a("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";b&&m&&!/^sk-ant-/.test(m)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
157
+ `),o.close();let _={...rt(),...r,BOSTRAT_PLANE_URL:d,BOSTRAT_PLANE_TOKEN:T,BOSTRAT_OWNER:p,BOSTRAT_NODE_NAME:u,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||u,BOSTRAT_REPOS_ROOT:w,BOSTRAT_STATE_REMOTE:x,BOSTRAT_CLAUDE_USE_API_KEY:b?"1":"0",ANTHROPIC_API_KEY:b?m:r.ANTHROPIC_API_KEY};nt(e,_,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
158
158
  0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
159
159
  Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
160
160
  wrote ${e}
161
161
 
162
- `);let O={...h,...process.env},N=await en(O,{envFile:e}),v=tn(N,M=>n.write(M+`
163
- `));return v&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:v,results:N}}function oo({envFile:e=ne()}={}){Qe(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=Fr(t,[Kr],{cwd:J,stdio:"inherit",env:process.env});for(let r of["SIGINT","SIGTERM"])process.on(r,()=>n.kill(r));return n.on("exit",(r,o)=>process.exit(o?1:r??1)),n}function so({agentDir:e=J,nodeBin:t=process.execPath,envFile:n=ne(),home:r=ae.homedir()}={}){let o=k.dirname(t),s=k.join(k.basename(Ge),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
162
+ `);let M={..._,...process.env},k=await nn(M,{envFile:e}),A=rn(k,F=>n.write(F+`
163
+ `));return A&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:A,results:k}}function ao({envFile:e=ne()}={}){tt(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=Lr(t,[zr],{cwd:Q,stdio:"inherit",env:process.env});for(let r of["SIGINT","SIGTERM"])process.on(r,()=>n.kill(r));return n.on("exit",(r,o)=>process.exit(o?1:r??1)),n}function io({agentDir:e=Q,nodeBin:t=process.execPath,envFile:n=ne(),home:r=ae.homedir()}={}){let o=v.dirname(t),a=v.join(v.basename(Je),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
164
164
  # ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
165
165
  [Unit]
166
166
  Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
@@ -170,7 +170,7 @@ After=default.target
170
170
  Type=simple
171
171
  WorkingDirectory=${e}
172
172
  # Pinned runtime: node-pty is compiled against exactly this node (SEGV trap).
173
- ExecStart=${t} --disable-warning=ExperimentalWarning ${s}
173
+ ExecStart=${t} --disable-warning=ExperimentalWarning ${a}
174
174
  EnvironmentFile=${n}
175
175
  # systemd's user PATH omits ~/.local/bin (cursor-agent, bostrat-view) and the
176
176
  # nvm bin dir \u2014 both are load-bearing for box spawning.
@@ -180,7 +180,7 @@ RestartSec=2
180
180
 
181
181
  [Install]
182
182
  WantedBy=default.target
183
- `}function ao({agentDir:e=J,nodeBin:t=process.execPath,home:n=ae.homedir()}={}){let r=k.dirname(t),o=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
183
+ `}function co({agentDir:e=Q,nodeBin:t=process.execPath,home:n=ae.homedir()}={}){let r=v.dirname(t),o=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
184
184
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
185
185
  <plist version="1.0">
186
186
  <dict>
@@ -202,7 +202,7 @@ WantedBy=default.target
202
202
  <key>StandardErrorPath</key><string>${o}/node.err.log</string>
203
203
  </dict>
204
204
  </plist>
205
- `}function io(e=process.platform,t=ae.homedir()){return e==="darwin"?{kind:"launchd",file:k.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:k.join(t,".config","systemd","user","bostrat-node.service")}}async function co({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=J}={}){let{kind:s,file:i}=io(n);if(!e&&o.split(k.sep).includes("_npx"))return r("\u2717 running from the npx cache \u2014 a service must point at a durable install."),r(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){s==="systemd"?(await V("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),B.rmSync(i,{force:!0}),await V("systemctl",["--user","daemon-reload"])):(await V("launchctl",["unload","-w",i]).catch(()=>{}),B.rmSync(i,{force:!0})),r(`removed ${i}`);return}B.mkdirSync(k.dirname(i),{recursive:!0}),s==="systemd"?(B.writeFileSync(i,so()),await V("systemctl",["--user","daemon-reload"]),t&&await V("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${i}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(B.mkdirSync(k.join(ae.homedir(),"Library","Logs","bostrat"),{recursive:!0}),B.writeFileSync(i,ao()),t&&await V("launchctl",["load","-w",i]),r(`installed ${i}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function ri(e=process.argv.slice(2)){let t=e[0],n=ne();if(t==="--version"||t==="-v"||t==="version")return console.log(Zt),0;if(t==="init")return(await ro({envFile:n})).ok?0:1;if(t==="doctor"){let r={...fe(n),...process.env};return tn(await en(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return oo({envFile:n}),null;if(t==="install-service")return await co({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(At(),xt));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:s}=await Promise.resolve().then(()=>(Jt(),Xt)),{detectInstallKind:i}=await Promise.resolve().then(()=>(Ke(),Kt)),d=i(),b=e.indexOf("--to"),f=b>=0?String(e[b+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Zt,installKind:d,policy:s({kind:d}),status:await o()},null,2)),0;if(!f)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let u=await r({to:f,kind:d,reason:"cli"});return u.ok?(console.log(`\u2713 self-update ${u.from??"?"} \u2192 ${u.to} started (${u.kind}) \u2014 status: ${u.statusFile}; the service restarts when the install completes`),0):(console.error(`\u2717 not started: ${u.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
205
+ `}function lo(e=process.platform,t=ae.homedir()){return e==="darwin"?{kind:"launchd",file:v.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:v.join(t,".config","systemd","user","bostrat-node.service")}}async function uo({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=Q}={}){let{kind:a,file:i}=lo(n);if(!e&&o.split(v.sep).includes("_npx"))return r("\u2717 running from the npx cache \u2014 a service must point at a durable install."),r(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){a==="systemd"?(await X("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),L.rmSync(i,{force:!0}),await X("systemctl",["--user","daemon-reload"])):(await X("launchctl",["unload","-w",i]).catch(()=>{}),L.rmSync(i,{force:!0})),r(`removed ${i}`);return}L.mkdirSync(v.dirname(i),{recursive:!0}),a==="systemd"?(L.writeFileSync(i,io()),await X("systemctl",["--user","daemon-reload"]),t&&await X("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${i}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(L.mkdirSync(v.join(ae.homedir(),"Library","Logs","bostrat"),{recursive:!0}),L.writeFileSync(i,co()),t&&await X("launchctl",["load","-w",i]),r(`installed ${i}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function ci(e=process.argv.slice(2)){let t=e[0],n=ne();if(t==="--version"||t==="-v"||t==="version")return console.log(en),0;if(t==="init")return(await so({envFile:n})).ok?0:1;if(t==="doctor"){let r={...me(n),...process.env};return rn(await nn(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return ao({envFile:n}),null;if(t==="install-service")return await uo({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(At(),vt));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:a}=await Promise.resolve().then(()=>(Qt(),Zt)),{detectInstallKind:i}=await Promise.resolve().then(()=>(ze(),zt)),d=i(),T=e.indexOf("--to"),p=T>=0?String(e[T+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:en,installKind:d,policy:a({kind:d}),status:await o()},null,2)),0;if(!p)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let u=await r({to:p,kind:d,reason:"cli"});return u.ok?(console.log(`\u2713 self-update ${u.from??"?"} \u2192 ${u.to} started (${u.kind}) \u2014 status: ${u.statusFile}; the service restarts when the install completes`),0):(console.error(`\u2717 not started: ${u.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
206
206
 
207
207
  usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
208
208
 
@@ -211,4 +211,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
211
211
  run start the node in the foreground (sources node.env)
212
212
  install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
213
213
  fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
214
- self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{ro as init,co as installService,ao as launchdPlist,ri as main,tn as printDoctor,oo as runAgent,en as runDoctor,io as servicePaths,so as systemdUnit};
214
+ self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{so as init,uo as installService,co as launchdPlist,ci as main,rn as printDoctor,ao as runAgent,nn as runDoctor,lo as servicePaths,io as systemdUnit};