bostrat-node 1.15.0 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +19 -19
- package/dist/index.js +236 -235
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var es=Object.defineProperty;var
|
|
1
|
+
var es=Object.defineProperty;var A=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var nn=(e,t)=>{for(var n in t)es(e,n,{get:t[n],enumerable:!0})};import gt from"node:fs";import rn from"node:path";import ts from"node:os";function tt(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 i={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return i?(r.protocol=i,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function St(e){let t;try{t=gt.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
|
|
2
2
|
`)){let i=r.trim();if(!i||i.startsWith("#"))continue;let a=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(i);if(!a)continue;let d=a[2].trim();(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))&&(d=d.slice(1,-1)),n[a[1]]=d}return n}function ar(e,t=process.env){let n=St(e);for(let[r,i]of Object.entries(n))r in t||(t[r]=i);return n}function cr(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
|
|
3
3
|
`).map(i=>i?`# ${i}`:"#"));for(let[i,a]of Object.entries(t))a==null||a===""||r.push(`${i}=${a}`);gt.mkdirSync(rn.dirname(e),{recursive:!0}),gt.writeFileSync(e,r.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`,{mode:384}),gt.chmodSync(e,384)}function lr(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 Tt,Ce,on=
|
|
6
|
-
`))if(d.trim())try{a.push(JSON.parse(vs(d)?
|
|
5
|
+
`,{mode:384}),gt.chmodSync(e,384)}function lr(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 Tt,Ce,on=A(()=>{Tt=process.env.BOSTRAT_STATE_DIR||rn.join(process.env.HOME||ts.tmpdir(),".bostrat"),Ce=()=>rn.join(Tt,"node.env")});var ae,nt,_t=A(()=>{ae="BOSTRAT_HOOK_TOKEN",nt="x-bostrat-hook"});var ur=A(()=>{_t()});var ns,Ha,dr=A(()=>{ns="check_for_update_on_startup",Ha=`${ns} = false`});import rs from"node:os";import fr from"node:path";var os,Va,Ya,sn=A(()=>{an();os=process.env.BOSTRAT_DEBUG_DIR||fr.join(rs.homedir(),".bostrat","debug"),Va=fr.join(os,"handoff.jsonl"),Ya=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as is}from"node:child_process";import{promisify as as}from"node:util";function cn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var ec,tc,nc,rc,ln=A(()=>{sn();ec=as(is),tc=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,nc=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,rc=Promise.resolve()});var pr=A(()=>{});import un from"node:path";import{execFile as cs}from"node:child_process";import{promisify as ls}from"node:util";var lc,hr,us,uc,dc,mr=A(()=>{lc=ls(cs),hr=process.env.HOME||"/home/globo",us=un.join(process.env.BOSTRAT_STATE_DIR||un.join(hr,".bostrat"),"repos"),uc=[...(process.env.BOSTRAT_REPOS_ROOT||un.join(hr,"Documents")).split(","),us].map(e=>e.trim()).filter(Boolean),dc=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function xt(e=Date.now()){if(ve)return{tripped:!1,holdMs:1/0};if(be>e)return{tripped:!1,holdMs:be-e};if((!ot||e-ot>=bt.windowMs)&&(ot=e,rt=0),rt++,rt<bt.trip)return{tripped:!1,holdMs:0};vt++;let t=Math.min(bt.minMs*2**(vt-1),bt.maxMs);return be=e+t,rt=0,ot=0,{tripped:!0,holdMs:t}}function wr(){rt=0,ot=0,vt=0,be=0}function st(e=Date.now()){return ve?1/0:be>e?be-e:0}function At(e=Date.now()){return st(e)>0}function dn(e={}){ve={at:Date.now(),...e},be=1/0}function fn(){return ve}function yr(e=Date.now()){return{held:At(e),holdMs:ve?null:st(e),holds:vt,removed:ve?{...ve}:null}}var ds,bt,rt,ot,vt,be,ve,pn=A(()=>{ds={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},bt={...ds},rt=0,ot=0,vt=0,be=0,ve=null});import gr from"node:path";import fs from"node:os";import{execFile as ps}from"node:child_process";import{promisify as hs}from"node:util";var _c,ms,bc,vc,xc,hn=A(()=>{mr();pn();_c=hs(ps),ms=process.env.BOSTRAT_STATE_DIR||gr.join(process.env.HOME||fs.tmpdir(),".bostrat"),bc=gr.join(ms,"repos"),vc=5*6e4,xc=10*6e4});var Tr=A(()=>{hn()});import ys from"node:fs/promises";import it from"node:path";import gs from"node:os";import{EventEmitter as Ts}from"node:events";function Ss(e){return e?.cwd?it.join(e.cwd,".bostrat","events"):it.join(Sr,"events")}async function kt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?it.join(Sr,"events"):Ss(e));let i;try{i=await ys.readFile(_s(n,r),"utf8")}catch{return[]}let a=[];for(let d of i.split(`
|
|
6
|
+
`))if(d.trim())try{a.push(JSON.parse(vs(d)?xs(d):d))}catch{}return a}var at,Sr,_s,bs,vs,xs,$t=A(()=>{at=new Ts;at.setMaxListeners(0);Sr=process.env.BOSTRAT_STATE_DIR||it.join(process.env.HOME||gs.tmpdir(),".bostrat");_s=(e,t)=>it.join(e,`${t}.ndjson`),bs=/(?<!\\)((?:\\\\)*)\\u0000/g,vs=e=>e.includes("\\u0000"),xs=e=>e.replace(bs,"$1\\ufffd")});import ks from"node:os";import $s from"node:path";import{execFile as Es}from"node:child_process";import{promisify as Os}from"node:util";var Uc,Hc,Wc,Kc,Gc,zc,_r=A(()=>{Tr();$t();Uc=Os(Es),Hc=process.env.BOSTRAT_STATE_DIR||$s.join(process.env.HOME||ks.tmpdir(),".bostrat"),Wc=25*1024,Kc=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,Gc=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,zc=Promise.resolve()});var Et=A(()=>{});var Jc,vr=A(()=>{hn();Et();Jc=60*6e4});var xr=A(()=>{vr()});import Ar from"node:path";import Rs from"node:os";var De,Ns,ll,mn,ul,dl,fl,kr=A(()=>{_t();De="BOSTRAT_NODE_URL",Ns=process.env.BOSTRAT_STATE_DIR||Ar.join(process.env.HOME||Rs.tmpdir(),".bostrat"),ll=Ar.join(Ns,"git-hooks"),mn=`#!/bin/sh
|
|
7
7
|
# bostrat git hook shim (agent/src/git-hooks.js) \u2014 chains to the repo's own hook,
|
|
8
8
|
# then stamps/reports for rework attribution when running inside a bostrat box.
|
|
9
9
|
hook=$(basename "$0")
|
|
@@ -47,7 +47,7 @@ exit 0
|
|
|
47
47
|
curl -sS -m 3 -X POST "$${De}/api/deps/refresh" \\
|
|
48
48
|
-H 'content-type: application/json' -H "${nt}: $${ae}" --data-binary '{}' >/dev/null 2>&1 || true
|
|
49
49
|
exit 0
|
|
50
|
-
`});import ct from"node:fs/promises";import Er from"node:os";import Be from"node:path";import{execFile as Is}from"node:child_process";import{promisify as Ms}from"node:util";function Rr(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function Nr(e=process.env){let t=String(e.BOSTRAT_BOX_CGROUPS??"").trim().toLowerCase();return["1","on","true","yes"].includes(t)?"on":["0","off","false","no"].includes(t)?"off":"auto"}function Bs(e=process.env){let t=Nr(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function Ls(e=Er.totalmem()){return Math.max(e-Cs*Or,Math.floor(e/2))}function js(e=process.env){return Be.join(Rr(e),Ds)}async function Fs(e){return(await ct.readFile(e,"utf8")).trim()}async function Ir({env:e=process.env,totalBytes:t=Er.totalmem(),force:n=!1}={}){if(!n&&!Bs(e))return Le={available:!1,reason:Nr(e)==="off"?"disabled (BOSTRAT_BOX_CGROUPS=0)":"not a Fly/container node (systemd owns the tree here)"},Le;let r=Rr(e),i=js(e);try{let a;try{a=(await Fs(Be.join(r,"cgroup.controllers"))).split(/\s+/).filter(Boolean)}catch(g){throw new Error(`no cgroup v2 tree at ${r} (${g?.code||g?.message||g})`)}let d=["cpu","memory"].filter(g=>a.includes(g));if(!d.length)throw new Error(`cgroup v2 at ${r} offers neither cpu nor memory (controllers: ${a.join(" ")||"none"})`);await ct.mkdir(i,{recursive:!0});let h=`+${d.join(" +")}`;for(let g of[Be.join(r,"cgroup.subtree_control"),Be.join(i,"cgroup.subtree_control")])try{await ct.writeFile(g,h)}catch(f){throw new Error(`cannot enable ${h} in ${g} (${f?.code||f?.message||f})`)}let m=Ls(t);d.includes("cpu")&&await ct.writeFile(Be.join(i,"cpu.weight"),String($r)),d.includes("memory")&&await ct.writeFile(Be.join(i,"memory.max"),String(m)),Le={available:!0,path:i,controllers:d,cpuWeight:d.includes("cpu")?$r:null,memoryMaxMb:d.includes("memory")?Math.round(m/Or):null}}catch(a){Le={available:!1,reason:a?.message||String(a)}}return Le}function Mr(e=Le){let t=`nice ${Ps} floor on every box`;if(!e)return`${t}; cgroup ceiling not probed yet`;if(e.available){let n=[];return e.cpuWeight!=null&&n.push(`cpu.weight ${e.cpuWeight}`),e.memoryMaxMb!=null&&n.push(`memory.max ${e.memoryMaxMb} MB`),`${t}; cgroup ceiling at ${e.path} (${n.join(", ")})`}return`${t}; cgroup ceiling unavailable \u2014 ${e.reason}`}var Tl,Ps,$r,Cs,Ds,Or,Le,wn=
|
|
50
|
+
`});import ct from"node:fs/promises";import Er from"node:os";import Be from"node:path";import{execFile as Is}from"node:child_process";import{promisify as Ms}from"node:util";function Rr(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function Nr(e=process.env){let t=String(e.BOSTRAT_BOX_CGROUPS??"").trim().toLowerCase();return["1","on","true","yes"].includes(t)?"on":["0","off","false","no"].includes(t)?"off":"auto"}function Bs(e=process.env){let t=Nr(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function Ls(e=Er.totalmem()){return Math.max(e-Cs*Or,Math.floor(e/2))}function js(e=process.env){return Be.join(Rr(e),Ds)}async function Fs(e){return(await ct.readFile(e,"utf8")).trim()}async function Ir({env:e=process.env,totalBytes:t=Er.totalmem(),force:n=!1}={}){if(!n&&!Bs(e))return Le={available:!1,reason:Nr(e)==="off"?"disabled (BOSTRAT_BOX_CGROUPS=0)":"not a Fly/container node (systemd owns the tree here)"},Le;let r=Rr(e),i=js(e);try{let a;try{a=(await Fs(Be.join(r,"cgroup.controllers"))).split(/\s+/).filter(Boolean)}catch(g){throw new Error(`no cgroup v2 tree at ${r} (${g?.code||g?.message||g})`)}let d=["cpu","memory"].filter(g=>a.includes(g));if(!d.length)throw new Error(`cgroup v2 at ${r} offers neither cpu nor memory (controllers: ${a.join(" ")||"none"})`);await ct.mkdir(i,{recursive:!0});let h=`+${d.join(" +")}`;for(let g of[Be.join(r,"cgroup.subtree_control"),Be.join(i,"cgroup.subtree_control")])try{await ct.writeFile(g,h)}catch(f){throw new Error(`cannot enable ${h} in ${g} (${f?.code||f?.message||f})`)}let m=Ls(t);d.includes("cpu")&&await ct.writeFile(Be.join(i,"cpu.weight"),String($r)),d.includes("memory")&&await ct.writeFile(Be.join(i,"memory.max"),String(m)),Le={available:!0,path:i,controllers:d,cpuWeight:d.includes("cpu")?$r:null,memoryMaxMb:d.includes("memory")?Math.round(m/Or):null}}catch(a){Le={available:!1,reason:a?.message||String(a)}}return Le}function Mr(e=Le){let t=`nice ${Ps} floor on every box`;if(!e)return`${t}; cgroup ceiling not probed yet`;if(e.available){let n=[];return e.cpuWeight!=null&&n.push(`cpu.weight ${e.cpuWeight}`),e.memoryMaxMb!=null&&n.push(`memory.max ${e.memoryMaxMb} MB`),`${t}; cgroup ceiling at ${e.path} (${n.join(", ")})`}return`${t}; cgroup ceiling unavailable \u2014 ${e.reason}`}var Tl,Ps,$r,Cs,Ds,Or,Le,wn=A(()=>{Tl=Ms(Is),Ps=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),$r=50,Cs=768,Ds="bostrat-boxes",Or=1024*1024;Le=null});import{execFile as Us}from"node:child_process";import{promisify as Hs}from"node:util";import Dr from"node:fs";import Ws from"node:os";function Br(e){return`/tmp/tmux-${e}/default`}function Gs({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let i=Br(r);return t?i:n?`${n}/bostrat/tmux-default`:i}async function gn(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Vs(e,{loginShell:t});return r===Lr?!0:r===yn?!1:n}async function Vs(e,{loginShell:t=!1,timeoutMs:n=zs}={}){if(!e)return yn;let r=t?process.env.SHELL||"/bin/sh":"sh",i=t?"-lic":"-c";try{return await Ks(r,[i,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),Lr}catch(a){return a?.killed||a?.signal?Cr:a?.code===1||a?.code===127?yn:Cr}}var Ks,Xl,Pr,Jl,Zl,Ql,eu,tu,Lr,yn,Cr,zs,Ot,nu,ru,ou,su,iu,au,an=A(()=>{ur();dr();ln();pr();_r();xr();sn();_t();kr();wn();Ks=Hs(Us),Xl=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";Pr=typeof process.getuid=="function"?process.getuid():0,Jl=Gs({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Dr.existsSync(Br(Pr))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:Pr}),Zl=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Ql=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",eu=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),tu=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);Lr="present",yn="absent",Cr="unknown",zs=5e3;Ot={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"},nu=(()=>{try{let e=Ws.homedir();if(e&&Dr.existsSync(e))return e}catch{}return"/"})(),ru=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,ou=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,su=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,iu=Number(process.env.BOSTRAT_BOX_COLS)||120,au=Number(process.env.BOSTRAT_BOX_ROWS)||40});var to={};nn(to,{NODE_IMAGE:()=>_n,commandPlan:()=>Zr,flyToml:()=>Jr,flyWizard:()=>li,parseFlyFlags:()=>Qr,stageConfig:()=>eo});import Sn from"node:fs";import xe from"node:path";import ni from"node:os";import ri from"node:readline/promises";import{execFile as oi}from"node:child_process";import{createRequire as si}from"node:module";import{randomUUID as ii}from"node:crypto";function Jr({app:e,region:t,nodeName:n=e,planeUrl:r=Xr,image:i=_n}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
|
|
51
51
|
# Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
|
|
52
52
|
# No [http_service] and none should be added: the node dials OUT to the plane;
|
|
53
53
|
# nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
|
|
@@ -89,14 +89,14 @@ swap_size_mb = 1024
|
|
|
89
89
|
memory = "2gb"
|
|
90
90
|
`}function Zr({app:e,org:t,region:n,sizeGb:r,token:i,dir:a}){let d=[`BOSTRAT_PLANE_TOKEN=${i}`];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> via stdin`,stdin:d.join(`
|
|
91
91
|
`)+`
|
|
92
|
-
`},{argv:["deploy",a,"-c",
|
|
93
|
-
`),d[0];if(d.length>1)return await e(`Fly org (${d.join(" / ")})`,d[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function li({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:i}={}){let a=Qr(e),d=ri.createInterface({input:t,output:n}),h=async(_,
|
|
92
|
+
`},{argv:["deploy",a,"-c",xe.join(a,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${a} -c ${xe.join(a,"fly.toml")} -a ${e} --ha=false`}]}function Qr(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--image":"image"};for(let r=0;r<e.length;r++){let i=e[r];if(i==="--yes"||i==="-y")t.yes=!0;else if(n[i])t[n[i]]=e[++r]??"";else if(i.startsWith("--")&&i.includes("=")){let[a,...d]=i.split("=");n[a]?t[n[a]]=d.join("="):a==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function eo({app:e,dest:t,toml:n}){let r=t||xe.join(ni.homedir(),".bostrat","fly",e);Sn.mkdirSync(r,{recursive:!0});for(let i of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])Sn.rmSync(xe.join(r,i),{recursive:!0,force:!0});return Sn.writeFileSync(xe.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function ci({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:i}=await Rt(["orgs","list","--json"],{exec:n}),a=JSON.parse(i),d=Array.isArray(a)?a.map(h=>h.Slug||h.slug).filter(Boolean):Object.keys(a);if(d.length===1)return t.write(`Org: ${d[0]} (your only org)
|
|
93
|
+
`),d[0];if(d.length>1)return await e(`Fly org (${d.join(" / ")})`,d[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function li({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:i}={}){let a=Qr(e),d=ri.createInterface({input:t,output:n}),h=async(_,x)=>(await d.question(x?`${_} [${x}]: `:`${_}: `)).trim()||x||"",m=_=>(d.close(),_);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
|
|
94
94
|
bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
|
|
95
95
|
|
|
96
96
|
`);try{await Rt(["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"),m(1)}try{let{stdout:_}=await Rt(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${_.trim()}
|
|
97
97
|
`)}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"),m(1)}let g=await ci({ask:h,output:n,exec:r,flag:a.org}),f=a.app||await h("App name",`bostrat-node-${ii().slice(0,4)}`),S=a.region||await h("Region (see `fly platform regions`)","iad"),$=a.sizeGb||Number(await h("Volume size GB (logins + repos live here)","10"))||10,b=a.name||f,v=a.planeUrl||Xr,R=a.token||await h("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!R)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.
|
|
98
98
|
`),m(1);let E=a.image||_n,{dir:P}=eo({app:f,dest:i,toml:Jr({app:f,region:S,nodeName:b,planeUrl:v,image:E})});n.write(`
|
|
99
|
-
wrote ${
|
|
99
|
+
wrote ${xe.join(P,"fly.toml")} \u2014 deploys the prebuilt node image ${E}
|
|
100
100
|
(claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
|
|
101
101
|
|
|
102
102
|
Plan (your flyctl, your org, your bill):
|
|
@@ -105,10 +105,10 @@ Plan (your flyctl, your org, your bill):
|
|
|
105
105
|
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.
|
|
106
106
|
`),m(1);for(let _ of k){n.write(`
|
|
107
107
|
\u2192 ${_.display}
|
|
108
|
-
`);try{let{stdout:
|
|
108
|
+
`);try{let{stdout:x,stderr:N}=await Rt(_.argv,{stdin:_.stdin,exec:r}),L=`${x||""}${N||""}`.trim();L&&n.write(L.split(`
|
|
109
109
|
`).map(C=>` ${C}`).join(`
|
|
110
110
|
`)+`
|
|
111
|
-
`)}catch(
|
|
111
|
+
`)}catch(x){let N=`${x?.stdout||""}${x?.stderr||""}${x?.message||""}`;if(_.tolerate&&_.tolerate.test(N)){n.write(` (already exists \u2014 continuing)
|
|
112
112
|
`);continue}return n.write(`\u2717 failed: ${N.trim().split(`
|
|
113
113
|
`).slice(-4).join(`
|
|
114
114
|
`)}
|
|
@@ -117,11 +117,11 @@ Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u201
|
|
|
117
117
|
\u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
|
|
118
118
|
chat: the node step advances on its own within a minute.
|
|
119
119
|
logs: fly logs -a ${f}
|
|
120
|
-
redeploy: fly deploy ${P} -c ${
|
|
120
|
+
redeploy: fly deploy ${P} -c ${xe.join(P,"fly.toml")} -a ${f} --ha=false
|
|
121
121
|
Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
|
|
122
122
|
boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
|
|
123
|
-
`),m(0)}var Xr,ai,_n,Rt,no=x(()=>{Xr="wss://plane.bostrat.ai/v1/node",ai=si(import.meta.url)("../package.json").version,_n=`ghcr.io/globocodes/bostrat-node:${ai}`;Rt=(e,{stdin:t,exec:n}={})=>new Promise((r,i)=>{if(n)return n(e,{stdin:t}).then(r,i);let a=oi("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,h,m)=>d?i(Object.assign(d,{stdout:h,stderr:m})):r({stdout:h,stderr:m}));t!=null&&a.stdin?.end(t)})});function ro(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!di.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 fi(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(i=>({...i,fromMs:ro(i.from,"from",n),toMs:ro(i.to,"to",n)}))}return t}var ui,di,Eu,Ou,oo=x(()=>{ui={"claude-opus-5-5":[{from:null,to:null,input:4,output:20,cacheWrite:8,cacheRead:.2,cacheReadX:.05,fast:{input:8,output:40,cacheWrite:16,cacheRead:.4},verifiedAt:"2026-09-28",note:"verified 2026-09-28 against platform.claude.com/docs/en/about-claude/pricing: $4/$20, 1h cache write $8 (2\xD7), cache hits $0.20 (0.05\xD7 \u2014 footnote 2), fast $8/$40; added before any fleet turn was recorded."}],"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"GA rates; verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-08-17",note:"$2/$10 is the standard price (intro pricing made permanent; the 2026-09-01 $3/$15 increase was cancelled) \u2014 verified 2026-08-17 against platform.claude.com/docs/en/about-claude/pricing."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-fable-5-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-09-07",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-03, re-verified 2026-08-17 (developers.openai.com pricing); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-08-24",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-terra":[{from:null,to:"2026-08-16",input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:2,output:12,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:"2026-08-16",input:1,output:6,cacheWrite:1.25,cacheRead:.1,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:.2,output:1.2,cacheWrite:.25,cacheRead:.02,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-09-07",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed)."}]},di=/^\d{4}-\d{2}-\d{2}$/;Eu=fi(ui),Ou=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var so=x(()=>{oo()});import io from"node:fs/promises";import lo from"node:path";import pi from"node:os";function fo(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function po(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function ho(e){let t=new Date(fo(e));return t.setDate(t.getDate()+7),t.getTime()}function mo(e){let t=new Date(po(e));return t.setMonth(t.getMonth()+1),t.getTime()}function gi(e=Date.now()){for(let[t,n]of Object.entries(wi)){let r=n.startOf(e);if(r!==Nt[t]){Nt[t]=r;for(let i of bn.values())i[t]=0;for(let i of ao)i.includes(`:${t}:`)&&!i.endsWith(`:${r}`)&&ao.delete(i)}}}function Ti(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 i={};for(let a of["weeklyUsd","monthlyUsd"]){let d=r?.[a];if(d==null||d==="")continue;let h=Number(d);if(!Number.isFinite(h)||h<=0)throw new Error(`${n}.${a} must be a positive number or null`);i[a]=h}Object.keys(i).length&&(t[n]=i)}return t}async function wo(e,{source:t="local",updatedAt:n=Date.now()}={}){je={caps:Ti(e),updatedAt:n,source:t};try{await io.mkdir(uo,{recursive:!0}),await io.writeFile(hi(),JSON.stringify(je,null,2))}catch{}return Si()}function Si(e=Date.now()){gi(e);let t=new Set([...bn.keys(),...Object.keys(je?.caps||{})]),n={};for(let r of t){let i=bn.get(r);n[r]={weeklyUsd:co(i?.weekly||0),monthlyUsd:co(i?.monthly||0)}}return{caps:je?.caps||{},configured:!!je,seeded:yi,updatedAt:je?.updatedAt??null,spent:n,windows:{weekly:{start:Nt.weekly,resetsAt:ho(e)},monthly:{start:Nt.monthly,resetsAt:mo(e)}},warnPct:mi}}var uo,hi,mi,wi,je,yi,Nt,bn,ao,co,yo=x(()=>{$t();so();uo=process.env.BOSTRAT_STATE_DIR||lo.join(process.env.HOME||pi.tmpdir(),".bostrat"),hi=()=>lo.join(uo,"usage-caps.json"),mi=.8;wi={weekly:{startOf:fo,nextStart:ho,capKey:"weeklyUsd"},monthly:{startOf:po,nextStart:mo,capKey:"monthlyUsd"}},je=null,yi=!1,Nt={weekly:0,monthly:0},bn=new Map,ao=new Set;co=e=>Math.round(e*1e4)/1e4});var xo={};nn(xo,{REMOVED_MARKER:()=>En,detectInstallKind:()=>He,detectProviderAuth:()=>Ao,maskToken:()=>$n,readRemovedMarker:()=>vo,startPlaneLink:()=>Li,updateCommandFor:()=>dt,versionLt:()=>Ue});import Fe from"node:fs";import ut from"node:fs/promises";import _i from"node:http";import W from"node:path";import Mt from"node:os";import{createRequire as bi}from"node:module";import vn from"ws";function $n(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function vo(e=En){try{let t=JSON.parse(Fe.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function He({env:e=process.env,pkgDir:t=W.resolve(W.dirname(new URL(import.meta.url).pathname),".."),exists:n=Fe.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(W.join(t,"..",".git"))?"git-checkout":"dev"}function Ue(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 i=0;i<Math.max(n.length,r.length);i++){let a=(n[i]||0)-(r[i]||0);if(a)return a<0}return!1}function dt(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 Ao({home:e=process.env.HOME||Mt.homedir(),env:t=process.env}={}){let n=r=>{try{return Fe.statSync(r),!0}catch{return!1}};return{claude:n(W.join(e,".claude",".credentials.json")),codex:n(W.join(t.CODEX_HOME||W.join(e,".codex"),"auth.json")),cursor:n(W.join(t.XDG_CONFIG_HOME||W.join(e,".config"),"cursor","auth.json"))}}function Li({url:e,token:t,nodeId:n=Mt.hostname(),name:r=Mt.hostname(),listTracks:i,detectAgents:a=null,onTracksTransferred:d=null,onTracksMoves:h=null,sampleMetrics:m=null,deliverySample:g=null,onHashKey:f=null,onViewBase:S=null,metricsMs:$=Bi,onUpdateAvailable:b=null,onUpdatePolicy:v=null,onConflictProbe:R=null,restart:E=null,onRestarted:P=null,onHelloRefused:k=null,updatePolicy:_=null,installKind:A=He(),selfUrl:N=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:L=null,removedMarkerFile:C=En,onRemoved:ke=null,onDegraded:Ge=null,onRecovered:$e=null,onRefused:Ft=null,onConnected:pt=null,ingestMode:Ee=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:ze=Ri,unackedRetryMs:Oe=Oi,pingMs:Ve=$i,deadLinkMs:O=Math.round(Ve*Ei),maxInflightEvents:ce=Pi,httpTimeoutMs:le=Ci,fanoutActive:ue=null,fanoutBatchCap:Ye=Di,stallBackoffMinMs:Fn=Mi,fetchImpl:Un=globalThis.fetch,log:y=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof i!="function")throw new Error("plane-link: listTracks is required");e=tt(e);let jo=N.replace(/^http/,"ws"),Hn=new Set,Wn=s=>{let l=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(!(!(l&&Q&&Ue(Q,l))||Hn.has(l))){Hn.add(l),y.log(`[plane-link] bostrat-node ${l} is available (this node runs ${Q}) \u2014 ${dt(A)}`);try{b?.({current:Q,latest:l,min:s.minNodeVersion??null,installKind:A,required:!!(s.minNodeVersion&&Ue(Q,s.minNodeVersion))})}catch(u){y.error(`[plane-link] update notice failed: ${u?.message||u}`)}}},we=new Map,ye=new Map,Ut=W.join(kn,"plane-link","cursor.json"),Ht=W.join(kn,"plane-link","dead-letter.ndjson"),Kn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),ne={},ee={},I=new Map,ht=null,de=null,re=0,qe=0,Gn=0,mt={},zn=new Set,Vn=Promise.resolve(),H="ws",Re=0,Z=!1,ge=0,Wt=!1,fe=It,Ne=new Set,oe=[],z=null,Y=null,q=!1,Kt=!1,Xe=go,Je=null,Gt=E&&typeof E=="object"?E:null,Ie=null,Me=null,se=null,Te=0,Yn=0,ie=null,zt=!1,wt=0,Ze=!1,pe=vo(C);if(pe)if(pe.tokenPreview===$n(t))Ze=!0,dn({reason:pe.reason??"removed",at:pe.at??null,nodeId:pe.nodeId??n}),y.error(`[plane-link] this node was REMOVED from the plane (${pe.reason??"removed"}${pe.at?` at ${new Date(pe.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${C} to force a dial.`);else try{Fe.unlinkSync(C),y.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function Vt({reason:s="removed",at:l=Date.now(),via:u="ctl"}={}){if(!Ze){Ze=!0,dn({reason:s,at:l,nodeId:n,via:u});try{Fe.mkdirSync(W.dirname(C),{recursive:!0}),Fe.writeFileSync(C,JSON.stringify({at:l,reason:s,via:u,nodeId:n,tokenPreview:$n(t)},null,2))}catch(o){y.error(`[plane-link] could not write ${C}: ${o?.message||o}`)}y.error(`[plane-link] the plane REMOVED this node (${s}, via ${u}) \u2014 going dormant: no more dials, ingest or broker calls. Re-provision with a new node token to reconnect; the box and its data are untouched.`);try{ke?.({reason:s,at:l,via:u})}catch{}sr({bye:!1})}}async function Fo(){try{ne=JSON.parse(await ut.readFile(Ut,"utf8"))}catch{ne={}}}function qn(){zt=!0,!Me&&(Me=setTimeout(async()=>{if(Me=null,!!zt){zt=!1;try{await ut.mkdir(W.dirname(Ut),{recursive:!0}),await ut.writeFile(Ut,JSON.stringify(ne))}catch(s){y.error("[plane-link] cursor flush failed:",s?.message||s)}}},ki),Me.unref?.())}function Yt(){try{return!!ue?.()}catch{return!1}}function qt(){let s=H==="http"?fe:It;return Yt()?Math.min(s,Ye):s}function j(s){return!Y||Y.readyState!==vn.OPEN?!1:(Y.send(JSON.stringify(s)),!0)}function Pe(s){let l=Date.now();for(let{trackId:o,event:c}of s){let p=I.get(c.id);I.set(c.id,{trackId:o,seq:c.seq,event:c,sentAt:l,firstSentAt:p?.firstSentAt??l,retryAt:l+Oe,tries:(p?.tries??0)+1,nacks:p?.nacks??0})}let u=s.map(({trackId:o,event:c})=>({trackId:o,event:Ii(c)}));return H==="http"?(zo(u),!0):j({v:F,ch:"events",type:"append",events:u})}function Uo(s){let l=null;for(let u of I.values())u.trackId===s&&(l==null||u.seq<l)&&(l=u.seq);return l}function Xt(s){let l=ee[s];if(l==null)return;let u=Uo(s),o=u==null?l:Math.min(l,u-1);o>(ne[s]??0)&&(ne[s]=o,qn())}function Qe(){if(ht=Date.now(),de!=null){let s=Date.now()-de;y.log(`[plane-link] spine sync recovered after ${Math.round(s/1e3)}s degraded (${re} stall redial(s))`);let l=de;de=null,re=0,qe=0,Z=!1,ge=0;try{$e?.({since:l,downMs:s})}catch(u){y.error(`[plane-link] onRecovered failed: ${u?.message||u}`)}}}function Jt(s){if(!Array.isArray(s)||!s.length)return;let l=new Set;for(let u of s){let o=I.get(u);o&&(I.delete(u),(ee[o.trackId]??0)<o.seq&&(ee[o.trackId]=o.seq),l.add(o.trackId))}for(let u of l)Xt(u);Qe()}function Xn(s,l){Gn++;let u={at:Date.now(),trackId:s.trackId,seq:s.seq,id:s.event?.id??null,type:s.event?.type??null,reason:l,event:s.event??null};y.error(`[plane-link] DEAD-LETTER ${s.trackId} seq ${s.seq} (${u.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${Ht}`),Vn=Vn.then(async()=>{await ut.mkdir(W.dirname(Ht),{recursive:!0}),await ut.appendFile(Ht,JSON.stringify(u)+`
|
|
124
|
-
`)}).catch(o=>y.error(`[plane-link] dead-letter write failed: ${o?.message||o}`))}function Ho(s,l){if(mt[s]=(mt[s]??0)+1,zn.has(s))return;zn.add(s);let u=Ni[s]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";y.error(`[plane-link] REFUSED by the plane (${s}) on track ${l}: events are being dropped, not stored \u2014 ${u}`);try{Ft?.({reason:s,trackId:l,count:mt[s],hint:u})}catch(o){y.error(`[plane-link] onRefused failed: ${o?.message||o}`)}}function Zt(s,l,u,o=null){if(!Array.isArray(s)||!s.length)return;let c=new Set,p=Date.now();for(let w of s){let T=I.get(w);T&&(u?(I.delete(w),Xn(T,l),String(l).startsWith(An)&&Ho(String(l).slice(An.length),T.trackId),(ee[T.trackId]??0)<T.seq&&(ee[T.trackId]=T.seq),c.add(T.trackId)):(T.nacks++,T.retryAt=p+Math.max(1e3,Number(o)||Oe)))}for(let w of c)Xt(w);Qe()}function Jn(s=Date.now()){let l=1/0;for(let u of I.values())u.firstSentAt<l&&(l=u.firstSentAt);return l===1/0?0:s-l}function Wo(s){if(!O||!s||s!==Y||!Te)return!1;let l=Date.now()-Te;if(l<=O)return!1;Yn++,y.error(`[plane-link] no frame from the plane for ${Math.round(l/1e3)}s \u2014 link is half-open; terminating and redialing`);try{s.terminate()}catch{}return!0}function Zn(){if(!q||!I.size)return;let s=Date.now(),l=Jn(s);if(l<ze||ht!=null&&s-ht<ze||H==="http"&&Z||qe>s)return;re++;let u=Math.min(Fn*2**(re-1),So);if(de==null){de=s-l,y.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${I.size} event(s) in flight (${H} door) \u2014 the plane is not answering appends`);try{Ge?.({since:de,unacked:I.size,oldestAgeMs:l,mode:H})}catch(o){y.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(H==="http"){Z=!0,ge=s+u,y.error(`[plane-link] ingest circuit OPEN (stall #${re}); probing /v1/ingest/health in ${Math.round(u/1e3)}s`);return}qe=s+u,y.error(`[plane-link] closing the link and redialing in ${Math.round(u/1e3)}s (stall redial #${re})`);try{Y?.terminate()}catch{}}function Qt(){if(!q)return;let s=Date.now();if(H==="http"&&Z)return;let l=[...I.values()].filter(o=>o.event&&o.retryAt<=s&&!(H==="http"&&Ne.has(o.trackId)));if(!l.length)return;l.sort((o,c)=>o.trackId===c.trackId?o.seq-c.seq:o.trackId<c.trackId?-1:1),y.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let u=qt();if(H==="http"){let o=new Map;for(let c of l)(o.get(c.trackId)??o.set(c.trackId,[]).get(c.trackId)).push(c);for(let[,c]of o){if(Re>=xn)return;Pe(c.slice(0,u).map(p=>({trackId:p.trackId,event:p.event})))}return}for(let o=0;o<l.length;o+=u){let c=l.slice(o,o+u).map(p=>({trackId:p.trackId,event:p.event}));if(!Pe(c))return}}async function Ko(s=null){for(;;){if(!q)return!1;let l=I.size<ce,u=H!=="http"||Re<xn&&!Z&&(!s||!Ne.has(s));if(l&&u)return!0;await new Promise(o=>setTimeout(o,100))}}function en(){if(z=null,!q||!oe.length)return;let s=oe;oe=[];let l=qt();if(H!=="http"){for(let c=0;c<s.length;c+=l)Pe(s.slice(c,c+l));return}let u=Yt(),o=new Map;for(let c of s)(o.get(c.trackId)??o.set(c.trackId,[]).get(c.trackId)).push(c);for(let[c,p]of o){if(Ne.has(c)||Re>=xn||Z){oe.push(...p);continue}if(u){Pe(p.slice(0,l)),oe.push(...p.slice(l));continue}for(let w=0;w<p.length;w+=l)Pe(p.slice(w,w+l))}oe.length&&!z&&(z=setTimeout(en,_o),z.unref?.())}let Go=s=>{let l=new Map;for(let{trackId:u,event:o}of s)(l.get(u)??l.set(u,[]).get(u)).push(o);return[...l].map(([u,o])=>({trackId:u,events:o}))},Se=(s,l,u,{progress:o})=>{let c=Date.now();for(let{event:p}of s){let w=I.get(p.id);w&&(w.nacks++,w.retryAt=c+Math.max(1e3,u||Oe))}o&&Qe()};async function zo(s){let l=new Set(s.map(u=>u.trackId));for(let u of l)Ne.add(u);Re++;try{let u=await Un(`${Kn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:Go(s)}),signal:AbortSignal.timeout(le)}),o=(Number(u.headers.get("retry-after"))||0)*1e3;if(u.status===200){let c=await u.json();fe=It;for(let T of c.results??[]){Jt(T.acked??[]);let D=(te,G)=>{let yt=new Map;for(let _e of te??[])(yt.get(_e.reason)??yt.set(_e.reason,[]).get(_e.reason)).push(_e.id);for(let[_e,ir]of yt)Zt(ir,_e,G,c.retryAfterMs??null)};D(T.rejected,!0),D(T.deferred,!1)}let p=new Set,w=new Map;for(let T of Array.isArray(c.refused)?c.refused:[])!T||typeof T.id!="string"||(p.add(T.id),(w.get(T.reason)??w.set(T.reason,[]).get(T.reason)).push(T.id));for(let[T,D]of w)Zt(D,`${An}${T}`,!0);Jt((c.discarded??[]).filter(T=>!p.has(T))),Qe();return}if(u.status===429){Se(s,"overloaded",o||5e3,{progress:!0});return}if(u.status===413&&s.length>1){fe=Math.max(1,Math.floor(s.length/2)),y.error(`[plane-link] ingest request too large (${s.length} events) \u2014 halving batches to ${fe}`),Se(s,"too_large",1e3,{progress:!0});return}if(u.status===413){let c=I.get(s[0].event.id);c&&(I.delete(c.event.id),Xn(c,"too_large"),(ee[c.trackId]??0)<c.seq&&(ee[c.trackId]=c.seq),Xt(c.trackId)),Qe();return}if(u.status===410){Vt({reason:"removed",via:"410"}),Se(s,"http_410",6e4,{progress:!1});return}if(u.status===401||u.status===403){let{tripped:c,holdMs:p}=At();if(c&&y.error(`[plane-link] holding every plane call for ${Math.round(p/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-wt>=bo){wt=Date.now();let w="";try{w=(await u.json())?.error??""}catch{}y.error(`[plane-link] plane refused ingest (HTTP ${u.status}${w?`: ${w}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}Se(s,`http_${u.status}`,Math.max(6e4,st()),{progress:!1});return}if(u.status===400){y.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${s.length} event(s) for retry; this is a bug, not data`),Se(s,"http_400",6e4,{progress:!1});return}Se(s,`http_${u.status}`,o||5e3,{progress:!1})}catch(u){let o=u?.name==="TimeoutError"||u?.name==="AbortError";o&&s.length>1&&(fe=Math.max(1,Math.floor(s.length/2)),y.error(`[plane-link] ingest request of ${s.length} event(s) outlived its ${le} ms deadline \u2014 halving batches to ${fe}`)),Se(s,o?"timeout":"network",5e3,{progress:!1})}finally{Re--;for(let u of l)Ne.delete(u)}}async function Vo(){if(H!=="http"||!Z||!q||Wt)return;let s=Date.now();if(!(ge>s||xt(s))){Wt=!0;try{let l=await Un(`${Kn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(le)});if(!l.ok)throw new Error(`HTTP ${l.status}`);y.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Z=!1,ge=0,qe=Date.now()+le+Oe+1e3;for(let u of I.values())u.retryAt=Math.min(u.retryAt,Date.now());Qt()}catch(l){re++;let u=Math.min(Fn*2**(re-1),So);ge=Date.now()+u,y.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(u/1e3)}s`)}finally{Wt=!1}}}function Qn(){let s=Date.now();return{mode:H,unacked:I.size,oldestUnackedAgeMs:Jn(s),lastProgressAt:ht,degradedSince:de,stallRedials:re,deadLettered:Gn,fanoutCap:Yt()?Ye:null,http:H==="http"?{inFlight:Re,circuitOpen:Z,nextProbeInMs:Z?Math.max(0,ge-s):0,batchCap:fe}:null}}async function er(){if(!m)return;let s;try{s=await m()}catch(u){y.error("[plane-link] metrics sample failed:",u?.message||u);return}let l=null;try{l=g?.()??null}catch{}s&&j({v:F,ch:"ctl",type:"metrics",metrics:{...s,planeLink:Qn(),...l?{delivery:l}:{}}})}function Yo(){m&&(ie&&clearInterval(ie),er(),ie=setInterval(er,$),ie.unref?.())}async function qo(){let s;try{s=await i()}catch(l){y.error("[plane-link] backfill listTracks failed:",l?.message||l);return}j({v:F,ch:"ctl",type:"tracks",ids:s.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of s)if(!q||!await tr(l))return}async function tr(s){let l;try{l=await kt(s)}catch{return!0}let u=ne[s.id]??0,o=l.filter(c=>c.seq>u&&typeof c.id=="string");for(let c=0;c<o.length;){if(!await Ko(s.id))return!1;let p=o.slice(c,c+qt()).map(w=>({trackId:s.id,event:w}));if(!Pe(p))return!1;c+=p.length}return!0}let tn=new Map;async function nr(s,l){if(tn.get(s)===l)return!1;tn.set(s,l);let u=null;try{u=(await i()).find(w=>w?.id===s)??null}catch{return!1}if(!u)return!1;let o;try{o=await kt(u)}catch{return!1}let c=[...o].reverse().find(w=>(w?.type==="track.transferred"||w?.type==="track.recovered")&&w.payload?.toNode===n);if(!c||!Number.isFinite(c.seq))return!1;let p=c.seq-1;return(ne[s]??0)>p&&(ne[s]=p,qn()),(ee[s]??0)>p&&(ee[s]=p),y.log(`[plane-link] re-sending ${s}'s move-commit (seq ${c.seq}, ${c.type}) \u2014 the plane's move record predates this node's adoption`),q?tr(u):!1}function rr(s){!q||!s?.trackId||typeof s.id!="string"||(oe.push({trackId:s.trackId,event:s}),z||(z=setTimeout(en,_o),z.unref?.()))}let et=new Map;async function Xo(s){let{reqId:l,method:u,path:o,headers:c={},body:p}=s,w=Object.fromEntries(Object.entries(c).filter(([,D])=>D!=null)),T=new AbortController;et.set(l,T);try{if(s.host){await Jo(s,w,T);return}L&&(w["x-bostrat-token"]=L);let D=await fetch(N+o,{method:u,headers:w,body:p?Buffer.from(p,"base64"):void 0,signal:T.signal}),te=Object.fromEntries(D.headers);for(let G of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete te[G];if(te["content-type"]||(te["content-type"]="application/octet-stream"),j({v:F,ch:"control",type:"http_head",reqId:l,status:D.status,headers:te}),D.body){for await(let G of D.body)if(!j({v:F,ch:"control",type:"http_data",reqId:l,data:Buffer.from(G).toString("base64")}))break}j({v:F,ch:"control",type:"http_end",reqId:l,error:null})}finally{et.delete(l)}}function Jo(s,l,u){let{reqId:o,method:c,path:p,body:w}=s,T=new URL(N);return new Promise(D=>{let te=_i.request({host:T.hostname,port:T.port,method:c,path:p,headers:{...l,host:s.host},signal:u.signal},G=>{let{connection:yt,"keep-alive":_e,"transfer-encoding":ir,upgrade:Ma,...Zo}=G.headers;j({v:F,ch:"control",type:"http_head",reqId:o,status:G.statusCode||502,headers:Zo}),G.on("data",Qo=>{j({v:F,ch:"control",type:"http_data",reqId:o,data:Buffer.from(Qo).toString("base64")})||G.destroy()}),G.on("end",()=>{j({v:F,ch:"control",type:"http_end",reqId:o,error:null}),D()}),G.on("error",()=>{j({v:F,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),D()})});te.on("error",G=>{j({v:F,ch:"control",type:"http_end",reqId:o,error:G?.message||"view request failed"}),D()}),w&&te.write(Buffer.from(w,"base64")),te.end()})}function or(){if(Kt||Ze)return;Y=new vn(e,{headers:{authorization:`Bearer ${t}`}});let s=Y;Te=0,s.on("ping",()=>{Te=Date.now()}),s.on("pong",()=>{Te=Date.now()}),Y.on("open",async()=>{let u=null;try{u=await a?.()||null}catch{u=null}j({v:F,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:Q,installKind:A,...typeof _=="function"?{updatePolicy:_()}:_?{updatePolicy:_}:{},providers:Ao(),...u?{agents:u}:{},...Gt?{restart:Gt}:{}})}),Y.on("message",u=>{Te=Date.now();let o;try{o=JSON.parse(u)}catch{return}if(o.ch==="ctl"&&o.type==="hello_ok"){tn.clear(),q=!0,Xe=go,Je=null,Gt=null,wr(),y.log(`[plane-link] connected to plane as ${n}`);try{pt?.()}catch{}if(typeof o.hashKey=="string"&&o.hashKey)try{f?.(o.hashKey)}catch{}try{S?.(typeof o.viewBase=="string"&&o.viewBase?o.viewBase:null)}catch{}o.minNodeVersion&&Q&&Ue(Q,o.minNodeVersion)&&y.error(`[plane-link] this node is bostrat-node ${Q}; the plane asks for \u2265${o.minNodeVersion} \u2014 update with: ${dt(A)}`);try{v?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}Wn(o);let c=o.ingest==="http";H=Ee==="ws"?"ws":Ee==="http"||c?"http":"ws",Ee==="http"&&!c&&y.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),H==="http"&&y.log("[plane-link] spine rides the HTTPS ingest door"),Z=!1,ge=0,fe=It,se&&clearInterval(se),Te=Date.now(),se=setInterval(()=>{Wo(s)||(j({v:F,ch:"ctl",type:"ping"}),Zn(),Vo().catch(()=>{}),Qt(),oe.length&&!z&&en())},Ve),se.unref?.(),Yo(),qo().catch(p=>y.error("[plane-link] backfill failed:",p?.message||p));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let c=typeof o.minNodeVersion=="string"?o.minNodeVersion:null,p=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;y.error(`[plane-link] plane REFUSED this node: bostrat-node ${Q??"?"} is below its minimum ${c??"?"} \u2014 ${o.fix||dt(A)}`),Xe=To,Je=0;try{k?.({current:Q,min:c,latest:p,fix:o.fix||dt(A),installKind:A})}catch(w){y.error(`[plane-link] refusal handler failed: ${w?.message||w}`)}return}if(o.ch==="ctl"&&o.type==="removed"){j({v:F,ch:"ctl",type:"removed_ack",nodeId:n}),Vt({reason:typeof o.reason=="string"?o.reason:"removed",at:Number(o.at)||Date.now(),via:"ctl"});return}if(o.ch==="ctl"&&o.type==="update_available"){Wn(o);return}if(o.ch==="ctl"&&o.type==="update_policy"){try{v?.(typeof o.mode=="string"?o.mode:null)}catch{}return}if(o.ch==="ctl"&&o.type==="conflict_probe"&&Array.isArray(o.trackIds)){try{R?.(o.trackIds.filter(c=>typeof c=="string"&&c).slice(0,200))}catch{}return}if(o.ch==="ctl"&&o.type==="restarted"){Promise.resolve().then(()=>P?.({kind:o.kind,at:o.at,reason:o.reason})).catch(c=>y.error("[plane-link] restart notice failed:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="usage_caps"){wo(o.caps??{},{source:"plane",updatedAt:o.updatedAt??Date.now()}).then(c=>y.log(`[plane-link] spend caps ${Object.keys(c.caps).length?`updated (${Object.keys(c.caps).join(", ")})`:"cleared"} from plane`)).catch(c=>y.error("[plane-link] spend-caps push rejected:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="transferred"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>d?.(o.tracks)).then(async c=>{for(let p of Array.isArray(c)?c:[])p?.stale&&p.id&&await nr(p.id,p.since??null)}).catch(c=>y.error("[plane-link] transfer notice failed:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="moves"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>h?.(o.tracks)).then(async c=>{for(let p of Array.isArray(c)?c:[])p?.stale&&p.id&&await nr(p.id,p.since??null)}).catch(c=>y.error("[plane-link] move-record reconcile failed:",c?.message||c));return}if(o.ch==="events"&&o.type==="ack"&&Array.isArray(o.ids)){Jt(o.ids);return}if(o.ch==="events"&&o.type==="nack"&&Array.isArray(o.ids)){Zt(o.ids,o.reason,o.permanent===!0,o.retryAfterMs??null);return}if(o.ch==="control"&&o.type==="http_open"){Xo(o).catch(c=>j({v:F,ch:"control",type:"http_end",reqId:o.reqId,error:c?.message||"tunnel error"}));return}if(o.ch==="control"&&o.type==="http_cancel"){et.get(o.reqId)?.abort();return}if(o.ch==="attach"&&o.type==="open"){let c=new vn(jo+o.path,Array.isArray(o.protocols)?o.protocols:[],o.host?{headers:{host:o.host}}:void 0);we.set(o.streamId,c),ye.set(o.streamId,[]),c.on("open",()=>{let w=ye.get(o.streamId)||[];ye.delete(o.streamId);for(let{buf:T,bin:D}of w)c.send(T,{binary:D})}),c.on("message",(w,T)=>{let D=T?w:Buffer.from(String(w));j({v:F,ch:"attach",type:"data",streamId:o.streamId,data:D.toString("base64"),...T?{bin:!0}:{}})});let p=()=>{ye.delete(o.streamId),we.delete(o.streamId)&&j({v:F,ch:"attach",type:"close",streamId:o.streamId})};c.on("close",p),c.on("error",p);return}if(o.ch==="attach"&&o.type==="data"){let c=we.get(o.streamId);if(!c)return;let p=Buffer.from(o.data,"base64"),w=o.bin===!0,T=ye.get(o.streamId);T?T.push({buf:p,bin:w}):c.send(p,{binary:w});return}if(o.ch==="attach"&&o.type==="close"){let c=we.get(o.streamId);we.delete(o.streamId),ye.delete(o.streamId),c?.close();return}});let l=()=>{q&&y.log("[plane-link] disconnected from plane"),q=!1,se&&(clearInterval(se),se=null),ie&&(clearInterval(ie),ie=null),I.clear(),ee={},oe=[],z&&(clearTimeout(z),z=null),Ne.clear();for(let c of we.values())c.close();we.clear(),ye.clear();for(let c of et.values())c.abort();if(et.clear(),Kt||Ie)return;Je==null&&(Je=Date.now());let u=Date.now()-Je<vi,o=Math.max(u?Ai+Math.random()*xi:Xe,qe-Date.now(),st());Ie=setTimeout(()=>{Ie=null,or()},o),Ie.unref?.(),u||(Xe=Math.min(Xe*2,To))};Y.on("close",l),Y.on("error",u=>{let o=/Unexpected server response: (\d+)/.exec(u?.message||"")?.[1];if(o==="410"){Vt({reason:"removed",via:"410"});return}if(o==="401"||o==="403"){let{tripped:c,holdMs:p}=At();c?y.error(`[plane-link] holding every plane call for ${Math.round(p/6e4)} min \u2014 three credential refusals in a row (HTTP ${o}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(p/6e4)} min.`):Date.now()-wt>=bo&&(wt=Date.now(),y.error(`[plane-link] plane refused this node's credentials (HTTP ${o}) \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)`))}l()})}at.on("event",rr),Fo().then(or);function sr({bye:s=!0}={}){Kt=!0,at.off("event",rr),Ie&&clearTimeout(Ie),Me&&clearTimeout(Me),se&&clearInterval(se),ie&&clearInterval(ie),z&&clearTimeout(z),s&&j({v:F,ch:"ctl",type:"bye",reason:"shutdown"}),Y?.close()}return{stop:()=>sr(),status:()=>({connected:q,nodeId:n,cursor:{...ne},inflight:I.size,...Qn(),auth:yr(),dormant:Ze,removed:fn(),deadLinkMs:O,deadLinkRedials:Yn,refused:{...mt}}),_tick:()=>{Zn(),Qt()}}}var Q,kn,En,F,go,To,vi,Ai,xi,It,ki,$i,Ei,Oi,On,Ri,An,Ni,Ii,Mi,So,Pi,_o,Ci,xn,Di,Bi,bo,Rn=x(()=>{$t();yo();on();pn();Q=(()=>{try{return bi(import.meta.url)("../package.json").version||null}catch{return null}})(),kn=process.env.BOSTRAT_STATE_DIR||W.join(process.env.HOME||Mt.tmpdir(),".bostrat"),En=W.join(kn,"plane-link","removed.json");F=1,go=1e3,To=3e4,vi=6e4,Ai=1500,xi=500,It=100,ki=2e3,$i=25e3,Ei=2.5,Oi=6e4,On=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Ri=On(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),An="refused:",Ni={forgedUserId:"this node's events carry a userId the plane's token does not own \u2014 remove BOSTRAT_OWNER from node.env and the shell environment, then restart the node (current releases never stamp one)",foreignTrack:"the Track belongs to another user's node \u2014 this node must not append to it",squattedTrack:"the Track id is already claimed by another user \u2014 a local Track collided with theirs",transferredAway:"the Track moved to another node \u2014 this copy is stale; it should be demoted, not resumed",slugHijack:"a View slug belongs to another owner \u2014 pick a different slug"},Ii=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},Mi=3e4,So=10*6e4,Pi=400,_o=250,Ci=On(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),xn=4,Di=Math.max(1,Math.round(On(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),Bi=6e4,bo=6e4});var ko=x(()=>{ln()});var Mo={};nn(Mo,{ACTIONABLE_KINDS:()=>Lt,INSTALL_ATTEMPTS:()=>Pt,INSTALL_RETRY_STEP_S:()=>$o,REGISTRY_RETRY_ATTEMPTS:()=>Mn,REGISTRY_WAIT_POLLS:()=>Nn,REGISTRY_WAIT_STEP_S:()=>In,RESTART_SIGNAL:()=>Oo,SELF_UPDATE_DIR:()=>Dt,SUPERVISOR_PID_FILE:()=>Eo,createAutoUpdater:()=>Qi,inFlight:()=>Bn,readStatus:()=>Dn,restartCommand:()=>Ro,restartStrategy:()=>Cn,selfUpdatePlan:()=>No,settleSelfUpdate:()=>Zi,startSelfUpdate:()=>Io,underService:()=>Pn,updatePolicy:()=>zi});import ft from"node:fs";import he from"node:fs/promises";import ji from"node:os";import U from"node:path";import{spawn as Fi,execFileSync as Ui}from"node:child_process";import{createRequire as Hi}from"node:module";function zi({kind:e=He(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:Lt.has(e)?e==="git-checkout"||Pn(t)?"auto":"prompt":"off"}function Pn(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Cn({env:e=process.env,platform:t=process.platform,uid:n=typeof process.getuid=="function"?process.getuid():0,serviceName:r=t==="darwin"?"com.bostrat.node":"bostrat-node.service",pidFile:i=Eo,readFile:a=h=>ft.readFileSync(h,"utf8"),alive:d=Vi}={}){let h=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(Pn(e))return h;let m=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(m)&&m>0)){try{m=Number(String(a(i)).trim())}catch{m=NaN}Number.isInteger(m)&&m>0&&d(m)||(m=NaN)}return Number.isInteger(m)&&m>0?{mode:"supervisor",pid:m}:h}function Vi(e){try{process.kill(e,0)}catch{return!1}try{let t=Ui("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/bostrat-node|\/cli\.js|node-cli\.js/.test(t)}catch{return!1}}function Ro(e){switch(e?.mode){case"systemd":return`systemctl --user restart ${X(e.serviceName||"bostrat-node.service")}`;case"launchd":return`launchctl kickstart -k gui/${Number(e.uid)||0}/${e.serviceName||"com.bostrat.node"}`;case"supervisor":return`kill -${Oo.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function No({kind:e,to:t,from:n=Ct,statusFile:r=Bt,logFile:i=U.join(Dt,"last.log"),port:a=Number(process.env.PORT)||3362,npmPrefix:d=null,serviceName:h=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:m=typeof process.getuid=="function"?process.getuid():0,restart:g=Cn({env:{},platform:process.platform,uid:m,serviceName:h,readFile:()=>{throw new Error("no pidfile")}}),liveDir:f=process.env.BOSTRAT_LIVE_CHECKOUT||U.resolve(U.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:S=Date.now(),attempts:$=1}={}){if(!Lt.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 b=(k,_="")=>`write_status ${X(k)} ${_}`,v=Ro(g),R=`
|
|
123
|
+
`),m(0)}var Xr,ai,_n,Rt,no=A(()=>{Xr="wss://plane.bostrat.ai/v1/node",ai=si(import.meta.url)("../package.json").version,_n=`ghcr.io/globocodes/bostrat-node:${ai}`;Rt=(e,{stdin:t,exec:n}={})=>new Promise((r,i)=>{if(n)return n(e,{stdin:t}).then(r,i);let a=oi("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,h,m)=>d?i(Object.assign(d,{stdout:h,stderr:m})):r({stdout:h,stderr:m}));t!=null&&a.stdin?.end(t)})});function ro(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!di.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 fi(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(i=>({...i,fromMs:ro(i.from,"from",n),toMs:ro(i.to,"to",n)}))}return t}var ui,di,Eu,Ou,oo=A(()=>{ui={"claude-opus-5-5":[{from:null,to:null,input:4,output:20,cacheWrite:8,cacheRead:.2,cacheReadX:.05,fast:{input:8,output:40,cacheWrite:16,cacheRead:.4},verifiedAt:"2026-09-28",note:"verified 2026-09-28 against platform.claude.com/docs/en/about-claude/pricing: $4/$20, 1h cache write $8 (2\xD7), cache hits $0.20 (0.05\xD7 \u2014 footnote 2), fast $8/$40; added before any fleet turn was recorded."}],"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"GA rates; verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-08-17",note:"$2/$10 is the standard price (intro pricing made permanent; the 2026-09-01 $3/$15 increase was cancelled) \u2014 verified 2026-08-17 against platform.claude.com/docs/en/about-claude/pricing."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-fable-5-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-09-07",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-03, re-verified 2026-08-17 (developers.openai.com pricing); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-08-24",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-terra":[{from:null,to:"2026-08-16",input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:2,output:12,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:"2026-08-16",input:1,output:6,cacheWrite:1.25,cacheRead:.1,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:.2,output:1.2,cacheWrite:.25,cacheRead:.02,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-09-07",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed)."}]},di=/^\d{4}-\d{2}-\d{2}$/;Eu=fi(ui),Ou=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var so=A(()=>{oo()});import io from"node:fs/promises";import lo from"node:path";import pi from"node:os";function fo(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function po(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function ho(e){let t=new Date(fo(e));return t.setDate(t.getDate()+7),t.getTime()}function mo(e){let t=new Date(po(e));return t.setMonth(t.getMonth()+1),t.getTime()}function gi(e=Date.now()){for(let[t,n]of Object.entries(wi)){let r=n.startOf(e);if(r!==Nt[t]){Nt[t]=r;for(let i of bn.values())i[t]=0;for(let i of ao)i.includes(`:${t}:`)&&!i.endsWith(`:${r}`)&&ao.delete(i)}}}function Ti(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 i={};for(let a of["weeklyUsd","monthlyUsd"]){let d=r?.[a];if(d==null||d==="")continue;let h=Number(d);if(!Number.isFinite(h)||h<=0)throw new Error(`${n}.${a} must be a positive number or null`);i[a]=h}Object.keys(i).length&&(t[n]=i)}return t}async function wo(e,{source:t="local",updatedAt:n=Date.now()}={}){je={caps:Ti(e),updatedAt:n,source:t};try{await io.mkdir(uo,{recursive:!0}),await io.writeFile(hi(),JSON.stringify(je,null,2))}catch{}return Si()}function Si(e=Date.now()){gi(e);let t=new Set([...bn.keys(),...Object.keys(je?.caps||{})]),n={};for(let r of t){let i=bn.get(r);n[r]={weeklyUsd:co(i?.weekly||0),monthlyUsd:co(i?.monthly||0)}}return{caps:je?.caps||{},configured:!!je,seeded:yi,updatedAt:je?.updatedAt??null,spent:n,windows:{weekly:{start:Nt.weekly,resetsAt:ho(e)},monthly:{start:Nt.monthly,resetsAt:mo(e)}},warnPct:mi}}var uo,hi,mi,wi,je,yi,Nt,bn,ao,co,yo=A(()=>{$t();so();uo=process.env.BOSTRAT_STATE_DIR||lo.join(process.env.HOME||pi.tmpdir(),".bostrat"),hi=()=>lo.join(uo,"usage-caps.json"),mi=.8;wi={weekly:{startOf:fo,nextStart:ho,capKey:"weeklyUsd"},monthly:{startOf:po,nextStart:mo,capKey:"monthlyUsd"}},je=null,yi=!1,Nt={weekly:0,monthly:0},bn=new Map,ao=new Set;co=e=>Math.round(e*1e4)/1e4});var Ao={};nn(Ao,{REMOVED_MARKER:()=>En,detectInstallKind:()=>He,detectProviderAuth:()=>xo,maskToken:()=>$n,readRemovedMarker:()=>vo,startPlaneLink:()=>Li,updateCommandFor:()=>dt,versionLt:()=>Ue});import Fe from"node:fs";import ut from"node:fs/promises";import _i from"node:http";import W from"node:path";import Mt from"node:os";import{createRequire as bi}from"node:module";import vn from"ws";function $n(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function vo(e=En){try{let t=JSON.parse(Fe.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function He({env:e=process.env,pkgDir:t=W.resolve(W.dirname(new URL(import.meta.url).pathname),".."),exists:n=Fe.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(W.join(t,"..",".git"))?"git-checkout":"dev"}function Ue(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 i=0;i<Math.max(n.length,r.length);i++){let a=(n[i]||0)-(r[i]||0);if(a)return a<0}return!1}function dt(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 xo({home:e=process.env.HOME||Mt.homedir(),env:t=process.env}={}){let n=r=>{try{return Fe.statSync(r),!0}catch{return!1}};return{claude:n(W.join(e,".claude",".credentials.json")),codex:n(W.join(t.CODEX_HOME||W.join(e,".codex"),"auth.json")),cursor:n(W.join(t.XDG_CONFIG_HOME||W.join(e,".config"),"cursor","auth.json"))}}function Li({url:e,token:t,nodeId:n=Mt.hostname(),name:r=Mt.hostname(),listTracks:i,detectAgents:a=null,onTracksTransferred:d=null,onTracksMoves:h=null,sampleMetrics:m=null,deliverySample:g=null,onHashKey:f=null,onViewBase:S=null,metricsMs:$=Bi,onUpdateAvailable:b=null,onUpdatePolicy:v=null,onConflictProbe:R=null,restart:E=null,onRestarted:P=null,onHelloRefused:k=null,updatePolicy:_=null,installKind:x=He(),selfUrl:N=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:L=null,removedMarkerFile:C=En,onRemoved:ke=null,onDegraded:Ge=null,onRecovered:$e=null,onRefused:Ft=null,onConnected:pt=null,ingestMode:Ee=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:ze=Ri,unackedRetryMs:Oe=Oi,pingMs:Ve=$i,deadLinkMs:O=Math.round(Ve*Ei),maxInflightEvents:ce=Pi,httpTimeoutMs:le=Ci,fanoutActive:ue=null,fanoutBatchCap:Ye=Di,stallBackoffMinMs:Fn=Mi,fetchImpl:Un=globalThis.fetch,log:y=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof i!="function")throw new Error("plane-link: listTracks is required");e=tt(e);let jo=N.replace(/^http/,"ws"),Hn=new Set,Wn=s=>{let l=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(!(!(l&&Q&&Ue(Q,l))||Hn.has(l))){Hn.add(l),y.log(`[plane-link] bostrat-node ${l} is available (this node runs ${Q}) \u2014 ${dt(x)}`);try{b?.({current:Q,latest:l,min:s.minNodeVersion??null,installKind:x,required:!!(s.minNodeVersion&&Ue(Q,s.minNodeVersion))})}catch(u){y.error(`[plane-link] update notice failed: ${u?.message||u}`)}}},we=new Map,ye=new Map,Ut=W.join(kn,"plane-link","cursor.json"),Ht=W.join(kn,"plane-link","dead-letter.ndjson"),Kn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),ne={},ee={},I=new Map,ht=null,de=null,re=0,qe=0,Gn=0,mt={},zn=new Set,Vn=Promise.resolve(),H="ws",Re=0,Z=!1,ge=0,Wt=!1,fe=It,Ne=new Set,oe=[],z=null,Y=null,q=!1,Kt=!1,Xe=go,Je=null,Gt=E&&typeof E=="object"?E:null,Ie=null,Me=null,se=null,Te=0,Yn=0,ie=null,zt=!1,wt=0,Ze=!1,pe=vo(C);if(pe)if(pe.tokenPreview===$n(t))Ze=!0,dn({reason:pe.reason??"removed",at:pe.at??null,nodeId:pe.nodeId??n}),y.error(`[plane-link] this node was REMOVED from the plane (${pe.reason??"removed"}${pe.at?` at ${new Date(pe.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${C} to force a dial.`);else try{Fe.unlinkSync(C),y.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function Vt({reason:s="removed",at:l=Date.now(),via:u="ctl"}={}){if(!Ze){Ze=!0,dn({reason:s,at:l,nodeId:n,via:u});try{Fe.mkdirSync(W.dirname(C),{recursive:!0}),Fe.writeFileSync(C,JSON.stringify({at:l,reason:s,via:u,nodeId:n,tokenPreview:$n(t)},null,2))}catch(o){y.error(`[plane-link] could not write ${C}: ${o?.message||o}`)}y.error(`[plane-link] the plane REMOVED this node (${s}, via ${u}) \u2014 going dormant: no more dials, ingest or broker calls. Re-provision with a new node token to reconnect; the box and its data are untouched.`);try{ke?.({reason:s,at:l,via:u})}catch{}sr({bye:!1})}}async function Fo(){try{ne=JSON.parse(await ut.readFile(Ut,"utf8"))}catch{ne={}}}function qn(){zt=!0,!Me&&(Me=setTimeout(async()=>{if(Me=null,!!zt){zt=!1;try{await ut.mkdir(W.dirname(Ut),{recursive:!0}),await ut.writeFile(Ut,JSON.stringify(ne))}catch(s){y.error("[plane-link] cursor flush failed:",s?.message||s)}}},ki),Me.unref?.())}function Yt(){try{return!!ue?.()}catch{return!1}}function qt(){let s=H==="http"?fe:It;return Yt()?Math.min(s,Ye):s}function j(s){return!Y||Y.readyState!==vn.OPEN?!1:(Y.send(JSON.stringify(s)),!0)}function Pe(s){let l=Date.now();for(let{trackId:o,event:c}of s){let p=I.get(c.id);I.set(c.id,{trackId:o,seq:c.seq,event:c,sentAt:l,firstSentAt:p?.firstSentAt??l,retryAt:l+Oe,tries:(p?.tries??0)+1,nacks:p?.nacks??0})}let u=s.map(({trackId:o,event:c})=>({trackId:o,event:Ii(c)}));return H==="http"?(zo(u),!0):j({v:F,ch:"events",type:"append",events:u})}function Uo(s){let l=null;for(let u of I.values())u.trackId===s&&(l==null||u.seq<l)&&(l=u.seq);return l}function Xt(s){let l=ee[s];if(l==null)return;let u=Uo(s),o=u==null?l:Math.min(l,u-1);o>(ne[s]??0)&&(ne[s]=o,qn())}function Qe(){if(ht=Date.now(),de!=null){let s=Date.now()-de;y.log(`[plane-link] spine sync recovered after ${Math.round(s/1e3)}s degraded (${re} stall redial(s))`);let l=de;de=null,re=0,qe=0,Z=!1,ge=0;try{$e?.({since:l,downMs:s})}catch(u){y.error(`[plane-link] onRecovered failed: ${u?.message||u}`)}}}function Jt(s){if(!Array.isArray(s)||!s.length)return;let l=new Set;for(let u of s){let o=I.get(u);o&&(I.delete(u),(ee[o.trackId]??0)<o.seq&&(ee[o.trackId]=o.seq),l.add(o.trackId))}for(let u of l)Xt(u);Qe()}function Xn(s,l){Gn++;let u={at:Date.now(),trackId:s.trackId,seq:s.seq,id:s.event?.id??null,type:s.event?.type??null,reason:l,event:s.event??null};y.error(`[plane-link] DEAD-LETTER ${s.trackId} seq ${s.seq} (${u.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${Ht}`),Vn=Vn.then(async()=>{await ut.mkdir(W.dirname(Ht),{recursive:!0}),await ut.appendFile(Ht,JSON.stringify(u)+`
|
|
124
|
+
`)}).catch(o=>y.error(`[plane-link] dead-letter write failed: ${o?.message||o}`))}function Ho(s,l){if(mt[s]=(mt[s]??0)+1,zn.has(s))return;zn.add(s);let u=Ni[s]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";y.error(`[plane-link] REFUSED by the plane (${s}) on track ${l}: events are being dropped, not stored \u2014 ${u}`);try{Ft?.({reason:s,trackId:l,count:mt[s],hint:u})}catch(o){y.error(`[plane-link] onRefused failed: ${o?.message||o}`)}}function Zt(s,l,u,o=null){if(!Array.isArray(s)||!s.length)return;let c=new Set,p=Date.now();for(let w of s){let T=I.get(w);T&&(u?(I.delete(w),Xn(T,l),String(l).startsWith(xn)&&Ho(String(l).slice(xn.length),T.trackId),(ee[T.trackId]??0)<T.seq&&(ee[T.trackId]=T.seq),c.add(T.trackId)):(T.nacks++,T.retryAt=p+Math.max(1e3,Number(o)||Oe)))}for(let w of c)Xt(w);Qe()}function Jn(s=Date.now()){let l=1/0;for(let u of I.values())u.firstSentAt<l&&(l=u.firstSentAt);return l===1/0?0:s-l}function Wo(s){if(!O||!s||s!==Y||!Te)return!1;let l=Date.now()-Te;if(l<=O)return!1;Yn++,y.error(`[plane-link] no frame from the plane for ${Math.round(l/1e3)}s \u2014 link is half-open; terminating and redialing`);try{s.terminate()}catch{}return!0}function Zn(){if(!q||!I.size)return;let s=Date.now(),l=Jn(s);if(l<ze||ht!=null&&s-ht<ze||H==="http"&&Z||qe>s)return;re++;let u=Math.min(Fn*2**(re-1),So);if(de==null){de=s-l,y.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${I.size} event(s) in flight (${H} door) \u2014 the plane is not answering appends`);try{Ge?.({since:de,unacked:I.size,oldestAgeMs:l,mode:H})}catch(o){y.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(H==="http"){Z=!0,ge=s+u,y.error(`[plane-link] ingest circuit OPEN (stall #${re}); probing /v1/ingest/health in ${Math.round(u/1e3)}s`);return}qe=s+u,y.error(`[plane-link] closing the link and redialing in ${Math.round(u/1e3)}s (stall redial #${re})`);try{Y?.terminate()}catch{}}function Qt(){if(!q)return;let s=Date.now();if(H==="http"&&Z)return;let l=[...I.values()].filter(o=>o.event&&o.retryAt<=s&&!(H==="http"&&Ne.has(o.trackId)));if(!l.length)return;l.sort((o,c)=>o.trackId===c.trackId?o.seq-c.seq:o.trackId<c.trackId?-1:1),y.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let u=qt();if(H==="http"){let o=new Map;for(let c of l)(o.get(c.trackId)??o.set(c.trackId,[]).get(c.trackId)).push(c);for(let[,c]of o){if(Re>=An)return;Pe(c.slice(0,u).map(p=>({trackId:p.trackId,event:p.event})))}return}for(let o=0;o<l.length;o+=u){let c=l.slice(o,o+u).map(p=>({trackId:p.trackId,event:p.event}));if(!Pe(c))return}}async function Ko(s=null){for(;;){if(!q)return!1;let l=I.size<ce,u=H!=="http"||Re<An&&!Z&&(!s||!Ne.has(s));if(l&&u)return!0;await new Promise(o=>setTimeout(o,100))}}function en(){if(z=null,!q||!oe.length)return;let s=oe;oe=[];let l=qt();if(H!=="http"){for(let c=0;c<s.length;c+=l)Pe(s.slice(c,c+l));return}let u=Yt(),o=new Map;for(let c of s)(o.get(c.trackId)??o.set(c.trackId,[]).get(c.trackId)).push(c);for(let[c,p]of o){if(Ne.has(c)||Re>=An||Z){oe.push(...p);continue}if(u){Pe(p.slice(0,l)),oe.push(...p.slice(l));continue}for(let w=0;w<p.length;w+=l)Pe(p.slice(w,w+l))}oe.length&&!z&&(z=setTimeout(en,_o),z.unref?.())}let Go=s=>{let l=new Map;for(let{trackId:u,event:o}of s)(l.get(u)??l.set(u,[]).get(u)).push(o);return[...l].map(([u,o])=>({trackId:u,events:o}))},Se=(s,l,u,{progress:o})=>{let c=Date.now();for(let{event:p}of s){let w=I.get(p.id);w&&(w.nacks++,w.retryAt=c+Math.max(1e3,u||Oe))}o&&Qe()};async function zo(s){let l=new Set(s.map(u=>u.trackId));for(let u of l)Ne.add(u);Re++;try{let u=await Un(`${Kn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:Go(s)}),signal:AbortSignal.timeout(le)}),o=(Number(u.headers.get("retry-after"))||0)*1e3;if(u.status===200){let c=await u.json();fe=It;for(let T of c.results??[]){Jt(T.acked??[]);let D=(te,G)=>{let yt=new Map;for(let _e of te??[])(yt.get(_e.reason)??yt.set(_e.reason,[]).get(_e.reason)).push(_e.id);for(let[_e,ir]of yt)Zt(ir,_e,G,c.retryAfterMs??null)};D(T.rejected,!0),D(T.deferred,!1)}let p=new Set,w=new Map;for(let T of Array.isArray(c.refused)?c.refused:[])!T||typeof T.id!="string"||(p.add(T.id),(w.get(T.reason)??w.set(T.reason,[]).get(T.reason)).push(T.id));for(let[T,D]of w)Zt(D,`${xn}${T}`,!0);Jt((c.discarded??[]).filter(T=>!p.has(T))),Qe();return}if(u.status===429){Se(s,"overloaded",o||5e3,{progress:!0});return}if(u.status===413&&s.length>1){fe=Math.max(1,Math.floor(s.length/2)),y.error(`[plane-link] ingest request too large (${s.length} events) \u2014 halving batches to ${fe}`),Se(s,"too_large",1e3,{progress:!0});return}if(u.status===413){let c=I.get(s[0].event.id);c&&(I.delete(c.event.id),Xn(c,"too_large"),(ee[c.trackId]??0)<c.seq&&(ee[c.trackId]=c.seq),Xt(c.trackId)),Qe();return}if(u.status===410){Vt({reason:"removed",via:"410"}),Se(s,"http_410",6e4,{progress:!1});return}if(u.status===401||u.status===403){let{tripped:c,holdMs:p}=xt();if(c&&y.error(`[plane-link] holding every plane call for ${Math.round(p/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-wt>=bo){wt=Date.now();let w="";try{w=(await u.json())?.error??""}catch{}y.error(`[plane-link] plane refused ingest (HTTP ${u.status}${w?`: ${w}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}Se(s,`http_${u.status}`,Math.max(6e4,st()),{progress:!1});return}if(u.status===400){y.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${s.length} event(s) for retry; this is a bug, not data`),Se(s,"http_400",6e4,{progress:!1});return}Se(s,`http_${u.status}`,o||5e3,{progress:!1})}catch(u){let o=u?.name==="TimeoutError"||u?.name==="AbortError";o&&s.length>1&&(fe=Math.max(1,Math.floor(s.length/2)),y.error(`[plane-link] ingest request of ${s.length} event(s) outlived its ${le} ms deadline \u2014 halving batches to ${fe}`)),Se(s,o?"timeout":"network",5e3,{progress:!1})}finally{Re--;for(let u of l)Ne.delete(u)}}async function Vo(){if(H!=="http"||!Z||!q||Wt)return;let s=Date.now();if(!(ge>s||At(s))){Wt=!0;try{let l=await Un(`${Kn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(le)});if(!l.ok)throw new Error(`HTTP ${l.status}`);y.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Z=!1,ge=0,qe=Date.now()+le+Oe+1e3;for(let u of I.values())u.retryAt=Math.min(u.retryAt,Date.now());Qt()}catch(l){re++;let u=Math.min(Fn*2**(re-1),So);ge=Date.now()+u,y.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(u/1e3)}s`)}finally{Wt=!1}}}function Qn(){let s=Date.now();return{mode:H,unacked:I.size,oldestUnackedAgeMs:Jn(s),lastProgressAt:ht,degradedSince:de,stallRedials:re,deadLettered:Gn,fanoutCap:Yt()?Ye:null,http:H==="http"?{inFlight:Re,circuitOpen:Z,nextProbeInMs:Z?Math.max(0,ge-s):0,batchCap:fe}:null}}async function er(){if(!m)return;let s;try{s=await m()}catch(u){y.error("[plane-link] metrics sample failed:",u?.message||u);return}let l=null;try{l=g?.()??null}catch{}s&&j({v:F,ch:"ctl",type:"metrics",metrics:{...s,planeLink:Qn(),...l?{delivery:l}:{}}})}function Yo(){m&&(ie&&clearInterval(ie),er(),ie=setInterval(er,$),ie.unref?.())}async function qo(){let s;try{s=await i()}catch(l){y.error("[plane-link] backfill listTracks failed:",l?.message||l);return}j({v:F,ch:"ctl",type:"tracks",ids:s.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of s)if(!q||!await tr(l))return}async function tr(s){let l;try{l=await kt(s)}catch{return!0}let u=ne[s.id]??0,o=l.filter(c=>c.seq>u&&typeof c.id=="string");for(let c=0;c<o.length;){if(!await Ko(s.id))return!1;let p=o.slice(c,c+qt()).map(w=>({trackId:s.id,event:w}));if(!Pe(p))return!1;c+=p.length}return!0}let tn=new Map;async function nr(s,l){if(tn.get(s)===l)return!1;tn.set(s,l);let u=null;try{u=(await i()).find(w=>w?.id===s)??null}catch{return!1}if(!u)return!1;let o;try{o=await kt(u)}catch{return!1}let c=[...o].reverse().find(w=>(w?.type==="track.transferred"||w?.type==="track.recovered")&&w.payload?.toNode===n);if(!c||!Number.isFinite(c.seq))return!1;let p=c.seq-1;return(ne[s]??0)>p&&(ne[s]=p,qn()),(ee[s]??0)>p&&(ee[s]=p),y.log(`[plane-link] re-sending ${s}'s move-commit (seq ${c.seq}, ${c.type}) \u2014 the plane's move record predates this node's adoption`),q?tr(u):!1}function rr(s){!q||!s?.trackId||typeof s.id!="string"||(oe.push({trackId:s.trackId,event:s}),z||(z=setTimeout(en,_o),z.unref?.()))}let et=new Map;async function Xo(s){let{reqId:l,method:u,path:o,headers:c={},body:p}=s,w=Object.fromEntries(Object.entries(c).filter(([,D])=>D!=null)),T=new AbortController;et.set(l,T);try{if(s.host){await Jo(s,w,T);return}L&&(w["x-bostrat-token"]=L);let D=await fetch(N+o,{method:u,headers:w,body:p?Buffer.from(p,"base64"):void 0,signal:T.signal}),te=Object.fromEntries(D.headers);for(let G of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete te[G];if(te["content-type"]||(te["content-type"]="application/octet-stream"),j({v:F,ch:"control",type:"http_head",reqId:l,status:D.status,headers:te}),D.body){for await(let G of D.body)if(!j({v:F,ch:"control",type:"http_data",reqId:l,data:Buffer.from(G).toString("base64")}))break}j({v:F,ch:"control",type:"http_end",reqId:l,error:null})}finally{et.delete(l)}}function Jo(s,l,u){let{reqId:o,method:c,path:p,body:w}=s,T=new URL(N);return new Promise(D=>{let te=_i.request({host:T.hostname,port:T.port,method:c,path:p,headers:{...l,host:s.host},signal:u.signal},G=>{let{connection:yt,"keep-alive":_e,"transfer-encoding":ir,upgrade:Ma,...Zo}=G.headers;j({v:F,ch:"control",type:"http_head",reqId:o,status:G.statusCode||502,headers:Zo}),G.on("data",Qo=>{j({v:F,ch:"control",type:"http_data",reqId:o,data:Buffer.from(Qo).toString("base64")})||G.destroy()}),G.on("end",()=>{j({v:F,ch:"control",type:"http_end",reqId:o,error:null}),D()}),G.on("error",()=>{j({v:F,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),D()})});te.on("error",G=>{j({v:F,ch:"control",type:"http_end",reqId:o,error:G?.message||"view request failed"}),D()}),w&&te.write(Buffer.from(w,"base64")),te.end()})}function or(){if(Kt||Ze)return;Y=new vn(e,{headers:{authorization:`Bearer ${t}`}});let s=Y;Te=0,s.on("ping",()=>{Te=Date.now()}),s.on("pong",()=>{Te=Date.now()}),Y.on("open",async()=>{let u=null;try{u=await a?.()||null}catch{u=null}j({v:F,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:Q,installKind:x,...typeof _=="function"?{updatePolicy:_()}:_?{updatePolicy:_}:{},providers:xo(),...u?{agents:u}:{},...Gt?{restart:Gt}:{}})}),Y.on("message",u=>{Te=Date.now();let o;try{o=JSON.parse(u)}catch{return}if(o.ch==="ctl"&&o.type==="hello_ok"){tn.clear(),q=!0,Xe=go,Je=null,Gt=null,wr(),y.log(`[plane-link] connected to plane as ${n}`);try{pt?.()}catch{}if(typeof o.hashKey=="string"&&o.hashKey)try{f?.(o.hashKey)}catch{}try{S?.(typeof o.viewBase=="string"&&o.viewBase?o.viewBase:null)}catch{}o.minNodeVersion&&Q&&Ue(Q,o.minNodeVersion)&&y.error(`[plane-link] this node is bostrat-node ${Q}; the plane asks for \u2265${o.minNodeVersion} \u2014 update with: ${dt(x)}`);try{v?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}Wn(o);let c=o.ingest==="http";H=Ee==="ws"?"ws":Ee==="http"||c?"http":"ws",Ee==="http"&&!c&&y.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),H==="http"&&y.log("[plane-link] spine rides the HTTPS ingest door"),Z=!1,ge=0,fe=It,se&&clearInterval(se),Te=Date.now(),se=setInterval(()=>{Wo(s)||(j({v:F,ch:"ctl",type:"ping"}),Zn(),Vo().catch(()=>{}),Qt(),oe.length&&!z&&en())},Ve),se.unref?.(),Yo(),qo().catch(p=>y.error("[plane-link] backfill failed:",p?.message||p));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let c=typeof o.minNodeVersion=="string"?o.minNodeVersion:null,p=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;y.error(`[plane-link] plane REFUSED this node: bostrat-node ${Q??"?"} is below its minimum ${c??"?"} \u2014 ${o.fix||dt(x)}`),Xe=To,Je=0;try{k?.({current:Q,min:c,latest:p,fix:o.fix||dt(x),installKind:x})}catch(w){y.error(`[plane-link] refusal handler failed: ${w?.message||w}`)}return}if(o.ch==="ctl"&&o.type==="removed"){j({v:F,ch:"ctl",type:"removed_ack",nodeId:n}),Vt({reason:typeof o.reason=="string"?o.reason:"removed",at:Number(o.at)||Date.now(),via:"ctl"});return}if(o.ch==="ctl"&&o.type==="update_available"){Wn(o);return}if(o.ch==="ctl"&&o.type==="update_policy"){try{v?.(typeof o.mode=="string"?o.mode:null)}catch{}return}if(o.ch==="ctl"&&o.type==="conflict_probe"&&Array.isArray(o.trackIds)){try{R?.(o.trackIds.filter(c=>typeof c=="string"&&c).slice(0,200))}catch{}return}if(o.ch==="ctl"&&o.type==="restarted"){Promise.resolve().then(()=>P?.({kind:o.kind,at:o.at,reason:o.reason})).catch(c=>y.error("[plane-link] restart notice failed:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="usage_caps"){wo(o.caps??{},{source:"plane",updatedAt:o.updatedAt??Date.now()}).then(c=>y.log(`[plane-link] spend caps ${Object.keys(c.caps).length?`updated (${Object.keys(c.caps).join(", ")})`:"cleared"} from plane`)).catch(c=>y.error("[plane-link] spend-caps push rejected:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="transferred"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>d?.(o.tracks)).then(async c=>{for(let p of Array.isArray(c)?c:[])p?.stale&&p.id&&await nr(p.id,p.since??null)}).catch(c=>y.error("[plane-link] transfer notice failed:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="moves"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>h?.(o.tracks)).then(async c=>{for(let p of Array.isArray(c)?c:[])p?.stale&&p.id&&await nr(p.id,p.since??null)}).catch(c=>y.error("[plane-link] move-record reconcile failed:",c?.message||c));return}if(o.ch==="events"&&o.type==="ack"&&Array.isArray(o.ids)){Jt(o.ids);return}if(o.ch==="events"&&o.type==="nack"&&Array.isArray(o.ids)){Zt(o.ids,o.reason,o.permanent===!0,o.retryAfterMs??null);return}if(o.ch==="control"&&o.type==="http_open"){Xo(o).catch(c=>j({v:F,ch:"control",type:"http_end",reqId:o.reqId,error:c?.message||"tunnel error"}));return}if(o.ch==="control"&&o.type==="http_cancel"){et.get(o.reqId)?.abort();return}if(o.ch==="attach"&&o.type==="open"){let c=new vn(jo+o.path,Array.isArray(o.protocols)?o.protocols:[],o.host?{headers:{host:o.host}}:void 0);we.set(o.streamId,c),ye.set(o.streamId,[]),c.on("open",()=>{let w=ye.get(o.streamId)||[];ye.delete(o.streamId);for(let{buf:T,bin:D}of w)c.send(T,{binary:D})}),c.on("message",(w,T)=>{let D=T?w:Buffer.from(String(w));j({v:F,ch:"attach",type:"data",streamId:o.streamId,data:D.toString("base64"),...T?{bin:!0}:{}})});let p=()=>{ye.delete(o.streamId),we.delete(o.streamId)&&j({v:F,ch:"attach",type:"close",streamId:o.streamId})};c.on("close",p),c.on("error",p);return}if(o.ch==="attach"&&o.type==="data"){let c=we.get(o.streamId);if(!c)return;let p=Buffer.from(o.data,"base64"),w=o.bin===!0,T=ye.get(o.streamId);T?T.push({buf:p,bin:w}):c.send(p,{binary:w});return}if(o.ch==="attach"&&o.type==="close"){let c=we.get(o.streamId);we.delete(o.streamId),ye.delete(o.streamId),c?.close();return}});let l=()=>{q&&y.log("[plane-link] disconnected from plane"),q=!1,se&&(clearInterval(se),se=null),ie&&(clearInterval(ie),ie=null),I.clear(),ee={},oe=[],z&&(clearTimeout(z),z=null),Ne.clear();for(let c of we.values())c.close();we.clear(),ye.clear();for(let c of et.values())c.abort();if(et.clear(),Kt||Ie)return;Je==null&&(Je=Date.now());let u=Date.now()-Je<vi,o=Math.max(u?xi+Math.random()*Ai:Xe,qe-Date.now(),st());Ie=setTimeout(()=>{Ie=null,or()},o),Ie.unref?.(),u||(Xe=Math.min(Xe*2,To))};Y.on("close",l),Y.on("error",u=>{let o=/Unexpected server response: (\d+)/.exec(u?.message||"")?.[1];if(o==="410"){Vt({reason:"removed",via:"410"});return}if(o==="401"||o==="403"){let{tripped:c,holdMs:p}=xt();c?y.error(`[plane-link] holding every plane call for ${Math.round(p/6e4)} min \u2014 three credential refusals in a row (HTTP ${o}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(p/6e4)} min.`):Date.now()-wt>=bo&&(wt=Date.now(),y.error(`[plane-link] plane refused this node's credentials (HTTP ${o}) \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)`))}l()})}at.on("event",rr),Fo().then(or);function sr({bye:s=!0}={}){Kt=!0,at.off("event",rr),Ie&&clearTimeout(Ie),Me&&clearTimeout(Me),se&&clearInterval(se),ie&&clearInterval(ie),z&&clearTimeout(z),s&&j({v:F,ch:"ctl",type:"bye",reason:"shutdown"}),Y?.close()}return{stop:()=>sr(),status:()=>({connected:q,nodeId:n,cursor:{...ne},inflight:I.size,...Qn(),auth:yr(),dormant:Ze,removed:fn(),deadLinkMs:O,deadLinkRedials:Yn,refused:{...mt}}),_tick:()=>{Zn(),Qt()}}}var Q,kn,En,F,go,To,vi,xi,Ai,It,ki,$i,Ei,Oi,On,Ri,xn,Ni,Ii,Mi,So,Pi,_o,Ci,An,Di,Bi,bo,Rn=A(()=>{$t();yo();on();pn();Q=(()=>{try{return bi(import.meta.url)("../package.json").version||null}catch{return null}})(),kn=process.env.BOSTRAT_STATE_DIR||W.join(process.env.HOME||Mt.tmpdir(),".bostrat"),En=W.join(kn,"plane-link","removed.json");F=1,go=1e3,To=3e4,vi=6e4,xi=1500,Ai=500,It=100,ki=2e3,$i=25e3,Ei=2.5,Oi=6e4,On=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Ri=On(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),xn="refused:",Ni={forgedUserId:"this node's events carry a userId the plane's token does not own \u2014 remove BOSTRAT_OWNER from node.env and the shell environment, then restart the node (current releases never stamp one)",foreignTrack:"the Track belongs to another user's node \u2014 this node must not append to it",squattedTrack:"the Track id is already claimed by another user \u2014 a local Track collided with theirs",transferredAway:"the Track moved to another node \u2014 this copy is stale; it should be demoted, not resumed",slugHijack:"a View slug belongs to another owner \u2014 pick a different slug"},Ii=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},Mi=3e4,So=10*6e4,Pi=400,_o=250,Ci=On(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),An=4,Di=Math.max(1,Math.round(On(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),Bi=6e4,bo=6e4});var ko=A(()=>{ln()});var Mo={};nn(Mo,{ACTIONABLE_KINDS:()=>Lt,INSTALL_ATTEMPTS:()=>Pt,INSTALL_RETRY_STEP_S:()=>$o,REGISTRY_RETRY_ATTEMPTS:()=>Mn,REGISTRY_WAIT_POLLS:()=>Nn,REGISTRY_WAIT_STEP_S:()=>In,RESTART_SIGNAL:()=>Oo,SELF_UPDATE_DIR:()=>Dt,SUPERVISOR_PID_FILE:()=>Eo,createAutoUpdater:()=>Qi,inFlight:()=>Bn,readStatus:()=>Dn,restartCommand:()=>Ro,restartStrategy:()=>Cn,selfUpdatePlan:()=>No,settleSelfUpdate:()=>Zi,startSelfUpdate:()=>Io,underService:()=>Pn,updatePolicy:()=>zi});import ft from"node:fs";import he from"node:fs/promises";import ji from"node:os";import U from"node:path";import{spawn as Fi,execFileSync as Ui}from"node:child_process";import{createRequire as Hi}from"node:module";function zi({kind:e=He(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:Lt.has(e)?e==="git-checkout"||Pn(t)?"auto":"prompt":"off"}function Pn(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Cn({env:e=process.env,platform:t=process.platform,uid:n=typeof process.getuid=="function"?process.getuid():0,serviceName:r=t==="darwin"?"com.bostrat.node":"bostrat-node.service",pidFile:i=Eo,readFile:a=h=>ft.readFileSync(h,"utf8"),alive:d=Vi}={}){let h=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(Pn(e))return h;let m=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(m)&&m>0)){try{m=Number(String(a(i)).trim())}catch{m=NaN}Number.isInteger(m)&&m>0&&d(m)||(m=NaN)}return Number.isInteger(m)&&m>0?{mode:"supervisor",pid:m}:h}function Vi(e){try{process.kill(e,0)}catch{return!1}try{let t=Ui("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/bostrat-node|\/cli\.js|node-cli\.js/.test(t)}catch{return!1}}function Ro(e){switch(e?.mode){case"systemd":return`systemctl --user restart ${X(e.serviceName||"bostrat-node.service")}`;case"launchd":return`launchctl kickstart -k gui/${Number(e.uid)||0}/${e.serviceName||"com.bostrat.node"}`;case"supervisor":return`kill -${Oo.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function No({kind:e,to:t,from:n=Ct,statusFile:r=Bt,logFile:i=U.join(Dt,"last.log"),port:a=Number(process.env.PORT)||3362,npmPrefix:d=null,serviceName:h=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:m=typeof process.getuid=="function"?process.getuid():0,restart:g=Cn({env:{},platform:process.platform,uid:m,serviceName:h,readFile:()=>{throw new Error("no pidfile")}}),liveDir:f=process.env.BOSTRAT_LIVE_CHECKOUT||U.resolve(U.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:S=Date.now(),attempts:$=1}={}){if(!Lt.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 b=(k,_="")=>`write_status ${X(k)} ${_}`,v=Ro(g),R=`
|
|
125
125
|
health() {
|
|
126
126
|
for i in $(seq 1 45); do
|
|
127
127
|
sleep 1
|
|
@@ -146,7 +146,7 @@ write_status() { # <status> [error] [retryable]
|
|
|
146
146
|
}
|
|
147
147
|
${R}
|
|
148
148
|
`;if(e==="npm-global"){let k=d?U.join(d,"bin","npm"):"npm",_=d?`export PATH=${X(U.join(d,"bin"))}:"$PATH"
|
|
149
|
-
`:"",
|
|
149
|
+
`:"",x=d?` --prefix ${X(d)}`:"",N=ke=>`${X(k)} install -g "bostrat-node@${ke}" --no-audit --no-fund${x}`,L=`
|
|
150
150
|
install_target() {
|
|
151
151
|
for i in $(seq 1 ${Pt}); do
|
|
152
152
|
if ${N("$TO")}; then return 0; fi
|
|
@@ -205,7 +205,7 @@ if [ -n "$FROM" ] && ${P("$FROM")}; then
|
|
|
205
205
|
fi
|
|
206
206
|
${b("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
|
|
207
207
|
exit 1
|
|
208
|
-
`}async function Dn(e=Bt){try{return JSON.parse(await he.readFile(e,"utf8"))}catch{return null}}async function Io({to:e,from:t=Ct,kind:n=He(),reason:r="manual",force:i=!1,statusFile:a=Bt,spawnImpl:d=Fi,now:h=Date.now,npmPrefix:m=void 0,log:g=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!Lt.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Ue(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let f=await Dn(a);if(Bn(f))return{ok:!1,reason:`an update to ${f.to} is already in flight`,status:f};let S=f?.to===e?Number(f.attempts)||1:0;if(!i&&f&&f.to===e&&(f.status==="failed"||f.status==="rolled-back")&&!(f.status==="failed"&&f.retryable===!0&&S<Mn))return{ok:!1,reason:`update to ${e} already ${f.status} (${f.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:f};let $=f?.to===e&&(f.status==="failed"||f.status==="rolled-back")?S+1:1;await he.mkdir(U.dirname(a),{recursive:!0});let b=m!==void 0?m:n==="npm-global"?cn(await qi())||U.resolve(U.dirname(process.execPath),".."):null,v=Cn(),R=No({kind:n,to:e,from:t,statusFile:a,npmPrefix:b,startedAt:h(),attempts:$,restart:v}),E=U.join(U.dirname(a),`update-${e}.sh`),P=U.join(U.dirname(a),"last.log");await he.writeFile(E,R,{mode:448}),await he.writeFile(a,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:$,startedAt:h(),updatedAt:h()}));let k=ft.existsSync("/run/systemd/system")&&await Xi("systemd-run"),_=k?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",E]]:["bash",[E]],A=async L=>{let C=`could not spawn updater: ${L?.message||L}`;return await he.writeFile(a,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,attempts:$,startedAt:h(),updatedAt:h(),error:C})).catch(()=>{}),g.error?.(`[self-update] ${C}`),C},N=null;try{k||(N=ft.openSync(P,"a"));let L=d(_[0],_[1],{detached:!0,stdio:k?"ignore":["ignore",N,N]});L.on?.("error",C=>{A(C)}),L.unref?.()}catch(L){return{ok:!1,reason:await A(L)}}finally{N!==null&&ft.closeSync(N)}return g.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}, restart via ${v.mode}) started \u2014 status ${a}`),{ok:!0,to:e,from:t,kind:n,scriptFile:E,statusFile:a}}async function qi(){try{return await he.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Xi(e){for(let t of String(process.env.PATH||"").split(U.delimiter))try{return await he.access(U.join(t,e),ft.constants.X_OK),!0}catch{}return!1}async function Zi({statusFile:e=Bt,current:t=Ct,now:n=Date.now,staleMs:r=Ji}={}){let i=await Dn(e);if(!i)return null;let a=d=>he.writeFile(e,JSON.stringify(d)).catch(()=>{});if(Bn(i)){if(t&&i.to===t){let d={...i,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await a(d),d}if(n()-Number(i.updatedAt||i.startedAt||0)>r){let d={...i,status:"failed",error:`updater went silent while ${i.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await a(d),d}return null}if(["failed","rolled-back","done"].includes(i.status)&&!i.announced){let d={...i,announced:!0};return await a(d),d}return null}function Qi({isBusy:e,start:t=Io,onStuck:n=null,onStarted:r=null,tickMs:i=Gi,stuckMs:a=Ki,now:d=Date.now,setIntervalImpl:h=setInterval,clearIntervalImpl:m=clearInterval,log:g=console}={}){let f=null,S=()=>{f?.timer&&m(f.timer),f=null},$=async()=>{if(!f)return;let b=!0;try{b=await e()!==!1}catch{b=!0}if(b){if(!f.stuckFired&&d()-f.since>=a){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let v=f;S();let R=await t({to:v.to,from:v.from,kind:v.kind,reason:"auto"});g.log?.(`[self-update] stasis reached \u2192 ${R.ok?"started":`not started: ${R.reason}`}`);try{await r?.({...v,result:R})}catch{}};return{arm({to:b,from:v=Ct,kind:R=He()}){return f?.to===b?!1:(S(),f={to:b,from:v,kind:R,since:d(),stuckFired:!1,timer:h($,i)},f.timer.unref?.(),!0)},tick:$,cancel:S,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var Ct,Wi,Dt,Bt,Ki,Gi,Nn,In,Mn,Pt,$o,Eo,Oo,Lt,X,Yi,Bn,Ji,Po=x(()=>{Rn();ko();Ct=(()=>{try{return Hi(import.meta.url)("../package.json").version||null}catch{return null}})(),Wi=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||ji.tmpdir(),".bostrat"),Dt=U.join(Wi,"self-update"),Bt=U.join(Dt,"status.json"),Ki=1440*6e4,Gi=6e4,Nn=60,In=15,Mn=3,Pt=6,$o=20,Eo=U.join(Dt,"supervisor.pid"),Oo="SIGUSR2",Lt=new Set(["npm-global","git-checkout"]);X=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Yi=new Set(["updating","restarting","rolling-back"]),Bn=e=>!!(e&&Yi.has(e.status));Ji=45*6e4});on();an();wn();import K from"node:fs";import M from"node:path";import Ke from"node:os";import{createRequire as Ln}from"node:module";import{execFile as ea,spawn as ta}from"node:child_process";import{promisify as na}from"node:util";import ra from"node:readline/promises";import{randomUUID as oa}from"node:crypto";import{fileURLToPath as sa}from"node:url";import Ys from"node:fs";import jr from"node:path";import qs from"node:os";var Xs=()=>process.env.BOSTRAT_STATE_DIR||jr.join(process.env.HOME||qs.tmpdir(),".bostrat"),Js=()=>jr.join(Xs(),"plane-link","public-host.json");var lt=null;function Zs(){if(lt)return lt;try{let e=JSON.parse(Ys.readFileSync(Js(),"utf8"));lt={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{lt={viewBase:null}}return lt}function Qs(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),i=r?r[1].toLowerCase():t,a=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return a?{proto:i,host:a}:null}function Fr(){return Zs().viewBase}function Ur(e=process.env.BOSTRAT_PUBLIC_HOST){return Qs(e,"https")}function Hr(e=process.env.BOSTRAT_PLANE_URL){let t=String(e||"").trim();if(!t)return null;let n=/^(wss?|https?):\/\/([^/?#]+)/i.exec(t);return n?`${/^(wss|https)$/i.test(n[1])?"https":"http"}://${n[2]}`:null}Et();import ei from"node:fs";import ti from"node:os";import Wr from"node:path";var Kr=3*6e4;function Tn(e=process.env){let t=e.BOSTRAT_STATE_DIR||Wr.join(e.HOME||ti.tmpdir(),".bostrat");return Wr.join(t,"heartbeat.json")}function Gr(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return Kr;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):Kr}function zr(e=Tn()){try{let t=JSON.parse(ei.readFileSync(e,"utf8"));if(!t||typeof t!="object")return null;let n=Number(t.ts),r=Number(t.pid);if(!Number.isFinite(n)||!Number.isFinite(r))return null;let i=Number(t.loopLagMs);return{pid:r,ts:n,loopLagMs:Number.isFinite(i)?i:null}}catch{return null}}Et();var Yr="BOSTRAT_RESTART_NOTICE",Tu=2*6e4;var Vr=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function qr({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:Vr(e),staleS:Vr(t)!=null?Math.round(t/1e3):null})}var Co=(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 i=0;i<Math.max(n.length,r.length);i++){let a=(n[i]||0)-(r[i]||0);if(a)return a<0}return!1},me=na(ea),jn=M.dirname(sa(import.meta.url)),xe=M.resolve(jn,".."),ia=M.join(jn,"index.js"),aa="wss://plane.bostrat.ai/v1/node",We=Ln(import.meta.url)("../package.json").version,B=(e,t)=>({name:e,level:"pass",detail:t}),J=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),V=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function ca(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?B("node runtime",`${process.version} at ${process.execPath}`):V("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function la(e){return e.BOSTRAT_OWNER?J("owner stamp",`BOSTRAT_OWNER=${String(e.BOSTRAT_OWNER).slice(0,12)}\u2026 is set \u2014 ignored by this release; on older releases it got every event refused (forgedUserId)`,"remove BOSTRAT_OWNER from node.env and any shell rc, then restart the node"):B("owner stamp","none (the plane infers the owner from the token)")}function ua(e){let t;try{t=K.statSync(e)}catch{return J("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?J("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):B("node.env",`${e} (0600)`)}async function da(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await me(t,["-V"],{timeout:5e3});return B("tmux",`${t} (${n.trim()})`)}catch{return V("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Do(e,{required:t=!1}={}){if(await gn(e,{loginShell:!0,failOpen:!1}))return B(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",i=Ot[e]?`${Ot[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?V(e,r,i):J(e,r,i)}async function fa(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await me(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return B("gh (GitHub CLI)",n)}catch{return J("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",Ot.gh)}}async function pa(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Do(t)));return e.some(t=>t.level==="pass")||e.push(V("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 ha(){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 gn(t,{failOpen:!1})?B(t,"resolves on the service PATH"):J(t,`not on the service PATH \u2014 ${n}`,r)))}async function ma(){try{let t=Ln(M.join(xe,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let i=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),a=setTimeout(()=>r(new Error("spawn timeout")),5e3);i.onExit(()=>{clearTimeout(a),n()})}),B("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${xe} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Ln(M.join(xe,"package.json")),r=M.join(M.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");K.existsSync(r)&&!(K.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return V("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function wa(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(K.existsSync(t))return B("chromium (mocks)",t);let n=process.platform==="darwin"?"brew install --cask chromium (or set BOSTRAT_CHROMIUM_BIN to Chrome.app's inner binary)":"apt install chromium fonts-dejavu-core fonts-liberation (or set BOSTRAT_CHROMIUM_BIN)";return(e.BOSTRAT_INSTALL_KIND==="container"?V:J)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function ya(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?V("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"):B("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function ga(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return J("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(),i=tt(e.BOSTRAT_PLANE_URL);return await new Promise(a=>{let d=new n(i,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),h=null,m=f=>{clearTimeout(g);try{d.close()}catch{}a(h?{...f,viewBase:h}:f)},g=setTimeout(()=>m(V("plane link",`no hello_ok within 5s from ${i}`,"check the URL, the token, and the plane's IP gate")),5e3);d.on("open",()=>d.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${oa().slice(0,8)}`,ephemeral:!0}))),d.on("message",f=>{try{let S=JSON.parse(f);S.type==="hello_ok"?(typeof S.viewBase=="string"&&S.viewBase&&(h=S.viewBase),S.minNodeVersion&&Co(We,S.minNodeVersion)?m(V("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${S.minNodeVersion} \u2014 this node is ${We}; the real link is refused until it updates`,`bostrat-node self-update --to ${S.latestNodeVersion||S.minNodeVersion}`)):S.latestNodeVersion&&Co(We,S.latestNodeVersion)?m(J("plane link",`hello_ok in ${Date.now()-r}ms (${i}); bostrat-node ${S.latestNodeVersion} is available (this node: ${We})`,`bostrat-node self-update --to ${S.latestNodeVersion}`)):m(B("plane link",`hello_ok in ${Date.now()-r}ms (${i})`))):S.type==="error"&&m(V("plane link",`plane said: ${S.code} ${S.message||""}`,"check the token"))}catch{}}),d.on("error",f=>m(V("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function Ta(){let e;try{e=JSON.parse(K.readFileSync(M.join(Tt,"content-outbox.json"),"utf8"))}catch{return B("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 V("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?J("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"):B("content outbox",t?`${t} op(s) in flight`:"drained")}async function Sa(e){let t=await Ir({env:e}),n=Mr(t);return t.available?B("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?J("box caps",n,"boxes run under nice only on this node; if Fly's init mounts /sys/fs/cgroup read-only this is the expected state (blueprint BP-NG-I4)"):B("box caps",n)}function _a(e){return e.BOSTRAT_STATE_REMOTE?B("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):J("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")}function ba(e,t){let n=t?.viewBase??null,r=Fr(),i=Ur(e.BOSTRAT_PUBLIC_HOST),a=(()=>{let d=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(d)return`${d.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let h=Hr(e.BOSTRAT_PLANE_URL);return h?`${h}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let d=i&&i.host!==n?`; BOSTRAT_PUBLIC_HOST=${i.host} is set but the plane's value wins`:"";return B("public host",`views https://<slug>.${n}/ (plane hello_ok)${d} \xB7 track links ${a}`)}return r?B("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${a}`):i?B("public host",`views ${i.proto}://<slug>.${i.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${a}`):V("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${a}`,"link a plane that sets PLANE_VIEW_BASE (bostrat-node init), or set BOSTRAT_PUBLIC_HOST in node.env for a plane-less node")}async function Bo(e,t={}){let n=[];n.push(await ca()),n.push(ua(t.envFile||Ce())),n.push(await da(e)),n.push(await Sa(e)),n.push(...await pa()),n.push(await Do("git",{required:!0})),n.push(await fa()),n.push(...await ha()),n.push(await ma()),n.push(wa(e)),n.push(ya(e)),n.push(la(e));let r=await ga(e,t);return n.push(r),n.push(ba(e,r)),n.push(Ta()),n.push(_a(e)),n}function Lo(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,i=e.filter(a=>a.level==="warn").length;return t(r?`
|
|
208
|
+
`}async function Dn(e=Bt){try{return JSON.parse(await he.readFile(e,"utf8"))}catch{return null}}async function Io({to:e,from:t=Ct,kind:n=He(),reason:r="manual",force:i=!1,statusFile:a=Bt,spawnImpl:d=Fi,now:h=Date.now,npmPrefix:m=void 0,log:g=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!Lt.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Ue(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let f=await Dn(a);if(Bn(f))return{ok:!1,reason:`an update to ${f.to} is already in flight`,status:f};let S=f?.to===e?Number(f.attempts)||1:0;if(!i&&f&&f.to===e&&(f.status==="failed"||f.status==="rolled-back")&&!(f.status==="failed"&&f.retryable===!0&&S<Mn))return{ok:!1,reason:`update to ${e} already ${f.status} (${f.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:f};let $=f?.to===e&&(f.status==="failed"||f.status==="rolled-back")?S+1:1;await he.mkdir(U.dirname(a),{recursive:!0});let b=m!==void 0?m:n==="npm-global"?cn(await qi())||U.resolve(U.dirname(process.execPath),".."):null,v=Cn(),R=No({kind:n,to:e,from:t,statusFile:a,npmPrefix:b,startedAt:h(),attempts:$,restart:v}),E=U.join(U.dirname(a),`update-${e}.sh`),P=U.join(U.dirname(a),"last.log");await he.writeFile(E,R,{mode:448}),await he.writeFile(a,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:$,startedAt:h(),updatedAt:h()}));let k=ft.existsSync("/run/systemd/system")&&await Xi("systemd-run"),_=k?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",E]]:["bash",[E]],x=async L=>{let C=`could not spawn updater: ${L?.message||L}`;return await he.writeFile(a,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,attempts:$,startedAt:h(),updatedAt:h(),error:C})).catch(()=>{}),g.error?.(`[self-update] ${C}`),C},N=null;try{k||(N=ft.openSync(P,"a"));let L=d(_[0],_[1],{detached:!0,stdio:k?"ignore":["ignore",N,N]});L.on?.("error",C=>{x(C)}),L.unref?.()}catch(L){return{ok:!1,reason:await x(L)}}finally{N!==null&&ft.closeSync(N)}return g.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}, restart via ${v.mode}) started \u2014 status ${a}`),{ok:!0,to:e,from:t,kind:n,scriptFile:E,statusFile:a}}async function qi(){try{return await he.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Xi(e){for(let t of String(process.env.PATH||"").split(U.delimiter))try{return await he.access(U.join(t,e),ft.constants.X_OK),!0}catch{}return!1}async function Zi({statusFile:e=Bt,current:t=Ct,now:n=Date.now,staleMs:r=Ji}={}){let i=await Dn(e);if(!i)return null;let a=d=>he.writeFile(e,JSON.stringify(d)).catch(()=>{});if(Bn(i)){if(t&&i.to===t){let d={...i,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await a(d),d}if(n()-Number(i.updatedAt||i.startedAt||0)>r){let d={...i,status:"failed",error:`updater went silent while ${i.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await a(d),d}return null}if(["failed","rolled-back","done"].includes(i.status)&&!i.announced){let d={...i,announced:!0};return await a(d),d}return null}function Qi({isBusy:e,start:t=Io,onStuck:n=null,onStarted:r=null,tickMs:i=Gi,stuckMs:a=Ki,now:d=Date.now,setIntervalImpl:h=setInterval,clearIntervalImpl:m=clearInterval,log:g=console}={}){let f=null,S=()=>{f?.timer&&m(f.timer),f=null},$=async()=>{if(!f)return;let b=!0;try{b=await e()!==!1}catch{b=!0}if(b){if(!f.stuckFired&&d()-f.since>=a){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let v=f;S();let R=await t({to:v.to,from:v.from,kind:v.kind,reason:"auto"});g.log?.(`[self-update] stasis reached \u2192 ${R.ok?"started":`not started: ${R.reason}`}`);try{await r?.({...v,result:R})}catch{}};return{arm({to:b,from:v=Ct,kind:R=He()}){return f?.to===b?!1:(S(),f={to:b,from:v,kind:R,since:d(),stuckFired:!1,timer:h($,i)},f.timer.unref?.(),!0)},tick:$,cancel:S,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var Ct,Wi,Dt,Bt,Ki,Gi,Nn,In,Mn,Pt,$o,Eo,Oo,Lt,X,Yi,Bn,Ji,Po=A(()=>{Rn();ko();Ct=(()=>{try{return Hi(import.meta.url)("../package.json").version||null}catch{return null}})(),Wi=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||ji.tmpdir(),".bostrat"),Dt=U.join(Wi,"self-update"),Bt=U.join(Dt,"status.json"),Ki=1440*6e4,Gi=6e4,Nn=60,In=15,Mn=3,Pt=6,$o=20,Eo=U.join(Dt,"supervisor.pid"),Oo="SIGUSR2",Lt=new Set(["npm-global","git-checkout"]);X=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Yi=new Set(["updating","restarting","rolling-back"]),Bn=e=>!!(e&&Yi.has(e.status));Ji=45*6e4});on();an();wn();import K from"node:fs";import M from"node:path";import Ke from"node:os";import{createRequire as Ln}from"node:module";import{execFile as ea,spawn as ta}from"node:child_process";import{promisify as na}from"node:util";import ra from"node:readline/promises";import{randomUUID as oa}from"node:crypto";import{fileURLToPath as sa}from"node:url";import Ys from"node:fs";import jr from"node:path";import qs from"node:os";var Xs=()=>process.env.BOSTRAT_STATE_DIR||jr.join(process.env.HOME||qs.tmpdir(),".bostrat"),Js=()=>jr.join(Xs(),"plane-link","public-host.json");var lt=null;function Zs(){if(lt)return lt;try{let e=JSON.parse(Ys.readFileSync(Js(),"utf8"));lt={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{lt={viewBase:null}}return lt}function Qs(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),i=r?r[1].toLowerCase():t,a=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return a?{proto:i,host:a}:null}function Fr(){return Zs().viewBase}function Ur(e=process.env.BOSTRAT_PUBLIC_HOST){return Qs(e,"https")}function Hr(e=process.env.BOSTRAT_PLANE_URL){let t=String(e||"").trim();if(!t)return null;let n=/^(wss?|https?):\/\/([^/?#]+)/i.exec(t);return n?`${/^(wss|https)$/i.test(n[1])?"https":"http"}://${n[2]}`:null}Et();import ei from"node:fs";import ti from"node:os";import Wr from"node:path";var Kr=3*6e4;function Tn(e=process.env){let t=e.BOSTRAT_STATE_DIR||Wr.join(e.HOME||ti.tmpdir(),".bostrat");return Wr.join(t,"heartbeat.json")}function Gr(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return Kr;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):Kr}function zr(e=Tn()){try{let t=JSON.parse(ei.readFileSync(e,"utf8"));if(!t||typeof t!="object")return null;let n=Number(t.ts),r=Number(t.pid);if(!Number.isFinite(n)||!Number.isFinite(r))return null;let i=Number(t.loopLagMs);return{pid:r,ts:n,loopLagMs:Number.isFinite(i)?i:null}}catch{return null}}Et();var Yr="BOSTRAT_RESTART_NOTICE",Tu=2*6e4;var Vr=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function qr({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:Vr(e),staleS:Vr(t)!=null?Math.round(t/1e3):null})}var Co=(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 i=0;i<Math.max(n.length,r.length);i++){let a=(n[i]||0)-(r[i]||0);if(a)return a<0}return!1},me=na(ea),jn=M.dirname(sa(import.meta.url)),Ae=M.resolve(jn,".."),ia=M.join(jn,"index.js"),aa="wss://plane.bostrat.ai/v1/node",We=Ln(import.meta.url)("../package.json").version,B=(e,t)=>({name:e,level:"pass",detail:t}),J=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),V=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function ca(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?B("node runtime",`${process.version} at ${process.execPath}`):V("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function la(e){return e.BOSTRAT_OWNER?J("owner stamp",`BOSTRAT_OWNER=${String(e.BOSTRAT_OWNER).slice(0,12)}\u2026 is set \u2014 ignored by this release; on older releases it got every event refused (forgedUserId)`,"remove BOSTRAT_OWNER from node.env and any shell rc, then restart the node"):B("owner stamp","none (the plane infers the owner from the token)")}function ua(e){let t;try{t=K.statSync(e)}catch{return J("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?J("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):B("node.env",`${e} (0600)`)}async function da(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await me(t,["-V"],{timeout:5e3});return B("tmux",`${t} (${n.trim()})`)}catch{return V("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Do(e,{required:t=!1}={}){if(await gn(e,{loginShell:!0,failOpen:!1}))return B(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",i=Ot[e]?`${Ot[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?V(e,r,i):J(e,r,i)}async function fa(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await me(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return B("gh (GitHub CLI)",n)}catch{return J("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",Ot.gh)}}async function pa(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Do(t)));return e.some(t=>t.level==="pass")||e.push(V("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 ha(){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 gn(t,{failOpen:!1})?B(t,"resolves on the service PATH"):J(t,`not on the service PATH \u2014 ${n}`,r)))}async function ma(){try{let t=Ln(M.join(Ae,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let i=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),a=setTimeout(()=>r(new Error("spawn timeout")),5e3);i.onExit(()=>{clearTimeout(a),n()})}),B("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${Ae} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Ln(M.join(Ae,"package.json")),r=M.join(M.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");K.existsSync(r)&&!(K.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return V("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function wa(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(K.existsSync(t))return B("chromium (mocks)",t);let n=process.platform==="darwin"?"brew install --cask chromium (or set BOSTRAT_CHROMIUM_BIN to Chrome.app's inner binary)":"apt install chromium fonts-dejavu-core fonts-liberation (or set BOSTRAT_CHROMIUM_BIN)";return(e.BOSTRAT_INSTALL_KIND==="container"?V:J)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function ya(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?V("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"):B("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function ga(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return J("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(),i=tt(e.BOSTRAT_PLANE_URL);return await new Promise(a=>{let d=new n(i,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),h=null,m=f=>{clearTimeout(g);try{d.close()}catch{}a(h?{...f,viewBase:h}:f)},g=setTimeout(()=>m(V("plane link",`no hello_ok within 5s from ${i}`,"check the URL, the token, and the plane's IP gate")),5e3);d.on("open",()=>d.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${oa().slice(0,8)}`,ephemeral:!0}))),d.on("message",f=>{try{let S=JSON.parse(f);S.type==="hello_ok"?(typeof S.viewBase=="string"&&S.viewBase&&(h=S.viewBase),S.minNodeVersion&&Co(We,S.minNodeVersion)?m(V("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${S.minNodeVersion} \u2014 this node is ${We}; the real link is refused until it updates`,`bostrat-node self-update --to ${S.latestNodeVersion||S.minNodeVersion}`)):S.latestNodeVersion&&Co(We,S.latestNodeVersion)?m(J("plane link",`hello_ok in ${Date.now()-r}ms (${i}); bostrat-node ${S.latestNodeVersion} is available (this node: ${We})`,`bostrat-node self-update --to ${S.latestNodeVersion}`)):m(B("plane link",`hello_ok in ${Date.now()-r}ms (${i})`))):S.type==="error"&&m(V("plane link",`plane said: ${S.code} ${S.message||""}`,"check the token"))}catch{}}),d.on("error",f=>m(V("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function Ta(){let e;try{e=JSON.parse(K.readFileSync(M.join(Tt,"content-outbox.json"),"utf8"))}catch{return B("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 V("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?J("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"):B("content outbox",t?`${t} op(s) in flight`:"drained")}async function Sa(e){let t=await Ir({env:e}),n=Mr(t);return t.available?B("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?J("box caps",n,"boxes run under nice only on this node; if Fly's init mounts /sys/fs/cgroup read-only this is the expected state (blueprint BP-NG-I4)"):B("box caps",n)}function _a(e){return e.BOSTRAT_STATE_REMOTE?B("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):J("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")}function ba(e,t){let n=t?.viewBase??null,r=Fr(),i=Ur(e.BOSTRAT_PUBLIC_HOST),a=(()=>{let d=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(d)return`${d.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let h=Hr(e.BOSTRAT_PLANE_URL);return h?`${h}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let d=i&&i.host!==n?`; BOSTRAT_PUBLIC_HOST=${i.host} is set but the plane's value wins`:"";return B("public host",`views https://<slug>.${n}/ (plane hello_ok)${d} \xB7 track links ${a}`)}return r?B("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${a}`):i?B("public host",`views ${i.proto}://<slug>.${i.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${a}`):V("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${a}`,"link a plane that sets PLANE_VIEW_BASE (bostrat-node init), or set BOSTRAT_PUBLIC_HOST in node.env for a plane-less node")}async function Bo(e,t={}){let n=[];n.push(await ca()),n.push(ua(t.envFile||Ce())),n.push(await da(e)),n.push(await Sa(e)),n.push(...await pa()),n.push(await Do("git",{required:!0})),n.push(await fa()),n.push(...await ha()),n.push(await ma()),n.push(wa(e)),n.push(ya(e)),n.push(la(e));let r=await ga(e,t);return n.push(r),n.push(ba(e,r)),n.push(Ta()),n.push(_a(e)),n}function Lo(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,i=e.filter(a=>a.level==="warn").length;return t(r?`
|
|
209
209
|
FAIL \u2014 ${r} blocking, ${i} warnings`:`
|
|
210
210
|
OK \u2014 0 blocking, ${i} warnings`),r===0}async function va({envFile:e=Ce(),input:t=process.stdin,output:n=process.stdout}={}){let r=St(e),i=ra.createInterface({input:t,output:n}),a=async(k,_)=>(await i.question(_?`${k} [${_}]: `:`${k}: `)).trim()||_||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
|
|
211
211
|
you type those inside each box, later (box-auth-policy).
|
|
@@ -225,8 +225,8 @@ Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores b
|
|
|
225
225
|
wrote ${e}
|
|
226
226
|
|
|
227
227
|
`);let R={...v,...process.env},E=await Bo(R,{envFile:e}),P=Lo(E,k=>n.write(k+`
|
|
228
|
-
`));return P&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:P,results:E}}var
|
|
229
|
-
`)}catch{}let r=Gr(process.env),i=Tn(process.env);console.log(r?`[bostrat-node] stall watchdog: relaunch the agent after ${Math.round(r/1e3)} s without a heartbeat (${i})`:"[bostrat-node] stall watchdog: off (BOSTRAT_HEARTBEAT_STALE_MS)");let a=$a({spawnChild:d=>ta(t,[ia],{cwd:
|
|
228
|
+
`));return P&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:P,results:E}}var xa="SIGUSR2",Aa=5*6e4,ka=1e4,jt=M.join(Tt,"self-update","supervisor.pid");function $a({spawnChild:e,exit:t=g=>process.exit(g),now:n=Date.now,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:i=clearTimeout,killGraceMs:a=15e3,rollbackGraceMs:d=Aa,stall:h=null,log:m=console}={}){let g=null,f=0,S=!1,$="update",b=0,v=null,R=null,E=null,P=0,k=0,_=0,x=!1,N=h&&h.staleMs>0?h.staleMs:0,L=h?.checkMs>0?h.checkMs:ka,C=()=>{v&&i(v),v=null},ke=()=>{g.kill("SIGTERM"),R=r(()=>g?.kill("SIGKILL"),a),R.unref?.()},Ge=null,$e=0,Ft=()=>{let O=null;try{O=h.readHeartbeat()}catch{}return O&&O.pid===g.pid&&Number.isFinite(O.ts)&&O.ts!==Ge&&(Ge=O.ts,$e=Math.max($e,Math.min(O.ts,n()))),n()-$e},pt=()=>{if(!g||x||S||!N)return!1;let O=Ft();return O<N?!1:(k++,_=O,m.error?.(`[bostrat-node] the agent (pid ${g.pid}) has written no heartbeat for ${Math.round(O/1e3)} s \u2014 stalled; relaunching it in place (boxes keep running on the host tmux server; stall relaunch #${k})`),$="stall",S=!0,ke(),!0)},Ee=()=>{N&&(E&&i(E),E=r(()=>{E=null,pt(),Ee()},L),E.unref?.())},ze=(O=null)=>{let ce=e(O);return g=ce,f=n(),Ge=null,$e=f,ce.on("exit",(le,ue)=>Oe(ce,le,ue)),E||Ee(),ce},Oe=(O,ce,le)=>{if(O!==g)return;if(g=null,R&&i(R),R=null,S){S=!1,Ve($);return}let ue=le?1:ce??1;if(!x&&ue!==0&&n()<b){let Ye=b-n();m.error?.(`[bostrat-node] the agent exited (code ${ue}) right after a self-update restart \u2014 holding ${Math.ceil(Ye/1e3)} s for the updater's rollback signal`),v=r(()=>t(ue),Ye);return}t(ue)},Ve=(O="update")=>{P++,O==="stall"?m.log?.(`[bostrat-node] relaunched the agent after a stall (restart #${P}, stall relaunch #${k})`):(b=n()+d,m.log?.(`[bostrat-node] restarting the agent (self-update, restart #${P})`)),$="update",ze(O==="stall"?{at:n(),staleMs:_}:null)};return{start:()=>ze(),restart(){if(x=!1,C(),$="update",!g){Ve("update");return}S||(S=!0,ke())},checkStall:pt,forward(O){x=!0,g?g.kill(O):(C(),t(1))},get child(){return g},get state(){return{alive:!!g,restartPending:S,restartReason:$,holding:!!v,restarts:P,stallRelaunches:k,stopping:x}}}}function Ea({envFile:e=Ce()}={}){ar(e),process.title="bostrat-node";let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n={...process.env,BOSTRAT_RUN_SUPERVISOR_PID:String(process.pid)};try{K.mkdirSync(M.dirname(jt),{recursive:!0}),K.writeFileSync(jt,`${process.pid}
|
|
229
|
+
`)}catch{}let r=Gr(process.env),i=Tn(process.env);console.log(r?`[bostrat-node] stall watchdog: relaunch the agent after ${Math.round(r/1e3)} s without a heartbeat (${i})`:"[bostrat-node] stall watchdog: off (BOSTRAT_HEARTBEAT_STALE_MS)");let a=$a({spawnChild:d=>ta(t,[ia],{cwd:Ae,stdio:"inherit",env:d?{...n,[Yr]:qr(d)}:n}),stall:r?{readHeartbeat:()=>zr(i),staleMs:r}:null});for(let d of["SIGINT","SIGTERM"])process.on(d,()=>a.forward(d));return process.on(xa,()=>a.restart()),process.on("exit",()=>{try{K.readFileSync(jt,"utf8").trim()===String(process.pid)&&K.rmSync(jt,{force:!0})}catch{}}),a.start()}function Oa({agentDir:e=Ae,nodeBin:t=process.execPath,envFile:n=Ce(),home:r=Ke.homedir()}={}){let i=M.dirname(t),a=M.join(M.basename(jn),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
|
|
230
230
|
# ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
|
|
231
231
|
[Unit]
|
|
232
232
|
Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
|
|
@@ -246,7 +246,7 @@ RestartSec=2
|
|
|
246
246
|
|
|
247
247
|
[Install]
|
|
248
248
|
WantedBy=default.target
|
|
249
|
-
`}function Ra({agentDir:e=
|
|
249
|
+
`}function Ra({agentDir:e=Ae,nodeBin:t=process.execPath,home:n=Ke.homedir()}={}){let r=M.dirname(t),i=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
|
|
250
250
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
251
251
|
<plist version="1.0">
|
|
252
252
|
<dict>
|
|
@@ -268,7 +268,7 @@ WantedBy=default.target
|
|
|
268
268
|
<key>StandardErrorPath</key><string>${i}/node.err.log</string>
|
|
269
269
|
</dict>
|
|
270
270
|
</plist>
|
|
271
|
-
`}function Na(e=process.platform,t=Ke.homedir()){return e==="darwin"?{kind:"launchd",file:M.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:M.join(t,".config","systemd","user","bostrat-node.service")}}async function Ia({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:i=
|
|
271
|
+
`}function Na(e=process.platform,t=Ke.homedir()){return e==="darwin"?{kind:"launchd",file:M.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:M.join(t,".config","systemd","user","bostrat-node.service")}}async function Ia({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:i=Ae}={}){let{kind:a,file:d}=Na(n);if(!e&&i.split(M.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 me("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),K.rmSync(d,{force:!0}),await me("systemctl",["--user","daemon-reload"])):(await me("launchctl",["unload","-w",d]).catch(()=>{}),K.rmSync(d,{force:!0})),r(`removed ${d}`);return}K.mkdirSync(M.dirname(d),{recursive:!0}),a==="systemd"?(K.writeFileSync(d,Oa()),await me("systemctl",["--user","daemon-reload"]),t&&await me("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${d}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(K.mkdirSync(M.join(Ke.homedir(),"Library","Logs","bostrat"),{recursive:!0}),K.writeFileSync(d,Ra()),t&&await me("launchctl",["load","-w",d]),r(`installed ${d}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function Od(e=process.argv.slice(2)){let t=e[0],n=Ce();if(t==="--version"||t==="-v"||t==="version")return console.log(We),0;if(t==="init")return(await va({envFile:n})).ok?0:1;if(t==="doctor"){let r={...St(n),...process.env};return Lo(await Bo(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return Ea({envFile:n}),null;if(t==="install-service")return await Ia({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(no(),to));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:i,updatePolicy:a}=await Promise.resolve().then(()=>(Po(),Mo)),{detectInstallKind:d}=await Promise.resolve().then(()=>(Rn(),Ao)),h=d(),m=e.indexOf("--to"),g=m>=0?String(e[m+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:We,installKind:h,policy:a({kind:h}),status:await i()},null,2)),0;if(!g)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 f=await r({to:g,kind:h,reason:"cli",force:!0});return f.ok?(console.log(`\u2713 self-update ${f.from??"?"} \u2192 ${f.to} started (${f.kind}) \u2014 status: ${f.statusFile}; the node restarts when the install completes`),0):(console.error(`\u2717 not started: ${f.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
|
|
272
272
|
|
|
273
273
|
usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
|
|
274
274
|
|
|
@@ -277,4 +277,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
|
|
|
277
277
|
run start the node in the foreground (sources node.env)
|
|
278
278
|
install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
|
|
279
279
|
fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
|
|
280
|
-
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{
|
|
280
|
+
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{xa as RESTART_SIGNAL,Aa as ROLLBACK_GRACE_MS,ka as STALL_CHECK_MS,jt as SUPERVISOR_PID_FILE,$a as createRunSupervisor,va as init,Ia as installService,Ra as launchdPlist,Od as main,Lo as printDoctor,Ea as runAgent,Bo as runDoctor,Na as servicePaths,Oa as systemdUnit};
|