bostrat-node 1.15.4 → 1.15.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +34 -34
- package/dist/index.js +269 -269
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
var hs=Object.defineProperty;var R=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var cn=(e,t)=>{for(var n in t)hs(e,n,{get:t[n],enumerable:!0})};import _t from"node:fs";import ln from"node:path";import ms from"node:os";function nt(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 s={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return s?(r.protocol=s,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function vt(e){let t;try{t=_t.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
|
|
2
|
-
`)){let s=r.trim();if(!s||s.startsWith("#"))continue;let a=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(s);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
|
|
2
|
+
`)){let s=r.trim();if(!s||s.startsWith("#"))continue;let a=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(s);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 fr(e,t=process.env){let n=vt(e);for(let[r,s]of Object.entries(n))r in t||(t[r]=s);return n}function hr(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
|
|
3
3
|
`).map(s=>s?`# ${s}`:"#"));for(let[s,a]of Object.entries(t))a==null||a===""||r.push(`${s}=${a}`);_t.mkdirSync(ln.dirname(e),{recursive:!0}),_t.writeFileSync(e,r.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`,{mode:384}),_t.chmodSync(e,384)}function mr(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 bt,Be,un=R(()=>{bt=process.env.BOSTRAT_STATE_DIR||ln.join(process.env.HOME||ms.tmpdir(),".bostrat"),Be=()=>ln.join(bt,"node.env")});var ae,rt,xt=R(()=>{ae="BOSTRAT_HOOK_TOKEN",rt="x-bostrat-hook"});var wr=R(()=>{xt()});var ws,mc,yr=R(()=>{ws="check_for_update_on_startup",mc=`${ws} = false`});import ys from"node:os";import gr from"node:path";var gs,Sc,_c,dn=R(()=>{
|
|
6
|
-
`))if(d.trim())try{a.push(JSON.parse(Ds(d)?Ls(d):d))}catch{}return a}var ct,
|
|
5
|
+
`,{mode:384}),_t.chmodSync(e,384)}function mr(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 bt,Be,un=R(()=>{bt=process.env.BOSTRAT_STATE_DIR||ln.join(process.env.HOME||ms.tmpdir(),".bostrat"),Be=()=>ln.join(bt,"node.env")});var ae,rt,xt=R(()=>{ae="BOSTRAT_HOOK_TOKEN",rt="x-bostrat-hook"});var wr=R(()=>{xt()});var ws,mc,yr=R(()=>{ws="check_for_update_on_startup",mc=`${ws} = false`});import ys from"node:os";import gr from"node:path";var gs,Sc,_c,dn=R(()=>{pn();gs=process.env.BOSTRAT_DEBUG_DIR||gr.join(ys.homedir(),".bostrat","debug"),Sc=gr.join(gs,"handoff.jsonl"),_c=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as Ss}from"node:child_process";import{promisify as _s}from"node:util";function fn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var kc,Ec,Oc,Rc,hn=R(()=>{dn();kc=_s(Ss),Ec=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Oc=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,Rc=Promise.resolve()});var Tr=R(()=>{});import mn from"node:path";import{execFile as bs}from"node:child_process";import{promisify as vs}from"node:util";var Cc,Sr,xs,Dc,Lc,_r=R(()=>{Cc=vs(bs),Sr=process.env.HOME||"/home/globo",xs=mn.join(process.env.BOSTRAT_STATE_DIR||mn.join(Sr,".bostrat"),"repos"),Dc=[...(process.env.BOSTRAT_REPOS_ROOT||mn.join(Sr,"Documents")).split(","),xs].map(e=>e.trim()).filter(Boolean),Lc=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function kt(e=Date.now()){if(ve)return{tripped:!1,holdMs:1/0};if(be>e)return{tripped:!1,holdMs:be-e};if((!st||e-st>=At.windowMs)&&(st=e,ot=0),ot++,ot<At.trip)return{tripped:!1,holdMs:0};$t++;let t=Math.min(At.minMs*2**($t-1),At.maxMs);return be=e+t,ot=0,st=0,{tripped:!0,holdMs:t}}function br(){ot=0,st=0,$t=0,be=0}function it(e=Date.now()){return ve?1/0:be>e?be-e:0}function Et(e=Date.now()){return it(e)>0}function wn(e={}){ve={at:Date.now(),...e},be=1/0}function yn(){return ve}function vr(e=Date.now()){return{held:Et(e),holdMs:ve?null:it(e),holds:$t,removed:ve?{...ve}:null}}var As,At,ot,st,$t,be,ve,gn=R(()=>{As={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},At={...As},ot=0,st=0,$t=0,be=0,ve=null});import xr from"node:path";import $s from"node:os";import{execFile as ks}from"node:child_process";import{promisify as Es}from"node:util";var Yc,Os,qc,Xc,Jc,Tn=R(()=>{_r();gn();Yc=Es(ks),Os=process.env.BOSTRAT_STATE_DIR||xr.join(process.env.HOME||$s.tmpdir(),".bostrat"),qc=xr.join(Os,"repos"),Xc=5*6e4,Jc=10*6e4});var Ar=R(()=>{Tn()});import Ns from"node:fs/promises";import at from"node:path";import Ms from"node:os";import{EventEmitter as Is}from"node:events";function Ps(e){return e?.cwd?at.join(e.cwd,".bostrat","events"):at.join($r,"events")}async function Ot(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?at.join($r,"events"):Ps(e));let s;try{s=await Ns.readFile(Bs(n,r),"utf8")}catch{return[]}let a=[];for(let d of s.split(`
|
|
6
|
+
`))if(d.trim())try{a.push(JSON.parse(Ds(d)?Ls(d):d))}catch{}return a}var ct,$r,Bs,Cs,Ds,Ls,Rt=R(()=>{ct=new Is;ct.setMaxListeners(0);$r=process.env.BOSTRAT_STATE_DIR||at.join(process.env.HOME||Ms.tmpdir(),".bostrat");Bs=(e,t)=>at.join(e,`${t}.ndjson`),Cs=/(?<!\\)((?:\\\\)*)\\u0000/g,Ds=e=>e.includes("\\u0000"),Ls=e=>e.replace(Cs,"$1\\ufffd")});import js from"node:os";import Us from"node:path";import{execFile as Hs}from"node:child_process";import{promisify as Ws}from"node:util";var hl,ml,wl,yl,gl,Tl,kr=R(()=>{Ar();Rt();hl=Ws(Hs),ml=process.env.BOSTRAT_STATE_DIR||Us.join(process.env.HOME||js.tmpdir(),".bostrat"),wl=25*1024,yl=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,gl=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,Tl=Promise.resolve()});var Nt=R(()=>{});var xl,Or=R(()=>{Tn();Nt();xl=60*6e4});var Rr=R(()=>{Or()});import Nr from"node:path";import Ks from"node:os";var Ce,Gs,Cl,Sn,Dl,Ll,Fl,Mr=R(()=>{xt();Ce="BOSTRAT_NODE_URL",Gs=process.env.BOSTRAT_STATE_DIR||Nr.join(process.env.HOME||Ks.tmpdir(),".bostrat"),Cl=Nr.join(Gs,"git-hooks"),Sn=`#!/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,8 +47,8 @@ exit 0
|
|
|
47
47
|
curl -sS -m 3 -X POST "$${Ce}/api/deps/refresh" \\
|
|
48
48
|
-H 'content-type: application/json' -H "${rt}: $${ae}" --data-binary '{}' >/dev/null 2>&1 || true
|
|
49
49
|
exit 0
|
|
50
|
-
`});import lt from"node:fs/promises";import Mt from"node:os";import De from"node:path";import{execFile as zs}from"node:child_process";import{promisify as Vs}from"node:util";function Br(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function Cr(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 ei(e=process.env){let t=Cr(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function Dr(e=Mt.totalmem()){return Math.max(e-Xs*ut,Math.floor(e/2))}function ti(e=Mt.totalmem(),t=process.env){let n=Number(t.BOSTRAT_BOX_MEMORY_MAX_MB);return Number.isFinite(n)&&n>=256?Math.floor(n)*ut:Math.min(Zs*ut,Dr(e))}function ni(e=process.env){return De.join(Br(e),Js)}async function ri(e){return(await lt.readFile(e,"utf8")).trim()}async function Lr({env:e=process.env,totalBytes:t=Mt.totalmem(),force:n=!1,platform:r=process.platform}={}){if(!n&&!ei(e))return Le=Cr(e)==="off"?{available:!1,reason:"disabled (BOSTRAT_BOX_CGROUPS=0)"}:await oi({env:e,totalBytes:t,platform:r}),Le;let s=Br(e),a=ni(e);try{let d;try{d=(await ri(De.join(s,"cgroup.controllers"))).split(/\s+/).filter(Boolean)}catch(
|
|
51
|
-
`)[0]})`}}let r=ti(t,e);return{available:!0,backend:"systemd",path:null,controllers:["memory"],cpuWeight:null,memoryMaxMb:Math.round(r/ut),swapMaxMb:Qs,systemctl:Pr(e),procRoot:e.BOSTRAT_PROC_ROOT||"/proc"}}function Fr(e=Le){let t=`nice ${qs} floor on every box`;if(!e)return`${t}; cgroup ceiling not probed yet`;if(e.available&&e.backend==="systemd")return`${t}; memory ceiling on each box's tmux-spawn scope, set through the systemd user manager (MemoryMax ${e.memoryMaxMb} MB, MemorySwapMax ${e.swapMaxMb} MB)`;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 Ys,qs,Ir,Xs,Js,Zs,Qs,ut,Le,Pr,_n=R(()=>{Ys=Vs(zs),qs=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),Ir=50,Xs=768,Js="bostrat-boxes",Zs=4096,Qs=512,ut=1024*1024;Le=null;Pr=(e=process.env)=>e.BOSTRAT_SYSTEMCTL_BIN||"systemctl"});import{execFile as si}from"node:child_process";import{promisify as ii}from"node:util";import Hr from"node:fs";import ai from"node:os";function Wr(e){return`/tmp/tmux-${e}/default`}function li({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let s=Wr(r);return t?s:n?`${n}/bostrat/tmux-default`:s}async function vn(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await di(e,{loginShell:t});return r===Kr?!0:r===bn?!1:n}async function di(e,{loginShell:t=!1,timeoutMs:n=ui}={}){if(!e)return bn;let r=t?process.env.SHELL||"/bin/sh":"sh",s=t?"-lic":"-c";try{return await ci(r,[s,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),Kr}catch(a){return a?.killed||a?.signal?Ur:a?.code===1||a?.code===127?bn:Ur}}var ci,bu,jr,vu,xu,Au
|
|
50
|
+
`});import lt from"node:fs/promises";import Mt from"node:os";import De from"node:path";import{execFile as zs}from"node:child_process";import{promisify as Vs}from"node:util";function Br(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function Cr(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 ei(e=process.env){let t=Cr(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function Dr(e=Mt.totalmem()){return Math.max(e-Xs*ut,Math.floor(e/2))}function ti(e=Mt.totalmem(),t=process.env){let n=Number(t.BOSTRAT_BOX_MEMORY_MAX_MB);return Number.isFinite(n)&&n>=256?Math.floor(n)*ut:Math.min(Zs*ut,Dr(e))}function ni(e=process.env){return De.join(Br(e),Js)}async function ri(e){return(await lt.readFile(e,"utf8")).trim()}async function Lr({env:e=process.env,totalBytes:t=Mt.totalmem(),force:n=!1,platform:r=process.platform}={}){if(!n&&!ei(e))return Le=Cr(e)==="off"?{available:!1,reason:"disabled (BOSTRAT_BOX_CGROUPS=0)"}:await oi({env:e,totalBytes:t,platform:r}),Le;let s=Br(e),a=ni(e);try{let d;try{d=(await ri(De.join(s,"cgroup.controllers"))).split(/\s+/).filter(Boolean)}catch(p){throw new Error(`no cgroup v2 tree at ${s} (${p?.code||p?.message||p})`)}let f=["cpu","memory"].filter(p=>d.includes(p));if(!f.length)throw new Error(`cgroup v2 at ${s} offers neither cpu nor memory (controllers: ${d.join(" ")||"none"})`);await lt.mkdir(a,{recursive:!0});let m=`+${f.join(" +")}`;for(let p of[De.join(s,"cgroup.subtree_control"),De.join(a,"cgroup.subtree_control")])try{await lt.writeFile(p,m)}catch(w){throw new Error(`cannot enable ${m} in ${p} (${w?.code||w?.message||w})`)}let S=Dr(t);f.includes("cpu")&&await lt.writeFile(De.join(a,"cpu.weight"),String(Ir)),f.includes("memory")&&await lt.writeFile(De.join(a,"memory.max"),String(S)),Le={available:!0,backend:"cgroupfs",path:a,controllers:f,cpuWeight:f.includes("cpu")?Ir:null,memoryMaxMb:f.includes("memory")?Math.round(S/ut):null}}catch(d){Le={available:!1,reason:d?.message||String(d)}}return Le}async function oi({env:e=process.env,totalBytes:t=Mt.totalmem(),platform:n=process.platform}={}){if(n!=="linux")return{available:!1,reason:`not a Fly/container node, and no systemd on ${n}`};try{await Ys(Pr(e),["--user","show","--property=Version","--value"],{timeout:3e3})}catch(s){return{available:!1,reason:`not a Fly/container node, and no systemd user manager to ask (${String(s?.stderr||s?.code||s?.message||s).trim().split(`
|
|
51
|
+
`)[0]})`}}let r=ti(t,e);return{available:!0,backend:"systemd",path:null,controllers:["memory"],cpuWeight:null,memoryMaxMb:Math.round(r/ut),swapMaxMb:Qs,systemctl:Pr(e),procRoot:e.BOSTRAT_PROC_ROOT||"/proc"}}function Fr(e=Le){let t=`nice ${qs} floor on every box`;if(!e)return`${t}; cgroup ceiling not probed yet`;if(e.available&&e.backend==="systemd")return`${t}; memory ceiling on each box's tmux-spawn scope, set through the systemd user manager (MemoryMax ${e.memoryMaxMb} MB, MemorySwapMax ${e.swapMaxMb} MB)`;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 Ys,qs,Ir,Xs,Js,Zs,Qs,ut,Le,Pr,_n=R(()=>{Ys=Vs(zs),qs=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),Ir=50,Xs=768,Js="bostrat-boxes",Zs=4096,Qs=512,ut=1024*1024;Le=null;Pr=(e=process.env)=>e.BOSTRAT_SYSTEMCTL_BIN||"systemctl"});import{execFile as si}from"node:child_process";import{promisify as ii}from"node:util";import Hr from"node:fs";import ai from"node:os";function Wr(e){return`/tmp/tmux-${e}/default`}function li({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let s=Wr(r);return t?s:n?`${n}/bostrat/tmux-default`:s}async function vn(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await di(e,{loginShell:t});return r===Kr?!0:r===bn?!1:n}async function di(e,{loginShell:t=!1,timeoutMs:n=ui}={}){if(!e)return bn;let r=t?process.env.SHELL||"/bin/sh":"sh",s=t?"-lic":"-c";try{return await ci(r,[s,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),Kr}catch(a){return a?.killed||a?.signal?Ur:a?.code===1||a?.code===127?bn:Ur}}var ci,bu,jr,vu,xu,Au,$u,ku,Kr,bn,Ur,ui,It,Eu,Ou,Ru,Nu,Mu,Iu,pn=R(()=>{wr();yr();hn();Tr();kr();Rr();dn();xt();Mr();_n();ci=ii(si),bu=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";jr=typeof process.getuid=="function"?process.getuid():0,vu=li({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Hr.existsSync(Wr(jr))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:jr}),xu=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Au=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",$u=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),ku=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);Kr="present",bn="absent",Ur="unknown",ui=5e3;It={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"},Eu=(()=>{try{let e=ai.homedir();if(e&&Hr.existsSync(e))return e}catch{}return"/"})(),Ou=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Ru=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Nu=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Mu=Number(process.env.BOSTRAT_BOX_COLS)||120,Iu=Number(process.env.BOSTRAT_BOX_ROWS)||40});var wo={};cn(wo,{NODE_IMAGE:()=>kn,commandPlan:()=>fo,flyToml:()=>po,flyWizard:()=>Bi,parseFlyFlags:()=>ho,stageConfig:()=>mo});import $n from"node:fs";import xe from"node:path";import Ei from"node:os";import Oi from"node:readline/promises";import{execFile as Ri}from"node:child_process";import{createRequire as Ni}from"node:module";import{randomUUID as Mi}from"node:crypto";function po({app:e,region:t,nodeName:n=e,planeUrl:r=uo,image:s=kn}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
|
|
52
52
|
# Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
|
|
53
53
|
# No [http_service] and none should be added: the node dials OUT to the plane;
|
|
54
54
|
# nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
|
|
@@ -88,41 +88,41 @@ swap_size_mb = 1024
|
|
|
88
88
|
# Scale later with: fly scale memory 4096 -a ${e}
|
|
89
89
|
size = "shared-cpu-2x"
|
|
90
90
|
memory = "2gb"
|
|
91
|
-
`}function
|
|
91
|
+
`}function fo({app:e,org:t,region:n,sizeGb:r,token:s,dir:a}){let d=[`BOSTRAT_PLANE_TOKEN=${s}`];return[{argv:["apps","create",e,"-o",t],display:`fly apps create ${e} -o ${t}`,tolerate:/already|taken|exists/i},{argv:["volumes","create","node_data","-a",e,"-r",n,"-s",String(r),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${r} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted> via stdin`,stdin:d.join(`
|
|
92
92
|
`)+`
|
|
93
|
-
`},{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 ho(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 s=e[r];if(s==="--yes"||s==="-y")t.yes=!0;else if(n[s])t[n[s]]=e[++r]??"";else if(s.startsWith("--")&&s.includes("=")){let[a,...d]=s.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 mo({app:e,dest:t,toml:n}){let r=t||xe.join(Ei.homedir(),".bostrat","fly",e)
|
|
94
|
-
`),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 Bi({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:s}={}){let a=ho(e),d=Oi.createInterface({input:t,output:n}),
|
|
93
|
+
`},{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 ho(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 s=e[r];if(s==="--yes"||s==="-y")t.yes=!0;else if(n[s])t[n[s]]=e[++r]??"";else if(s.startsWith("--")&&s.includes("=")){let[a,...d]=s.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 mo({app:e,dest:t,toml:n}){let r=t||xe.join(Ei.homedir(),".bostrat","fly",e);$n.mkdirSync(r,{recursive:!0});for(let s of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])$n.rmSync(xe.join(r,s),{recursive:!0,force:!0});return $n.writeFileSync(xe.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function Pi({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:s}=await Bt(["orgs","list","--json"],{exec:n}),a=JSON.parse(s),d=Array.isArray(a)?a.map(f=>f.Slug||f.slug).filter(Boolean):Object.keys(a);if(d.length===1)return t.write(`Org: ${d[0]} (your only org)
|
|
94
|
+
`),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 Bi({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:s}={}){let a=ho(e),d=Oi.createInterface({input:t,output:n}),f=async(g,A)=>(await d.question(A?`${g} [${A}]: `:`${g}: `)).trim()||A||"",m=g=>(d.close(),g);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
|
|
95
95
|
bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
|
|
96
96
|
|
|
97
97
|
`);try{await Bt(["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:g}=await Bt(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${g.trim()}
|
|
98
|
-
`)}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 S=await Pi({ask:
|
|
99
|
-
`),m(1);let O=a.image
|
|
98
|
+
`)}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 S=await Pi({ask:f,output:n,exec:r,flag:a.org}),p=a.app||await f("App name",`bostrat-node-${Mi().slice(0,4)}`),w=a.region||await f("Region (see `fly platform regions`)","iad"),E=a.sizeGb||Number(await f("Volume size GB (logins + repos live here)","10"))||10,b=a.name||p,x=a.planeUrl||uo,N=a.token||await f("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!N)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.
|
|
99
|
+
`),m(1);let O=a.image||kn,{dir:P}=mo({app:p,dest:s,toml:po({app:p,region:w,nodeName:b,planeUrl:x,image:O})});n.write(`
|
|
100
100
|
wrote ${xe.join(P,"fly.toml")} \u2014 deploys the prebuilt node image ${O}
|
|
101
101
|
(claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
|
|
102
102
|
|
|
103
103
|
Plan (your flyctl, your org, your bill):
|
|
104
|
-
`);let v=
|
|
105
|
-
`);if(!a.yes&&(await
|
|
104
|
+
`);let v=fo({app:p,org:S,region:w,sizeGb:E,token:N,dir:P});for(let g of v)n.write(` $ ${g.display}
|
|
105
|
+
`);if(!a.yes&&(await f(`
|
|
106
106
|
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.
|
|
107
107
|
`),m(1);for(let g of v){n.write(`
|
|
108
108
|
\u2192 ${g.display}
|
|
109
|
-
`);try{let{stdout:A,stderr
|
|
109
|
+
`);try{let{stdout:A,stderr:$}=await Bt(g.argv,{stdin:g.stdin,exec:r}),k=`${A||""}${$||""}`.trim();k&&n.write(k.split(`
|
|
110
110
|
`).map(I=>` ${I}`).join(`
|
|
111
111
|
`)+`
|
|
112
|
-
`)}catch(A){let
|
|
113
|
-
`);continue}return n.write(`\u2717 failed: ${
|
|
112
|
+
`)}catch(A){let $=`${A?.stdout||""}${A?.stderr||""}${A?.message||""}`;if(g.tolerate&&g.tolerate.test($)){n.write(` (already exists \u2014 continuing)
|
|
113
|
+
`);continue}return n.write(`\u2717 failed: ${$.trim().split(`
|
|
114
114
|
`).slice(-4).join(`
|
|
115
115
|
`)}
|
|
116
116
|
fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
|
|
117
117
|
`),m(1)}}return n.write(`
|
|
118
118
|
\u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
|
|
119
119
|
chat: the node step advances on its own within a minute.
|
|
120
|
-
logs: fly logs -a ${
|
|
121
|
-
redeploy: fly deploy ${P} -c ${xe.join(P,"fly.toml")} -a ${
|
|
120
|
+
logs: fly logs -a ${p}
|
|
121
|
+
redeploy: fly deploy ${P} -c ${xe.join(P,"fly.toml")} -a ${p} --ha=false
|
|
122
122
|
Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
|
|
123
123
|
boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
|
|
124
|
-
`),m(0)}var uo,Ii,$n,Bt,yo=R(()=>{uo="wss://plane.bostrat.ai/v1/node",Ii=Ni(import.meta.url)("../package.json").version,$n=`ghcr.io/globocodes/bostrat-node:${Ii}`;Bt=(e,{stdin:t,exec:n}={})=>new Promise((r,s)=>{if(n)return n(e,{stdin:t}).then(r,s);let a=Ri("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,p,m)=>d?s(Object.assign(d,{stdout:p,stderr:m})):r({stdout:p,stderr:m}));t!=null&&a.stdin?.end(t)})});function go(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 Li(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(s=>({...s,fromMs:go(s.from,"from",n),toMs:go(s.to,"to",n)}))}return t}var Ci,Di,ad,cd,To=R(()=>{Ci={"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}$/;ad=Li(Ci),cd=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var So=R(()=>{To()});import _o from"node:fs/promises";import xo from"node:path";import Fi from"node:os";function ko(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function $o(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Eo(e){let t=new Date(ko(e));return t.setDate(t.getDate()+7),t.getTime()}function Oo(e){let t=new Date($o(e));return t.setMonth(t.getMonth()+1),t.getTime()}function Ki(e=Date.now()){for(let[t,n]of Object.entries(Hi)){let r=n.startOf(e);if(r!==Ct[t]){Ct[t]=r;for(let s of En.values())s[t]=0;for(let s of bo)s.includes(`:${t}:`)&&!s.endsWith(`:${r}`)&&bo.delete(s)}}}function Gi(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 s={};for(let a of["weeklyUsd","monthlyUsd"]){let d=r?.[a];if(d==null||d==="")continue;let p=Number(d);if(!Number.isFinite(p)||p<=0)throw new Error(`${n}.${a} must be a positive number or null`);s[a]=p}Object.keys(s).length&&(t[n]=s)}return t}async function Ro(e,{source:t="local",updatedAt:n=Date.now()}={}){je={caps:Gi(e),updatedAt:n,source:t};try{await _o.mkdir(Ao,{recursive:!0}),await _o.writeFile(ji(),JSON.stringify(je,null,2))}catch{}return zi()}function zi(e=Date.now()){Ki(e);let t=new Set([...En.keys(),...Object.keys(je?.caps||{})]),n={};for(let r of t){let s=En.get(r);n[r]={weeklyUsd:vo(s?.weekly||0),monthlyUsd:vo(s?.monthly||0)}}return{caps:je?.caps||{},configured:!!je,seeded:Wi,updatedAt:je?.updatedAt??null,spent:n,windows:{weekly:{start:Ct.weekly,resetsAt:Eo(e)},monthly:{start:Ct.monthly,resetsAt:Oo(e)}},warnPct:Ui}}var Ao,ji,Ui,Hi,je,Wi,Ct,En,bo,vo,No=R(()=>{Rt();So();Ao=process.env.BOSTRAT_STATE_DIR||xo.join(process.env.HOME||Fi.tmpdir(),".bostrat"),ji=()=>xo.join(Ao,"usage-caps.json"),Ui=.8;Hi={weekly:{startOf:ko,nextStart:Eo,capKey:"weeklyUsd"},monthly:{startOf:$o,nextStart:Oo,capKey:"monthlyUsd"}},je=null,Wi=!1,Ct={weekly:0,monthly:0},En=new Map,bo=new Set;vo=e=>Math.round(e*1e4)/1e4});var Fo={};cn(Fo,{REMOVED_MARKER:()=>Pn,detectInstallKind:()=>We,detectProviderAuth:()=>Lo,maskToken:()=>In,readRemovedMarker:()=>Do,startPlaneLink:()=>ua,updateCommandFor:()=>ht,versionLt:()=>He});import Ue from"node:fs";import pt from"node:fs/promises";import Vi from"node:http";import W from"node:path";import Lt from"node:os";import{createRequire as Yi}from"node:module";import On from"ws";function In(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function Do(e=Pn){try{let t=JSON.parse(Ue.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function We({env:e=process.env,pkgDir:t=W.resolve(W.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ue.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 He(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 s=0;s<Math.max(n.length,r.length);s++){let a=(n[s]||0)-(r[s]||0);if(a)return a<0}return!1}function ht(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 Lo({home:e=process.env.HOME||Lt.homedir(),env:t=process.env}={}){let n=r=>{try{return Ue.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 ua({url:e,token:t,nodeId:n=Lt.hostname(),name:r=Lt.hostname(),listTracks:s,detectAgents:a=null,onTracksTransferred:d=null,onTracksMoves:p=null,sampleMetrics:m=null,deliverySample:S=null,onHashKey:f=null,onViewBase:w=null,metricsMs:E=la,onUpdateAvailable:b=null,onUpdatePolicy:x=null,onConflictProbe:N=null,restart:O=null,onRestarted:P=null,onHelloRefused:v=null,updatePolicy:g=null,installKind:A=We(),selfUrl:k=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:$=null,removedMarkerFile:I=Pn,onRemoved:ke=null,onDegraded:ze=null,onRecovered:$e=null,onRefused:Gt=null,onConnected:wt=null,ingestMode:Ee=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:Ve=na,unackedRetryMs:Oe=ta,pingMs:Ye=Qi,deadLinkMs:M=Math.round(Ye*ea),maxInflightEvents:ce=ia,httpTimeoutMs:le=aa,fanoutActive:ue=null,fanoutBatchCap:qe=ca,stallBackoffMinMs:zn=sa,fetchImpl:Vn=globalThis.fetch,log:T=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof s!="function")throw new Error("plane-link: listTracks is required");e=nt(e);let Qo=k.replace(/^http/,"ws"),Yn=new Set,qn=i=>{let l=typeof i.latestNodeVersion=="string"?i.latestNodeVersion:null;if(!(!(l&&Q&&He(Q,l))||Yn.has(l))){Yn.add(l),T.log(`[plane-link] bostrat-node ${l} is available (this node runs ${Q}) \u2014 ${ht(A)}`);try{b?.({current:Q,latest:l,min:i.minNodeVersion??null,installKind:A,required:!!(i.minNodeVersion&&He(Q,i.minNodeVersion))})}catch(u){T.error(`[plane-link] update notice failed: ${u?.message||u}`)}}},we=new Map,ye=new Map,zt=W.join(Mn,"plane-link","cursor.json"),Vt=W.join(Mn,"plane-link","dead-letter.ndjson"),Xn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),ne={},ee={},B=new Map,yt=null,de=null,re=0,Xe=0,Jn=0,gt={},Zn=new Set,Qn=Promise.resolve(),H="ws",Re=0,Z=!1,ge=0,Yt=!1,fe=Dt,Ne=new Set,oe=[],z=null,q=null,X=!1,qt=!1,Je=Mo,Ze=null,Xt=O&&typeof O=="object"?O:null,Me=null,Ie=null,se=null,Te=0,er=0,ie=null,Jt=!1,Tt=0,Qe=!1,pe=Do(I);if(pe)if(pe.tokenPreview===In(t))Qe=!0,wn({reason:pe.reason??"removed",at:pe.at??null,nodeId:pe.nodeId??n}),T.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 ${I} to force a dial.`);else try{Ue.unlinkSync(I),T.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function Zt({reason:i="removed",at:l=Date.now(),via:u="ctl"}={}){if(!Qe){Qe=!0,wn({reason:i,at:l,nodeId:n,via:u});try{Ue.mkdirSync(W.dirname(I),{recursive:!0}),Ue.writeFileSync(I,JSON.stringify({at:l,reason:i,via:u,nodeId:n,tokenPreview:In(t)},null,2))}catch(o){T.error(`[plane-link] could not write ${I}: ${o?.message||o}`)}T.error(`[plane-link] the plane REMOVED this node (${i}, 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:i,at:l,via:u})}catch{}dr({bye:!1})}}async function es(){try{ne=JSON.parse(await pt.readFile(zt,"utf8"))}catch{ne={}}}function tr(){Jt=!0,!Ie&&(Ie=setTimeout(async()=>{if(Ie=null,!!Jt){Jt=!1;try{await pt.mkdir(W.dirname(zt),{recursive:!0}),await pt.writeFile(zt,JSON.stringify(ne))}catch(i){T.error("[plane-link] cursor flush failed:",i?.message||i)}}},Zi),Ie.unref?.())}function Qt(){try{return!!ue?.()}catch{return!1}}function en(){let i=H==="http"?fe:Dt;return Qt()?Math.min(i,qe):i}function F(i){return!q||q.readyState!==On.OPEN?!1:(q.send(JSON.stringify(i)),!0)}function Pe(i){let l=Date.now();for(let{trackId:o,event:c}of i){let h=B.get(c.id);B.set(c.id,{trackId:o,seq:c.seq,event:c,sentAt:l,firstSentAt:h?.firstSentAt??l,retryAt:l+Oe,tries:(h?.tries??0)+1,nacks:h?.nacks??0})}let u=i.map(({trackId:o,event:c})=>({trackId:o,event:oa(c)}));return H==="http"?(is(u),!0):F({v:j,ch:"events",type:"append",events:u})}function ts(i){let l=null;for(let u of B.values())u.trackId===i&&(l==null||u.seq<l)&&(l=u.seq);return l}function tn(i){let l=ee[i];if(l==null)return;let u=ts(i),o=u==null?l:Math.min(l,u-1);o>(ne[i]??0)&&(ne[i]=o,tr())}function et(){if(yt=Date.now(),de!=null){let i=Date.now()-de;T.log(`[plane-link] spine sync recovered after ${Math.round(i/1e3)}s degraded (${re} stall redial(s))`);let l=de;de=null,re=0,Xe=0,Z=!1,ge=0;try{$e?.({since:l,downMs:i})}catch(u){T.error(`[plane-link] onRecovered failed: ${u?.message||u}`)}}}function nn(i){if(!Array.isArray(i)||!i.length)return;let l=new Set;for(let u of i){let o=B.get(u);o&&(B.delete(u),(ee[o.trackId]??0)<o.seq&&(ee[o.trackId]=o.seq),l.add(o.trackId))}for(let u of l)tn(u);et()}function nr(i,l){Jn++;let u={at:Date.now(),trackId:i.trackId,seq:i.seq,id:i.event?.id??null,type:i.event?.type??null,reason:l,event:i.event??null};T.error(`[plane-link] DEAD-LETTER ${i.trackId} seq ${i.seq} (${u.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${Vt}`),Qn=Qn.then(async()=>{await pt.mkdir(W.dirname(Vt),{recursive:!0}),await pt.appendFile(Vt,JSON.stringify(u)+`
|
|
125
|
-
`)}).catch(o=>T.error(`[plane-link] dead-letter write failed: ${o?.message||o}`))}function ns(i,l){if(gt[i]=(gt[i]??0)+1,Zn.has(i))return;Zn.add(i);let u=ra[i]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";T.error(`[plane-link] REFUSED by the plane (${i}) on track ${l}: events are being dropped, not stored \u2014 ${u}`);try{Gt?.({reason:i,trackId:l,count:gt[i],hint:u})}catch(o){T.error(`[plane-link] onRefused failed: ${o?.message||o}`)}}function rn(i,l,u,o=null){if(!Array.isArray(i)||!i.length)return;let c=new Set,h=Date.now();for(let y of i){let _=B.get(y);_&&(u?(B.delete(y),nr(_,l),String(l).startsWith(Rn)&&ns(String(l).slice(Rn.length),_.trackId),(ee[_.trackId]??0)<_.seq&&(ee[_.trackId]=_.seq),c.add(_.trackId)):(_.nacks++,_.retryAt=h+Math.max(1e3,Number(o)||Oe)))}for(let y of c)tn(y);et()}function rr(i=Date.now()){let l=1/0;for(let u of B.values())u.firstSentAt<l&&(l=u.firstSentAt);return l===1/0?0:i-l}function rs(i){if(!M||!i||i!==q||!Te)return!1;let l=Date.now()-Te;if(l<=M)return!1;er++,T.error(`[plane-link] no frame from the plane for ${Math.round(l/1e3)}s \u2014 link is half-open; terminating and redialing`);try{i.terminate()}catch{}return!0}function or(){if(!X||!B.size)return;let i=Date.now(),l=rr(i);if(l<Ve||yt!=null&&i-yt<Ve||H==="http"&&Z||Xe>i)return;re++;let u=Math.min(zn*2**(re-1),Po);if(de==null){de=i-l,T.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${B.size} event(s) in flight (${H} door) \u2014 the plane is not answering appends`);try{ze?.({since:de,unacked:B.size,oldestAgeMs:l,mode:H})}catch(o){T.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(H==="http"){Z=!0,ge=i+u,T.error(`[plane-link] ingest circuit OPEN (stall #${re}); probing /v1/ingest/health in ${Math.round(u/1e3)}s`);return}Xe=i+u,T.error(`[plane-link] closing the link and redialing in ${Math.round(u/1e3)}s (stall redial #${re})`);try{q?.terminate()}catch{}}function on(){if(!X)return;let i=Date.now();if(H==="http"&&Z)return;let l=[...B.values()].filter(o=>o.event&&o.retryAt<=i&&!(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),T.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let u=en();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>=Nn)return;Pe(c.slice(0,u).map(h=>({trackId:h.trackId,event:h.event})))}return}for(let o=0;o<l.length;o+=u){let c=l.slice(o,o+u).map(h=>({trackId:h.trackId,event:h.event}));if(!Pe(c))return}}async function os(i=null){for(;;){if(!X)return!1;let l=B.size<ce,u=H!=="http"||Re<Nn&&!Z&&(!i||!Ne.has(i));if(l&&u)return!0;await new Promise(o=>setTimeout(o,100))}}function sn(){if(z=null,!X||!oe.length)return;let i=oe;oe=[];let l=en();if(H!=="http"){for(let c=0;c<i.length;c+=l)Pe(i.slice(c,c+l));return}let u=Qt(),o=new Map;for(let c of i)(o.get(c.trackId)??o.set(c.trackId,[]).get(c.trackId)).push(c);for(let[c,h]of o){if(Ne.has(c)||Re>=Nn||Z){oe.push(...h);continue}if(u){Pe(h.slice(0,l)),oe.push(...h.slice(l));continue}for(let y=0;y<h.length;y+=l)Pe(h.slice(y,y+l))}oe.length&&!z&&(z=setTimeout(sn,Bo),z.unref?.())}let ss=i=>{let l=new Map;for(let{trackId:u,event:o}of i)(l.get(u)??l.set(u,[]).get(u)).push(o);return[...l].map(([u,o])=>({trackId:u,events:o}))},Se=(i,l,u,{progress:o})=>{let c=Date.now();for(let{event:h}of i){let y=B.get(h.id);y&&(y.nacks++,y.retryAt=c+Math.max(1e3,u||Oe))}o&&et()};async function is(i){let l=new Set(i.map(u=>u.trackId));for(let u of l)Ne.add(u);Re++;try{let u=await Vn(`${Xn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:ss(i)}),signal:AbortSignal.timeout(le)}),o=(Number(u.headers.get("retry-after"))||0)*1e3;if(u.status===200){let c=await u.json();fe=Dt;for(let _ of c.results??[]){nn(_.acked??[]);let L=(te,G)=>{let St=new Map;for(let _e of te??[])(St.get(_e.reason)??St.set(_e.reason,[]).get(_e.reason)).push(_e.id);for(let[_e,fr]of St)rn(fr,_e,G,c.retryAfterMs??null)};L(_.rejected,!0),L(_.deferred,!1)}let h=new Set,y=new Map;for(let _ of Array.isArray(c.refused)?c.refused:[])!_||typeof _.id!="string"||(h.add(_.id),(y.get(_.reason)??y.set(_.reason,[]).get(_.reason)).push(_.id));for(let[_,L]of y)rn(L,`${Rn}${_}`,!0);nn((c.discarded??[]).filter(_=>!h.has(_))),et();return}if(u.status===429){Se(i,"overloaded",o||5e3,{progress:!0});return}if(u.status===413&&i.length>1){fe=Math.max(1,Math.floor(i.length/2)),T.error(`[plane-link] ingest request too large (${i.length} events) \u2014 halving batches to ${fe}`),Se(i,"too_large",1e3,{progress:!0});return}if(u.status===413){let c=B.get(i[0].event.id);c&&(B.delete(c.event.id),nr(c,"too_large"),(ee[c.trackId]??0)<c.seq&&(ee[c.trackId]=c.seq),tn(c.trackId)),et();return}if(u.status===410){Zt({reason:"removed",via:"410"}),Se(i,"http_410",6e4,{progress:!1});return}if(u.status===401||u.status===403){let{tripped:c,holdMs:h}=$t();if(c&&T.error(`[plane-link] holding every plane call for ${Math.round(h/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Tt>=Co){Tt=Date.now();let y="";try{y=(await u.json())?.error??""}catch{}T.error(`[plane-link] plane refused ingest (HTTP ${u.status}${y?`: ${y}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}Se(i,`http_${u.status}`,Math.max(6e4,it()),{progress:!1});return}if(u.status===400){T.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${i.length} event(s) for retry; this is a bug, not data`),Se(i,"http_400",6e4,{progress:!1});return}Se(i,`http_${u.status}`,o||5e3,{progress:!1})}catch(u){let o=u?.name==="TimeoutError"||u?.name==="AbortError";o&&i.length>1&&(fe=Math.max(1,Math.floor(i.length/2)),T.error(`[plane-link] ingest request of ${i.length} event(s) outlived its ${le} ms deadline \u2014 halving batches to ${fe}`)),Se(i,o?"timeout":"network",5e3,{progress:!1})}finally{Re--;for(let u of l)Ne.delete(u)}}async function as(){if(H!=="http"||!Z||!X||Yt)return;let i=Date.now();if(!(ge>i||Et(i))){Yt=!0;try{let l=await Vn(`${Xn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(le)});if(!l.ok)throw new Error(`HTTP ${l.status}`);T.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Z=!1,ge=0,Xe=Date.now()+le+Oe+1e3;for(let u of B.values())u.retryAt=Math.min(u.retryAt,Date.now());on()}catch(l){re++;let u=Math.min(zn*2**(re-1),Po);ge=Date.now()+u,T.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(u/1e3)}s`)}finally{Yt=!1}}}function sr(){let i=Date.now();return{mode:H,unacked:B.size,oldestUnackedAgeMs:rr(i),lastProgressAt:yt,degradedSince:de,stallRedials:re,deadLettered:Jn,fanoutCap:Qt()?qe:null,http:H==="http"?{inFlight:Re,circuitOpen:Z,nextProbeInMs:Z?Math.max(0,ge-i):0,batchCap:fe}:null}}async function ir(){if(!m)return;let i;try{i=await m()}catch(u){T.error("[plane-link] metrics sample failed:",u?.message||u);return}let l=null;try{l=S?.()??null}catch{}i&&F({v:j,ch:"ctl",type:"metrics",metrics:{...i,planeLink:sr(),...l?{delivery:l}:{}}})}function cs(){m&&(ie&&clearInterval(ie),ir(),ie=setInterval(ir,E),ie.unref?.())}async function ls(){let i;try{i=await s()}catch(l){T.error("[plane-link] backfill listTracks failed:",l?.message||l);return}F({v:j,ch:"ctl",type:"tracks",ids:i.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of i)if(!X||!await ar(l))return}async function ar(i){let l;try{l=await Ot(i)}catch{return!0}let u=ne[i.id]??0,o=l.filter(c=>c.seq>u&&typeof c.id=="string");for(let c=0;c<o.length;){if(!await os(i.id))return!1;let h=o.slice(c,c+en()).map(y=>({trackId:i.id,event:y}));if(!Pe(h))return!1;c+=h.length}return!0}let an=new Map;async function cr(i,l){if(an.get(i)===l)return!1;an.set(i,l);let u=null;try{u=(await s()).find(y=>y?.id===i)??null}catch{return!1}if(!u)return!1;let o;try{o=await Ot(u)}catch{return!1}let c=[...o].reverse().find(y=>(y?.type==="track.transferred"||y?.type==="track.recovered")&&y.payload?.toNode===n);if(!c||!Number.isFinite(c.seq))return!1;let h=c.seq-1;return(ne[i]??0)>h&&(ne[i]=h,tr()),(ee[i]??0)>h&&(ee[i]=h),T.log(`[plane-link] re-sending ${i}'s move-commit (seq ${c.seq}, ${c.type}) \u2014 the plane's move record predates this node's adoption`),X?ar(u):!1}function lr(i){!X||!i?.trackId||typeof i.id!="string"||(oe.push({trackId:i.trackId,event:i}),z||(z=setTimeout(sn,Bo),z.unref?.()))}let tt=new Map;async function us(i){let{reqId:l,method:u,path:o,headers:c={},body:h}=i,y=Object.fromEntries(Object.entries(c).filter(([,L])=>L!=null)),_=new AbortController;tt.set(l,_);try{if(i.host){await ds(i,y,_);return}$&&(y["x-bostrat-token"]=$);let L=await fetch(k+o,{method:u,headers:y,body:h?Buffer.from(h,"base64"):void 0,signal:_.signal}),te=Object.fromEntries(L.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"),F({v:j,ch:"control",type:"http_head",reqId:l,status:L.status,headers:te}),L.body){for await(let G of L.body)if(!F({v:j,ch:"control",type:"http_data",reqId:l,data:Buffer.from(G).toString("base64")}))break}F({v:j,ch:"control",type:"http_end",reqId:l,error:null})}finally{tt.delete(l)}}function ds(i,l,u){let{reqId:o,method:c,path:h,body:y}=i,_=new URL(k);return new Promise(L=>{let te=Vi.request({host:_.hostname,port:_.port,method:c,path:h,headers:{...l,host:i.host},signal:u.signal},G=>{let{connection:St,"keep-alive":_e,"transfer-encoding":fr,upgrade:ic,...fs}=G.headers;F({v:j,ch:"control",type:"http_head",reqId:o,status:G.statusCode||502,headers:fs}),G.on("data",ps=>{F({v:j,ch:"control",type:"http_data",reqId:o,data:Buffer.from(ps).toString("base64")})||G.destroy()}),G.on("end",()=>{F({v:j,ch:"control",type:"http_end",reqId:o,error:null}),L()}),G.on("error",()=>{F({v:j,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),L()})});te.on("error",G=>{F({v:j,ch:"control",type:"http_end",reqId:o,error:G?.message||"view request failed"}),L()}),y&&te.write(Buffer.from(y,"base64")),te.end()})}function ur(){if(qt||Qe)return;q=new On(e,{headers:{authorization:`Bearer ${t}`}});let i=q;Te=0,i.on("ping",()=>{Te=Date.now()}),i.on("pong",()=>{Te=Date.now()}),q.on("open",async()=>{let u=null;try{u=await a?.()||null}catch{u=null}F({v:j,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:Q,installKind:A,...typeof g=="function"?{updatePolicy:g()}:g?{updatePolicy:g}:{},providers:Lo(),...u?{agents:u}:{},...Xt?{restart:Xt}:{}})}),q.on("message",u=>{Te=Date.now();let o;try{o=JSON.parse(u)}catch{return}if(o.ch==="ctl"&&o.type==="hello_ok"){an.clear(),X=!0,Je=Mo,Ze=null,Xt=null,br(),T.log(`[plane-link] connected to plane as ${n}`);try{wt?.()}catch{}if(typeof o.hashKey=="string"&&o.hashKey)try{f?.(o.hashKey)}catch{}try{w?.(typeof o.viewBase=="string"&&o.viewBase?o.viewBase:null)}catch{}o.minNodeVersion&&Q&&He(Q,o.minNodeVersion)&&T.error(`[plane-link] this node is bostrat-node ${Q}; the plane asks for \u2265${o.minNodeVersion} \u2014 update with: ${ht(A)}`);try{x?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}qn(o);let c=o.ingest==="http";H=Ee==="ws"?"ws":Ee==="http"||c?"http":"ws",Ee==="http"&&!c&&T.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),H==="http"&&T.log("[plane-link] spine rides the HTTPS ingest door"),Z=!1,ge=0,fe=Dt,se&&clearInterval(se),Te=Date.now(),se=setInterval(()=>{rs(i)||(F({v:j,ch:"ctl",type:"ping"}),or(),as().catch(()=>{}),on(),oe.length&&!z&&sn())},Ye),se.unref?.(),cs(),ls().catch(h=>T.error("[plane-link] backfill failed:",h?.message||h));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let c=typeof o.minNodeVersion=="string"?o.minNodeVersion:null,h=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;T.error(`[plane-link] plane REFUSED this node: bostrat-node ${Q??"?"} is below its minimum ${c??"?"} \u2014 ${o.fix||ht(A)}`),Je=Io,Ze=0;try{v?.({current:Q,min:c,latest:h,fix:o.fix||ht(A),installKind:A})}catch(y){T.error(`[plane-link] refusal handler failed: ${y?.message||y}`)}return}if(o.ch==="ctl"&&o.type==="removed"){F({v:j,ch:"ctl",type:"removed_ack",nodeId:n}),Zt({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"){qn(o);return}if(o.ch==="ctl"&&o.type==="update_policy"){try{x?.(typeof o.mode=="string"?o.mode:null)}catch{}return}if(o.ch==="ctl"&&o.type==="conflict_probe"&&Array.isArray(o.trackIds)){try{N?.(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=>T.error("[plane-link] restart notice failed:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="usage_caps"){Ro(o.caps??{},{source:"plane",updatedAt:o.updatedAt??Date.now()}).then(c=>T.log(`[plane-link] spend caps ${Object.keys(c.caps).length?`updated (${Object.keys(c.caps).join(", ")})`:"cleared"} from plane`)).catch(c=>T.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 h of Array.isArray(c)?c:[])h?.stale&&h.id&&await cr(h.id,h.since??null)}).catch(c=>T.error("[plane-link] transfer notice failed:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="moves"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>p?.(o.tracks)).then(async c=>{for(let h of Array.isArray(c)?c:[])h?.stale&&h.id&&await cr(h.id,h.since??null)}).catch(c=>T.error("[plane-link] move-record reconcile failed:",c?.message||c));return}if(o.ch==="events"&&o.type==="ack"&&Array.isArray(o.ids)){nn(o.ids);return}if(o.ch==="events"&&o.type==="nack"&&Array.isArray(o.ids)){rn(o.ids,o.reason,o.permanent===!0,o.retryAfterMs??null);return}if(o.ch==="control"&&o.type==="http_open"){us(o).catch(c=>F({v:j,ch:"control",type:"http_end",reqId:o.reqId,error:c?.message||"tunnel error"}));return}if(o.ch==="control"&&o.type==="http_cancel"){tt.get(o.reqId)?.abort();return}if(o.ch==="attach"&&o.type==="open"){let c=new On(Qo+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 y=ye.get(o.streamId)||[];ye.delete(o.streamId);for(let{buf:_,bin:L}of y)c.send(_,{binary:L})}),c.on("message",(y,_)=>{let L=_?y:Buffer.from(String(y));F({v:j,ch:"attach",type:"data",streamId:o.streamId,data:L.toString("base64"),..._?{bin:!0}:{}})});let h=()=>{ye.delete(o.streamId),we.delete(o.streamId)&&F({v:j,ch:"attach",type:"close",streamId:o.streamId})};c.on("close",h),c.on("error",h);return}if(o.ch==="attach"&&o.type==="data"){let c=we.get(o.streamId);if(!c)return;let h=Buffer.from(o.data,"base64"),y=o.bin===!0,_=ye.get(o.streamId);_?_.push({buf:h,bin:y}):c.send(h,{binary:y});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=()=>{X&&T.log("[plane-link] disconnected from plane"),X=!1,se&&(clearInterval(se),se=null),ie&&(clearInterval(ie),ie=null),B.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 tt.values())c.abort();if(tt.clear(),qt||Me)return;Ze==null&&(Ze=Date.now());let u=Date.now()-Ze<qi,o=Math.max(u?Xi+Math.random()*Ji:Je,Xe-Date.now(),it());Me=setTimeout(()=>{Me=null,ur()},o),Me.unref?.(),u||(Je=Math.min(Je*2,Io))};q.on("close",l),q.on("error",u=>{let o=/Unexpected server response: (\d+)/.exec(u?.message||"")?.[1];if(o==="410"){Zt({reason:"removed",via:"410"});return}if(o==="401"||o==="403"){let{tripped:c,holdMs:h}=$t();c?T.error(`[plane-link] holding every plane call for ${Math.round(h/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(h/6e4)} min.`):Date.now()-Tt>=Co&&(Tt=Date.now(),T.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()})}ct.on("event",lr),es().then(ur);function dr({bye:i=!0}={}){qt=!0,ct.off("event",lr),Me&&clearTimeout(Me),Ie&&clearTimeout(Ie),se&&clearInterval(se),ie&&clearInterval(ie),z&&clearTimeout(z),i&&F({v:j,ch:"ctl",type:"bye",reason:"shutdown"}),q?.close()}return{stop:()=>dr(),status:()=>({connected:X,nodeId:n,cursor:{...ne},inflight:B.size,...sr(),auth:vr(),dormant:Qe,removed:yn(),deadLinkMs:M,deadLinkRedials:er,refused:{...gt}}),_tick:()=>{or(),on()}}}var Q,Mn,Pn,j,Mo,Io,qi,Xi,Ji,Dt,Zi,Qi,ea,ta,Bn,na,Rn,ra,oa,sa,Po,ia,Bo,aa,Nn,ca,la,Co,Cn=R(()=>{Rt();No();un();gn();Q=(()=>{try{return Yi(import.meta.url)("../package.json").version||null}catch{return null}})(),Mn=process.env.BOSTRAT_STATE_DIR||W.join(process.env.HOME||Lt.tmpdir(),".bostrat"),Pn=W.join(Mn,"plane-link","removed.json");j=1,Mo=1e3,Io=3e4,qi=6e4,Xi=1500,Ji=500,Dt=100,Zi=2e3,Qi=25e3,ea=2.5,ta=6e4,Bn=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},na=Bn(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Rn="refused:",ra={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"},oa=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},sa=3e4,Po=10*6e4,ia=400,Bo=250,aa=Bn(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Nn=4,ca=Math.max(1,Math.round(Bn(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),la=6e4,Co=6e4});var jo=R(()=>{hn()});var Vo={};cn(Vo,{ACTIONABLE_KINDS:()=>Wt,INSTALL_ATTEMPTS:()=>Ft,INSTALL_RETRY_STEP_S:()=>Uo,REGISTRY_RETRY_ATTEMPTS:()=>Fn,REGISTRY_WAIT_POLLS:()=>Dn,REGISTRY_WAIT_STEP_S:()=>Ln,RESTART_SIGNAL:()=>Wo,SELF_UPDATE_DIR:()=>Ut,SUPERVISOR_PID_FILE:()=>Ho,createAutoUpdater:()=>Aa,inFlight:()=>Wn,readStatus:()=>Hn,restartCommand:()=>Ko,restartStrategy:()=>Un,selfUpdatePlan:()=>Go,settleSelfUpdate:()=>xa,startSelfUpdate:()=>zo,underService:()=>jn,updatePolicy:()=>ga});import mt from"node:fs";import he from"node:fs/promises";import da from"node:os";import U from"node:path";import{spawn as fa,execFileSync as pa}from"node:child_process";import{createRequire as ha}from"node:module";function ga({kind:e=We(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:Wt.has(e)?e==="git-checkout"||jn(t)?"auto":"prompt":"off"}function jn(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Un({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:s=Ho,readFile:a=p=>mt.readFileSync(p,"utf8"),alive:d=Ta}={}){let p=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(jn(e))return p;let m=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(m)&&m>0)){try{m=Number(String(a(s)).trim())}catch{m=NaN}Number.isInteger(m)&&m>0&&d(m)||(m=NaN)}return Number.isInteger(m)&&m>0?{mode:"supervisor",pid:m}:p}function Ta(e){try{process.kill(e,0)}catch{return!1}try{let t=pa("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 Ko(e){switch(e?.mode){case"systemd":return`systemctl --user restart ${J(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 -${Wo.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function Go({kind:e,to:t,from:n=jt,statusFile:r=Ht,logFile:s=U.join(Ut,"last.log"),port:a=Number(process.env.PORT)||3362,npmPrefix:d=null,serviceName:p=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:m=typeof process.getuid=="function"?process.getuid():0,restart:S=Un({env:{},platform:process.platform,uid:m,serviceName:p,readFile:()=>{throw new Error("no pidfile")}}),liveDir:f=process.env.BOSTRAT_LIVE_CHECKOUT||U.resolve(U.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:w=Date.now(),attempts:E=1}={}){if(!Wt.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=(v,g="")=>`write_status ${J(v)} ${g}`,x=Ko(S),N=`
|
|
124
|
+
`),m(0)}var uo,Ii,kn,Bt,yo=R(()=>{uo="wss://plane.bostrat.ai/v1/node",Ii=Ni(import.meta.url)("../package.json").version,kn=`ghcr.io/globocodes/bostrat-node:${Ii}`;Bt=(e,{stdin:t,exec:n}={})=>new Promise((r,s)=>{if(n)return n(e,{stdin:t}).then(r,s);let a=Ri("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,f,m)=>d?s(Object.assign(d,{stdout:f,stderr:m})):r({stdout:f,stderr:m}));t!=null&&a.stdin?.end(t)})});function go(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 Li(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(s=>({...s,fromMs:go(s.from,"from",n),toMs:go(s.to,"to",n)}))}return t}var Ci,Di,ad,cd,To=R(()=>{Ci={"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-10-05",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; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"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-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"claude-sonnet-5-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.20 (0.1\xD7); same rates as Sonnet 5, own row so the id never prefix-resolves."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",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; re-verified 2026-10-05 (live pricing page, footnote 3 still published)."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (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-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend then; re-verified 2026-10-05 (live pricing page: $10/$50, 1h write $20, hits $1 at 0.1\xD7)."}],"gpt-5.5-pro":[{from:null,to:null,input:30,output:180,cacheWrite:30,cacheRead:30,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $30 in / $180 out, no cached-input or cache-write price published (both priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5-cyber":[{from:null,to:null,input:12.5,output:75,cacheWrite:12.5,cacheRead:1.25,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing, Cyber models table): $12.50 in / $1.25 cached / $75 out, no cache-write price published (priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-10-05",note:"verified 2026-07-03, re-verified 2026-08-17 and 2026-10-05 (developers.openai.com pricing: $5 / $0.50 cached / $30); 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-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (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-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (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)."}],"gpt-6.1-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.10 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.20 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-luna":[{from:null,to:null,input:.1,output:.5,cacheWrite:.125,cacheRead:.01,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $0.10 in / $0.01 cached / $0.125 cache writes (1.25\xD7) / $0.50 out; added before any fleet turn was recorded."}]},Di=/^\d{4}-\d{2}-\d{2}$/;ad=Li(Ci),cd=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var So=R(()=>{To()});import _o from"node:fs/promises";import xo from"node:path";import Fi from"node:os";function $o(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function ko(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Eo(e){let t=new Date($o(e));return t.setDate(t.getDate()+7),t.getTime()}function Oo(e){let t=new Date(ko(e));return t.setMonth(t.getMonth()+1),t.getTime()}function Ki(e=Date.now()){for(let[t,n]of Object.entries(Hi)){let r=n.startOf(e);if(r!==Ct[t]){Ct[t]=r;for(let s of En.values())s[t]=0;for(let s of bo)s.includes(`:${t}:`)&&!s.endsWith(`:${r}`)&&bo.delete(s)}}}function Gi(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 s={};for(let a of["weeklyUsd","monthlyUsd"]){let d=r?.[a];if(d==null||d==="")continue;let f=Number(d);if(!Number.isFinite(f)||f<=0)throw new Error(`${n}.${a} must be a positive number or null`);s[a]=f}Object.keys(s).length&&(t[n]=s)}return t}async function Ro(e,{source:t="local",updatedAt:n=Date.now()}={}){je={caps:Gi(e),updatedAt:n,source:t};try{await _o.mkdir(Ao,{recursive:!0}),await _o.writeFile(ji(),JSON.stringify(je,null,2))}catch{}return zi()}function zi(e=Date.now()){Ki(e);let t=new Set([...En.keys(),...Object.keys(je?.caps||{})]),n={};for(let r of t){let s=En.get(r);n[r]={weeklyUsd:vo(s?.weekly||0),monthlyUsd:vo(s?.monthly||0)}}return{caps:je?.caps||{},configured:!!je,seeded:Wi,updatedAt:je?.updatedAt??null,spent:n,windows:{weekly:{start:Ct.weekly,resetsAt:Eo(e)},monthly:{start:Ct.monthly,resetsAt:Oo(e)}},warnPct:Ui}}var Ao,ji,Ui,Hi,je,Wi,Ct,En,bo,vo,No=R(()=>{Rt();So();Ao=process.env.BOSTRAT_STATE_DIR||xo.join(process.env.HOME||Fi.tmpdir(),".bostrat"),ji=()=>xo.join(Ao,"usage-caps.json"),Ui=.8;Hi={weekly:{startOf:$o,nextStart:Eo,capKey:"weeklyUsd"},monthly:{startOf:ko,nextStart:Oo,capKey:"monthlyUsd"}},je=null,Wi=!1,Ct={weekly:0,monthly:0},En=new Map,bo=new Set;vo=e=>Math.round(e*1e4)/1e4});var Fo={};cn(Fo,{REMOVED_MARKER:()=>Pn,detectInstallKind:()=>We,detectProviderAuth:()=>Lo,maskToken:()=>In,readRemovedMarker:()=>Do,startPlaneLink:()=>ua,updateCommandFor:()=>ht,versionLt:()=>He});import Ue from"node:fs";import ft from"node:fs/promises";import Vi from"node:http";import W from"node:path";import Lt from"node:os";import{createRequire as Yi}from"node:module";import On from"ws";function In(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function Do(e=Pn){try{let t=JSON.parse(Ue.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function We({env:e=process.env,pkgDir:t=W.resolve(W.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ue.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 He(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 s=0;s<Math.max(n.length,r.length);s++){let a=(n[s]||0)-(r[s]||0);if(a)return a<0}return!1}function ht(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 Lo({home:e=process.env.HOME||Lt.homedir(),env:t=process.env}={}){let n=r=>{try{return Ue.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 ua({url:e,token:t,nodeId:n=Lt.hostname(),name:r=Lt.hostname(),listTracks:s,detectAgents:a=null,onTracksTransferred:d=null,onTracksMoves:f=null,sampleMetrics:m=null,deliverySample:S=null,onHashKey:p=null,onViewBase:w=null,metricsMs:E=la,onUpdateAvailable:b=null,onUpdatePolicy:x=null,onConflictProbe:N=null,restart:O=null,onRestarted:P=null,onHelloRefused:v=null,updatePolicy:g=null,installKind:A=We(),selfUrl:$=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:k=null,removedMarkerFile:I=Pn,onRemoved:$e=null,onDegraded:ze=null,onRecovered:ke=null,onRefused:Gt=null,onConnected:wt=null,ingestMode:Ee=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:Ve=na,unackedRetryMs:Oe=ta,pingMs:Ye=Qi,deadLinkMs:M=Math.round(Ye*ea),maxInflightEvents:ce=ia,httpTimeoutMs:le=aa,fanoutActive:ue=null,fanoutBatchCap:qe=ca,stallBackoffMinMs:zn=sa,fetchImpl:Vn=globalThis.fetch,log:T=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof s!="function")throw new Error("plane-link: listTracks is required");e=nt(e);let Qo=$.replace(/^http/,"ws"),Yn=new Set,qn=i=>{let l=typeof i.latestNodeVersion=="string"?i.latestNodeVersion:null;if(!(!(l&&Q&&He(Q,l))||Yn.has(l))){Yn.add(l),T.log(`[plane-link] bostrat-node ${l} is available (this node runs ${Q}) \u2014 ${ht(A)}`);try{b?.({current:Q,latest:l,min:i.minNodeVersion??null,installKind:A,required:!!(i.minNodeVersion&&He(Q,i.minNodeVersion))})}catch(u){T.error(`[plane-link] update notice failed: ${u?.message||u}`)}}},we=new Map,ye=new Map,zt=W.join(Mn,"plane-link","cursor.json"),Vt=W.join(Mn,"plane-link","dead-letter.ndjson"),Xn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),ne={},ee={},B=new Map,yt=null,de=null,re=0,Xe=0,Jn=0,gt={},Zn=new Set,Qn=Promise.resolve(),H="ws",Re=0,Z=!1,ge=0,Yt=!1,pe=Dt,Ne=new Set,oe=[],z=null,q=null,X=!1,qt=!1,Je=Mo,Ze=null,Xt=O&&typeof O=="object"?O:null,Me=null,Ie=null,se=null,Te=0,er=0,ie=null,Jt=!1,Tt=0,Qe=!1,fe=Do(I);if(fe)if(fe.tokenPreview===In(t))Qe=!0,wn({reason:fe.reason??"removed",at:fe.at??null,nodeId:fe.nodeId??n}),T.error(`[plane-link] this node was REMOVED from the plane (${fe.reason??"removed"}${fe.at?` at ${new Date(fe.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${I} to force a dial.`);else try{Ue.unlinkSync(I),T.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function Zt({reason:i="removed",at:l=Date.now(),via:u="ctl"}={}){if(!Qe){Qe=!0,wn({reason:i,at:l,nodeId:n,via:u});try{Ue.mkdirSync(W.dirname(I),{recursive:!0}),Ue.writeFileSync(I,JSON.stringify({at:l,reason:i,via:u,nodeId:n,tokenPreview:In(t)},null,2))}catch(o){T.error(`[plane-link] could not write ${I}: ${o?.message||o}`)}T.error(`[plane-link] the plane REMOVED this node (${i}, 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{$e?.({reason:i,at:l,via:u})}catch{}dr({bye:!1})}}async function es(){try{ne=JSON.parse(await ft.readFile(zt,"utf8"))}catch{ne={}}}function tr(){Jt=!0,!Ie&&(Ie=setTimeout(async()=>{if(Ie=null,!!Jt){Jt=!1;try{await ft.mkdir(W.dirname(zt),{recursive:!0}),await ft.writeFile(zt,JSON.stringify(ne))}catch(i){T.error("[plane-link] cursor flush failed:",i?.message||i)}}},Zi),Ie.unref?.())}function Qt(){try{return!!ue?.()}catch{return!1}}function en(){let i=H==="http"?pe:Dt;return Qt()?Math.min(i,qe):i}function F(i){return!q||q.readyState!==On.OPEN?!1:(q.send(JSON.stringify(i)),!0)}function Pe(i){let l=Date.now();for(let{trackId:o,event:c}of i){let h=B.get(c.id);B.set(c.id,{trackId:o,seq:c.seq,event:c,sentAt:l,firstSentAt:h?.firstSentAt??l,retryAt:l+Oe,tries:(h?.tries??0)+1,nacks:h?.nacks??0})}let u=i.map(({trackId:o,event:c})=>({trackId:o,event:oa(c)}));return H==="http"?(is(u),!0):F({v:j,ch:"events",type:"append",events:u})}function ts(i){let l=null;for(let u of B.values())u.trackId===i&&(l==null||u.seq<l)&&(l=u.seq);return l}function tn(i){let l=ee[i];if(l==null)return;let u=ts(i),o=u==null?l:Math.min(l,u-1);o>(ne[i]??0)&&(ne[i]=o,tr())}function et(){if(yt=Date.now(),de!=null){let i=Date.now()-de;T.log(`[plane-link] spine sync recovered after ${Math.round(i/1e3)}s degraded (${re} stall redial(s))`);let l=de;de=null,re=0,Xe=0,Z=!1,ge=0;try{ke?.({since:l,downMs:i})}catch(u){T.error(`[plane-link] onRecovered failed: ${u?.message||u}`)}}}function nn(i){if(!Array.isArray(i)||!i.length)return;let l=new Set;for(let u of i){let o=B.get(u);o&&(B.delete(u),(ee[o.trackId]??0)<o.seq&&(ee[o.trackId]=o.seq),l.add(o.trackId))}for(let u of l)tn(u);et()}function nr(i,l){Jn++;let u={at:Date.now(),trackId:i.trackId,seq:i.seq,id:i.event?.id??null,type:i.event?.type??null,reason:l,event:i.event??null};T.error(`[plane-link] DEAD-LETTER ${i.trackId} seq ${i.seq} (${u.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${Vt}`),Qn=Qn.then(async()=>{await ft.mkdir(W.dirname(Vt),{recursive:!0}),await ft.appendFile(Vt,JSON.stringify(u)+`
|
|
125
|
+
`)}).catch(o=>T.error(`[plane-link] dead-letter write failed: ${o?.message||o}`))}function ns(i,l){if(gt[i]=(gt[i]??0)+1,Zn.has(i))return;Zn.add(i);let u=ra[i]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";T.error(`[plane-link] REFUSED by the plane (${i}) on track ${l}: events are being dropped, not stored \u2014 ${u}`);try{Gt?.({reason:i,trackId:l,count:gt[i],hint:u})}catch(o){T.error(`[plane-link] onRefused failed: ${o?.message||o}`)}}function rn(i,l,u,o=null){if(!Array.isArray(i)||!i.length)return;let c=new Set,h=Date.now();for(let y of i){let _=B.get(y);_&&(u?(B.delete(y),nr(_,l),String(l).startsWith(Rn)&&ns(String(l).slice(Rn.length),_.trackId),(ee[_.trackId]??0)<_.seq&&(ee[_.trackId]=_.seq),c.add(_.trackId)):(_.nacks++,_.retryAt=h+Math.max(1e3,Number(o)||Oe)))}for(let y of c)tn(y);et()}function rr(i=Date.now()){let l=1/0;for(let u of B.values())u.firstSentAt<l&&(l=u.firstSentAt);return l===1/0?0:i-l}function rs(i){if(!M||!i||i!==q||!Te)return!1;let l=Date.now()-Te;if(l<=M)return!1;er++,T.error(`[plane-link] no frame from the plane for ${Math.round(l/1e3)}s \u2014 link is half-open; terminating and redialing`);try{i.terminate()}catch{}return!0}function or(){if(!X||!B.size)return;let i=Date.now(),l=rr(i);if(l<Ve||yt!=null&&i-yt<Ve||H==="http"&&Z||Xe>i)return;re++;let u=Math.min(zn*2**(re-1),Po);if(de==null){de=i-l,T.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${B.size} event(s) in flight (${H} door) \u2014 the plane is not answering appends`);try{ze?.({since:de,unacked:B.size,oldestAgeMs:l,mode:H})}catch(o){T.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(H==="http"){Z=!0,ge=i+u,T.error(`[plane-link] ingest circuit OPEN (stall #${re}); probing /v1/ingest/health in ${Math.round(u/1e3)}s`);return}Xe=i+u,T.error(`[plane-link] closing the link and redialing in ${Math.round(u/1e3)}s (stall redial #${re})`);try{q?.terminate()}catch{}}function on(){if(!X)return;let i=Date.now();if(H==="http"&&Z)return;let l=[...B.values()].filter(o=>o.event&&o.retryAt<=i&&!(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),T.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let u=en();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>=Nn)return;Pe(c.slice(0,u).map(h=>({trackId:h.trackId,event:h.event})))}return}for(let o=0;o<l.length;o+=u){let c=l.slice(o,o+u).map(h=>({trackId:h.trackId,event:h.event}));if(!Pe(c))return}}async function os(i=null){for(;;){if(!X)return!1;let l=B.size<ce,u=H!=="http"||Re<Nn&&!Z&&(!i||!Ne.has(i));if(l&&u)return!0;await new Promise(o=>setTimeout(o,100))}}function sn(){if(z=null,!X||!oe.length)return;let i=oe;oe=[];let l=en();if(H!=="http"){for(let c=0;c<i.length;c+=l)Pe(i.slice(c,c+l));return}let u=Qt(),o=new Map;for(let c of i)(o.get(c.trackId)??o.set(c.trackId,[]).get(c.trackId)).push(c);for(let[c,h]of o){if(Ne.has(c)||Re>=Nn||Z){oe.push(...h);continue}if(u){Pe(h.slice(0,l)),oe.push(...h.slice(l));continue}for(let y=0;y<h.length;y+=l)Pe(h.slice(y,y+l))}oe.length&&!z&&(z=setTimeout(sn,Bo),z.unref?.())}let ss=i=>{let l=new Map;for(let{trackId:u,event:o}of i)(l.get(u)??l.set(u,[]).get(u)).push(o);return[...l].map(([u,o])=>({trackId:u,events:o}))},Se=(i,l,u,{progress:o})=>{let c=Date.now();for(let{event:h}of i){let y=B.get(h.id);y&&(y.nacks++,y.retryAt=c+Math.max(1e3,u||Oe))}o&&et()};async function is(i){let l=new Set(i.map(u=>u.trackId));for(let u of l)Ne.add(u);Re++;try{let u=await Vn(`${Xn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:ss(i)}),signal:AbortSignal.timeout(le)}),o=(Number(u.headers.get("retry-after"))||0)*1e3;if(u.status===200){let c=await u.json();pe=Dt;for(let _ of c.results??[]){nn(_.acked??[]);let L=(te,G)=>{let St=new Map;for(let _e of te??[])(St.get(_e.reason)??St.set(_e.reason,[]).get(_e.reason)).push(_e.id);for(let[_e,pr]of St)rn(pr,_e,G,c.retryAfterMs??null)};L(_.rejected,!0),L(_.deferred,!1)}let h=new Set,y=new Map;for(let _ of Array.isArray(c.refused)?c.refused:[])!_||typeof _.id!="string"||(h.add(_.id),(y.get(_.reason)??y.set(_.reason,[]).get(_.reason)).push(_.id));for(let[_,L]of y)rn(L,`${Rn}${_}`,!0);nn((c.discarded??[]).filter(_=>!h.has(_))),et();return}if(u.status===429){Se(i,"overloaded",o||5e3,{progress:!0});return}if(u.status===413&&i.length>1){pe=Math.max(1,Math.floor(i.length/2)),T.error(`[plane-link] ingest request too large (${i.length} events) \u2014 halving batches to ${pe}`),Se(i,"too_large",1e3,{progress:!0});return}if(u.status===413){let c=B.get(i[0].event.id);c&&(B.delete(c.event.id),nr(c,"too_large"),(ee[c.trackId]??0)<c.seq&&(ee[c.trackId]=c.seq),tn(c.trackId)),et();return}if(u.status===410){Zt({reason:"removed",via:"410"}),Se(i,"http_410",6e4,{progress:!1});return}if(u.status===401||u.status===403){let{tripped:c,holdMs:h}=kt();if(c&&T.error(`[plane-link] holding every plane call for ${Math.round(h/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Tt>=Co){Tt=Date.now();let y="";try{y=(await u.json())?.error??""}catch{}T.error(`[plane-link] plane refused ingest (HTTP ${u.status}${y?`: ${y}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}Se(i,`http_${u.status}`,Math.max(6e4,it()),{progress:!1});return}if(u.status===400){T.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${i.length} event(s) for retry; this is a bug, not data`),Se(i,"http_400",6e4,{progress:!1});return}Se(i,`http_${u.status}`,o||5e3,{progress:!1})}catch(u){let o=u?.name==="TimeoutError"||u?.name==="AbortError";o&&i.length>1&&(pe=Math.max(1,Math.floor(i.length/2)),T.error(`[plane-link] ingest request of ${i.length} event(s) outlived its ${le} ms deadline \u2014 halving batches to ${pe}`)),Se(i,o?"timeout":"network",5e3,{progress:!1})}finally{Re--;for(let u of l)Ne.delete(u)}}async function as(){if(H!=="http"||!Z||!X||Yt)return;let i=Date.now();if(!(ge>i||Et(i))){Yt=!0;try{let l=await Vn(`${Xn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(le)});if(!l.ok)throw new Error(`HTTP ${l.status}`);T.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Z=!1,ge=0,Xe=Date.now()+le+Oe+1e3;for(let u of B.values())u.retryAt=Math.min(u.retryAt,Date.now());on()}catch(l){re++;let u=Math.min(zn*2**(re-1),Po);ge=Date.now()+u,T.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(u/1e3)}s`)}finally{Yt=!1}}}function sr(){let i=Date.now();return{mode:H,unacked:B.size,oldestUnackedAgeMs:rr(i),lastProgressAt:yt,degradedSince:de,stallRedials:re,deadLettered:Jn,fanoutCap:Qt()?qe:null,http:H==="http"?{inFlight:Re,circuitOpen:Z,nextProbeInMs:Z?Math.max(0,ge-i):0,batchCap:pe}:null}}async function ir(){if(!m)return;let i;try{i=await m()}catch(u){T.error("[plane-link] metrics sample failed:",u?.message||u);return}let l=null;try{l=S?.()??null}catch{}i&&F({v:j,ch:"ctl",type:"metrics",metrics:{...i,planeLink:sr(),...l?{delivery:l}:{}}})}function cs(){m&&(ie&&clearInterval(ie),ir(),ie=setInterval(ir,E),ie.unref?.())}async function ls(){let i;try{i=await s()}catch(l){T.error("[plane-link] backfill listTracks failed:",l?.message||l);return}F({v:j,ch:"ctl",type:"tracks",ids:i.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of i)if(!X||!await ar(l))return}async function ar(i){let l;try{l=await Ot(i)}catch{return!0}let u=ne[i.id]??0,o=l.filter(c=>c.seq>u&&typeof c.id=="string");for(let c=0;c<o.length;){if(!await os(i.id))return!1;let h=o.slice(c,c+en()).map(y=>({trackId:i.id,event:y}));if(!Pe(h))return!1;c+=h.length}return!0}let an=new Map;async function cr(i,l){if(an.get(i)===l)return!1;an.set(i,l);let u=null;try{u=(await s()).find(y=>y?.id===i)??null}catch{return!1}if(!u)return!1;let o;try{o=await Ot(u)}catch{return!1}let c=[...o].reverse().find(y=>(y?.type==="track.transferred"||y?.type==="track.recovered")&&y.payload?.toNode===n);if(!c||!Number.isFinite(c.seq))return!1;let h=c.seq-1;return(ne[i]??0)>h&&(ne[i]=h,tr()),(ee[i]??0)>h&&(ee[i]=h),T.log(`[plane-link] re-sending ${i}'s move-commit (seq ${c.seq}, ${c.type}) \u2014 the plane's move record predates this node's adoption`),X?ar(u):!1}function lr(i){!X||!i?.trackId||typeof i.id!="string"||(oe.push({trackId:i.trackId,event:i}),z||(z=setTimeout(sn,Bo),z.unref?.()))}let tt=new Map;async function us(i){let{reqId:l,method:u,path:o,headers:c={},body:h}=i,y=Object.fromEntries(Object.entries(c).filter(([,L])=>L!=null)),_=new AbortController;tt.set(l,_);try{if(i.host){await ds(i,y,_);return}k&&(y["x-bostrat-token"]=k);let L=await fetch($+o,{method:u,headers:y,body:h?Buffer.from(h,"base64"):void 0,signal:_.signal}),te=Object.fromEntries(L.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"),F({v:j,ch:"control",type:"http_head",reqId:l,status:L.status,headers:te}),L.body){for await(let G of L.body)if(!F({v:j,ch:"control",type:"http_data",reqId:l,data:Buffer.from(G).toString("base64")}))break}F({v:j,ch:"control",type:"http_end",reqId:l,error:null})}finally{tt.delete(l)}}function ds(i,l,u){let{reqId:o,method:c,path:h,body:y}=i,_=new URL($);return new Promise(L=>{let te=Vi.request({host:_.hostname,port:_.port,method:c,path:h,headers:{...l,host:i.host},signal:u.signal},G=>{let{connection:St,"keep-alive":_e,"transfer-encoding":pr,upgrade:ic,...ps}=G.headers;F({v:j,ch:"control",type:"http_head",reqId:o,status:G.statusCode||502,headers:ps}),G.on("data",fs=>{F({v:j,ch:"control",type:"http_data",reqId:o,data:Buffer.from(fs).toString("base64")})||G.destroy()}),G.on("end",()=>{F({v:j,ch:"control",type:"http_end",reqId:o,error:null}),L()}),G.on("error",()=>{F({v:j,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),L()})});te.on("error",G=>{F({v:j,ch:"control",type:"http_end",reqId:o,error:G?.message||"view request failed"}),L()}),y&&te.write(Buffer.from(y,"base64")),te.end()})}function ur(){if(qt||Qe)return;q=new On(e,{headers:{authorization:`Bearer ${t}`}});let i=q;Te=0,i.on("ping",()=>{Te=Date.now()}),i.on("pong",()=>{Te=Date.now()}),q.on("open",async()=>{let u=null;try{u=await a?.()||null}catch{u=null}F({v:j,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:Q,installKind:A,...typeof g=="function"?{updatePolicy:g()}:g?{updatePolicy:g}:{},providers:Lo(),...u?{agents:u}:{},...Xt?{restart:Xt}:{}})}),q.on("message",u=>{Te=Date.now();let o;try{o=JSON.parse(u)}catch{return}if(o.ch==="ctl"&&o.type==="hello_ok"){an.clear(),X=!0,Je=Mo,Ze=null,Xt=null,br(),T.log(`[plane-link] connected to plane as ${n}`);try{wt?.()}catch{}if(typeof o.hashKey=="string"&&o.hashKey)try{p?.(o.hashKey)}catch{}try{w?.(typeof o.viewBase=="string"&&o.viewBase?o.viewBase:null)}catch{}o.minNodeVersion&&Q&&He(Q,o.minNodeVersion)&&T.error(`[plane-link] this node is bostrat-node ${Q}; the plane asks for \u2265${o.minNodeVersion} \u2014 update with: ${ht(A)}`);try{x?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}qn(o);let c=o.ingest==="http";H=Ee==="ws"?"ws":Ee==="http"||c?"http":"ws",Ee==="http"&&!c&&T.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),H==="http"&&T.log("[plane-link] spine rides the HTTPS ingest door"),Z=!1,ge=0,pe=Dt,se&&clearInterval(se),Te=Date.now(),se=setInterval(()=>{rs(i)||(F({v:j,ch:"ctl",type:"ping"}),or(),as().catch(()=>{}),on(),oe.length&&!z&&sn())},Ye),se.unref?.(),cs(),ls().catch(h=>T.error("[plane-link] backfill failed:",h?.message||h));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let c=typeof o.minNodeVersion=="string"?o.minNodeVersion:null,h=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;T.error(`[plane-link] plane REFUSED this node: bostrat-node ${Q??"?"} is below its minimum ${c??"?"} \u2014 ${o.fix||ht(A)}`),Je=Io,Ze=0;try{v?.({current:Q,min:c,latest:h,fix:o.fix||ht(A),installKind:A})}catch(y){T.error(`[plane-link] refusal handler failed: ${y?.message||y}`)}return}if(o.ch==="ctl"&&o.type==="removed"){F({v:j,ch:"ctl",type:"removed_ack",nodeId:n}),Zt({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"){qn(o);return}if(o.ch==="ctl"&&o.type==="update_policy"){try{x?.(typeof o.mode=="string"?o.mode:null)}catch{}return}if(o.ch==="ctl"&&o.type==="conflict_probe"&&Array.isArray(o.trackIds)){try{N?.(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=>T.error("[plane-link] restart notice failed:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="usage_caps"){Ro(o.caps??{},{source:"plane",updatedAt:o.updatedAt??Date.now()}).then(c=>T.log(`[plane-link] spend caps ${Object.keys(c.caps).length?`updated (${Object.keys(c.caps).join(", ")})`:"cleared"} from plane`)).catch(c=>T.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 h of Array.isArray(c)?c:[])h?.stale&&h.id&&await cr(h.id,h.since??null)}).catch(c=>T.error("[plane-link] transfer notice failed:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="moves"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>f?.(o.tracks)).then(async c=>{for(let h of Array.isArray(c)?c:[])h?.stale&&h.id&&await cr(h.id,h.since??null)}).catch(c=>T.error("[plane-link] move-record reconcile failed:",c?.message||c));return}if(o.ch==="events"&&o.type==="ack"&&Array.isArray(o.ids)){nn(o.ids);return}if(o.ch==="events"&&o.type==="nack"&&Array.isArray(o.ids)){rn(o.ids,o.reason,o.permanent===!0,o.retryAfterMs??null);return}if(o.ch==="control"&&o.type==="http_open"){us(o).catch(c=>F({v:j,ch:"control",type:"http_end",reqId:o.reqId,error:c?.message||"tunnel error"}));return}if(o.ch==="control"&&o.type==="http_cancel"){tt.get(o.reqId)?.abort();return}if(o.ch==="attach"&&o.type==="open"){let c=new On(Qo+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 y=ye.get(o.streamId)||[];ye.delete(o.streamId);for(let{buf:_,bin:L}of y)c.send(_,{binary:L})}),c.on("message",(y,_)=>{let L=_?y:Buffer.from(String(y));F({v:j,ch:"attach",type:"data",streamId:o.streamId,data:L.toString("base64"),..._?{bin:!0}:{}})});let h=()=>{ye.delete(o.streamId),we.delete(o.streamId)&&F({v:j,ch:"attach",type:"close",streamId:o.streamId})};c.on("close",h),c.on("error",h);return}if(o.ch==="attach"&&o.type==="data"){let c=we.get(o.streamId);if(!c)return;let h=Buffer.from(o.data,"base64"),y=o.bin===!0,_=ye.get(o.streamId);_?_.push({buf:h,bin:y}):c.send(h,{binary:y});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=()=>{X&&T.log("[plane-link] disconnected from plane"),X=!1,se&&(clearInterval(se),se=null),ie&&(clearInterval(ie),ie=null),B.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 tt.values())c.abort();if(tt.clear(),qt||Me)return;Ze==null&&(Ze=Date.now());let u=Date.now()-Ze<qi,o=Math.max(u?Xi+Math.random()*Ji:Je,Xe-Date.now(),it());Me=setTimeout(()=>{Me=null,ur()},o),Me.unref?.(),u||(Je=Math.min(Je*2,Io))};q.on("close",l),q.on("error",u=>{let o=/Unexpected server response: (\d+)/.exec(u?.message||"")?.[1];if(o==="410"){Zt({reason:"removed",via:"410"});return}if(o==="401"||o==="403"){let{tripped:c,holdMs:h}=kt();c?T.error(`[plane-link] holding every plane call for ${Math.round(h/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(h/6e4)} min.`):Date.now()-Tt>=Co&&(Tt=Date.now(),T.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()})}ct.on("event",lr),es().then(ur);function dr({bye:i=!0}={}){qt=!0,ct.off("event",lr),Me&&clearTimeout(Me),Ie&&clearTimeout(Ie),se&&clearInterval(se),ie&&clearInterval(ie),z&&clearTimeout(z),i&&F({v:j,ch:"ctl",type:"bye",reason:"shutdown"}),q?.close()}return{stop:()=>dr(),status:()=>({connected:X,nodeId:n,cursor:{...ne},inflight:B.size,...sr(),auth:vr(),dormant:Qe,removed:yn(),deadLinkMs:M,deadLinkRedials:er,refused:{...gt}}),_tick:()=>{or(),on()}}}var Q,Mn,Pn,j,Mo,Io,qi,Xi,Ji,Dt,Zi,Qi,ea,ta,Bn,na,Rn,ra,oa,sa,Po,ia,Bo,aa,Nn,ca,la,Co,Cn=R(()=>{Rt();No();un();gn();Q=(()=>{try{return Yi(import.meta.url)("../package.json").version||null}catch{return null}})(),Mn=process.env.BOSTRAT_STATE_DIR||W.join(process.env.HOME||Lt.tmpdir(),".bostrat"),Pn=W.join(Mn,"plane-link","removed.json");j=1,Mo=1e3,Io=3e4,qi=6e4,Xi=1500,Ji=500,Dt=100,Zi=2e3,Qi=25e3,ea=2.5,ta=6e4,Bn=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},na=Bn(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Rn="refused:",ra={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"},oa=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},sa=3e4,Po=10*6e4,ia=400,Bo=250,aa=Bn(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Nn=4,ca=Math.max(1,Math.round(Bn(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),la=6e4,Co=6e4});var jo=R(()=>{hn()});var Vo={};cn(Vo,{ACTIONABLE_KINDS:()=>Wt,INSTALL_ATTEMPTS:()=>Ft,INSTALL_RETRY_STEP_S:()=>Uo,REGISTRY_RETRY_ATTEMPTS:()=>Fn,REGISTRY_WAIT_POLLS:()=>Dn,REGISTRY_WAIT_STEP_S:()=>Ln,RESTART_SIGNAL:()=>Wo,SELF_UPDATE_DIR:()=>Ut,SUPERVISOR_PID_FILE:()=>Ho,createAutoUpdater:()=>Aa,inFlight:()=>Wn,readStatus:()=>Hn,restartCommand:()=>Ko,restartStrategy:()=>Un,selfUpdatePlan:()=>Go,settleSelfUpdate:()=>xa,startSelfUpdate:()=>zo,underService:()=>jn,updatePolicy:()=>ga});import mt from"node:fs";import he from"node:fs/promises";import da from"node:os";import U from"node:path";import{spawn as pa,execFileSync as fa}from"node:child_process";import{createRequire as ha}from"node:module";function ga({kind:e=We(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:Wt.has(e)?e==="git-checkout"||jn(t)?"auto":"prompt":"off"}function jn(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Un({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:s=Ho,readFile:a=f=>mt.readFileSync(f,"utf8"),alive:d=Ta}={}){let f=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(jn(e))return f;let m=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(m)&&m>0)){try{m=Number(String(a(s)).trim())}catch{m=NaN}Number.isInteger(m)&&m>0&&d(m)||(m=NaN)}return Number.isInteger(m)&&m>0?{mode:"supervisor",pid:m}:f}function Ta(e){try{process.kill(e,0)}catch{return!1}try{let t=fa("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 Ko(e){switch(e?.mode){case"systemd":return`systemctl --user restart ${J(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 -${Wo.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function Go({kind:e,to:t,from:n=jt,statusFile:r=Ht,logFile:s=U.join(Ut,"last.log"),port:a=Number(process.env.PORT)||3362,npmPrefix:d=null,serviceName:f=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:m=typeof process.getuid=="function"?process.getuid():0,restart:S=Un({env:{},platform:process.platform,uid:m,serviceName:f,readFile:()=>{throw new Error("no pidfile")}}),liveDir:p=process.env.BOSTRAT_LIVE_CHECKOUT||U.resolve(U.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:w=Date.now(),attempts:E=1}={}){if(!Wt.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=(v,g="")=>`write_status ${J(v)} ${g}`,x=Ko(S),N=`
|
|
126
126
|
health() {
|
|
127
127
|
for i in $(seq 1 45); do
|
|
128
128
|
sleep 1
|
|
@@ -147,10 +147,10 @@ write_status() { # <status> [error] [retryable]
|
|
|
147
147
|
}
|
|
148
148
|
${N}
|
|
149
149
|
`;if(e==="npm-global"){let v=d?U.join(d,"bin","npm"):"npm",g=d?`export PATH=${J(U.join(d,"bin"))}:"$PATH"
|
|
150
|
-
`:"",A=d?` --prefix ${J(d)}`:""
|
|
150
|
+
`:"",A=d?` --prefix ${J(d)}`:"",$=$e=>`${J(v)} install -g "bostrat-node@${$e}" --no-audit --no-fund${A}`,k=`
|
|
151
151
|
install_target() {
|
|
152
152
|
for i in $(seq 1 ${Ft}); do
|
|
153
|
-
if ${
|
|
153
|
+
if ${$("$TO")}; then return 0; fi
|
|
154
154
|
[ "$i" -lt ${Ft} ] && sleep ${Uo}
|
|
155
155
|
done
|
|
156
156
|
return 1
|
|
@@ -161,7 +161,7 @@ wait_for_registry() {
|
|
|
161
161
|
sleep ${Ln}
|
|
162
162
|
done
|
|
163
163
|
return 1
|
|
164
|
-
}`;return O+g+I
|
|
164
|
+
}`;return O+g+I+k+`
|
|
165
165
|
${b("updating",'"" ')}
|
|
166
166
|
if ! wait_for_registry; then
|
|
167
167
|
${b("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(Dn*Ln/60)} min, attempt $ATTEMPTS of ${Fn})" retryable`)}
|
|
@@ -182,14 +182,14 @@ if health; then
|
|
|
182
182
|
fi
|
|
183
183
|
# \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
|
|
184
184
|
${b("rolling-back",'"agent did not answer on :'+a+' after the update"')}
|
|
185
|
-
if [ -n "$FROM" ] && ${
|
|
185
|
+
if [ -n "$FROM" ] && ${$("$FROM")} && ${x} && health; then
|
|
186
186
|
${b("rolled-back",'"agent did not answer on :'+a+' after the update; rolled back"')}
|
|
187
187
|
exit 1
|
|
188
188
|
fi
|
|
189
189
|
${b("failed",'"agent did not answer after the update AND the rollback"')}
|
|
190
190
|
exit 1
|
|
191
|
-
`}let P=v=>`( cd ${J(
|
|
192
|
-
LIVE=${J(
|
|
191
|
+
`}let P=v=>`( cd ${J(p)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${v}" )`;return O+`
|
|
192
|
+
LIVE=${J(p)}
|
|
193
193
|
TMP_SCRIPT="$(mktemp)"
|
|
194
194
|
trap 'rm -f "$TMP_SCRIPT"' EXIT
|
|
195
195
|
# "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
|
|
@@ -206,29 +206,29 @@ if [ -n "$FROM" ] && ${P("$FROM")}; then
|
|
|
206
206
|
fi
|
|
207
207
|
${b("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
|
|
208
208
|
exit 1
|
|
209
|
-
`}async function Hn(e=Ht){try{return JSON.parse(await he.readFile(e,"utf8"))}catch{return null}}async function zo({to:e,from:t=jt,kind:n=We(),reason:r="manual",force:s=!1,statusFile:a=Ht,spawnImpl:d=
|
|
210
|
-
`).catch(()=>{})),x(a),b({state:"own",pid:k.pid})},O=()=>{p&&(p.kill("SIGTERM"),Pt.rmSync(E,{force:!0}))};return process.on("exit",O),{ready:N().catch(()=>m),status:()=>m,stop(){f=!0,clearTimeout(S),process.off("exit",O);let v=p;p=null,v&&(v.kill("SIGTERM"),Pt.rmSync(E,{force:!0}))}}}import Si from"node:fs";import Qr from"node:path";import _i from"node:os";var bi=()=>process.env.BOSTRAT_STATE_DIR||Qr.join(process.env.HOME||_i.tmpdir(),".bostrat"),vi=()=>Qr.join(bi(),"plane-link","public-host.json");var ft=null;function xi(){if(ft)return ft;try{let e=JSON.parse(Si.readFileSync(vi(),"utf8"));ft={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{ft={viewBase:null}}return ft}function Ai(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),s=r?r[1].toLowerCase():t,a=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return a?{proto:s,host:a}:null}function eo(){return xi().viewBase}function to(e=process.env.BOSTRAT_PUBLIC_HOST){return Ai(e,"https")}function no(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}Nt();import ki from"node:fs";import $i from"node:os";import ro from"node:path";var oo=3*6e4;function An(e=process.env){let t=e.BOSTRAT_STATE_DIR||ro.join(e.HOME||$i.tmpdir(),".bostrat");return ro.join(t,"heartbeat.json")}function so(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return oo;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):oo}function io(e=An()){try{let t=JSON.parse(ki.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 s=Number(t.loopLagMs);return{pid:r,ts:n,loopLagMs:Number.isFinite(s)?s:null}}catch{return null}}Nt();var co="BOSTRAT_RESTART_NOTICE",Zu=2*6e4;var ao=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function lo({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:ao(e),staleS:ao(t)!=null?Math.round(t/1e3):null})}var qo=(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 s=0;s<Math.max(n.length,r.length);s++){let a=(n[s]||0)-(r[s]||0);if(a)return a<0}return!1},me=Ea(ka),Gn=C.dirname(Na(import.meta.url)),Ae=C.resolve(Gn,".."),Ma=C.join(Gn,"index.js"),Ia="wss://plane.bostrat.ai/v1/node",Ke=Kn(import.meta.url)("../package.json").version,D=(e,t)=>({name:e,level:"pass",detail:t}),Y=(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 Pa(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?D("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 Ba(e){return e.BOSTRAT_OWNER?Y("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"):D("owner stamp","none (the plane infers the owner from the token)")}function Ca(e){let t;try{t=K.statSync(e)}catch{return Y("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?Y("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):D("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 D("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 Xo(e,{required:t=!1}={}){if(await vn(e,{loginShell:!0,failOpen:!1}))return D(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",s=It[e]?`${It[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,s):Y(e,r,s)}async function La(){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 D("gh (GitHub CLI)",n)}catch{return Y("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",It.gh)}}async function Fa(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Xo(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 ja(){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 vn(t,{failOpen:!1})?D(t,"resolves on the service PATH"):Y(t,`not on the service PATH \u2014 ${n}`,r)))}async function Ua(){try{let t=Kn(C.join(Ae,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let s=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),a=setTimeout(()=>r(new Error("spawn timeout")),5e3);s.onExit(()=>{clearTimeout(a),n()})}),D("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=Kn(C.join(Ae,"package.json")),r=C.join(C.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 Ha(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(K.existsSync(t))return D("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:Y)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function Wa(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"):D("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function Ka(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return Y("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),s=nt(e.BOSTRAT_PLANE_URL);return await new Promise(a=>{let d=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),p=null,m=f=>{clearTimeout(S);try{d.close()}catch{}a(p?{...f,viewBase:p}:f)},S=setTimeout(()=>m(V("plane link",`no hello_ok within 5s from ${s}`,"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-${Ra().slice(0,8)}`,ephemeral:!0}))),d.on("message",f=>{try{let w=JSON.parse(f);w.type==="hello_ok"?(typeof w.viewBase=="string"&&w.viewBase&&(p=w.viewBase),w.minNodeVersion&&qo(Ke,w.minNodeVersion)?m(V("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${w.minNodeVersion} \u2014 this node is ${Ke}; the real link is refused until it updates`,`bostrat-node self-update --to ${w.latestNodeVersion||w.minNodeVersion}`)):w.latestNodeVersion&&qo(Ke,w.latestNodeVersion)?m(Y("plane link",`hello_ok in ${Date.now()-r}ms (${s}); bostrat-node ${w.latestNodeVersion} is available (this node: ${Ke})`,`bostrat-node self-update --to ${w.latestNodeVersion}`)):m(D("plane link",`hello_ok in ${Date.now()-r}ms (${s})`))):w.type==="error"&&m(V("plane link",`plane said: ${w.code} ${w.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 Ga(){let e;try{e=JSON.parse(K.readFileSync(C.join(bt,"content-outbox.json"),"utf8"))}catch{return D("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?Y("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):D("content outbox",t?`${t} op(s) in flight`:"drained")}async function za(e){let t=await Lr({env:e}),n=Fr(t);return t.available?D("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?Y("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)"):D("box caps",n)}async function Va(e){let t=await Jr({env:e}),n=xn(t);return t.state==="absent"?Y("oom guard",n,"install earlyoom (apt install earlyoom) \u2014 the node starts it with its own tuning at the next boot"):D("oom guard",n)}function Ya(e){return e.BOSTRAT_STATE_REMOTE?D("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):Y("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}function qa(e,t){let n=t?.viewBase??null,r=eo(),s=to(e.BOSTRAT_PUBLIC_HOST),a=(()=>{let d=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(d)return`${d.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let p=no(e.BOSTRAT_PLANE_URL);return p?`${p}/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=s&&s.host!==n?`; BOSTRAT_PUBLIC_HOST=${s.host} is set but the plane's value wins`:"";return D("public host",`views https://<slug>.${n}/ (plane hello_ok)${d} \xB7 track links ${a}`)}return r?D("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${a}`):s?D("public host",`views ${s.proto}://<slug>.${s.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 Jo(e,t={}){let n=[];n.push(await Pa()),n.push(Ca(t.envFile||Be())),n.push(await Da(e)),n.push(await za(e)),n.push(await Va(e)),n.push(...await Fa()),n.push(await Xo("git",{required:!0})),n.push(await La()),n.push(...await ja()),n.push(await Ua()),n.push(Ha(e)),n.push(Wa(e)),n.push(Ba(e));let r=await Ka(e,t);return n.push(r),n.push(qa(e,r)),n.push(Ga()),n.push(Ya(e)),n}function Zo(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,s=e.filter(a=>a.level==="warn").length;return t(r?`
|
|
209
|
+
`}async function Hn(e=Ht){try{return JSON.parse(await he.readFile(e,"utf8"))}catch{return null}}async function zo({to:e,from:t=jt,kind:n=We(),reason:r="manual",force:s=!1,statusFile:a=Ht,spawnImpl:d=pa,now:f=Date.now,npmPrefix:m=void 0,log:S=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!Wt.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!He(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let p=await Hn(a);if(Wn(p))return{ok:!1,reason:`an update to ${p.to} is already in flight`,status:p};let w=p?.to===e?Number(p.attempts)||1:0;if(!s&&p&&p.to===e&&(p.status==="failed"||p.status==="rolled-back")&&!(p.status==="failed"&&p.retryable===!0&&w<Fn))return{ok:!1,reason:`update to ${e} already ${p.status} (${p.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:p};let E=p?.to===e&&(p.status==="failed"||p.status==="rolled-back")?w+1:1;await he.mkdir(U.dirname(a),{recursive:!0});let b=m!==void 0?m:n==="npm-global"?fn(await _a())||U.resolve(U.dirname(process.execPath),".."):null,x=Un(),N=Go({kind:n,to:e,from:t,statusFile:a,npmPrefix:b,startedAt:f(),attempts:E,restart:x}),O=U.join(U.dirname(a),`update-${e}.sh`),P=U.join(U.dirname(a),"last.log");await he.writeFile(O,N,{mode:448}),await he.writeFile(a,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:E,startedAt:f(),updatedAt:f()}));let v=mt.existsSync("/run/systemd/system")&&await ba("systemd-run"),g=v?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",O]]:["bash",[O]],A=async k=>{let I=`could not spawn updater: ${k?.message||k}`;return await he.writeFile(a,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,attempts:E,startedAt:f(),updatedAt:f(),error:I})).catch(()=>{}),S.error?.(`[self-update] ${I}`),I},$=null;try{v||($=mt.openSync(P,"a"));let k=d(g[0],g[1],{detached:!0,stdio:v?"ignore":["ignore",$,$]});k.on?.("error",I=>{A(I)}),k.unref?.()}catch(k){return{ok:!1,reason:await A(k)}}finally{$!==null&&mt.closeSync($)}return S.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}, restart via ${x.mode}) started \u2014 status ${a}`),{ok:!0,to:e,from:t,kind:n,scriptFile:O,statusFile:a}}async function _a(){try{return await he.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function ba(e){for(let t of String(process.env.PATH||"").split(U.delimiter))try{return await he.access(U.join(t,e),mt.constants.X_OK),!0}catch{}return!1}async function xa({statusFile:e=Ht,current:t=jt,now:n=Date.now,staleMs:r=va}={}){let s=await Hn(e);if(!s)return null;let a=d=>he.writeFile(e,JSON.stringify(d)).catch(()=>{});if(Wn(s)){if(t&&s.to===t){let d={...s,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await a(d),d}if(n()-Number(s.updatedAt||s.startedAt||0)>r){let d={...s,status:"failed",error:`updater went silent while ${s.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(s.status)&&!s.announced){let d={...s,announced:!0};return await a(d),d}return null}function Aa({isBusy:e,start:t=zo,onStuck:n=null,onStarted:r=null,tickMs:s=ya,stuckMs:a=wa,now:d=Date.now,setIntervalImpl:f=setInterval,clearIntervalImpl:m=clearInterval,log:S=console}={}){let p=null,w=()=>{p?.timer&&m(p.timer),p=null},E=async()=>{if(!p)return;let b=!0;try{b=await e()!==!1}catch{b=!0}if(b){if(!p.stuckFired&&d()-p.since>=a){p.stuckFired=!0;try{await n?.({to:p.to,from:p.from,since:p.since})}catch{}}return}let x=p;w();let N=await t({to:x.to,from:x.from,kind:x.kind,reason:"auto"});S.log?.(`[self-update] stasis reached \u2192 ${N.ok?"started":`not started: ${N.reason}`}`);try{await r?.({...x,result:N})}catch{}};return{arm({to:b,from:x=jt,kind:N=We()}){return p?.to===b?!1:(w(),p={to:b,from:x,kind:N,since:d(),stuckFired:!1,timer:f(E,s)},p.timer.unref?.(),!0)},tick:E,cancel:w,get armed(){return p?{to:p.to,from:p.from,kind:p.kind,since:p.since}:null}}}var jt,ma,Ut,Ht,wa,ya,Dn,Ln,Fn,Ft,Uo,Ho,Wo,Wt,J,Sa,Wn,va,Yo=R(()=>{Cn();jo();jt=(()=>{try{return ha(import.meta.url)("../package.json").version||null}catch{return null}})(),ma=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||da.tmpdir(),".bostrat"),Ut=U.join(ma,"self-update"),Ht=U.join(Ut,"status.json"),wa=1440*6e4,ya=6e4,Dn=60,Ln=15,Fn=3,Ft=6,Uo=20,Ho=U.join(Ut,"supervisor.pid"),Wo="SIGUSR2",Wt=new Set(["npm-global","git-checkout"]);J=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Sa=new Set(["updating","restarting","rolling-back"]),Wn=e=>!!(e&&Sa.has(e.status));va=45*6e4});un();pn();_n();import K from"node:fs";import C from"node:path";import Ge from"node:os";import{createRequire as Kn}from"node:module";import{execFile as $a,spawn as ka}from"node:child_process";import{promisify as Ea}from"node:util";import Oa from"node:readline/promises";import{randomUUID as Ra}from"node:crypto";import{fileURLToPath as Na}from"node:url";import Pt from"node:fs";import Fe from"node:fs/promises";import pi from"node:os";import dt from"node:path";import fi from"node:readline";import{spawn as hi}from"node:child_process";var mi="^(ugrep|rg|2\\.1\\.[0-9]+|cursor-agent|codex|npm|node|MainThread)",wi="^(bostrat-|tmux|earlyoom|systemd|sshd)",yi=()=>["-m","10","-s","70","-r","600","--prefer",mi,"--avoid",wi],Gr="BOSTRAT_OOM_GUARD_OWNER",gi=6e4,Ti=5e3;function zr(e=process.env){return!["0","off","false","no"].includes(String(e.BOSTRAT_OOM_GUARD??"").trim().toLowerCase())}function Vr(e=process.env){let t=e.BOSTRAT_STATE_DIR||dt.join(e.HOME||pi.tmpdir(),".bostrat");return dt.join(t,"oom-guard.pid")}function Yr(e=process.env){if(e.BOSTRAT_EARLYOOM_BIN)return Pt.existsSync(e.BOSTRAT_EARLYOOM_BIN)?e.BOSTRAT_EARLYOOM_BIN:null;let t=[...String(e.PATH||"").split(":").filter(Boolean),"/usr/bin","/usr/sbin","/usr/local/bin","/bin"];for(let n of t){let r=dt.join(n,"earlyoom");if(Pt.existsSync(r))return r}return null}async function qr({procRoot:e="/proc"}={}){let t=[];try{t=await Fe.readdir(e)}catch{return[]}let n=[];for(let r of t){if(!/^\d+$/.test(r))continue;(await Fe.readFile(dt.join(e,r,"comm"),"utf8").catch(()=>"")).trim()==="earlyoom"&&n.push({pid:Number(r)})}return n}async function Xr(e){let t=Number((await Fe.readFile(e,"utf8").catch(()=>"")).trim());return Number.isInteger(t)&&t>0?t:null}async function Jr({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc"}={}){if(!zr(e))return{state:"off"};if(t!=="linux")return{state:"unsupported",platform:t};let r=await qr({procRoot:n}),s=await Xr(Vr(e)),a=r.find(f=>f.pid===s);if(a)return{state:"own",pid:a.pid};if(r.length)return{state:"host",pid:r[0].pid};let d=Yr(e);return d?{state:"stopped",bin:d}:{state:"absent"}}function xn(e){switch(e?.state){case"own":return`earlyoom running under the node (pid ${e.pid}; acts at 10% memory available and 70% swap free)`;case"host":return`the host's own earlyoom is running (pid ${e.pid}) \u2014 the node starts none beside it`;case"stopped":return`earlyoom is installed (${e.bin}) and not running \u2014 the node starts it at boot`;case"absent":return"none \u2014 earlyoom is not installed, so memory exhaustion is left to the kernel's OOM killer";case"off":return"disabled (BOSTRAT_OOM_GUARD=0)";case"unsupported":return`not available on ${e.platform}`;default:return"not checked yet"}}function Zr({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc",log:r=console.log,spawnImpl:s=hi,checkMs:a=gi,relaunchMs:d=Ti}={}){let f=null,m={state:null},S=null,p=!1,w="",E=Vr(e),b=v=>{m=v;let g=`[oom-guard] ${xn(v)}`;return g!==w&&r(g),w=g,v},x=v=>{p||(clearTimeout(S),S=setTimeout(()=>N().catch(()=>{}),v),S.unref?.())},N=async()=>{if(p||f)return m;if(!zr(e))return b({state:"off"});if(t!=="linux")return b({state:"unsupported",platform:t});let v=await Xr(E),g=await qr({procRoot:n});if(v&&g.some(k=>k.pid===v)){try{process.kill(v,"SIGTERM")}catch{}g=g.filter(k=>k.pid!==v)}if(g.length)return x(a),b({state:"host",pid:g[0].pid});let A=Yr(e);if(!A)return x(a),b({state:"absent"});let $;try{$=s(A,yi(),{stdio:["ignore","pipe","pipe"]})}catch(k){return r(`[oom-guard] could not start ${A}: ${k?.message||k}`),x(a),m}f=$;for(let k of[$.stdout,$.stderr])k&&fi.createInterface({input:k}).on("line",I=>r(`[earlyoom] ${I}`));return $.on("error",k=>{r(`[oom-guard] ${A}: ${k?.message||k}`),!(f!==$||$.pid)&&(f=null,x(a))}),$.on("exit",(k,I)=>{f===$&&(f=null,Fe.rm(E,{force:!0}).catch(()=>{}),!p&&(r(`[oom-guard] earlyoom exited (${I||`code ${k}`}) \u2014 relaunching in ${Math.round(d/1e3)} s`),m={state:"stopped",bin:A},w="",x(d)))}),$.pid&&(await Fe.mkdir(dt.dirname(E),{recursive:!0}).catch(()=>{}),await Fe.writeFile(E,`${$.pid}
|
|
210
|
+
`).catch(()=>{})),x(a),b({state:"own",pid:$.pid})},O=()=>{f&&(f.kill("SIGTERM"),Pt.rmSync(E,{force:!0}))};return process.on("exit",O),{ready:N().catch(()=>m),status:()=>m,stop(){p=!0,clearTimeout(S),process.off("exit",O);let v=f;f=null,v&&(v.kill("SIGTERM"),Pt.rmSync(E,{force:!0}))}}}import Si from"node:fs";import Qr from"node:path";import _i from"node:os";var bi=()=>process.env.BOSTRAT_STATE_DIR||Qr.join(process.env.HOME||_i.tmpdir(),".bostrat"),vi=()=>Qr.join(bi(),"plane-link","public-host.json");var pt=null;function xi(){if(pt)return pt;try{let e=JSON.parse(Si.readFileSync(vi(),"utf8"));pt={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{pt={viewBase:null}}return pt}function Ai(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),s=r?r[1].toLowerCase():t,a=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return a?{proto:s,host:a}:null}function eo(){return xi().viewBase}function to(e=process.env.BOSTRAT_PUBLIC_HOST){return Ai(e,"https")}function no(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}Nt();import $i from"node:fs";import ki from"node:os";import ro from"node:path";var oo=3*6e4;function An(e=process.env){let t=e.BOSTRAT_STATE_DIR||ro.join(e.HOME||ki.tmpdir(),".bostrat");return ro.join(t,"heartbeat.json")}function so(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return oo;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):oo}function io(e=An()){try{let t=JSON.parse($i.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 s=Number(t.loopLagMs);return{pid:r,ts:n,loopLagMs:Number.isFinite(s)?s:null}}catch{return null}}Nt();var co="BOSTRAT_RESTART_NOTICE",Zu=2*6e4;var ao=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function lo({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:ao(e),staleS:ao(t)!=null?Math.round(t/1e3):null})}var qo=(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 s=0;s<Math.max(n.length,r.length);s++){let a=(n[s]||0)-(r[s]||0);if(a)return a<0}return!1},me=Ea($a),Gn=C.dirname(Na(import.meta.url)),Ae=C.resolve(Gn,".."),Ma=C.join(Gn,"index.js"),Ia="wss://plane.bostrat.ai/v1/node",Ke=Kn(import.meta.url)("../package.json").version,D=(e,t)=>({name:e,level:"pass",detail:t}),Y=(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 Pa(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?D("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 Ba(e){return e.BOSTRAT_OWNER?Y("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"):D("owner stamp","none (the plane infers the owner from the token)")}function Ca(e){let t;try{t=K.statSync(e)}catch{return Y("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?Y("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):D("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 D("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 Xo(e,{required:t=!1}={}){if(await vn(e,{loginShell:!0,failOpen:!1}))return D(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",s=It[e]?`${It[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,s):Y(e,r,s)}async function La(){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 D("gh (GitHub CLI)",n)}catch{return Y("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",It.gh)}}async function Fa(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Xo(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 ja(){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 vn(t,{failOpen:!1})?D(t,"resolves on the service PATH"):Y(t,`not on the service PATH \u2014 ${n}`,r)))}async function Ua(){try{let t=Kn(C.join(Ae,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let s=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),a=setTimeout(()=>r(new Error("spawn timeout")),5e3);s.onExit(()=>{clearTimeout(a),n()})}),D("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=Kn(C.join(Ae,"package.json")),r=C.join(C.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 Ha(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(K.existsSync(t))return D("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:Y)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function Wa(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"):D("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function Ka(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return Y("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),s=nt(e.BOSTRAT_PLANE_URL);return await new Promise(a=>{let d=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),f=null,m=p=>{clearTimeout(S);try{d.close()}catch{}a(f?{...p,viewBase:f}:p)},S=setTimeout(()=>m(V("plane link",`no hello_ok within 5s from ${s}`,"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-${Ra().slice(0,8)}`,ephemeral:!0}))),d.on("message",p=>{try{let w=JSON.parse(p);w.type==="hello_ok"?(typeof w.viewBase=="string"&&w.viewBase&&(f=w.viewBase),w.minNodeVersion&&qo(Ke,w.minNodeVersion)?m(V("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${w.minNodeVersion} \u2014 this node is ${Ke}; the real link is refused until it updates`,`bostrat-node self-update --to ${w.latestNodeVersion||w.minNodeVersion}`)):w.latestNodeVersion&&qo(Ke,w.latestNodeVersion)?m(Y("plane link",`hello_ok in ${Date.now()-r}ms (${s}); bostrat-node ${w.latestNodeVersion} is available (this node: ${Ke})`,`bostrat-node self-update --to ${w.latestNodeVersion}`)):m(D("plane link",`hello_ok in ${Date.now()-r}ms (${s})`))):w.type==="error"&&m(V("plane link",`plane said: ${w.code} ${w.message||""}`,"check the token"))}catch{}}),d.on("error",p=>m(V("plane link",`${p?.message||p}`,"check the URL, the token, and the plane's IP gate")))})}function Ga(){let e;try{e=JSON.parse(K.readFileSync(C.join(bt,"content-outbox.json"),"utf8"))}catch{return D("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?Y("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):D("content outbox",t?`${t} op(s) in flight`:"drained")}async function za(e){let t=await Lr({env:e}),n=Fr(t);return t.available?D("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?Y("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)"):D("box caps",n)}async function Va(e){let t=await Jr({env:e}),n=xn(t);return t.state==="absent"?Y("oom guard",n,"install earlyoom (apt install earlyoom) \u2014 the node starts it with its own tuning at the next boot"):D("oom guard",n)}function Ya(e){return e.BOSTRAT_STATE_REMOTE?D("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):Y("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}function qa(e,t){let n=t?.viewBase??null,r=eo(),s=to(e.BOSTRAT_PUBLIC_HOST),a=(()=>{let d=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(d)return`${d.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let f=no(e.BOSTRAT_PLANE_URL);return f?`${f}/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=s&&s.host!==n?`; BOSTRAT_PUBLIC_HOST=${s.host} is set but the plane's value wins`:"";return D("public host",`views https://<slug>.${n}/ (plane hello_ok)${d} \xB7 track links ${a}`)}return r?D("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${a}`):s?D("public host",`views ${s.proto}://<slug>.${s.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 Jo(e,t={}){let n=[];n.push(await Pa()),n.push(Ca(t.envFile||Be())),n.push(await Da(e)),n.push(await za(e)),n.push(await Va(e)),n.push(...await Fa()),n.push(await Xo("git",{required:!0})),n.push(await La()),n.push(...await ja()),n.push(await Ua()),n.push(Ha(e)),n.push(Wa(e)),n.push(Ba(e));let r=await Ka(e,t);return n.push(r),n.push(qa(e,r)),n.push(Ga()),n.push(Ya(e)),n}function Zo(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,s=e.filter(a=>a.level==="warn").length;return t(r?`
|
|
211
211
|
FAIL \u2014 ${r} blocking, ${s} warnings`:`
|
|
212
212
|
OK \u2014 0 blocking, ${s} warnings`),r===0}async function Xa({envFile:e=Be(),input:t=process.stdin,output:n=process.stdout}={}){let r=vt(e),s=Oa.createInterface({input:t,output:n}),a=async(v,g)=>(await s.question(g?`${v} [${g}]: `:`${v}: `)).trim()||g||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
|
|
213
213
|
you type those inside each box, later (box-auth-policy).
|
|
214
214
|
|
|
215
|
-
`);let d=await a("Plane URL",r.BOSTRAT_PLANE_URL||Ia),
|
|
215
|
+
`);let d=await a("Plane URL",r.BOSTRAT_PLANE_URL||Ia),f=nt(d);f!==d.trim()&&n.write(` \u2192 using ${f}
|
|
216
216
|
`);let m=await a("Node token (minted plane-side; stored 0600)",r.BOSTRAT_PLANE_TOKEN);r.BOSTRAT_OWNER&&n.write(` \u2192 dropping BOSTRAT_OWNER from node.env \u2014 the plane infers the owner from the token; a stale id here got every event refused.
|
|
217
|
-
`);let S=await a("Node name",r.BOSTRAT_NODE_NAME||Ge.hostname().split(".")[0]),
|
|
217
|
+
`);let S=await a("Node name",r.BOSTRAT_NODE_NAME||Ge.hostname().split(".")[0]),p=await a("Repos root",r.BOSTRAT_REPOS_ROOT||C.join(Ge.homedir(),"Documents")),w=await a("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),E=(await a("Route NEW claude boxes through a BYO API key? (y/N)",r.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");E&&n.write(`
|
|
218
218
|
BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
|
|
219
219
|
injected per box, stored 0600 in node.env, never sent to the plane.
|
|
220
220
|
\u2022 create/copy a key: https://console.anthropic.com/settings/keys
|
|
221
221
|
\u2022 set a monthly spend limit while you're there \u2014 the key is live.
|
|
222
222
|
|
|
223
223
|
`);let b=E?await a("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";E&&b&&!/^sk-ant-/.test(b)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
|
|
224
|
-
`),s.close();let x={...mr(),...r,BOSTRAT_PLANE_URL:
|
|
224
|
+
`),s.close();let x={...mr(),...r,BOSTRAT_PLANE_URL:f,BOSTRAT_PLANE_TOKEN:m,BOSTRAT_NODE_NAME:S,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||S,BOSTRAT_REPOS_ROOT:p,BOSTRAT_STATE_REMOTE:w,BOSTRAT_CLAUDE_USE_API_KEY:E?"1":"0",ANTHROPIC_API_KEY:E?b:r.ANTHROPIC_API_KEY};delete x.BOSTRAT_OWNER,hr(e,x,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
|
|
225
225
|
0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
|
|
226
226
|
Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
|
|
227
227
|
wrote ${e}
|
|
228
228
|
|
|
229
229
|
`);let N={...x,...process.env},O=await Jo(N,{envFile:e}),P=Zo(O,v=>n.write(v+`
|
|
230
|
-
`));return P&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:P,results:O}}var Ja="SIGUSR2",Za=5*6e4,Qa=1e4,Kt=C.join(bt,"self-update","supervisor.pid");function ec({spawnChild:e,exit:t=S=>process.exit(S),now:n=Date.now,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:s=clearTimeout,killGraceMs:a=15e3,rollbackGraceMs:d=Za,stall:
|
|
231
|
-
`)}catch{}let r=so(process.env),s=An(process.env);console.log(r?`[bostrat-node] stall watchdog: relaunch the agent after ${Math.round(r/1e3)} s without a heartbeat (${s})`:"[bostrat-node] stall watchdog: off (BOSTRAT_HEARTBEAT_STALE_MS)");let a=ec({spawnChild:d
|
|
230
|
+
`));return P&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:P,results:O}}var Ja="SIGUSR2",Za=5*6e4,Qa=1e4,Kt=C.join(bt,"self-update","supervisor.pid");function ec({spawnChild:e,exit:t=S=>process.exit(S),now:n=Date.now,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:s=clearTimeout,killGraceMs:a=15e3,rollbackGraceMs:d=Za,stall:f=null,log:m=console}={}){let S=null,p=0,w=!1,E="update",b=0,x=null,N=null,O=null,P=0,v=0,g=0,A=!1,$=f&&f.staleMs>0?f.staleMs:0,k=f?.checkMs>0?f.checkMs:Qa,I=()=>{x&&s(x),x=null},$e=()=>{S.kill("SIGTERM"),N=r(()=>S?.kill("SIGKILL"),a),N.unref?.()},ze=null,ke=0,Gt=()=>{let M=null;try{M=f.readHeartbeat()}catch{}return M&&M.pid===S.pid&&Number.isFinite(M.ts)&&M.ts!==ze&&(ze=M.ts,ke=Math.max(ke,Math.min(M.ts,n()))),n()-ke},wt=()=>{if(!S||A||w||!$)return!1;let M=Gt();return M<$?!1:(v++,g=M,m.error?.(`[bostrat-node] the agent (pid ${S.pid}) has written no heartbeat for ${Math.round(M/1e3)} s \u2014 stalled; relaunching it in place (boxes keep running on the host tmux server; stall relaunch #${v})`),E="stall",w=!0,$e(),!0)},Ee=()=>{$&&(O&&s(O),O=r(()=>{O=null,wt(),Ee()},k),O.unref?.())},Ve=(M=null)=>{let ce=e(M);return S=ce,p=n(),ze=null,ke=p,ce.on("exit",(le,ue)=>Oe(ce,le,ue)),O||Ee(),ce},Oe=(M,ce,le)=>{if(M!==S)return;if(S=null,N&&s(N),N=null,w){w=!1,Ye(E);return}let ue=le?1:ce??1;if(!A&&ue!==0&&n()<b){let qe=b-n();m.error?.(`[bostrat-node] the agent exited (code ${ue}) right after a self-update restart \u2014 holding ${Math.ceil(qe/1e3)} s for the updater's rollback signal`),x=r(()=>t(ue),qe);return}t(ue)},Ye=(M="update")=>{P++,M==="stall"?m.log?.(`[bostrat-node] relaunched the agent after a stall (restart #${P}, stall relaunch #${v})`):(b=n()+d,m.log?.(`[bostrat-node] restarting the agent (self-update, restart #${P})`)),E="update",Ve(M==="stall"?{at:n(),staleMs:g}:null)};return{start:()=>Ve(),restart(){if(A=!1,I(),E="update",!S){Ye("update");return}w||(w=!0,$e())},checkStall:wt,forward(M){A=!0,S?S.kill(M):(I(),t(1))},get child(){return S},get state(){return{alive:!!S,restartPending:w,restartReason:E,holding:!!x,restarts:P,stallRelaunches:v,stopping:A}}}}function tc({envFile:e=Be()}={}){fr(e),process.title="bostrat-node";let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n={...process.env,BOSTRAT_RUN_SUPERVISOR_PID:String(process.pid),[Gr]:"supervisor"};Zr();try{K.mkdirSync(C.dirname(Kt),{recursive:!0}),K.writeFileSync(Kt,`${process.pid}
|
|
231
|
+
`)}catch{}let r=so(process.env),s=An(process.env);console.log(r?`[bostrat-node] stall watchdog: relaunch the agent after ${Math.round(r/1e3)} s without a heartbeat (${s})`:"[bostrat-node] stall watchdog: off (BOSTRAT_HEARTBEAT_STALE_MS)");let a=ec({spawnChild:d=>ka(t,[Ma],{cwd:Ae,stdio:"inherit",env:d?{...n,[co]:lo(d)}:n}),stall:r?{readHeartbeat:()=>io(s),staleMs:r}:null});for(let d of["SIGINT","SIGTERM"])process.on(d,()=>a.forward(d));return process.on(Ja,()=>a.restart()),process.on("exit",()=>{try{K.readFileSync(Kt,"utf8").trim()===String(process.pid)&&K.rmSync(Kt,{force:!0})}catch{}}),a.start()}function nc({agentDir:e=Ae,nodeBin:t=process.execPath,envFile:n=Be(),home:r=Ge.homedir()}={}){let s=C.dirname(t),a=C.join(C.basename(Gn),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
|
|
232
232
|
# ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
|
|
233
233
|
[Unit]
|
|
234
234
|
Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
|
|
@@ -270,7 +270,7 @@ WantedBy=default.target
|
|
|
270
270
|
<key>StandardErrorPath</key><string>${s}/node.err.log</string>
|
|
271
271
|
</dict>
|
|
272
272
|
</plist>
|
|
273
|
-
`}function oc(e=process.platform,t=Ge.homedir()){return e==="darwin"?{kind:"launchd",file:C.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:C.join(t,".config","systemd","user","bostrat-node.service")}}async function sc({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:s=Ae}={}){let{kind:a,file:d}=oc(n);if(!e&&s.split(C.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(C.dirname(d),{recursive:!0}),a==="systemd"?(K.writeFileSync(d,nc()),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(C.join(Ge.homedir(),"Library","Logs","bostrat"),{recursive:!0}),K.writeFileSync(d,rc()),t&&await me("launchctl",["load","-w",d]),r(`installed ${d}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function
|
|
273
|
+
`}function oc(e=process.platform,t=Ge.homedir()){return e==="darwin"?{kind:"launchd",file:C.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:C.join(t,".config","systemd","user","bostrat-node.service")}}async function sc({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:s=Ae}={}){let{kind:a,file:d}=oc(n);if(!e&&s.split(C.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(C.dirname(d),{recursive:!0}),a==="systemd"?(K.writeFileSync(d,nc()),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(C.join(Ge.homedir(),"Library","Logs","bostrat"),{recursive:!0}),K.writeFileSync(d,rc()),t&&await me("launchctl",["load","-w",d]),r(`installed ${d}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function lp(e=process.argv.slice(2)){let t=e[0],n=Be();if(t==="--version"||t==="-v"||t==="version")return console.log(Ke),0;if(t==="init")return(await Xa({envFile:n})).ok?0:1;if(t==="doctor"){let r={...vt(n),...process.env};return Zo(await Jo(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return tc({envFile:n}),null;if(t==="install-service")return await sc({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(yo(),wo));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:s,updatePolicy:a}=await Promise.resolve().then(()=>(Yo(),Vo)),{detectInstallKind:d}=await Promise.resolve().then(()=>(Cn(),Fo)),f=d(),m=e.indexOf("--to"),S=m>=0?String(e[m+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Ke,installKind:f,policy:a({kind:f}),status:await s()},null,2)),0;if(!S)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 p=await r({to:S,kind:f,reason:"cli",force:!0});return p.ok?(console.log(`\u2713 self-update ${p.from??"?"} \u2192 ${p.to} started (${p.kind}) \u2014 status: ${p.statusFile}; the node restarts when the install completes`),0):(console.error(`\u2717 not started: ${p.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
|
|
274
274
|
|
|
275
275
|
usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
|
|
276
276
|
|
|
@@ -279,4 +279,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
|
|
|
279
279
|
run start the node in the foreground (sources node.env)
|
|
280
280
|
install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
|
|
281
281
|
fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
|
|
282
|
-
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{Ja as RESTART_SIGNAL,Za as ROLLBACK_GRACE_MS,Qa as STALL_CHECK_MS,Kt as SUPERVISOR_PID_FILE,ec as createRunSupervisor,Xa as init,sc as installService,rc as launchdPlist,
|
|
282
|
+
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{Ja as RESTART_SIGNAL,Za as ROLLBACK_GRACE_MS,Qa as STALL_CHECK_MS,Kt as SUPERVISOR_PID_FILE,ec as createRunSupervisor,Xa as init,sc as installService,rc as launchdPlist,lp as main,Zo as printDoctor,tc as runAgent,Jo as runDoctor,oc as servicePaths,nc as systemdUnit};
|