bostrat-node 1.15.1 → 1.15.2
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/bin/bostrat-blueprint +1 -1
- package/dist/cli.js +77 -75
- package/dist/index.js +281 -267
- package/node-entrypoint.sh +3 -24
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)){let
|
|
3
|
-
`).map(
|
|
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 xt(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 pr(e,t=process.env){let n=xt(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
|
+
`).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}),
|
|
6
|
-
`))if(d.trim())try{a.push(JSON.parse(
|
|
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,vt=R(()=>{ae="BOSTRAT_HOOK_TOKEN",rt="x-bostrat-hook"});var wr=R(()=>{vt()});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(()=>{fn();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 pn(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 xs}from"node:util";var Cc,Sr,vs,Dc,Lc,_r=R(()=>{Cc=xs(bs),Sr=process.env.HOME||"/home/globo",vs=mn.join(process.env.BOSTRAT_STATE_DIR||mn.join(Sr,".bostrat"),"repos"),Dc=[...(process.env.BOSTRAT_REPOS_ROOT||mn.join(Sr,"Documents")).split(","),vs].map(e=>e.trim()).filter(Boolean),Lc=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function kt(e=Date.now()){if(xe)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 xe?1/0:be>e?be-e:0}function Et(e=Date.now()){return it(e)>0}function wn(e={}){xe={at:Date.now(),...e},be=1/0}function yn(){return xe}function xr(e=Date.now()){return{held:Et(e),holdMs:xe?null:it(e),holds:$t,removed:xe?{...xe}:null}}var As,At,ot,st,$t,be,xe,gn=R(()=>{As={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},At={...As},ot=0,st=0,$t=0,be=0,xe=null});import vr 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||vr.join(process.env.HOME||$s.tmpdir(),".bostrat"),qc=vr.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 vl,Or=R(()=>{Tn();Nt();vl=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(()=>{vt();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")
|
|
@@ -18,36 +18,37 @@ esac
|
|
|
18
18
|
if [ -x "$orig/$hook" ] && [ "$orig/$hook" != "$0" ]; then
|
|
19
19
|
"$orig/$hook" "$@" || exit $?
|
|
20
20
|
fi
|
|
21
|
-
`,
|
|
21
|
+
`,Dl=`${Sn}
|
|
22
22
|
# \u2500\u2500 bostrat: append provenance trailers (Layer 0). Skipped for merge commits
|
|
23
23
|
# (nobody "wrote" a merge) and outside a box (no token / no node url).
|
|
24
24
|
[ -z "$${ae}" ] && exit 0
|
|
25
|
-
[ -z "$${
|
|
25
|
+
[ -z "$${Ce}" ] && exit 0
|
|
26
26
|
[ "$2" = "merge" ] && exit 0
|
|
27
|
-
trailers=$(curl -sS -m 3 -H "${
|
|
27
|
+
trailers=$(curl -sS -m 3 -H "${rt}: $${ae}" "$${Ce}/api/git/trailers" 2>/dev/null) || exit 0
|
|
28
28
|
[ -z "$trailers" ] && exit 0
|
|
29
29
|
printf '%s\\n' "$trailers" | while IFS= read -r line; do
|
|
30
30
|
[ -n "$line" ] && git interpret-trailers --in-place --if-exists addIfDifferent --trailer "$line" "$1" >/dev/null 2>&1 || true
|
|
31
31
|
done
|
|
32
32
|
exit 0
|
|
33
|
-
`,
|
|
33
|
+
`,Ll=`${Sn}
|
|
34
34
|
# \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
|
|
35
35
|
[ -z "$${ae}" ] && exit 0
|
|
36
|
-
[ -z "$${
|
|
36
|
+
[ -z "$${Ce}" ] && exit 0
|
|
37
37
|
sha=$(git rev-parse HEAD 2>/dev/null) || exit 0
|
|
38
38
|
cwd=$(git rev-parse --show-toplevel 2>/dev/null)
|
|
39
|
-
printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${
|
|
40
|
-
-H 'content-type: application/json' -H "${
|
|
39
|
+
printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${Ce}/api/git/committed" \\
|
|
40
|
+
-H 'content-type: application/json' -H "${rt}: $${ae}" --data-binary @- >/dev/null 2>&1 || true
|
|
41
41
|
exit 0
|
|
42
|
-
`,
|
|
42
|
+
`,Fl=`${Sn}
|
|
43
43
|
# \u2500\u2500 bostrat: the tree moved \u2014 let the node re-read this workspace's lockfiles.
|
|
44
44
|
[ -z "$${ae}" ] && exit 0
|
|
45
|
-
[ -z "$${
|
|
45
|
+
[ -z "$${Ce}" ] && exit 0
|
|
46
46
|
[ "$hook" = "post-checkout" ] && [ "$3" != "1" ] && exit 0
|
|
47
|
-
curl -sS -m 3 -X POST "$${
|
|
48
|
-
-H 'content-type: application/json' -H "${
|
|
47
|
+
curl -sS -m 3 -X POST "$${Ce}/api/deps/refresh" \\
|
|
48
|
+
-H 'content-type: application/json' -H "${rt}: $${ae}" --data-binary '{}' >/dev/null 2>&1 || true
|
|
49
49
|
exit 0
|
|
50
|
-
`});import
|
|
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(f){throw new Error(`no cgroup v2 tree at ${s} (${f?.code||f?.message||f})`)}let p=["cpu","memory"].filter(f=>d.includes(f));if(!p.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=`+${p.join(" +")}`;for(let f of[De.join(s,"cgroup.subtree_control"),De.join(a,"cgroup.subtree_control")])try{await lt.writeFile(f,m)}catch(w){throw new Error(`cannot enable ${m} in ${f} (${w?.code||w?.message||w})`)}let S=Dr(t);p.includes("cpu")&&await lt.writeFile(De.join(a,"cpu.weight"),String(Ir)),p.includes("memory")&&await lt.writeFile(De.join(a,"memory.max"),String(S)),Le={available:!0,backend:"cgroupfs",path:a,controllers:p,cpuWeight:p.includes("cpu")?Ir:null,memoryMaxMb:p.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 xn(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,xu,vu,Au,$u,ku,Kr,bn,Ur,ui,It,Eu,Ou,Ru,Nu,Mu,Iu,fn=R(()=>{wr();yr();hn();Tr();kr();Rr();dn();vt();Mr();_n();ci=ii(si),bu=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";jr=typeof process.getuid=="function"?process.getuid():0,xu=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}),vu=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:()=>po,flyToml:()=>fo,flyWizard:()=>Bi,parseFlyFlags:()=>ho,stageConfig:()=>mo});import $n from"node:fs";import ve 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 fo({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\`.
|
|
51
52
|
# Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
|
|
52
53
|
# No [http_service] and none should be added: the node dials OUT to the plane;
|
|
53
54
|
# nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
|
|
@@ -62,7 +63,7 @@ swap_size_mb = 1024
|
|
|
62
63
|
# The published node image (claude + cursor-agent + codex baked in, logged
|
|
63
64
|
# out), pinned to the bostrat-node version that wrote this file. Update with:
|
|
64
65
|
# npm i -g bostrat-node && bostrat-node fly (re-run is safe), or bump the tag.
|
|
65
|
-
image = "${
|
|
66
|
+
image = "${s}"
|
|
66
67
|
|
|
67
68
|
[env]
|
|
68
69
|
PORT = "3362"
|
|
@@ -87,29 +88,29 @@ swap_size_mb = 1024
|
|
|
87
88
|
# Scale later with: fly scale memory 4096 -a ${e}
|
|
88
89
|
size = "shared-cpu-2x"
|
|
89
90
|
memory = "2gb"
|
|
90
|
-
`}function
|
|
91
|
+
`}function po({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(`
|
|
91
92
|
`)+`
|
|
92
|
-
`},{argv:["deploy",a,"-c",
|
|
93
|
-
`),d[0];if(d.length>1)return await e(`Fly org (${d.join(" / ")})`,d[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function
|
|
93
|
+
`},{argv:["deploy",a,"-c",ve.join(a,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${a} -c ${ve.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||ve.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(ve.join(r,s),{recursive:!0,force:!0});return $n.writeFileSync(ve.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(p=>p.Slug||p.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}),p=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.
|
|
94
95
|
bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
|
|
95
96
|
|
|
96
|
-
`);try{await
|
|
97
|
-
`)}catch{return n.write("\u2717 not signed in to Fly. Run `fly auth login` (or `fly auth signup`) and re-run `bostrat-node fly`.\n"),m(1)}let
|
|
98
|
-
`),m(1);let
|
|
99
|
-
wrote ${
|
|
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:p,output:n,exec:r,flag:a.org}),f=a.app||await p("App name",`bostrat-node-${Mi().slice(0,4)}`),w=a.region||await p("Region (see `fly platform regions`)","iad"),E=a.sizeGb||Number(await p("Volume size GB (logins + repos live here)","10"))||10,b=a.name||f,v=a.planeUrl||uo,N=a.token||await p("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:f,dest:s,toml:fo({app:f,region:w,nodeName:b,planeUrl:v,image:O})});n.write(`
|
|
100
|
+
wrote ${ve.join(P,"fly.toml")} \u2014 deploys the prebuilt node image ${O}
|
|
100
101
|
(claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
|
|
101
102
|
|
|
102
103
|
Plan (your flyctl, your org, your bill):
|
|
103
|
-
`);let
|
|
104
|
-
`);if(!a.yes&&(await
|
|
104
|
+
`);let x=po({app:f,org:S,region:w,sizeGb:E,token:N,dir:P});for(let g of x)n.write(` $ ${g.display}
|
|
105
|
+
`);if(!a.yes&&(await p(`
|
|
105
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.
|
|
106
|
-
`),m(1);for(let
|
|
107
|
-
\u2192 ${
|
|
108
|
-
`);try{let{stdout:
|
|
109
|
-
`).map(
|
|
107
|
+
`),m(1);for(let g of x){n.write(`
|
|
108
|
+
\u2192 ${g.display}
|
|
109
|
+
`);try{let{stdout:A,stderr:$}=await Bt(g.argv,{stdin:g.stdin,exec:r}),k=`${A||""}${$||""}`.trim();k&&n.write(k.split(`
|
|
110
|
+
`).map(I=>` ${I}`).join(`
|
|
110
111
|
`)+`
|
|
111
|
-
`)}catch(
|
|
112
|
-
`);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(`
|
|
113
114
|
`).slice(-4).join(`
|
|
114
115
|
`)}
|
|
115
116
|
fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
|
|
@@ -117,57 +118,57 @@ Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u201
|
|
|
117
118
|
\u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
|
|
118
119
|
chat: the node step advances on its own within a minute.
|
|
119
120
|
logs: fly logs -a ${f}
|
|
120
|
-
redeploy: fly deploy ${P} -c ${
|
|
121
|
+
redeploy: fly deploy ${P} -c ${ve.join(P,"fly.toml")} -a ${f} --ha=false
|
|
121
122
|
Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
|
|
122
123
|
boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
|
|
123
|
-
`),m(0)}var Xr,ai,_n,Rt,no=A(()=>{Xr="wss://plane.bostrat.ai/v1/node",ai=si(import.meta.url)("../package.json").version,_n=`ghcr.io/globocodes/bostrat-node:${ai}`;Rt=(e,{stdin:t,exec:n}={})=>new Promise((r,i)=>{if(n)return n(e,{stdin:t}).then(r,i);let a=oi("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,h,m)=>d?i(Object.assign(d,{stdout:h,stderr:m})):r({stdout:h,stderr:m}));t!=null&&a.stdin?.end(t)})});function ro(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!di.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let r=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(r))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return r}function fi(e){let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||r.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=r.map(i=>({...i,fromMs:ro(i.from,"from",n),toMs:ro(i.to,"to",n)}))}return t}var ui,di,Eu,Ou,oo=A(()=>{ui={"claude-opus-5-5":[{from:null,to:null,input:4,output:20,cacheWrite:8,cacheRead:.2,cacheReadX:.05,fast:{input:8,output:40,cacheWrite:16,cacheRead:.4},verifiedAt:"2026-09-28",note:"verified 2026-09-28 against platform.claude.com/docs/en/about-claude/pricing: $4/$20, 1h cache write $8 (2\xD7), cache hits $0.20 (0.05\xD7 \u2014 footnote 2), fast $8/$40; added before any fleet turn was recorded."}],"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"GA rates; verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-08-17",note:"$2/$10 is the standard price (intro pricing made permanent; the 2026-09-01 $3/$15 increase was cancelled) \u2014 verified 2026-08-17 against platform.claude.com/docs/en/about-claude/pricing."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-fable-5-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-09-07",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-03, re-verified 2026-08-17 (developers.openai.com pricing); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-08-24",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-terra":[{from:null,to:"2026-08-16",input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:2,output:12,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:"2026-08-16",input:1,output:6,cacheWrite:1.25,cacheRead:.1,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:.2,output:1.2,cacheWrite:.25,cacheRead:.02,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-09-07",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed)."}]},di=/^\d{4}-\d{2}-\d{2}$/;Eu=fi(ui),Ou=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var so=A(()=>{oo()});import io from"node:fs/promises";import lo from"node:path";import pi from"node:os";function fo(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function po(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function ho(e){let t=new Date(fo(e));return t.setDate(t.getDate()+7),t.getTime()}function mo(e){let t=new Date(po(e));return t.setMonth(t.getMonth()+1),t.getTime()}function gi(e=Date.now()){for(let[t,n]of Object.entries(wi)){let r=n.startOf(e);if(r!==Nt[t]){Nt[t]=r;for(let i of bn.values())i[t]=0;for(let i of ao)i.includes(`:${t}:`)&&!i.endsWith(`:${r}`)&&ao.delete(i)}}}function Ti(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let i={};for(let a of["weeklyUsd","monthlyUsd"]){let d=r?.[a];if(d==null||d==="")continue;let h=Number(d);if(!Number.isFinite(h)||h<=0)throw new Error(`${n}.${a} must be a positive number or null`);i[a]=h}Object.keys(i).length&&(t[n]=i)}return t}async function wo(e,{source:t="local",updatedAt:n=Date.now()}={}){je={caps:Ti(e),updatedAt:n,source:t};try{await io.mkdir(uo,{recursive:!0}),await io.writeFile(hi(),JSON.stringify(je,null,2))}catch{}return Si()}function Si(e=Date.now()){gi(e);let t=new Set([...bn.keys(),...Object.keys(je?.caps||{})]),n={};for(let r of t){let i=bn.get(r);n[r]={weeklyUsd:co(i?.weekly||0),monthlyUsd:co(i?.monthly||0)}}return{caps:je?.caps||{},configured:!!je,seeded:yi,updatedAt:je?.updatedAt??null,spent:n,windows:{weekly:{start:Nt.weekly,resetsAt:ho(e)},monthly:{start:Nt.monthly,resetsAt:mo(e)}},warnPct:mi}}var uo,hi,mi,wi,je,yi,Nt,bn,ao,co,yo=A(()=>{$t();so();uo=process.env.BOSTRAT_STATE_DIR||lo.join(process.env.HOME||pi.tmpdir(),".bostrat"),hi=()=>lo.join(uo,"usage-caps.json"),mi=.8;wi={weekly:{startOf:fo,nextStart:ho,capKey:"weeklyUsd"},monthly:{startOf:po,nextStart:mo,capKey:"monthlyUsd"}},je=null,yi=!1,Nt={weekly:0,monthly:0},bn=new Map,ao=new Set;co=e=>Math.round(e*1e4)/1e4});var Ao={};nn(Ao,{REMOVED_MARKER:()=>En,detectInstallKind:()=>He,detectProviderAuth:()=>xo,maskToken:()=>$n,readRemovedMarker:()=>vo,startPlaneLink:()=>Li,updateCommandFor:()=>dt,versionLt:()=>Ue});import Fe from"node:fs";import ut from"node:fs/promises";import _i from"node:http";import W from"node:path";import Mt from"node:os";import{createRequire as bi}from"node:module";import vn from"ws";function $n(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function vo(e=En){try{let t=JSON.parse(Fe.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function He({env:e=process.env,pkgDir:t=W.resolve(W.dirname(new URL(import.meta.url).pathname),".."),exists:n=Fe.existsSync}={}){let r=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(r)?r:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(W.join(t,"..",".git"))?"git-checkout":"dev"}function Ue(e,t){let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let i=0;i<Math.max(n.length,r.length);i++){let a=(n[i]||0)-(r[i]||0);if(a)return a<0}return!1}function dt(e){switch(e){case"npm-global":return"npm install -g bostrat-node && restart the bostrat-node service";case"git-checkout":return"scripts/deploy-pi.sh (or The Bakery \u2192 Deploy to Pi \u2192 bostrat)";case"container":return"Links \u2192 Fly \u2192 Update (or the plane's auto-update while the node sleeps)";default:return"update this node's bostrat-node checkout/install"}}function xo({home:e=process.env.HOME||Mt.homedir(),env:t=process.env}={}){let n=r=>{try{return Fe.statSync(r),!0}catch{return!1}};return{claude:n(W.join(e,".claude",".credentials.json")),codex:n(W.join(t.CODEX_HOME||W.join(e,".codex"),"auth.json")),cursor:n(W.join(t.XDG_CONFIG_HOME||W.join(e,".config"),"cursor","auth.json"))}}function Li({url:e,token:t,nodeId:n=Mt.hostname(),name:r=Mt.hostname(),listTracks:i,detectAgents:a=null,onTracksTransferred:d=null,onTracksMoves:h=null,sampleMetrics:m=null,deliverySample:g=null,onHashKey:f=null,onViewBase:S=null,metricsMs:$=Bi,onUpdateAvailable:b=null,onUpdatePolicy:v=null,onConflictProbe:R=null,restart:E=null,onRestarted:P=null,onHelloRefused:k=null,updatePolicy:_=null,installKind:x=He(),selfUrl:N=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:L=null,removedMarkerFile:C=En,onRemoved:ke=null,onDegraded:Ge=null,onRecovered:$e=null,onRefused:Ft=null,onConnected:pt=null,ingestMode:Ee=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:ze=Ri,unackedRetryMs:Oe=Oi,pingMs:Ve=$i,deadLinkMs:O=Math.round(Ve*Ei),maxInflightEvents:ce=Pi,httpTimeoutMs:le=Ci,fanoutActive:ue=null,fanoutBatchCap:Ye=Di,stallBackoffMinMs:Fn=Mi,fetchImpl:Un=globalThis.fetch,log:y=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof i!="function")throw new Error("plane-link: listTracks is required");e=tt(e);let jo=N.replace(/^http/,"ws"),Hn=new Set,Wn=s=>{let l=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(!(!(l&&Q&&Ue(Q,l))||Hn.has(l))){Hn.add(l),y.log(`[plane-link] bostrat-node ${l} is available (this node runs ${Q}) \u2014 ${dt(x)}`);try{b?.({current:Q,latest:l,min:s.minNodeVersion??null,installKind:x,required:!!(s.minNodeVersion&&Ue(Q,s.minNodeVersion))})}catch(u){y.error(`[plane-link] update notice failed: ${u?.message||u}`)}}},we=new Map,ye=new Map,Ut=W.join(kn,"plane-link","cursor.json"),Ht=W.join(kn,"plane-link","dead-letter.ndjson"),Kn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),ne={},ee={},I=new Map,ht=null,de=null,re=0,qe=0,Gn=0,mt={},zn=new Set,Vn=Promise.resolve(),H="ws",Re=0,Z=!1,ge=0,Wt=!1,fe=It,Ne=new Set,oe=[],z=null,Y=null,q=!1,Kt=!1,Xe=go,Je=null,Gt=E&&typeof E=="object"?E:null,Ie=null,Me=null,se=null,Te=0,Yn=0,ie=null,zt=!1,wt=0,Ze=!1,pe=vo(C);if(pe)if(pe.tokenPreview===$n(t))Ze=!0,dn({reason:pe.reason??"removed",at:pe.at??null,nodeId:pe.nodeId??n}),y.error(`[plane-link] this node was REMOVED from the plane (${pe.reason??"removed"}${pe.at?` at ${new Date(pe.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${C} to force a dial.`);else try{Fe.unlinkSync(C),y.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function Vt({reason:s="removed",at:l=Date.now(),via:u="ctl"}={}){if(!Ze){Ze=!0,dn({reason:s,at:l,nodeId:n,via:u});try{Fe.mkdirSync(W.dirname(C),{recursive:!0}),Fe.writeFileSync(C,JSON.stringify({at:l,reason:s,via:u,nodeId:n,tokenPreview:$n(t)},null,2))}catch(o){y.error(`[plane-link] could not write ${C}: ${o?.message||o}`)}y.error(`[plane-link] the plane REMOVED this node (${s}, via ${u}) \u2014 going dormant: no more dials, ingest or broker calls. Re-provision with a new node token to reconnect; the box and its data are untouched.`);try{ke?.({reason:s,at:l,via:u})}catch{}sr({bye:!1})}}async function Fo(){try{ne=JSON.parse(await ut.readFile(Ut,"utf8"))}catch{ne={}}}function qn(){zt=!0,!Me&&(Me=setTimeout(async()=>{if(Me=null,!!zt){zt=!1;try{await ut.mkdir(W.dirname(Ut),{recursive:!0}),await ut.writeFile(Ut,JSON.stringify(ne))}catch(s){y.error("[plane-link] cursor flush failed:",s?.message||s)}}},ki),Me.unref?.())}function Yt(){try{return!!ue?.()}catch{return!1}}function qt(){let s=H==="http"?fe:It;return Yt()?Math.min(s,Ye):s}function j(s){return!Y||Y.readyState!==vn.OPEN?!1:(Y.send(JSON.stringify(s)),!0)}function Pe(s){let l=Date.now();for(let{trackId:o,event:c}of s){let p=I.get(c.id);I.set(c.id,{trackId:o,seq:c.seq,event:c,sentAt:l,firstSentAt:p?.firstSentAt??l,retryAt:l+Oe,tries:(p?.tries??0)+1,nacks:p?.nacks??0})}let u=s.map(({trackId:o,event:c})=>({trackId:o,event:Ii(c)}));return H==="http"?(zo(u),!0):j({v:F,ch:"events",type:"append",events:u})}function Uo(s){let l=null;for(let u of I.values())u.trackId===s&&(l==null||u.seq<l)&&(l=u.seq);return l}function Xt(s){let l=ee[s];if(l==null)return;let u=Uo(s),o=u==null?l:Math.min(l,u-1);o>(ne[s]??0)&&(ne[s]=o,qn())}function Qe(){if(ht=Date.now(),de!=null){let s=Date.now()-de;y.log(`[plane-link] spine sync recovered after ${Math.round(s/1e3)}s degraded (${re} stall redial(s))`);let l=de;de=null,re=0,qe=0,Z=!1,ge=0;try{$e?.({since:l,downMs:s})}catch(u){y.error(`[plane-link] onRecovered failed: ${u?.message||u}`)}}}function Jt(s){if(!Array.isArray(s)||!s.length)return;let l=new Set;for(let u of s){let o=I.get(u);o&&(I.delete(u),(ee[o.trackId]??0)<o.seq&&(ee[o.trackId]=o.seq),l.add(o.trackId))}for(let u of l)Xt(u);Qe()}function Xn(s,l){Gn++;let u={at:Date.now(),trackId:s.trackId,seq:s.seq,id:s.event?.id??null,type:s.event?.type??null,reason:l,event:s.event??null};y.error(`[plane-link] DEAD-LETTER ${s.trackId} seq ${s.seq} (${u.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${Ht}`),Vn=Vn.then(async()=>{await ut.mkdir(W.dirname(Ht),{recursive:!0}),await ut.appendFile(Ht,JSON.stringify(u)+`
|
|
124
|
-
`)}).catch(o=>y.error(`[plane-link] dead-letter write failed: ${o?.message||o}`))}function Ho(s,l){if(mt[s]=(mt[s]??0)+1,zn.has(s))return;zn.add(s);let u=Ni[s]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";y.error(`[plane-link] REFUSED by the plane (${s}) on track ${l}: events are being dropped, not stored \u2014 ${u}`);try{Ft?.({reason:s,trackId:l,count:mt[s],hint:u})}catch(o){y.error(`[plane-link] onRefused failed: ${o?.message||o}`)}}function Zt(s,l,u,o=null){if(!Array.isArray(s)||!s.length)return;let c=new Set,p=Date.now();for(let w of s){let T=I.get(w);T&&(u?(I.delete(w),Xn(T,l),String(l).startsWith(xn)&&Ho(String(l).slice(xn.length),T.trackId),(ee[T.trackId]??0)<T.seq&&(ee[T.trackId]=T.seq),c.add(T.trackId)):(T.nacks++,T.retryAt=p+Math.max(1e3,Number(o)||Oe)))}for(let w of c)Xt(w);Qe()}function Jn(s=Date.now()){let l=1/0;for(let u of I.values())u.firstSentAt<l&&(l=u.firstSentAt);return l===1/0?0:s-l}function Wo(s){if(!O||!s||s!==Y||!Te)return!1;let l=Date.now()-Te;if(l<=O)return!1;Yn++,y.error(`[plane-link] no frame from the plane for ${Math.round(l/1e3)}s \u2014 link is half-open; terminating and redialing`);try{s.terminate()}catch{}return!0}function Zn(){if(!q||!I.size)return;let s=Date.now(),l=Jn(s);if(l<ze||ht!=null&&s-ht<ze||H==="http"&&Z||qe>s)return;re++;let u=Math.min(Fn*2**(re-1),So);if(de==null){de=s-l,y.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${I.size} event(s) in flight (${H} door) \u2014 the plane is not answering appends`);try{Ge?.({since:de,unacked:I.size,oldestAgeMs:l,mode:H})}catch(o){y.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(H==="http"){Z=!0,ge=s+u,y.error(`[plane-link] ingest circuit OPEN (stall #${re}); probing /v1/ingest/health in ${Math.round(u/1e3)}s`);return}qe=s+u,y.error(`[plane-link] closing the link and redialing in ${Math.round(u/1e3)}s (stall redial #${re})`);try{Y?.terminate()}catch{}}function Qt(){if(!q)return;let s=Date.now();if(H==="http"&&Z)return;let l=[...I.values()].filter(o=>o.event&&o.retryAt<=s&&!(H==="http"&&Ne.has(o.trackId)));if(!l.length)return;l.sort((o,c)=>o.trackId===c.trackId?o.seq-c.seq:o.trackId<c.trackId?-1:1),y.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let u=qt();if(H==="http"){let o=new Map;for(let c of l)(o.get(c.trackId)??o.set(c.trackId,[]).get(c.trackId)).push(c);for(let[,c]of o){if(Re>=An)return;Pe(c.slice(0,u).map(p=>({trackId:p.trackId,event:p.event})))}return}for(let o=0;o<l.length;o+=u){let c=l.slice(o,o+u).map(p=>({trackId:p.trackId,event:p.event}));if(!Pe(c))return}}async function Ko(s=null){for(;;){if(!q)return!1;let l=I.size<ce,u=H!=="http"||Re<An&&!Z&&(!s||!Ne.has(s));if(l&&u)return!0;await new Promise(o=>setTimeout(o,100))}}function en(){if(z=null,!q||!oe.length)return;let s=oe;oe=[];let l=qt();if(H!=="http"){for(let c=0;c<s.length;c+=l)Pe(s.slice(c,c+l));return}let u=Yt(),o=new Map;for(let c of s)(o.get(c.trackId)??o.set(c.trackId,[]).get(c.trackId)).push(c);for(let[c,p]of o){if(Ne.has(c)||Re>=An||Z){oe.push(...p);continue}if(u){Pe(p.slice(0,l)),oe.push(...p.slice(l));continue}for(let w=0;w<p.length;w+=l)Pe(p.slice(w,w+l))}oe.length&&!z&&(z=setTimeout(en,_o),z.unref?.())}let Go=s=>{let l=new Map;for(let{trackId:u,event:o}of s)(l.get(u)??l.set(u,[]).get(u)).push(o);return[...l].map(([u,o])=>({trackId:u,events:o}))},Se=(s,l,u,{progress:o})=>{let c=Date.now();for(let{event:p}of s){let w=I.get(p.id);w&&(w.nacks++,w.retryAt=c+Math.max(1e3,u||Oe))}o&&Qe()};async function zo(s){let l=new Set(s.map(u=>u.trackId));for(let u of l)Ne.add(u);Re++;try{let u=await Un(`${Kn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:Go(s)}),signal:AbortSignal.timeout(le)}),o=(Number(u.headers.get("retry-after"))||0)*1e3;if(u.status===200){let c=await u.json();fe=It;for(let T of c.results??[]){Jt(T.acked??[]);let D=(te,G)=>{let yt=new Map;for(let _e of te??[])(yt.get(_e.reason)??yt.set(_e.reason,[]).get(_e.reason)).push(_e.id);for(let[_e,ir]of yt)Zt(ir,_e,G,c.retryAfterMs??null)};D(T.rejected,!0),D(T.deferred,!1)}let p=new Set,w=new Map;for(let T of Array.isArray(c.refused)?c.refused:[])!T||typeof T.id!="string"||(p.add(T.id),(w.get(T.reason)??w.set(T.reason,[]).get(T.reason)).push(T.id));for(let[T,D]of w)Zt(D,`${xn}${T}`,!0);Jt((c.discarded??[]).filter(T=>!p.has(T))),Qe();return}if(u.status===429){Se(s,"overloaded",o||5e3,{progress:!0});return}if(u.status===413&&s.length>1){fe=Math.max(1,Math.floor(s.length/2)),y.error(`[plane-link] ingest request too large (${s.length} events) \u2014 halving batches to ${fe}`),Se(s,"too_large",1e3,{progress:!0});return}if(u.status===413){let c=I.get(s[0].event.id);c&&(I.delete(c.event.id),Xn(c,"too_large"),(ee[c.trackId]??0)<c.seq&&(ee[c.trackId]=c.seq),Xt(c.trackId)),Qe();return}if(u.status===410){Vt({reason:"removed",via:"410"}),Se(s,"http_410",6e4,{progress:!1});return}if(u.status===401||u.status===403){let{tripped:c,holdMs:p}=xt();if(c&&y.error(`[plane-link] holding every plane call for ${Math.round(p/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-wt>=bo){wt=Date.now();let w="";try{w=(await u.json())?.error??""}catch{}y.error(`[plane-link] plane refused ingest (HTTP ${u.status}${w?`: ${w}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}Se(s,`http_${u.status}`,Math.max(6e4,st()),{progress:!1});return}if(u.status===400){y.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${s.length} event(s) for retry; this is a bug, not data`),Se(s,"http_400",6e4,{progress:!1});return}Se(s,`http_${u.status}`,o||5e3,{progress:!1})}catch(u){let o=u?.name==="TimeoutError"||u?.name==="AbortError";o&&s.length>1&&(fe=Math.max(1,Math.floor(s.length/2)),y.error(`[plane-link] ingest request of ${s.length} event(s) outlived its ${le} ms deadline \u2014 halving batches to ${fe}`)),Se(s,o?"timeout":"network",5e3,{progress:!1})}finally{Re--;for(let u of l)Ne.delete(u)}}async function Vo(){if(H!=="http"||!Z||!q||Wt)return;let s=Date.now();if(!(ge>s||At(s))){Wt=!0;try{let l=await Un(`${Kn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(le)});if(!l.ok)throw new Error(`HTTP ${l.status}`);y.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Z=!1,ge=0,qe=Date.now()+le+Oe+1e3;for(let u of I.values())u.retryAt=Math.min(u.retryAt,Date.now());Qt()}catch(l){re++;let u=Math.min(Fn*2**(re-1),So);ge=Date.now()+u,y.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(u/1e3)}s`)}finally{Wt=!1}}}function Qn(){let s=Date.now();return{mode:H,unacked:I.size,oldestUnackedAgeMs:Jn(s),lastProgressAt:ht,degradedSince:de,stallRedials:re,deadLettered:Gn,fanoutCap:Yt()?Ye:null,http:H==="http"?{inFlight:Re,circuitOpen:Z,nextProbeInMs:Z?Math.max(0,ge-s):0,batchCap:fe}:null}}async function er(){if(!m)return;let s;try{s=await m()}catch(u){y.error("[plane-link] metrics sample failed:",u?.message||u);return}let l=null;try{l=g?.()??null}catch{}s&&j({v:F,ch:"ctl",type:"metrics",metrics:{...s,planeLink:Qn(),...l?{delivery:l}:{}}})}function Yo(){m&&(ie&&clearInterval(ie),er(),ie=setInterval(er,$),ie.unref?.())}async function qo(){let s;try{s=await i()}catch(l){y.error("[plane-link] backfill listTracks failed:",l?.message||l);return}j({v:F,ch:"ctl",type:"tracks",ids:s.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of s)if(!q||!await tr(l))return}async function tr(s){let l;try{l=await kt(s)}catch{return!0}let u=ne[s.id]??0,o=l.filter(c=>c.seq>u&&typeof c.id=="string");for(let c=0;c<o.length;){if(!await Ko(s.id))return!1;let p=o.slice(c,c+qt()).map(w=>({trackId:s.id,event:w}));if(!Pe(p))return!1;c+=p.length}return!0}let tn=new Map;async function nr(s,l){if(tn.get(s)===l)return!1;tn.set(s,l);let u=null;try{u=(await i()).find(w=>w?.id===s)??null}catch{return!1}if(!u)return!1;let o;try{o=await kt(u)}catch{return!1}let c=[...o].reverse().find(w=>(w?.type==="track.transferred"||w?.type==="track.recovered")&&w.payload?.toNode===n);if(!c||!Number.isFinite(c.seq))return!1;let p=c.seq-1;return(ne[s]??0)>p&&(ne[s]=p,qn()),(ee[s]??0)>p&&(ee[s]=p),y.log(`[plane-link] re-sending ${s}'s move-commit (seq ${c.seq}, ${c.type}) \u2014 the plane's move record predates this node's adoption`),q?tr(u):!1}function rr(s){!q||!s?.trackId||typeof s.id!="string"||(oe.push({trackId:s.trackId,event:s}),z||(z=setTimeout(en,_o),z.unref?.()))}let et=new Map;async function Xo(s){let{reqId:l,method:u,path:o,headers:c={},body:p}=s,w=Object.fromEntries(Object.entries(c).filter(([,D])=>D!=null)),T=new AbortController;et.set(l,T);try{if(s.host){await Jo(s,w,T);return}L&&(w["x-bostrat-token"]=L);let D=await fetch(N+o,{method:u,headers:w,body:p?Buffer.from(p,"base64"):void 0,signal:T.signal}),te=Object.fromEntries(D.headers);for(let G of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete te[G];if(te["content-type"]||(te["content-type"]="application/octet-stream"),j({v:F,ch:"control",type:"http_head",reqId:l,status:D.status,headers:te}),D.body){for await(let G of D.body)if(!j({v:F,ch:"control",type:"http_data",reqId:l,data:Buffer.from(G).toString("base64")}))break}j({v:F,ch:"control",type:"http_end",reqId:l,error:null})}finally{et.delete(l)}}function Jo(s,l,u){let{reqId:o,method:c,path:p,body:w}=s,T=new URL(N);return new Promise(D=>{let te=_i.request({host:T.hostname,port:T.port,method:c,path:p,headers:{...l,host:s.host},signal:u.signal},G=>{let{connection:yt,"keep-alive":_e,"transfer-encoding":ir,upgrade:Ma,...Zo}=G.headers;j({v:F,ch:"control",type:"http_head",reqId:o,status:G.statusCode||502,headers:Zo}),G.on("data",Qo=>{j({v:F,ch:"control",type:"http_data",reqId:o,data:Buffer.from(Qo).toString("base64")})||G.destroy()}),G.on("end",()=>{j({v:F,ch:"control",type:"http_end",reqId:o,error:null}),D()}),G.on("error",()=>{j({v:F,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),D()})});te.on("error",G=>{j({v:F,ch:"control",type:"http_end",reqId:o,error:G?.message||"view request failed"}),D()}),w&&te.write(Buffer.from(w,"base64")),te.end()})}function or(){if(Kt||Ze)return;Y=new vn(e,{headers:{authorization:`Bearer ${t}`}});let s=Y;Te=0,s.on("ping",()=>{Te=Date.now()}),s.on("pong",()=>{Te=Date.now()}),Y.on("open",async()=>{let u=null;try{u=await a?.()||null}catch{u=null}j({v:F,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:Q,installKind:x,...typeof _=="function"?{updatePolicy:_()}:_?{updatePolicy:_}:{},providers:xo(),...u?{agents:u}:{},...Gt?{restart:Gt}:{}})}),Y.on("message",u=>{Te=Date.now();let o;try{o=JSON.parse(u)}catch{return}if(o.ch==="ctl"&&o.type==="hello_ok"){tn.clear(),q=!0,Xe=go,Je=null,Gt=null,wr(),y.log(`[plane-link] connected to plane as ${n}`);try{pt?.()}catch{}if(typeof o.hashKey=="string"&&o.hashKey)try{f?.(o.hashKey)}catch{}try{S?.(typeof o.viewBase=="string"&&o.viewBase?o.viewBase:null)}catch{}o.minNodeVersion&&Q&&Ue(Q,o.minNodeVersion)&&y.error(`[plane-link] this node is bostrat-node ${Q}; the plane asks for \u2265${o.minNodeVersion} \u2014 update with: ${dt(x)}`);try{v?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}Wn(o);let c=o.ingest==="http";H=Ee==="ws"?"ws":Ee==="http"||c?"http":"ws",Ee==="http"&&!c&&y.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),H==="http"&&y.log("[plane-link] spine rides the HTTPS ingest door"),Z=!1,ge=0,fe=It,se&&clearInterval(se),Te=Date.now(),se=setInterval(()=>{Wo(s)||(j({v:F,ch:"ctl",type:"ping"}),Zn(),Vo().catch(()=>{}),Qt(),oe.length&&!z&&en())},Ve),se.unref?.(),Yo(),qo().catch(p=>y.error("[plane-link] backfill failed:",p?.message||p));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let c=typeof o.minNodeVersion=="string"?o.minNodeVersion:null,p=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;y.error(`[plane-link] plane REFUSED this node: bostrat-node ${Q??"?"} is below its minimum ${c??"?"} \u2014 ${o.fix||dt(x)}`),Xe=To,Je=0;try{k?.({current:Q,min:c,latest:p,fix:o.fix||dt(x),installKind:x})}catch(w){y.error(`[plane-link] refusal handler failed: ${w?.message||w}`)}return}if(o.ch==="ctl"&&o.type==="removed"){j({v:F,ch:"ctl",type:"removed_ack",nodeId:n}),Vt({reason:typeof o.reason=="string"?o.reason:"removed",at:Number(o.at)||Date.now(),via:"ctl"});return}if(o.ch==="ctl"&&o.type==="update_available"){Wn(o);return}if(o.ch==="ctl"&&o.type==="update_policy"){try{v?.(typeof o.mode=="string"?o.mode:null)}catch{}return}if(o.ch==="ctl"&&o.type==="conflict_probe"&&Array.isArray(o.trackIds)){try{R?.(o.trackIds.filter(c=>typeof c=="string"&&c).slice(0,200))}catch{}return}if(o.ch==="ctl"&&o.type==="restarted"){Promise.resolve().then(()=>P?.({kind:o.kind,at:o.at,reason:o.reason})).catch(c=>y.error("[plane-link] restart notice failed:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="usage_caps"){wo(o.caps??{},{source:"plane",updatedAt:o.updatedAt??Date.now()}).then(c=>y.log(`[plane-link] spend caps ${Object.keys(c.caps).length?`updated (${Object.keys(c.caps).join(", ")})`:"cleared"} from plane`)).catch(c=>y.error("[plane-link] spend-caps push rejected:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="transferred"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>d?.(o.tracks)).then(async c=>{for(let p of Array.isArray(c)?c:[])p?.stale&&p.id&&await nr(p.id,p.since??null)}).catch(c=>y.error("[plane-link] transfer notice failed:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="moves"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>h?.(o.tracks)).then(async c=>{for(let p of Array.isArray(c)?c:[])p?.stale&&p.id&&await nr(p.id,p.since??null)}).catch(c=>y.error("[plane-link] move-record reconcile failed:",c?.message||c));return}if(o.ch==="events"&&o.type==="ack"&&Array.isArray(o.ids)){Jt(o.ids);return}if(o.ch==="events"&&o.type==="nack"&&Array.isArray(o.ids)){Zt(o.ids,o.reason,o.permanent===!0,o.retryAfterMs??null);return}if(o.ch==="control"&&o.type==="http_open"){Xo(o).catch(c=>j({v:F,ch:"control",type:"http_end",reqId:o.reqId,error:c?.message||"tunnel error"}));return}if(o.ch==="control"&&o.type==="http_cancel"){et.get(o.reqId)?.abort();return}if(o.ch==="attach"&&o.type==="open"){let c=new vn(jo+o.path,Array.isArray(o.protocols)?o.protocols:[],o.host?{headers:{host:o.host}}:void 0);we.set(o.streamId,c),ye.set(o.streamId,[]),c.on("open",()=>{let w=ye.get(o.streamId)||[];ye.delete(o.streamId);for(let{buf:T,bin:D}of w)c.send(T,{binary:D})}),c.on("message",(w,T)=>{let D=T?w:Buffer.from(String(w));j({v:F,ch:"attach",type:"data",streamId:o.streamId,data:D.toString("base64"),...T?{bin:!0}:{}})});let p=()=>{ye.delete(o.streamId),we.delete(o.streamId)&&j({v:F,ch:"attach",type:"close",streamId:o.streamId})};c.on("close",p),c.on("error",p);return}if(o.ch==="attach"&&o.type==="data"){let c=we.get(o.streamId);if(!c)return;let p=Buffer.from(o.data,"base64"),w=o.bin===!0,T=ye.get(o.streamId);T?T.push({buf:p,bin:w}):c.send(p,{binary:w});return}if(o.ch==="attach"&&o.type==="close"){let c=we.get(o.streamId);we.delete(o.streamId),ye.delete(o.streamId),c?.close();return}});let l=()=>{q&&y.log("[plane-link] disconnected from plane"),q=!1,se&&(clearInterval(se),se=null),ie&&(clearInterval(ie),ie=null),I.clear(),ee={},oe=[],z&&(clearTimeout(z),z=null),Ne.clear();for(let c of we.values())c.close();we.clear(),ye.clear();for(let c of et.values())c.abort();if(et.clear(),Kt||Ie)return;Je==null&&(Je=Date.now());let u=Date.now()-Je<vi,o=Math.max(u?xi+Math.random()*Ai:Xe,qe-Date.now(),st());Ie=setTimeout(()=>{Ie=null,or()},o),Ie.unref?.(),u||(Xe=Math.min(Xe*2,To))};Y.on("close",l),Y.on("error",u=>{let o=/Unexpected server response: (\d+)/.exec(u?.message||"")?.[1];if(o==="410"){Vt({reason:"removed",via:"410"});return}if(o==="401"||o==="403"){let{tripped:c,holdMs:p}=xt();c?y.error(`[plane-link] holding every plane call for ${Math.round(p/6e4)} min \u2014 three credential refusals in a row (HTTP ${o}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(p/6e4)} min.`):Date.now()-wt>=bo&&(wt=Date.now(),y.error(`[plane-link] plane refused this node's credentials (HTTP ${o}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`))}l()})}at.on("event",rr),Fo().then(or);function sr({bye:s=!0}={}){Kt=!0,at.off("event",rr),Ie&&clearTimeout(Ie),Me&&clearTimeout(Me),se&&clearInterval(se),ie&&clearInterval(ie),z&&clearTimeout(z),s&&j({v:F,ch:"ctl",type:"bye",reason:"shutdown"}),Y?.close()}return{stop:()=>sr(),status:()=>({connected:q,nodeId:n,cursor:{...ne},inflight:I.size,...Qn(),auth:yr(),dormant:Ze,removed:fn(),deadLinkMs:O,deadLinkRedials:Yn,refused:{...mt}}),_tick:()=>{Zn(),Qt()}}}var Q,kn,En,F,go,To,vi,xi,Ai,It,ki,$i,Ei,Oi,On,Ri,xn,Ni,Ii,Mi,So,Pi,_o,Ci,An,Di,Bi,bo,Rn=A(()=>{$t();yo();on();pn();Q=(()=>{try{return bi(import.meta.url)("../package.json").version||null}catch{return null}})(),kn=process.env.BOSTRAT_STATE_DIR||W.join(process.env.HOME||Mt.tmpdir(),".bostrat"),En=W.join(kn,"plane-link","removed.json");F=1,go=1e3,To=3e4,vi=6e4,xi=1500,Ai=500,It=100,ki=2e3,$i=25e3,Ei=2.5,Oi=6e4,On=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Ri=On(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),xn="refused:",Ni={forgedUserId:"this node's events carry a userId the plane's token does not own \u2014 remove BOSTRAT_OWNER from node.env and the shell environment, then restart the node (current releases never stamp one)",foreignTrack:"the Track belongs to another user's node \u2014 this node must not append to it",squattedTrack:"the Track id is already claimed by another user \u2014 a local Track collided with theirs",transferredAway:"the Track moved to another node \u2014 this copy is stale; it should be demoted, not resumed",slugHijack:"a View slug belongs to another owner \u2014 pick a different slug"},Ii=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},Mi=3e4,So=10*6e4,Pi=400,_o=250,Ci=On(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),An=4,Di=Math.max(1,Math.round(On(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),Bi=6e4,bo=6e4});var ko=A(()=>{ln()});var Mo={};nn(Mo,{ACTIONABLE_KINDS:()=>Lt,INSTALL_ATTEMPTS:()=>Pt,INSTALL_RETRY_STEP_S:()=>$o,REGISTRY_RETRY_ATTEMPTS:()=>Mn,REGISTRY_WAIT_POLLS:()=>Nn,REGISTRY_WAIT_STEP_S:()=>In,RESTART_SIGNAL:()=>Oo,SELF_UPDATE_DIR:()=>Dt,SUPERVISOR_PID_FILE:()=>Eo,createAutoUpdater:()=>Qi,inFlight:()=>Bn,readStatus:()=>Dn,restartCommand:()=>Ro,restartStrategy:()=>Cn,selfUpdatePlan:()=>No,settleSelfUpdate:()=>Zi,startSelfUpdate:()=>Io,underService:()=>Pn,updatePolicy:()=>zi});import ft from"node:fs";import he from"node:fs/promises";import ji from"node:os";import U from"node:path";import{spawn as Fi,execFileSync as Ui}from"node:child_process";import{createRequire as Hi}from"node:module";function zi({kind:e=He(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:Lt.has(e)?e==="git-checkout"||Pn(t)?"auto":"prompt":"off"}function Pn(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Cn({env:e=process.env,platform:t=process.platform,uid:n=typeof process.getuid=="function"?process.getuid():0,serviceName:r=t==="darwin"?"com.bostrat.node":"bostrat-node.service",pidFile:i=Eo,readFile:a=h=>ft.readFileSync(h,"utf8"),alive:d=Vi}={}){let h=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(Pn(e))return h;let m=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(m)&&m>0)){try{m=Number(String(a(i)).trim())}catch{m=NaN}Number.isInteger(m)&&m>0&&d(m)||(m=NaN)}return Number.isInteger(m)&&m>0?{mode:"supervisor",pid:m}:h}function Vi(e){try{process.kill(e,0)}catch{return!1}try{let t=Ui("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/bostrat-node|\/cli\.js|node-cli\.js/.test(t)}catch{return!1}}function Ro(e){switch(e?.mode){case"systemd":return`systemctl --user restart ${X(e.serviceName||"bostrat-node.service")}`;case"launchd":return`launchctl kickstart -k gui/${Number(e.uid)||0}/${e.serviceName||"com.bostrat.node"}`;case"supervisor":return`kill -${Oo.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function No({kind:e,to:t,from:n=Ct,statusFile:r=Bt,logFile:i=U.join(Dt,"last.log"),port:a=Number(process.env.PORT)||3362,npmPrefix:d=null,serviceName:h=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:m=typeof process.getuid=="function"?process.getuid():0,restart:g=Cn({env:{},platform:process.platform,uid:m,serviceName:h,readFile:()=>{throw new Error("no pidfile")}}),liveDir:f=process.env.BOSTRAT_LIVE_CHECKOUT||U.resolve(U.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:S=Date.now(),attempts:$=1}={}){if(!Lt.has(e))throw new Error(`self-update: install kind "${e}" is not actionable here`);if(!/^\d+\.\d+\.\d+$/.test(String(t)))throw new Error(`self-update: bad target version "${t}"`);if(n&&!/^\d+\.\d+\.\d+$/.test(String(n)))throw new Error(`self-update: bad current version "${n}"`);let b=(k,_="")=>`write_status ${X(k)} ${_}`,v=Ro(g),R=`
|
|
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,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 vo 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 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:xo(s?.weekly||0),monthlyUsd:xo(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,xo,No=R(()=>{Rt();So();Ao=process.env.BOSTRAT_STATE_DIR||vo.join(process.env.HOME||Fi.tmpdir(),".bostrat"),ji=()=>vo.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;xo=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:v=null,onConflictProbe:N=null,restart:O=null,onRestarted:P=null,onHelloRefused:x=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,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{$e?.({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{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 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}=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&&(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}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":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{v?.(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{x?.({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{v?.(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}=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:xr(),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:()=>va,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=(x,g="")=>`write_status ${J(x)} ${g}`,v=Ko(S),N=`
|
|
125
126
|
health() {
|
|
126
127
|
for i in $(seq 1 45); do
|
|
127
128
|
sleep 1
|
|
128
129
|
if curl -sf -o /dev/null "http://127.0.0.1:${a}/api/health"; then return 0; fi
|
|
129
130
|
done
|
|
130
131
|
return 1
|
|
131
|
-
}`,
|
|
132
|
+
}`,O=`#!/usr/bin/env bash
|
|
132
133
|
# bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
|
|
133
134
|
# ${n??"?"} \u2192 ${t} (${e}). Status: ${r}
|
|
134
135
|
set -u
|
|
135
|
-
FROM=${
|
|
136
|
-
TO=${
|
|
137
|
-
STATUS_FILE=${
|
|
138
|
-
STARTED_AT=${Number(
|
|
139
|
-
ATTEMPTS=${Number(
|
|
136
|
+
FROM=${J(n??"")}
|
|
137
|
+
TO=${J(t)}
|
|
138
|
+
STATUS_FILE=${J(r)}
|
|
139
|
+
STARTED_AT=${Number(w)}
|
|
140
|
+
ATTEMPTS=${Number(E)||1}
|
|
140
141
|
write_status() { # <status> [error] [retryable]
|
|
141
142
|
local err="\${2:-}"
|
|
142
143
|
err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
|
|
143
144
|
printf '{"status":"%s","from":"%s","to":"%s","kind":"%s","attempts":%s,"startedAt":%s,"updatedAt":%s%s%s}\\n' \\
|
|
144
|
-
"$1" "$FROM" "$TO" ${
|
|
145
|
+
"$1" "$FROM" "$TO" ${J(e)} "$ATTEMPTS" "$STARTED_AT" "$(date +%s000)" \\
|
|
145
146
|
"\${err:+,\\"error\\":\\"$err\\"}" "\${3:+,\\"retryable\\":true}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
|
|
146
147
|
}
|
|
147
|
-
${
|
|
148
|
-
`;if(e==="npm-global"){let
|
|
149
|
-
`:"",
|
|
148
|
+
${N}
|
|
149
|
+
`;if(e==="npm-global"){let x=d?U.join(d,"bin","npm"):"npm",g=d?`export PATH=${J(U.join(d,"bin"))}:"$PATH"
|
|
150
|
+
`:"",A=d?` --prefix ${J(d)}`:"",$=$e=>`${J(x)} install -g "bostrat-node@${$e}" --no-audit --no-fund${A}`,k=`
|
|
150
151
|
install_target() {
|
|
151
|
-
for i in $(seq 1 ${
|
|
152
|
-
if ${
|
|
153
|
-
[ "$i" -lt ${
|
|
152
|
+
for i in $(seq 1 ${Ft}); do
|
|
153
|
+
if ${$("$TO")}; then return 0; fi
|
|
154
|
+
[ "$i" -lt ${Ft} ] && sleep ${Uo}
|
|
154
155
|
done
|
|
155
156
|
return 1
|
|
156
|
-
}`,
|
|
157
|
+
}`,I=`
|
|
157
158
|
wait_for_registry() {
|
|
158
|
-
for i in $(seq 1 ${
|
|
159
|
-
if [ "$(${
|
|
160
|
-
sleep ${
|
|
159
|
+
for i in $(seq 1 ${Dn}); do
|
|
160
|
+
if [ "$(${J(x)} view "bostrat-node@$TO" version --prefer-online 2>/dev/null)" = "$TO" ]; then return 0; fi
|
|
161
|
+
sleep ${Ln}
|
|
161
162
|
done
|
|
162
163
|
return 1
|
|
163
|
-
}`;return
|
|
164
|
+
}`;return O+g+I+k+`
|
|
164
165
|
${b("updating",'"" ')}
|
|
165
166
|
if ! wait_for_registry; then
|
|
166
|
-
${b("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(
|
|
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`)}
|
|
167
168
|
exit 1
|
|
168
169
|
fi
|
|
169
170
|
if ! install_target; then
|
|
170
|
-
${b("failed",`"npm install failed (${
|
|
171
|
+
${b("failed",`"npm install failed (${Ft} attempts)"`)}
|
|
171
172
|
exit 1
|
|
172
173
|
fi
|
|
173
174
|
${b("restarting")}
|
|
@@ -181,14 +182,14 @@ if health; then
|
|
|
181
182
|
fi
|
|
182
183
|
# \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
|
|
183
184
|
${b("rolling-back",'"agent did not answer on :'+a+' after the update"')}
|
|
184
|
-
if [ -n "$FROM" ] && ${
|
|
185
|
+
if [ -n "$FROM" ] && ${$("$FROM")} && ${v} && health; then
|
|
185
186
|
${b("rolled-back",'"agent did not answer on :'+a+' after the update; rolled back"')}
|
|
186
187
|
exit 1
|
|
187
188
|
fi
|
|
188
189
|
${b("failed",'"agent did not answer after the update AND the rollback"')}
|
|
189
190
|
exit 1
|
|
190
|
-
`}let P=
|
|
191
|
-
LIVE=${
|
|
191
|
+
`}let P=x=>`( cd ${J(f)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${x}" )`;return O+`
|
|
192
|
+
LIVE=${J(f)}
|
|
192
193
|
TMP_SCRIPT="$(mktemp)"
|
|
193
194
|
trap 'rm -f "$TMP_SCRIPT"' EXIT
|
|
194
195
|
# "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
|
|
@@ -205,28 +206,29 @@ if [ -n "$FROM" ] && ${P("$FROM")}; then
|
|
|
205
206
|
fi
|
|
206
207
|
${b("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
|
|
207
208
|
exit 1
|
|
208
|
-
`}async function Dn(e=Bt){try{return JSON.parse(await he.readFile(e,"utf8"))}catch{return null}}async function Io({to:e,from:t=Ct,kind:n=He(),reason:r="manual",force:i=!1,statusFile:a=Bt,spawnImpl:d=Fi,now:h=Date.now,npmPrefix:m=void 0,log:g=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!Lt.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Ue(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let f=await Dn(a);if(Bn(f))return{ok:!1,reason:`an update to ${f.to} is already in flight`,status:f};let S=f?.to===e?Number(f.attempts)||1:0;if(!i&&f&&f.to===e&&(f.status==="failed"||f.status==="rolled-back")&&!(f.status==="failed"&&f.retryable===!0&&S<Mn))return{ok:!1,reason:`update to ${e} already ${f.status} (${f.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:f};let $=f?.to===e&&(f.status==="failed"||f.status==="rolled-back")?S+1:1;await he.mkdir(U.dirname(a),{recursive:!0});let b=m!==void 0?m:n==="npm-global"?cn(await qi())||U.resolve(U.dirname(process.execPath),".."):null,v=Cn(),R=No({kind:n,to:e,from:t,statusFile:a,npmPrefix:b,startedAt:h(),attempts:$,restart:v}),E=U.join(U.dirname(a),`update-${e}.sh`),P=U.join(U.dirname(a),"last.log");await he.writeFile(E,R,{mode:448}),await he.writeFile(a,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:$,startedAt:h(),updatedAt:h()}));let k=ft.existsSync("/run/systemd/system")&&await Xi("systemd-run"),_=k?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",E]]:["bash",[E]],x=async L=>{let C=`could not spawn updater: ${L?.message||L}`;return await he.writeFile(a,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,attempts:$,startedAt:h(),updatedAt:h(),error:C})).catch(()=>{}),g.error?.(`[self-update] ${C}`),C},N=null;try{k||(N=ft.openSync(P,"a"));let L=d(_[0],_[1],{detached:!0,stdio:k?"ignore":["ignore",N,N]});L.on?.("error",C=>{x(C)}),L.unref?.()}catch(L){return{ok:!1,reason:await x(L)}}finally{N!==null&&ft.closeSync(N)}return g.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}, restart via ${v.mode}) started \u2014 status ${a}`),{ok:!0,to:e,from:t,kind:n,scriptFile:E,statusFile:a}}async function qi(){try{return await he.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Xi(e){for(let t of String(process.env.PATH||"").split(U.delimiter))try{return await he.access(U.join(t,e),ft.constants.X_OK),!0}catch{}return!1}async function Zi({statusFile:e=Bt,current:t=Ct,now:n=Date.now,staleMs:r=Ji}={}){let i=await Dn(e);if(!i)return null;let a=d=>he.writeFile(e,JSON.stringify(d)).catch(()=>{});if(Bn(i)){if(t&&i.to===t){let d={...i,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await a(d),d}if(n()-Number(i.updatedAt||i.startedAt||0)>r){let d={...i,status:"failed",error:`updater went silent while ${i.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await a(d),d}return null}if(["failed","rolled-back","done"].includes(i.status)&&!i.announced){let d={...i,announced:!0};return await a(d),d}return null}function Qi({isBusy:e,start:t=Io,onStuck:n=null,onStarted:r=null,tickMs:i=Gi,stuckMs:a=Ki,now:d=Date.now,setIntervalImpl:h=setInterval,clearIntervalImpl:m=clearInterval,log:g=console}={}){let f=null,S=()=>{f?.timer&&m(f.timer),f=null},$=async()=>{if(!f)return;let b=!0;try{b=await e()!==!1}catch{b=!0}if(b){if(!f.stuckFired&&d()-f.since>=a){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let v=f;S();let R=await t({to:v.to,from:v.from,kind:v.kind,reason:"auto"});g.log?.(`[self-update] stasis reached \u2192 ${R.ok?"started":`not started: ${R.reason}`}`);try{await r?.({...v,result:R})}catch{}};return{arm({to:b,from:v=Ct,kind:R=He()}){return f?.to===b?!1:(S(),f={to:b,from:v,kind:R,since:d(),stuckFired:!1,timer:h($,i)},f.timer.unref?.(),!0)},tick:$,cancel:S,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var Ct,Wi,Dt,Bt,Ki,Gi,Nn,In,Mn,Pt,$o,Eo,Oo,Lt,X,Yi,Bn,Ji,Po=A(()=>{Rn();ko();Ct=(()=>{try{return Hi(import.meta.url)("../package.json").version||null}catch{return null}})(),Wi=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||ji.tmpdir(),".bostrat"),Dt=U.join(Wi,"self-update"),Bt=U.join(Dt,"status.json"),Ki=1440*6e4,Gi=6e4,Nn=60,In=15,Mn=3,Pt=6,$o=20,Eo=U.join(Dt,"supervisor.pid"),Oo="SIGUSR2",Lt=new Set(["npm-global","git-checkout"]);X=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Yi=new Set(["updating","restarting","rolling-back"]),Bn=e=>!!(e&&Yi.has(e.status));Ji=45*6e4});on();an();wn();import K from"node:fs";import M from"node:path";import Ke from"node:os";import{createRequire as Ln}from"node:module";import{execFile as ea,spawn as ta}from"node:child_process";import{promisify as na}from"node:util";import ra from"node:readline/promises";import{randomUUID as oa}from"node:crypto";import{fileURLToPath as sa}from"node:url";import Ys from"node:fs";import jr from"node:path";import qs from"node:os";var Xs=()=>process.env.BOSTRAT_STATE_DIR||jr.join(process.env.HOME||qs.tmpdir(),".bostrat"),Js=()=>jr.join(Xs(),"plane-link","public-host.json");var lt=null;function Zs(){if(lt)return lt;try{let e=JSON.parse(Ys.readFileSync(Js(),"utf8"));lt={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{lt={viewBase:null}}return lt}function Qs(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),i=r?r[1].toLowerCase():t,a=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return a?{proto:i,host:a}:null}function Fr(){return Zs().viewBase}function Ur(e=process.env.BOSTRAT_PUBLIC_HOST){return Qs(e,"https")}function Hr(e=process.env.BOSTRAT_PLANE_URL){let t=String(e||"").trim();if(!t)return null;let n=/^(wss?|https?):\/\/([^/?#]+)/i.exec(t);return n?`${/^(wss|https)$/i.test(n[1])?"https":"http"}://${n[2]}`:null}Et();import ei from"node:fs";import ti from"node:os";import Wr from"node:path";var Kr=3*6e4;function Tn(e=process.env){let t=e.BOSTRAT_STATE_DIR||Wr.join(e.HOME||ti.tmpdir(),".bostrat");return Wr.join(t,"heartbeat.json")}function Gr(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return Kr;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):Kr}function zr(e=Tn()){try{let t=JSON.parse(ei.readFileSync(e,"utf8"));if(!t||typeof t!="object")return null;let n=Number(t.ts),r=Number(t.pid);if(!Number.isFinite(n)||!Number.isFinite(r))return null;let i=Number(t.loopLagMs);return{pid:r,ts:n,loopLagMs:Number.isFinite(i)?i:null}}catch{return null}}Et();var Yr="BOSTRAT_RESTART_NOTICE",Tu=2*6e4;var Vr=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function qr({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:Vr(e),staleS:Vr(t)!=null?Math.round(t/1e3):null})}var Co=(e,t)=>{let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let i=0;i<Math.max(n.length,r.length);i++){let a=(n[i]||0)-(r[i]||0);if(a)return a<0}return!1},me=na(ea),jn=M.dirname(sa(import.meta.url)),Ae=M.resolve(jn,".."),ia=M.join(jn,"index.js"),aa="wss://plane.bostrat.ai/v1/node",We=Ln(import.meta.url)("../package.json").version,B=(e,t)=>({name:e,level:"pass",detail:t}),J=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),V=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function ca(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?B("node runtime",`${process.version} at ${process.execPath}`):V("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function la(e){return e.BOSTRAT_OWNER?J("owner stamp",`BOSTRAT_OWNER=${String(e.BOSTRAT_OWNER).slice(0,12)}\u2026 is set \u2014 ignored by this release; on older releases it got every event refused (forgedUserId)`,"remove BOSTRAT_OWNER from node.env and any shell rc, then restart the node"):B("owner stamp","none (the plane infers the owner from the token)")}function ua(e){let t;try{t=K.statSync(e)}catch{return J("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?J("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):B("node.env",`${e} (0600)`)}async function da(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await me(t,["-V"],{timeout:5e3});return B("tmux",`${t} (${n.trim()})`)}catch{return V("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Do(e,{required:t=!1}={}){if(await gn(e,{loginShell:!0,failOpen:!1}))return B(e,"resolves on the login-shell PATH");let r="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",i=Ot[e]?`${Ot[e]}${e==="cursor-agent"?" # installs to ~/.local/bin \u2014 ensure your login shell has it on PATH":""}`:`install ${e} so \`$SHELL -lic 'command -v ${e}'\` finds it`;return t?V(e,r,i):J(e,r,i)}async function fa(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await me(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return B("gh (GitHub CLI)",n)}catch{return J("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",Ot.gh)}}async function pa(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Do(t)));return e.some(t=>t.level==="pass")||e.push(V("agent CLIs","no agent CLI found at all \u2014 a node with nothing to drive","install at least one of claude / codex / cursor-agent")),e}async function ha(){let e=[...process.platform==="linux"?[["fuser","stopped views can't free their ports (they leak, and the port can't be reused)","apt install psmisc"]]:[],["pgrep","agent-swap can't detect an idle pane shell \u2014 swaps may misfire","apt install procps"],["npm","codex auto-update and `npm run` views are unavailable","install Node.js with npm on the service PATH"]];return Promise.all(e.map(async([t,n,r])=>await gn(t,{failOpen:!1})?B(t,"resolves on the service PATH"):J(t,`not on the service PATH \u2014 ${n}`,r)))}async function ma(){try{let t=Ln(M.join(Ae,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let i=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),a=setTimeout(()=>r(new Error("spawn timeout")),5e3);i.onExit(()=>{clearTimeout(a),n()})}),B("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${Ae} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Ln(M.join(Ae,"package.json")),r=M.join(M.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");K.existsSync(r)&&!(K.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return V("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function wa(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(K.existsSync(t))return B("chromium (mocks)",t);let n=process.platform==="darwin"?"brew install --cask chromium (or set BOSTRAT_CHROMIUM_BIN to Chrome.app's inner binary)":"apt install chromium fonts-dejavu-core fonts-liberation (or set BOSTRAT_CHROMIUM_BIN)";return(e.BOSTRAT_INSTALL_KIND==="container"?V:J)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function ya(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?V("claude lane","BOSTRAT_CLAUDE_USE_API_KEY=1 but ANTHROPIC_API_KEY is empty","add the key to node.env or set the flag to 0"):B("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function ga(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return J("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),i=tt(e.BOSTRAT_PLANE_URL);return await new Promise(a=>{let d=new n(i,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),h=null,m=f=>{clearTimeout(g);try{d.close()}catch{}a(h?{...f,viewBase:h}:f)},g=setTimeout(()=>m(V("plane link",`no hello_ok within 5s from ${i}`,"check the URL, the token, and the plane's IP gate")),5e3);d.on("open",()=>d.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${oa().slice(0,8)}`,ephemeral:!0}))),d.on("message",f=>{try{let S=JSON.parse(f);S.type==="hello_ok"?(typeof S.viewBase=="string"&&S.viewBase&&(h=S.viewBase),S.minNodeVersion&&Co(We,S.minNodeVersion)?m(V("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${S.minNodeVersion} \u2014 this node is ${We}; the real link is refused until it updates`,`bostrat-node self-update --to ${S.latestNodeVersion||S.minNodeVersion}`)):S.latestNodeVersion&&Co(We,S.latestNodeVersion)?m(J("plane link",`hello_ok in ${Date.now()-r}ms (${i}); bostrat-node ${S.latestNodeVersion} is available (this node: ${We})`,`bostrat-node self-update --to ${S.latestNodeVersion}`)):m(B("plane link",`hello_ok in ${Date.now()-r}ms (${i})`))):S.type==="error"&&m(V("plane link",`plane said: ${S.code} ${S.message||""}`,"check the token"))}catch{}}),d.on("error",f=>m(V("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function Ta(){let e;try{e=JSON.parse(K.readFileSync(M.join(Tt,"content-outbox.json"),"utf8"))}catch{return B("content outbox","empty \u2014 every deliverable has reached the plane")}let t=e.ops?.length||0,n=e.parked?.length||0;if(n){let r=e.parked[0];return V("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?J("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):B("content outbox",t?`${t} op(s) in flight`:"drained")}async function Sa(e){let t=await Ir({env:e}),n=Mr(t);return t.available?B("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?J("box caps",n,"boxes run under nice only on this node; if Fly's init mounts /sys/fs/cgroup read-only this is the expected state (blueprint BP-NG-I4)"):B("box caps",n)}function _a(e){return e.BOSTRAT_STATE_REMOTE?B("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):J("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}function ba(e,t){let n=t?.viewBase??null,r=Fr(),i=Ur(e.BOSTRAT_PUBLIC_HOST),a=(()=>{let d=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(d)return`${d.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let h=Hr(e.BOSTRAT_PLANE_URL);return h?`${h}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let d=i&&i.host!==n?`; BOSTRAT_PUBLIC_HOST=${i.host} is set but the plane's value wins`:"";return B("public host",`views https://<slug>.${n}/ (plane hello_ok)${d} \xB7 track links ${a}`)}return r?B("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${a}`):i?B("public host",`views ${i.proto}://<slug>.${i.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${a}`):V("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${a}`,"link a plane that sets PLANE_VIEW_BASE (bostrat-node init), or set BOSTRAT_PUBLIC_HOST in node.env for a plane-less node")}async function Bo(e,t={}){let n=[];n.push(await ca()),n.push(ua(t.envFile||Ce())),n.push(await da(e)),n.push(await Sa(e)),n.push(...await pa()),n.push(await Do("git",{required:!0})),n.push(await fa()),n.push(...await ha()),n.push(await ma()),n.push(wa(e)),n.push(ya(e)),n.push(la(e));let r=await ga(e,t);return n.push(r),n.push(ba(e,r)),n.push(Ta()),n.push(_a(e)),n}function Lo(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let a of e)t(`${n[a.level]} ${a.name}: ${a.detail}`),a.fix&&a.level!=="pass"&&t(` fix: ${a.fix}`);let r=e.filter(a=>a.level==="fail").length,i=e.filter(a=>a.level==="warn").length;return t(r?`
|
|
209
|
-
FAIL \u2014 ${r} blocking, ${i} warnings`:`
|
|
210
|
-
|
|
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=fa,now:p=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 f=await Hn(a);if(Wn(f))return{ok:!1,reason:`an update to ${f.to} is already in flight`,status:f};let w=f?.to===e?Number(f.attempts)||1:0;if(!s&&f&&f.to===e&&(f.status==="failed"||f.status==="rolled-back")&&!(f.status==="failed"&&f.retryable===!0&&w<Fn))return{ok:!1,reason:`update to ${e} already ${f.status} (${f.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:f};let E=f?.to===e&&(f.status==="failed"||f.status==="rolled-back")?w+1:1;await he.mkdir(U.dirname(a),{recursive:!0});let b=m!==void 0?m:n==="npm-global"?pn(await _a())||U.resolve(U.dirname(process.execPath),".."):null,v=Un(),N=Go({kind:n,to:e,from:t,statusFile:a,npmPrefix:b,startedAt:p(),attempts:E,restart:v}),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:p(),updatedAt:p()}));let x=mt.existsSync("/run/systemd/system")&&await ba("systemd-run"),g=x?["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:p(),updatedAt:p(),error:I})).catch(()=>{}),S.error?.(`[self-update] ${I}`),I},$=null;try{x||($=mt.openSync(P,"a"));let k=d(g[0],g[1],{detached:!0,stdio:x?"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 ${v.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 va({statusFile:e=Ht,current:t=jt,now:n=Date.now,staleMs:r=xa}={}){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:p=setInterval,clearIntervalImpl:m=clearInterval,log:S=console}={}){let f=null,w=()=>{f?.timer&&m(f.timer),f=null},E=async()=>{if(!f)return;let b=!0;try{b=await e()!==!1}catch{b=!0}if(b){if(!f.stuckFired&&d()-f.since>=a){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let v=f;w();let N=await t({to:v.to,from:v.from,kind:v.kind,reason:"auto"});S.log?.(`[self-update] stasis reached \u2192 ${N.ok?"started":`not started: ${N.reason}`}`);try{await r?.({...v,result:N})}catch{}};return{arm({to:b,from:v=jt,kind:N=We()}){return f?.to===b?!1:(w(),f={to:b,from:v,kind:N,since:d(),stuckFired:!1,timer:p(E,s)},f.timer.unref?.(),!0)},tick:E,cancel:w,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var jt,ma,Ut,Ht,wa,ya,Dn,Ln,Fn,Ft,Uo,Ho,Wo,Wt,J,Sa,Wn,xa,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));xa=45*6e4});un();fn();_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 fi from"node:os";import dt from"node:path";import pi 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||fi.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(p=>p.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 vn(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 p=null,m={state:null},S=null,f=!1,w="",E=Vr(e),b=x=>{m=x;let g=`[oom-guard] ${vn(x)}`;return g!==w&&r(g),w=g,x},v=x=>{f||(clearTimeout(S),S=setTimeout(()=>N().catch(()=>{}),x),S.unref?.())},N=async()=>{if(f||p)return m;if(!zr(e))return b({state:"off"});if(t!=="linux")return b({state:"unsupported",platform:t});let x=await Xr(E),g=await qr({procRoot:n});if(x&&g.some(k=>k.pid===x)){try{process.kill(x,"SIGTERM")}catch{}g=g.filter(k=>k.pid!==x)}if(g.length)return v(a),b({state:"host",pid:g[0].pid});let A=Yr(e);if(!A)return v(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}`),v(a),m}p=$;for(let k of[$.stdout,$.stderr])k&&pi.createInterface({input:k}).on("line",I=>r(`[earlyoom] ${I}`));return $.on("error",k=>{r(`[oom-guard] ${A}: ${k?.message||k}`),!(p!==$||$.pid)&&(p=null,v(a))}),$.on("exit",(k,I)=>{p===$&&(p=null,Fe.rm(E,{force:!0}).catch(()=>{}),!f&&(r(`[oom-guard] earlyoom exited (${I||`code ${k}`}) \u2014 relaunching in ${Math.round(d/1e3)} s`),m={state:"stopped",bin:A},w="",v(d)))}),$.pid&&(await Fe.mkdir(dt.dirname(E),{recursive:!0}).catch(()=>{}),await Fe.writeFile(E,`${$.pid}
|
|
210
|
+
`).catch(()=>{})),v(a),b({state:"own",pid:$.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 x=p;p=null,x&&(x.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"),xi=()=>Qr.join(bi(),"plane-link","public-host.json");var ft=null;function vi(){if(ft)return ft;try{let e=JSON.parse(Si.readFileSync(xi(),"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 vi().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 xn(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 xn(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=vn(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?`
|
|
211
|
+
FAIL \u2014 ${r} blocking, ${s} warnings`:`
|
|
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=xt(e),s=Oa.createInterface({input:t,output:n}),a=async(x,g)=>(await s.question(g?`${x} [${g}]: `:`${x}: `)).trim()||g||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
|
|
211
213
|
you type those inside each box, later (box-auth-policy).
|
|
212
214
|
|
|
213
|
-
`);let d=await a("Plane URL",r.BOSTRAT_PLANE_URL||
|
|
215
|
+
`);let d=await a("Plane URL",r.BOSTRAT_PLANE_URL||Ia),p=nt(d);p!==d.trim()&&n.write(` \u2192 using ${p}
|
|
214
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.
|
|
215
|
-
`);let
|
|
217
|
+
`);let S=await a("Node name",r.BOSTRAT_NODE_NAME||Ge.hostname().split(".")[0]),f=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(`
|
|
216
218
|
BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
|
|
217
219
|
injected per box, stored 0600 in node.env, never sent to the plane.
|
|
218
220
|
\u2022 create/copy a key: https://console.anthropic.com/settings/keys
|
|
219
221
|
\u2022 set a monthly spend limit while you're there \u2014 the key is live.
|
|
220
222
|
|
|
221
|
-
`);let b
|
|
222
|
-
`),
|
|
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 v={...mr(),...r,BOSTRAT_PLANE_URL:p,BOSTRAT_PLANE_TOKEN:m,BOSTRAT_NODE_NAME:S,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||S,BOSTRAT_REPOS_ROOT:f,BOSTRAT_STATE_REMOTE:w,BOSTRAT_CLAUDE_USE_API_KEY:E?"1":"0",ANTHROPIC_API_KEY:E?b:r.ANTHROPIC_API_KEY};delete v.BOSTRAT_OWNER,hr(e,v,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
|
|
223
225
|
0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
|
|
224
226
|
Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
|
|
225
227
|
wrote ${e}
|
|
226
228
|
|
|
227
|
-
`);let
|
|
228
|
-
`));return P&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:P,results:
|
|
229
|
-
`)}catch{}let r=
|
|
229
|
+
`);let N={...v,...process.env},O=await Jo(N,{envFile:e}),P=Zo(O,x=>n.write(x+`
|
|
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:p=null,log:m=console}={}){let S=null,f=0,w=!1,E="update",b=0,v=null,N=null,O=null,P=0,x=0,g=0,A=!1,$=p&&p.staleMs>0?p.staleMs:0,k=p?.checkMs>0?p.checkMs:Qa,I=()=>{v&&s(v),v=null},$e=()=>{S.kill("SIGTERM"),N=r(()=>S?.kill("SIGKILL"),a),N.unref?.()},ze=null,ke=0,Gt=()=>{let M=null;try{M=p.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:(x++,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 #${x})`),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,f=n(),ze=null,ke=f,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`),v=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 #${x})`):(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:!!v,restarts:P,stallRelaunches:x,stopping:A}}}}function tc({envFile:e=Be()}={}){pr(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
|
|
230
232
|
# ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
|
|
231
233
|
[Unit]
|
|
232
234
|
Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
|
|
@@ -240,13 +242,13 @@ ExecStart=${t} --disable-warning=ExperimentalWarning ${a}
|
|
|
240
242
|
EnvironmentFile=${n}
|
|
241
243
|
# systemd's user PATH omits ~/.local/bin (cursor-agent, bostrat-view) and the
|
|
242
244
|
# nvm bin dir \u2014 both are load-bearing for box spawning.
|
|
243
|
-
Environment=PATH=${r}/.local/bin:${
|
|
245
|
+
Environment=PATH=${r}/.local/bin:${s}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
|
244
246
|
Restart=on-failure
|
|
245
247
|
RestartSec=2
|
|
246
248
|
|
|
247
249
|
[Install]
|
|
248
250
|
WantedBy=default.target
|
|
249
|
-
`}function
|
|
251
|
+
`}function rc({agentDir:e=Ae,nodeBin:t=process.execPath,home:n=Ge.homedir()}={}){let r=C.dirname(t),s=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
|
|
250
252
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
251
253
|
<plist version="1.0">
|
|
252
254
|
<dict>
|
|
@@ -264,11 +266,11 @@ WantedBy=default.target
|
|
|
264
266
|
</dict>
|
|
265
267
|
<key>RunAtLoad</key><true/>
|
|
266
268
|
<key>KeepAlive</key><true/>
|
|
267
|
-
<key>StandardOutPath</key><string>${
|
|
268
|
-
<key>StandardErrorPath</key><string>${
|
|
269
|
+
<key>StandardOutPath</key><string>${s}/node.out.log</string>
|
|
270
|
+
<key>StandardErrorPath</key><string>${s}/node.err.log</string>
|
|
269
271
|
</dict>
|
|
270
272
|
</plist>
|
|
271
|
-
`}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 uf(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={...xt(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)),p=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:p,policy:a({kind:p}),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 f=await r({to:S,kind:p,reason:"cli",force:!0});return f.ok?(console.log(`\u2713 self-update ${f.from??"?"} \u2192 ${f.to} started (${f.kind}) \u2014 status: ${f.statusFile}; the node restarts when the install completes`),0):(console.error(`\u2717 not started: ${f.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
|
|
272
274
|
|
|
273
275
|
usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
|
|
274
276
|
|
|
@@ -277,4 +279,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
|
|
|
277
279
|
run start the node in the foreground (sources node.env)
|
|
278
280
|
install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
|
|
279
281
|
fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
|
|
280
|
-
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{
|
|
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,uf as main,Zo as printDoctor,tc as runAgent,Jo as runDoctor,oc as servicePaths,nc as systemdUnit};
|