bostrat-node 1.14.4 → 1.14.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/bostrat-blueprint +1 -1
- package/dist/cli.js +93 -93
- package/dist/index.js +287 -260
- package/node-entrypoint.sh +31 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)){let
|
|
3
|
-
`).map(
|
|
1
|
+
var Ho=Object.defineProperty;var $=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Xt=(e,t)=>{for(var n in t)Ho(e,n,{get:t[n],enumerable:!0})};import gt from"node:fs";import Jt from"node:path";import Wo from"node:os";function et(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 St(e){let t;try{t=gt.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 Qn(e,t=process.env){let n=St(e);for(let[r,s]of Object.entries(n))r in t||(t[r]=s);return n}function er(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}`);gt.mkdirSync(Jt.dirname(e),{recursive:!0}),gt.writeFileSync(e,r.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`,{mode:384}),
|
|
6
|
-
`))if(d.trim())try{
|
|
5
|
+
`,{mode:384}),gt.chmodSync(e,384)}function tr(e=process.platform){return e==="darwin"?{BOSTRAT_TMUX_BIN:"/opt/homebrew/bin/tmux",BOSTRAT_TMUX_SOCKET:`/tmp/tmux-${process.getuid?.()??501}/bostrat`,BOSTRAT_CHROMIUM_BIN:"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"}:{}}var Tt,Me,Zt=$(()=>{Tt=process.env.BOSTRAT_STATE_DIR||Jt.join(process.env.HOME||Wo.tmpdir(),".bostrat"),Me=()=>Jt.join(Tt,"node.env")});var ae,tt,_t=$(()=>{ae="BOSTRAT_HOOK_TOKEN",tt="x-bostrat-hook"});var nr=$(()=>{_t()});var Ko,Ra,rr=$(()=>{Ko="check_for_update_on_startup",Ra=`${Ko} = false`});import Go from"node:os";import or from"node:path";var zo,Da,Ca,Qt=$(()=>{en();zo=process.env.BOSTRAT_DEBUG_DIR||or.join(Go.homedir(),".bostrat","debug"),Da=or.join(zo,"handoff.jsonl"),Ca=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as Yo}from"node:child_process";import{promisify as qo}from"node:util";function tn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Ha,Wa,Ka,Ga,nn=$(()=>{Qt();Ha=qo(Yo),Wa=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Ka=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,Ga=Promise.resolve()});var sr=$(()=>{});import rn from"node:path";import{execFile as Xo}from"node:child_process";import{promisify as Jo}from"node:util";var Ja,ir,Zo,Za,Qa,ar=$(()=>{Ja=Jo(Xo),ir=process.env.HOME||"/home/globo",Zo=rn.join(process.env.BOSTRAT_STATE_DIR||rn.join(ir,".bostrat"),"repos"),Za=[...(process.env.BOSTRAT_REPOS_ROOT||rn.join(ir,"Documents")).split(","),Zo].map(e=>e.trim()).filter(Boolean),Qa=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function At(e=Date.now()){if(ve)return{tripped:!1,holdMs:1/0};if(be>e)return{tripped:!1,holdMs:be-e};if((!rt||e-rt>=bt.windowMs)&&(rt=e,nt=0),nt++,nt<bt.trip)return{tripped:!1,holdMs:0};vt++;let t=Math.min(bt.minMs*2**(vt-1),bt.maxMs);return be=e+t,nt=0,rt=0,{tripped:!0,holdMs:t}}function cr(){nt=0,rt=0,vt=0,be=0}function ot(e=Date.now()){return ve?1/0:be>e?be-e:0}function xt(e=Date.now()){return ot(e)>0}function on(e={}){ve={at:Date.now(),...e},be=1/0}function sn(){return ve}function lr(e=Date.now()){return{held:xt(e),holdMs:ve?null:ot(e),holds:vt,removed:ve?{...ve}:null}}var Qo,bt,nt,rt,vt,be,ve,an=$(()=>{Qo={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},bt={...Qo},nt=0,rt=0,vt=0,be=0,ve=null});import ur from"node:path";import es from"node:os";import{execFile as ts}from"node:child_process";import{promisify as ns}from"node:util";var lc,rs,uc,dc,fc,cn=$(()=>{ar();an();lc=ns(ts),rs=process.env.BOSTRAT_STATE_DIR||ur.join(process.env.HOME||es.tmpdir(),".bostrat"),uc=ur.join(rs,"repos"),dc=5*6e4,fc=10*6e4});var dr=$(()=>{cn()});import ss from"node:fs/promises";import st from"node:path";import is from"node:os";import{EventEmitter as as}from"node:events";function cs(e){return e?.cwd?st.join(e.cwd,".bostrat","events"):st.join(fr,"events")}async function $t(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?st.join(fr,"events"):cs(e));let s;try{s=await ss.readFile(ls(n,r),"utf8")}catch{return[]}let a=[];for(let d of s.split(`
|
|
6
|
+
`))if(d.trim())try{a.push(JSON.parse(ds(d)?fs(d):d))}catch{}return a}var it,fr,ls,us,ds,fs,kt=$(()=>{it=new as;it.setMaxListeners(0);fr=process.env.BOSTRAT_STATE_DIR||st.join(process.env.HOME||is.tmpdir(),".bostrat");ls=(e,t)=>st.join(e,`${t}.ndjson`),us=/(?<!\\)((?:\\\\)*)\\u0000/g,ds=e=>e.includes("\\u0000"),fs=e=>e.replace(us,"$1\\ufffd")});import hs from"node:os";import ms from"node:path";import{execFile as ws}from"node:child_process";import{promisify as ys}from"node:util";var Oc,Rc,Nc,Ic,Mc,Pc,pr=$(()=>{dr();kt();Oc=ys(ws),Rc=process.env.BOSTRAT_STATE_DIR||ms.join(process.env.HOME||hs.tmpdir(),".bostrat"),Nc=25*1024,Ic=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,Mc=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,Pc=Promise.resolve()});var ln=$(()=>{});var jc,hr=$(()=>{cn();ln();jc=60*6e4});var mr=$(()=>{hr()});import wr from"node:path";import Ts from"node:os";var Pe,Ss,Jc,un,Zc,Qc,el,yr=$(()=>{_t();Pe="BOSTRAT_NODE_URL",Ss=process.env.BOSTRAT_STATE_DIR||wr.join(process.env.HOME||Ts.tmpdir(),".bostrat"),Jc=wr.join(Ss,"git-hooks"),un=`#!/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,36 @@ esac
|
|
|
18
18
|
if [ -x "$orig/$hook" ] && [ "$orig/$hook" != "$0" ]; then
|
|
19
19
|
"$orig/$hook" "$@" || exit $?
|
|
20
20
|
fi
|
|
21
|
-
`,
|
|
21
|
+
`,Zc=`${un}
|
|
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
|
-
[ -z "$${
|
|
25
|
-
[ -z "$${
|
|
24
|
+
[ -z "$${ae}" ] && exit 0
|
|
25
|
+
[ -z "$${Pe}" ] && exit 0
|
|
26
26
|
[ "$2" = "merge" ] && exit 0
|
|
27
|
-
trailers=$(curl -sS -m 3 -H "${
|
|
27
|
+
trailers=$(curl -sS -m 3 -H "${tt}: $${ae}" "$${Pe}/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
|
+
`,Qc=`${un}
|
|
34
34
|
# \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
|
|
35
|
-
[ -z "$${
|
|
36
|
-
[ -z "$${
|
|
35
|
+
[ -z "$${ae}" ] && exit 0
|
|
36
|
+
[ -z "$${Pe}" ] && 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 "$${Pe}/api/git/committed" \\
|
|
40
|
+
-H 'content-type: application/json' -H "${tt}: $${ae}" --data-binary @- >/dev/null 2>&1 || true
|
|
41
41
|
exit 0
|
|
42
|
-
`,
|
|
42
|
+
`,el=`${un}
|
|
43
43
|
# \u2500\u2500 bostrat: the tree moved \u2014 let the node re-read this workspace's lockfiles.
|
|
44
|
-
[ -z "$${
|
|
45
|
-
[ -z "$${
|
|
44
|
+
[ -z "$${ae}" ] && exit 0
|
|
45
|
+
[ -z "$${Pe}" ] && 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 "$${Pe}/api/deps/refresh" \\
|
|
48
|
+
-H 'content-type: application/json' -H "${tt}: $${ae}" --data-binary '{}' >/dev/null 2>&1 || true
|
|
49
49
|
exit 0
|
|
50
|
-
`});import{execFile as
|
|
50
|
+
`});import at from"node:fs/promises";import Tr from"node:os";import De from"node:path";import{execFile as _s}from"node:child_process";import{promisify as bs}from"node:util";function _r(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function br(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 $s(e=process.env){let t=br(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function ks(e=Tr.totalmem()){return Math.max(e-As*Sr,Math.floor(e/2))}function Es(e=process.env){return De.join(_r(e),xs)}async function Os(e){return(await at.readFile(e,"utf8")).trim()}async function vr({env:e=process.env,totalBytes:t=Tr.totalmem(),force:n=!1}={}){if(!n&&!$s(e))return Ce={available:!1,reason:br(e)==="off"?"disabled (BOSTRAT_BOX_CGROUPS=0)":"not a Fly/container node (systemd owns the tree here)"},Ce;let r=_r(e),s=Es(e);try{let a;try{a=(await Os(De.join(r,"cgroup.controllers"))).split(/\s+/).filter(Boolean)}catch(y){throw new Error(`no cgroup v2 tree at ${r} (${y?.code||y?.message||y})`)}let d=["cpu","memory"].filter(y=>a.includes(y));if(!d.length)throw new Error(`cgroup v2 at ${r} offers neither cpu nor memory (controllers: ${a.join(" ")||"none"})`);await at.mkdir(s,{recursive:!0});let h=`+${d.join(" +")}`;for(let y of[De.join(r,"cgroup.subtree_control"),De.join(s,"cgroup.subtree_control")])try{await at.writeFile(y,h)}catch(f){throw new Error(`cannot enable ${h} in ${y} (${f?.code||f?.message||f})`)}let m=ks(t);d.includes("cpu")&&await at.writeFile(De.join(s,"cpu.weight"),String(gr)),d.includes("memory")&&await at.writeFile(De.join(s,"memory.max"),String(m)),Ce={available:!0,path:s,controllers:d,cpuWeight:d.includes("cpu")?gr:null,memoryMaxMb:d.includes("memory")?Math.round(m/Sr):null}}catch(a){Ce={available:!1,reason:a?.message||String(a)}}return Ce}function Ar(e=Ce){let t=`nice ${vs} floor on every box`;if(!e)return`${t}; cgroup ceiling not probed yet`;if(e.available){let n=[];return e.cpuWeight!=null&&n.push(`cpu.weight ${e.cpuWeight}`),e.memoryMaxMb!=null&&n.push(`memory.max ${e.memoryMaxMb} MB`),`${t}; cgroup ceiling at ${e.path} (${n.join(", ")})`}return`${t}; cgroup ceiling unavailable \u2014 ${e.reason}`}var al,vs,gr,As,xs,Sr,Ce,dn=$(()=>{al=bs(_s),vs=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),gr=50,As=768,xs="bostrat-boxes",Sr=1024*1024;Ce=null});import{execFile as Rs}from"node:child_process";import{promisify as Ns}from"node:util";import kr from"node:fs";import Is from"node:os";function Er(e){return`/tmp/tmux-${e}/default`}function Ps({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let s=Er(r);return t?s:n?`${n}/bostrat/tmux-default`:s}async function pn(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Cs(e,{loginShell:t});return r===Or?!0:r===fn?!1:n}async function Cs(e,{loginShell:t=!1,timeoutMs:n=Ds}={}){if(!e)return fn;let r=t?process.env.SHELL||"/bin/sh":"sh",s=t?"-lic":"-c";try{return await Ms(r,[s,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),Or}catch(a){return a?.killed||a?.signal?$r:a?.code===1||a?.code===127?fn:$r}}var Ms,Ll,xr,jl,Fl,Ul,Hl,Wl,Or,fn,$r,Ds,Et,Kl,Gl,zl,Vl,Yl,ql,en=$(()=>{nr();rr();nn();sr();pr();mr();Qt();_t();yr();dn();Ms=Ns(Rs),Ll=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";xr=typeof process.getuid=="function"?process.getuid():0,jl=Ps({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return kr.existsSync(Er(xr))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:xr}),Fl=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Ul=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Hl=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),Wl=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);Or="present",fn="absent",$r="unknown",Ds=5e3;Et={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"},Kl=(()=>{try{let e=Is.homedir();if(e&&kr.existsSync(e))return e}catch{}return"/"})(),Gl=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,zl=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Vl=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Yl=Number(process.env.BOSTRAT_BOX_COLS)||120,ql=Number(process.env.BOSTRAT_BOX_ROWS)||40});var Wr={};Xt(Wr,{NODE_IMAGE:()=>wn,commandPlan:()=>Fr,flyToml:()=>jr,flyWizard:()=>Zs,parseFlyFlags:()=>Ur,stageConfig:()=>Hr});import mn from"node:fs";import Ae from"node:path";import Gs from"node:os";import zs from"node:readline/promises";import{execFile as Vs}from"node:child_process";import{createRequire as Ys}from"node:module";import{randomUUID as qs}from"node:crypto";function jr({app:e,region:t,nodeName:n=e,planeUrl:r=Lr,image:s=wn}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
|
|
51
51
|
# Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
|
|
52
52
|
# No [http_service] and none should be added: the node dials OUT to the plane;
|
|
53
53
|
# nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
|
|
@@ -62,14 +62,14 @@ swap_size_mb = 1024
|
|
|
62
62
|
# The published node image (claude + cursor-agent + codex baked in, logged
|
|
63
63
|
# out), pinned to the bostrat-node version that wrote this file. Update with:
|
|
64
64
|
# npm i -g bostrat-node && bostrat-node fly (re-run is safe), or bump the tag.
|
|
65
|
-
image = "${
|
|
65
|
+
image = "${s}"
|
|
66
66
|
|
|
67
67
|
[env]
|
|
68
68
|
PORT = "3362"
|
|
69
69
|
# $HOME on the volume: your agent logins, repos, and node state survive
|
|
70
70
|
# machine replacement (the "your login stays on your node" promise).
|
|
71
71
|
HOME = "/data/home"
|
|
72
|
-
BOSTRAT_PLANE_URL = "${
|
|
72
|
+
BOSTRAT_PLANE_URL = "${r}"
|
|
73
73
|
BOSTRAT_NODE_ID = "${e}"
|
|
74
74
|
BOSTRAT_NODE_NAME = "${n}"
|
|
75
75
|
BOSTRAT_REPOS_ROOT = "/data/home/repos"
|
|
@@ -87,92 +87,92 @@ swap_size_mb = 1024
|
|
|
87
87
|
# Scale later with: fly scale memory 4096 -a ${e}
|
|
88
88
|
size = "shared-cpu-2x"
|
|
89
89
|
memory = "2gb"
|
|
90
|
-
`}function
|
|
90
|
+
`}function Fr({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
91
|
`)+`
|
|
92
|
-
`},{argv:["deploy",
|
|
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
|
|
92
|
+
`},{argv:["deploy",a,"-c",Ae.join(a,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${a} -c ${Ae.join(a,"fly.toml")} -a ${e} --ha=false`}]}function Ur(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 Hr({app:e,dest:t,toml:n}){let r=t||Ae.join(Gs.homedir(),".bostrat","fly",e);mn.mkdirSync(r,{recursive:!0});for(let s of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])mn.rmSync(Ae.join(r,s),{recursive:!0,force:!0});return mn.writeFileSync(Ae.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function Js({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:s}=await Ot(["orgs","list","--json"],{exec:n}),a=JSON.parse(s),d=Array.isArray(a)?a.map(h=>h.Slug||h.slug).filter(Boolean):Object.keys(a);if(d.length===1)return t.write(`Org: ${d[0]} (your only org)
|
|
93
|
+
`),d[0];if(d.length>1)return await e(`Fly org (${d.join(" / ")})`,d[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function Zs({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:s}={}){let a=Ur(e),d=zs.createInterface({input:t,output:n}),h=async(_,O)=>(await d.question(O?`${_} [${O}]: `:`${_}: `)).trim()||O||"",m=_=>(d.close(),_);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
|
|
94
94
|
bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
|
|
95
95
|
|
|
96
|
-
`);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"),
|
|
98
|
-
`),
|
|
99
|
-
wrote ${
|
|
96
|
+
`);try{await Ot(["version"],{exec:r})}catch{return n.write("\u2717 `fly` (flyctl) is not installed or not on PATH.\n install: https://fly.io/docs/flyctl/install/ \u2014 then re-run `bostrat-node fly`\n"),m(1)}try{let{stdout:_}=await Ot(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${_.trim()}
|
|
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 y=await Js({ask:h,output:n,exec:r,flag:a.org}),f=a.app||await h("App name",`bostrat-node-${qs().slice(0,4)}`),S=a.region||await h("Region (see `fly platform regions`)","iad"),R=a.sizeGb||Number(await h("Volume size GB (logins + repos live here)","10"))||10,b=a.name||f,v=a.planeUrl||Lr,N=a.token||await h("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.
|
|
98
|
+
`),m(1);let k=a.image||wn,{dir:E}=Hr({app:f,dest:s,toml:jr({app:f,region:S,nodeName:b,planeUrl:v,image:k})});n.write(`
|
|
99
|
+
wrote ${Ae.join(E,"fly.toml")} \u2014 deploys the prebuilt node image ${k}
|
|
100
100
|
(claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
|
|
101
101
|
|
|
102
102
|
Plan (your flyctl, your org, your bill):
|
|
103
|
-
`);let
|
|
104
|
-
`);if(!
|
|
103
|
+
`);let A=Fr({app:f,org:y,region:S,sizeGb:R,token:N,dir:E});for(let _ of A)n.write(` $ ${_.display}
|
|
104
|
+
`);if(!a.yes&&(await h(`
|
|
105
105
|
Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u2014 nothing was created. Re-run any time; the staged context is kept.
|
|
106
|
-
`),
|
|
107
|
-
\u2192 ${
|
|
108
|
-
`);try{let{stdout:
|
|
106
|
+
`),m(1);for(let _ of A){n.write(`
|
|
107
|
+
\u2192 ${_.display}
|
|
108
|
+
`);try{let{stdout:O,stderr:U}=await Ot(_.argv,{stdin:_.stdin,exec:r}),C=`${O||""}${U||""}`.trim();C&&n.write(C.split(`
|
|
109
109
|
`).map(K=>` ${K}`).join(`
|
|
110
110
|
`)+`
|
|
111
|
-
`)}catch(
|
|
112
|
-
`);continue}return n.write(`\u2717 failed: ${
|
|
111
|
+
`)}catch(O){let U=`${O?.stdout||""}${O?.stderr||""}${O?.message||""}`;if(_.tolerate&&_.tolerate.test(U)){n.write(` (already exists \u2014 continuing)
|
|
112
|
+
`);continue}return n.write(`\u2717 failed: ${U.trim().split(`
|
|
113
113
|
`).slice(-4).join(`
|
|
114
114
|
`)}
|
|
115
115
|
fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
|
|
116
|
-
`),
|
|
116
|
+
`),m(1)}}return n.write(`
|
|
117
117
|
\u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
|
|
118
118
|
chat: the node step advances on its own within a minute.
|
|
119
119
|
logs: fly logs -a ${f}
|
|
120
|
-
redeploy: fly deploy ${E} -c ${
|
|
120
|
+
redeploy: fly deploy ${E} -c ${Ae.join(E,"fly.toml")} -a ${f} --ha=false
|
|
121
121
|
Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
|
|
122
122
|
boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
|
|
123
|
-
`),h(0)}var Tr,vs,nn,wt,kr=k(()=>{Tr="wss://plane.bostrat.ai/v1/node",vs=Ss(import.meta.url)("../package.json").version,nn=`ghcr.io/globocodes/bostrat-node:${vs}`;wt=(e,{stdin:t,exec:n}={})=>new Promise((o,i)=>{if(n)return n(e,{stdin:t}).then(o,i);let c=Ts("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,m,h)=>d?i(Object.assign(d,{stdout:m,stderr:h})):o({stdout:m,stderr:h}));t!=null&&c.stdin?.end(t)})});function $r(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!$s.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let o=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(o))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return o}function xs(e){let t={};for(let[n,o]of Object.entries(e)){if(!Array.isArray(o)||o.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=o.map(i=>({...i,fromMs:$r(i.from,"from",n),toMs:$r(i.to,"to",n)}))}return t}var ks,$s,vl,bl,xr=k(()=>{ks={"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)."}]},$s=/^\d{4}-\d{2}-\d{2}$/;vl=xs(ks),bl=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var Er=k(()=>{xr()});import Or from"node:fs/promises";import Ir from"node:path";import Es from"node:os";function Pr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Dr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Cr(e){let t=new Date(Pr(e));return t.setDate(t.getDate()+7),t.getTime()}function Lr(e){let t=new Date(Dr(e));return t.setMonth(t.getMonth()+1),t.getTime()}function Ms(e=Date.now()){for(let[t,n]of Object.entries(Ns)){let o=n.startOf(e);if(o!==yt[t]){yt[t]=o;for(let i of rn.values())i[t]=0;for(let i of Rr)i.includes(`:${t}:`)&&!i.endsWith(`:${o}`)&&Rr.delete(i)}}}function Ps(e){let t={};for(let[n,o]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 c of["weeklyUsd","monthlyUsd"]){let d=o?.[c];if(d==null||d==="")continue;let m=Number(d);if(!Number.isFinite(m)||m<=0)throw new Error(`${n}.${c} must be a positive number or null`);i[c]=m}Object.keys(i).length&&(t[n]=i)}return t}async function Br(e,{source:t="local",updatedAt:n=Date.now()}={}){Oe={caps:Ps(e),updatedAt:n,source:t};try{await Or.mkdir(Mr,{recursive:!0}),await Or.writeFile(Os(),JSON.stringify(Oe,null,2))}catch{}return Ds()}function Ds(e=Date.now()){Ms(e);let t=new Set([...rn.keys(),...Object.keys(Oe?.caps||{})]),n={};for(let o of t){let i=rn.get(o);n[o]={weeklyUsd:Nr(i?.weekly||0),monthlyUsd:Nr(i?.monthly||0)}}return{caps:Oe?.caps||{},configured:!!Oe,seeded:Is,updatedAt:Oe?.updatedAt??null,spent:n,windows:{weekly:{start:yt.weekly,resetsAt:Cr(e)},monthly:{start:yt.monthly,resetsAt:Lr(e)}},warnPct:Rs}}var Mr,Os,Rs,Ns,Oe,Is,yt,rn,Rr,Nr,jr=k(()=>{ht();Er();Mr=process.env.BOSTRAT_STATE_DIR||Ir.join(process.env.HOME||Es.tmpdir(),".bostrat"),Os=()=>Ir.join(Mr,"usage-caps.json"),Rs=.8;Ns={weekly:{startOf:Pr,nextStart:Cr,capKey:"weeklyUsd"},monthly:{startOf:Dr,nextStart:Lr,capKey:"monthlyUsd"}},Oe=null,Is=!1,yt={weekly:0,monthly:0},rn=new Map,Rr=new Set;Nr=e=>Math.round(e*1e4)/1e4});var Yr={};Ft(Yr,{REMOVED_MARKER:()=>un,detectInstallKind:()=>Ie,detectProviderAuth:()=>Gr,maskToken:()=>ln,readRemovedMarker:()=>zr,startPlaneLink:()=>Zs,updateCommandFor:()=>Je,versionLt:()=>Ne});import Re from"node:fs";import Xe from"node:fs/promises";import Cs from"node:http";import U from"node:path";import gt from"node:os";import{createRequire as Ls}from"node:module";import on from"ws";function ln(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function zr(e=un){try{let t=JSON.parse(Re.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function Ie({env:e=process.env,pkgDir:t=U.resolve(U.dirname(new URL(import.meta.url).pathname),".."),exists:n=Re.existsSync}={}){let o=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(o)?o:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(U.join(t,"..",".git"))?"git-checkout":"dev"}function Ne(e,t){let n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);if(n.some(Number.isNaN)||o.some(Number.isNaN))return!1;for(let i=0;i<Math.max(n.length,o.length);i++){let c=(n[i]||0)-(o[i]||0);if(c)return c<0}return!1}function Je(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 Gr({home:e=process.env.HOME||gt.homedir(),env:t=process.env}={}){let n=o=>{try{return Re.statSync(o),!0}catch{return!1}};return{claude:n(U.join(e,".claude",".credentials.json")),codex:n(U.join(t.CODEX_HOME||U.join(e,".codex"),"auth.json")),cursor:n(U.join(t.XDG_CONFIG_HOME||U.join(e,".config"),"cursor","auth.json"))}}function Zs({url:e,token:t,nodeId:n=gt.hostname(),name:o=gt.hostname(),listTracks:i,detectAgents:c=null,onTracksTransferred:d=null,onTracksMoves:m=null,sampleMetrics:h=null,deliverySample:x=null,onHashKey:f=null,onViewBase:T=null,metricsMs:$=Js,onUpdateAvailable:_=null,onUpdatePolicy:v=null,onHelloRefused:M=null,updatePolicy:O=null,installKind:E=Ie(),selfUrl:b=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:S=null,removedMarkerFile:A=un,onRemoved:P=null,onDegraded:R=null,onRecovered:K=null,onRefused:kt=null,onConnected:co=null,ingestMode:$t=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:_n=zs,unackedRetryMs:Qe=Ws,pingMs:vn=Hs,deadLinkMs:xt=Math.round(vn*Ks),maxInflightEvents:lo=qs,httpTimeoutMs:et=Xs,stallBackoffMinMs:bn=Ys,fetchImpl:An=globalThis.fetch,log:w=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=He(e);let uo=b.replace(/^http/,"ws"),kn=new Set,$n=s=>{let l=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(!(!(l&&Z&&Ne(Z,l))||kn.has(l))){kn.add(l),w.log(`[plane-link] bostrat-node ${l} is available (this node runs ${Z}) \u2014 ${Je(E)}`);try{_?.({current:Z,latest:l,min:s.minNodeVersion??null,installKind:E,required:!!(s.minNodeVersion&&Ne(Z,s.minNodeVersion))})}catch(a){w.error(`[plane-link] update notice failed: ${a?.message||a}`)}}},pe=new Map,he=new Map,Et=U.join(cn,"plane-link","cursor.json"),Ot=U.join(cn,"plane-link","dead-letter.ndjson"),xn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),ne={},ee={},N=new Map,tt=null,ae=null,re=0,De=0,En=0,nt={},On=new Set,Rn=Promise.resolve(),C="ws",be=0,J=!1,me=0,Rt=!1,V=ue,Ae=new Set,ce=[],z=null,Y=null,q=!1,Nt=!1,Ce=Fr,Le=null,ke=null,$e=null,oe=null,we=0,Nn=0,se=null,It=!1,rt=0,Be=!1,le=zr(A);if(le)if(le.tokenPreview===ln(t))Be=!0,Yt({reason:le.reason??"removed",at:le.at??null,nodeId:le.nodeId??n}),w.error(`[plane-link] this node was REMOVED from the plane (${le.reason??"removed"}${le.at?` at ${new Date(le.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${A} to force a dial.`);else try{Re.unlinkSync(A),w.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function Mt({reason:s="removed",at:l=Date.now(),via:a="ctl"}={}){if(!Be){Be=!0,Yt({reason:s,at:l,nodeId:n,via:a});try{Re.mkdirSync(U.dirname(A),{recursive:!0}),Re.writeFileSync(A,JSON.stringify({at:l,reason:s,via:a,nodeId:n,tokenPreview:ln(t)},null,2))}catch(r){w.error(`[plane-link] could not write ${A}: ${r?.message||r}`)}w.error(`[plane-link] the plane REMOVED this node (${s}, via ${a}) \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{P?.({reason:s,at:l,via:a})}catch{}Hn({bye:!1})}}async function fo(){try{ne=JSON.parse(await Xe.readFile(Et,"utf8"))}catch{ne={}}}function In(){It=!0,!$e&&($e=setTimeout(async()=>{if($e=null,!!It){It=!1;try{await Xe.mkdir(U.dirname(Et),{recursive:!0}),await Xe.writeFile(Et,JSON.stringify(ne))}catch(s){w.error("[plane-link] cursor flush failed:",s?.message||s)}}},Us),$e.unref?.())}function L(s){return!Y||Y.readyState!==on.OPEN?!1:(Y.send(JSON.stringify(s)),!0)}function je(s){let l=Date.now();for(let{trackId:r,event:u}of s){let p=N.get(u.id);N.set(u.id,{trackId:r,seq:u.seq,event:u,sentAt:l,firstSentAt:p?.firstSentAt??l,retryAt:l+Qe,tries:(p?.tries??0)+1,nacks:p?.nacks??0})}let a=s.map(({trackId:r,event:u})=>({trackId:r,event:Vs(u)}));return C==="http"?(go(a),!0):L({v:B,ch:"events",type:"append",events:a})}function po(s){let l=null;for(let a of N.values())a.trackId===s&&(l==null||a.seq<l)&&(l=a.seq);return l}function Pt(s){let l=ee[s];if(l==null)return;let a=po(s),r=a==null?l:Math.min(l,a-1);r>(ne[s]??0)&&(ne[s]=r,In())}function Fe(){if(tt=Date.now(),ae!=null){let s=Date.now()-ae;w.log(`[plane-link] spine sync recovered after ${Math.round(s/1e3)}s degraded (${re} stall redial(s))`);let l=ae;ae=null,re=0,De=0,J=!1,me=0;try{K?.({since:l,downMs:s})}catch(a){w.error(`[plane-link] onRecovered failed: ${a?.message||a}`)}}}function Dt(s){if(!Array.isArray(s)||!s.length)return;let l=new Set;for(let a of s){let r=N.get(a);r&&(N.delete(a),(ee[r.trackId]??0)<r.seq&&(ee[r.trackId]=r.seq),l.add(r.trackId))}for(let a of l)Pt(a);Fe()}function Mn(s,l){En++;let a={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};w.error(`[plane-link] DEAD-LETTER ${s.trackId} seq ${s.seq} (${a.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${Ot}`),Rn=Rn.then(async()=>{await Xe.mkdir(U.dirname(Ot),{recursive:!0}),await Xe.appendFile(Ot,JSON.stringify(a)+`
|
|
124
|
-
`)}).catch(r=>w.error(`[plane-link] dead-letter write failed: ${r?.message||r}`))}function ho(s,l){if(nt[s]=(nt[s]??0)+1,On.has(s))return;On.add(s);let a=Gs[s]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";w.error(`[plane-link] REFUSED by the plane (${s}) on track ${l}: events are being dropped, not stored \u2014 ${a}`);try{kt?.({reason:s,trackId:l,count:nt[s],hint:a})}catch(r){w.error(`[plane-link] onRefused failed: ${r?.message||r}`)}}function Ct(s,l,a,r=null){if(!Array.isArray(s)||!s.length)return;let u=new Set,p=Date.now();for(let g of s){let y=N.get(g);y&&(a?(N.delete(g),Mn(y,l),String(l).startsWith(sn)&&ho(String(l).slice(sn.length),y.trackId),(ee[y.trackId]??0)<y.seq&&(ee[y.trackId]=y.seq),u.add(y.trackId)):(y.nacks++,y.retryAt=p+Math.max(1e3,Number(r)||Qe)))}for(let g of u)Pt(g);Fe()}function Pn(s=Date.now()){let l=1/0;for(let a of N.values())a.firstSentAt<l&&(l=a.firstSentAt);return l===1/0?0:s-l}function mo(s){if(!xt||!s||s!==Y||!we)return!1;let l=Date.now()-we;if(l<=xt)return!1;Nn++,w.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 Dn(){if(!q||!N.size)return;let s=Date.now(),l=Pn(s);if(l<_n||tt!=null&&s-tt<_n||C==="http"&&J||De>s)return;re++;let a=Math.min(bn*2**(re-1),Hr);if(ae==null){ae=s-l,w.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${N.size} event(s) in flight (${C} door) \u2014 the plane is not answering appends`);try{R?.({since:ae,unacked:N.size,oldestAgeMs:l,mode:C})}catch(r){w.error(`[plane-link] onDegraded failed: ${r?.message||r}`)}}if(C==="http"){J=!0,me=s+a,w.error(`[plane-link] ingest circuit OPEN (stall #${re}); probing /v1/ingest/health in ${Math.round(a/1e3)}s`);return}De=s+a,w.error(`[plane-link] closing the link and redialing in ${Math.round(a/1e3)}s (stall redial #${re})`);try{Y?.terminate()}catch{}}function Lt(){if(!q)return;let s=Date.now();if(C==="http"&&J)return;let l=[...N.values()].filter(r=>r.event&&r.retryAt<=s&&!(C==="http"&&Ae.has(r.trackId)));if(!l.length)return;l.sort((r,u)=>r.trackId===u.trackId?r.seq-u.seq:r.trackId<u.trackId?-1:1),w.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let a=C==="http"?V:ue;if(C==="http"){let r=new Map;for(let u of l)(r.get(u.trackId)??r.set(u.trackId,[]).get(u.trackId)).push(u);for(let[,u]of r){if(be>=an)return;je(u.slice(0,a).map(p=>({trackId:p.trackId,event:p.event})))}return}for(let r=0;r<l.length;r+=a){let u=l.slice(r,r+a).map(p=>({trackId:p.trackId,event:p.event}));if(!je(u))return}}async function wo(s=null){for(;;){if(!q)return!1;let l=N.size<lo,a=C!=="http"||be<an&&!J&&(!s||!Ae.has(s));if(l&&a)return!0;await new Promise(r=>setTimeout(r,100))}}function Bt(){if(z=null,!q||!ce.length)return;let s=ce;if(ce=[],C!=="http"){for(let a=0;a<s.length;a+=ue)je(s.slice(a,a+ue));return}let l=new Map;for(let a of s)(l.get(a.trackId)??l.set(a.trackId,[]).get(a.trackId)).push(a);for(let[a,r]of l){if(Ae.has(a)||be>=an||J){ce.push(...r);continue}for(let u=0;u<r.length;u+=V)je(r.slice(u,u+V))}ce.length&&!z&&(z=setTimeout(Bt,Kr),z.unref?.())}let yo=s=>{let l=new Map;for(let{trackId:a,event:r}of s)(l.get(a)??l.set(a,[]).get(a)).push(r);return[...l].map(([a,r])=>({trackId:a,events:r}))},ye=(s,l,a,{progress:r})=>{let u=Date.now();for(let{event:p}of s){let g=N.get(p.id);g&&(g.nacks++,g.retryAt=u+Math.max(1e3,a||Qe))}r&&Fe()};async function go(s){let l=new Set(s.map(a=>a.trackId));for(let a of l)Ae.add(a);be++;try{let a=await An(`${xn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:yo(s)}),signal:AbortSignal.timeout(et)}),r=(Number(a.headers.get("retry-after"))||0)*1e3;if(a.status===200){let u=await a.json();V=ue;for(let y of u.results??[]){Dt(y.acked??[]);let D=(te,W)=>{let ot=new Map;for(let ge of te??[])(ot.get(ge.reason)??ot.set(ge.reason,[]).get(ge.reason)).push(ge.id);for(let[ge,Kn]of ot)Ct(Kn,ge,W,u.retryAfterMs??null)};D(y.rejected,!0),D(y.deferred,!1)}let p=new Set,g=new Map;for(let y of Array.isArray(u.refused)?u.refused:[])!y||typeof y.id!="string"||(p.add(y.id),(g.get(y.reason)??g.set(y.reason,[]).get(y.reason)).push(y.id));for(let[y,D]of g)Ct(D,`${sn}${y}`,!0);Dt((u.discarded??[]).filter(y=>!p.has(y))),Fe();return}if(a.status===429){ye(s,"overloaded",r||5e3,{progress:!0});return}if(a.status===413&&s.length>1){V=Math.max(1,Math.floor(s.length/2)),w.error(`[plane-link] ingest request too large (${s.length} events) \u2014 halving batches to ${V}`),ye(s,"too_large",1e3,{progress:!0});return}if(a.status===413){let u=N.get(s[0].event.id);u&&(N.delete(u.event.id),Mn(u,"too_large"),(ee[u.trackId]??0)<u.seq&&(ee[u.trackId]=u.seq),Pt(u.trackId)),Fe();return}if(a.status===410){Mt({reason:"removed",via:"410"}),ye(s,"http_410",6e4,{progress:!1});return}if(a.status===401||a.status===403){let{tripped:u,holdMs:p}=dt();if(u&&w.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()-rt>=Wr){rt=Date.now();let g="";try{g=(await a.json())?.error??""}catch{}w.error(`[plane-link] plane refused ingest (HTTP ${a.status}${g?`: ${g}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}ye(s,`http_${a.status}`,Math.max(6e4,Ge()),{progress:!1});return}if(a.status===400){w.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`),ye(s,"http_400",6e4,{progress:!1});return}ye(s,`http_${a.status}`,r||5e3,{progress:!1})}catch(a){let r=a?.name==="TimeoutError"||a?.name==="AbortError";r&&s.length>1&&(V=Math.max(1,Math.floor(s.length/2)),w.error(`[plane-link] ingest request of ${s.length} event(s) outlived its ${et} ms deadline \u2014 halving batches to ${V}`)),ye(s,r?"timeout":"network",5e3,{progress:!1})}finally{be--;for(let a of l)Ae.delete(a)}}async function To(){if(C!=="http"||!J||!q||Rt)return;let s=Date.now();if(!(me>s||ft(s))){Rt=!0;try{let l=await An(`${xn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(et)});if(!l.ok)throw new Error(`HTTP ${l.status}`);w.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),J=!1,me=0,De=Date.now()+et+Qe+1e3;for(let a of N.values())a.retryAt=Math.min(a.retryAt,Date.now());Lt()}catch(l){re++;let a=Math.min(bn*2**(re-1),Hr);me=Date.now()+a,w.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(a/1e3)}s`)}finally{Rt=!1}}}function Cn(){let s=Date.now();return{mode:C,unacked:N.size,oldestUnackedAgeMs:Pn(s),lastProgressAt:tt,degradedSince:ae,stallRedials:re,deadLettered:En,http:C==="http"?{inFlight:be,circuitOpen:J,nextProbeInMs:J?Math.max(0,me-s):0,batchCap:V}:null}}async function Ln(){if(!h)return;let s;try{s=await h()}catch(a){w.error("[plane-link] metrics sample failed:",a?.message||a);return}let l=null;try{l=x?.()??null}catch{}s&&L({v:B,ch:"ctl",type:"metrics",metrics:{...s,planeLink:Cn(),...l?{delivery:l}:{}}})}function So(){h&&(se&&clearInterval(se),Ln(),se=setInterval(Ln,$),se.unref?.())}async function _o(){let s;try{s=await i()}catch(l){w.error("[plane-link] backfill listTracks failed:",l?.message||l);return}L({v:B,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 Bn(l))return}async function Bn(s){let l;try{l=await pt(s)}catch{return!0}let a=ne[s.id]??0,r=l.filter(p=>p.seq>a&&typeof p.id=="string"),u=C==="http"?V:ue;for(let p=0;p<r.length;p+=u){if(!await wo(s.id))return!1;let g=r.slice(p,p+Math.min(u,C==="http"?V:ue)).map(y=>({trackId:s.id,event:y}));if(!je(g))return!1}return!0}let jt=new Map;async function jn(s,l){if(jt.get(s)===l)return!1;jt.set(s,l);let a=null;try{a=(await i()).find(g=>g?.id===s)??null}catch{return!1}if(!a)return!1;let r;try{r=await pt(a)}catch{return!1}let u=[...r].reverse().find(g=>(g?.type==="track.transferred"||g?.type==="track.recovered")&&g.payload?.toNode===n);if(!u||!Number.isFinite(u.seq))return!1;let p=u.seq-1;return(ne[s]??0)>p&&(ne[s]=p,In()),(ee[s]??0)>p&&(ee[s]=p),w.log(`[plane-link] re-sending ${s}'s move-commit (seq ${u.seq}, ${u.type}) \u2014 the plane's move record predates this node's adoption`),q?Bn(a):!1}function Fn(s){!q||!s?.trackId||typeof s.id!="string"||(ce.push({trackId:s.trackId,event:s}),z||(z=setTimeout(Bt,Kr),z.unref?.()))}let Ue=new Map;async function vo(s){let{reqId:l,method:a,path:r,headers:u={},body:p}=s,g=Object.fromEntries(Object.entries(u).filter(([,D])=>D!=null)),y=new AbortController;Ue.set(l,y);try{if(s.host){await bo(s,g,y);return}S&&(g["x-bostrat-token"]=S);let D=await fetch(b+r,{method:a,headers:g,body:p?Buffer.from(p,"base64"):void 0,signal:y.signal}),te=Object.fromEntries(D.headers);for(let W of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete te[W];if(te["content-type"]||(te["content-type"]="application/octet-stream"),L({v:B,ch:"control",type:"http_head",reqId:l,status:D.status,headers:te}),D.body){for await(let W of D.body)if(!L({v:B,ch:"control",type:"http_data",reqId:l,data:Buffer.from(W).toString("base64")}))break}L({v:B,ch:"control",type:"http_end",reqId:l,error:null})}finally{Ue.delete(l)}}function bo(s,l,a){let{reqId:r,method:u,path:p,body:g}=s,y=new URL(b);return new Promise(D=>{let te=Cs.request({host:y.hostname,port:y.port,method:u,path:p,headers:{...l,host:s.host},signal:a.signal},W=>{let{connection:ot,"keep-alive":ge,"transfer-encoding":Kn,upgrade:zi,...Ao}=W.headers;L({v:B,ch:"control",type:"http_head",reqId:r,status:W.statusCode||502,headers:Ao}),W.on("data",ko=>{L({v:B,ch:"control",type:"http_data",reqId:r,data:Buffer.from(ko).toString("base64")})||W.destroy()}),W.on("end",()=>{L({v:B,ch:"control",type:"http_end",reqId:r,error:null}),D()}),W.on("error",()=>{L({v:B,ch:"control",type:"http_end",reqId:r,error:"view upstream error"}),D()})});te.on("error",W=>{L({v:B,ch:"control",type:"http_end",reqId:r,error:W?.message||"view request failed"}),D()}),g&&te.write(Buffer.from(g,"base64")),te.end()})}function Un(){if(Nt||Be)return;Y=new on(e,{headers:{authorization:`Bearer ${t}`}});let s=Y;we=0,s.on("ping",()=>{we=Date.now()}),s.on("pong",()=>{we=Date.now()}),Y.on("open",async()=>{let a=null;try{a=await c?.()||null}catch{a=null}L({v:B,ch:"ctl",type:"hello",nodeId:n,name:o,platform:process.platform,version:Z,installKind:E,...typeof O=="function"?{updatePolicy:O()}:O?{updatePolicy:O}:{},providers:Gr(),...a?{agents:a}:{}})}),Y.on("message",a=>{we=Date.now();let r;try{r=JSON.parse(a)}catch{return}if(r.ch==="ctl"&&r.type==="hello_ok"){jt.clear(),q=!0,Ce=Fr,Le=null,Qn(),w.log(`[plane-link] connected to plane as ${n}`);try{co?.()}catch{}if(typeof r.hashKey=="string"&&r.hashKey)try{f?.(r.hashKey)}catch{}try{T?.(typeof r.viewBase=="string"&&r.viewBase?r.viewBase:null)}catch{}r.minNodeVersion&&Z&&Ne(Z,r.minNodeVersion)&&w.error(`[plane-link] this node is bostrat-node ${Z}; the plane asks for \u2265${r.minNodeVersion} \u2014 update with: ${Je(E)}`);try{v?.(typeof r.updatePolicy=="string"?r.updatePolicy:null)}catch{}$n(r);let u=r.ingest==="http";C=$t==="ws"?"ws":$t==="http"||u?"http":"ws",$t==="http"&&!u&&w.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),C==="http"&&w.log("[plane-link] spine rides the HTTPS ingest door"),J=!1,me=0,V=ue,oe&&clearInterval(oe),we=Date.now(),oe=setInterval(()=>{mo(s)||(L({v:B,ch:"ctl",type:"ping"}),Dn(),To().catch(()=>{}),Lt(),ce.length&&!z&&Bt())},vn),oe.unref?.(),So(),_o().catch(p=>w.error("[plane-link] backfill failed:",p?.message||p));return}if(r.ch==="ctl"&&r.type==="hello_refused"){let u=typeof r.minNodeVersion=="string"?r.minNodeVersion:null,p=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;w.error(`[plane-link] plane REFUSED this node: bostrat-node ${Z??"?"} is below its minimum ${u??"?"} \u2014 ${r.fix||Je(E)}`),Ce=Ur,Le=0;try{M?.({current:Z,min:u,latest:p,fix:r.fix||Je(E),installKind:E})}catch(g){w.error(`[plane-link] refusal handler failed: ${g?.message||g}`)}return}if(r.ch==="ctl"&&r.type==="removed"){L({v:B,ch:"ctl",type:"removed_ack",nodeId:n}),Mt({reason:typeof r.reason=="string"?r.reason:"removed",at:Number(r.at)||Date.now(),via:"ctl"});return}if(r.ch==="ctl"&&r.type==="update_available"){$n(r);return}if(r.ch==="ctl"&&r.type==="update_policy"){try{v?.(typeof r.mode=="string"?r.mode:null)}catch{}return}if(r.ch==="ctl"&&r.type==="usage_caps"){Br(r.caps??{},{source:"plane",updatedAt:r.updatedAt??Date.now()}).then(u=>w.log(`[plane-link] spend caps ${Object.keys(u.caps).length?`updated (${Object.keys(u.caps).join(", ")})`:"cleared"} from plane`)).catch(u=>w.error("[plane-link] spend-caps push rejected:",u?.message||u));return}if(r.ch==="ctl"&&r.type==="transferred"&&Array.isArray(r.tracks)){Promise.resolve().then(()=>d?.(r.tracks)).then(async u=>{for(let p of Array.isArray(u)?u:[])p?.stale&&p.id&&await jn(p.id,p.since??null)}).catch(u=>w.error("[plane-link] transfer notice failed:",u?.message||u));return}if(r.ch==="ctl"&&r.type==="moves"&&Array.isArray(r.tracks)){Promise.resolve().then(()=>m?.(r.tracks)).then(async u=>{for(let p of Array.isArray(u)?u:[])p?.stale&&p.id&&await jn(p.id,p.since??null)}).catch(u=>w.error("[plane-link] move-record reconcile failed:",u?.message||u));return}if(r.ch==="events"&&r.type==="ack"&&Array.isArray(r.ids)){Dt(r.ids);return}if(r.ch==="events"&&r.type==="nack"&&Array.isArray(r.ids)){Ct(r.ids,r.reason,r.permanent===!0,r.retryAfterMs??null);return}if(r.ch==="control"&&r.type==="http_open"){vo(r).catch(u=>L({v:B,ch:"control",type:"http_end",reqId:r.reqId,error:u?.message||"tunnel error"}));return}if(r.ch==="control"&&r.type==="http_cancel"){Ue.get(r.reqId)?.abort();return}if(r.ch==="attach"&&r.type==="open"){let u=new on(uo+r.path,Array.isArray(r.protocols)?r.protocols:[],r.host?{headers:{host:r.host}}:void 0);pe.set(r.streamId,u),he.set(r.streamId,[]),u.on("open",()=>{let g=he.get(r.streamId)||[];he.delete(r.streamId);for(let{buf:y,bin:D}of g)u.send(y,{binary:D})}),u.on("message",(g,y)=>{let D=y?g:Buffer.from(String(g));L({v:B,ch:"attach",type:"data",streamId:r.streamId,data:D.toString("base64"),...y?{bin:!0}:{}})});let p=()=>{he.delete(r.streamId),pe.delete(r.streamId)&&L({v:B,ch:"attach",type:"close",streamId:r.streamId})};u.on("close",p),u.on("error",p);return}if(r.ch==="attach"&&r.type==="data"){let u=pe.get(r.streamId);if(!u)return;let p=Buffer.from(r.data,"base64"),g=r.bin===!0,y=he.get(r.streamId);y?y.push({buf:p,bin:g}):u.send(p,{binary:g});return}if(r.ch==="attach"&&r.type==="close"){let u=pe.get(r.streamId);pe.delete(r.streamId),he.delete(r.streamId),u?.close();return}});let l=()=>{q&&w.log("[plane-link] disconnected from plane"),q=!1,oe&&(clearInterval(oe),oe=null),se&&(clearInterval(se),se=null),N.clear(),ee={},ce=[],z&&(clearTimeout(z),z=null),Ae.clear();for(let u of pe.values())u.close();pe.clear(),he.clear();for(let u of Ue.values())u.abort();if(Ue.clear(),Nt||ke)return;Le==null&&(Le=Date.now());let a=Date.now()-Le<Bs,r=Math.max(a?js+Math.random()*Fs:Ce,De-Date.now(),Ge());ke=setTimeout(()=>{ke=null,Un()},r),ke.unref?.(),a||(Ce=Math.min(Ce*2,Ur))};Y.on("close",l),Y.on("error",a=>{let r=/Unexpected server response: (\d+)/.exec(a?.message||"")?.[1];if(r==="410"){Mt({reason:"removed",via:"410"});return}if(r==="401"||r==="403"){let{tripped:u,holdMs:p}=dt();u?w.error(`[plane-link] holding every plane call for ${Math.round(p/6e4)} min \u2014 three credential refusals in a row (HTTP ${r}) 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()-rt>=Wr&&(rt=Date.now(),w.error(`[plane-link] plane refused this node's credentials (HTTP ${r}) \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()})}Ye.on("event",Fn),fo().then(Un);function Hn({bye:s=!0}={}){Nt=!0,Ye.off("event",Fn),ke&&clearTimeout(ke),$e&&clearTimeout($e),oe&&clearInterval(oe),se&&clearInterval(se),z&&clearTimeout(z),s&&L({v:B,ch:"ctl",type:"bye",reason:"shutdown"}),Y?.close()}return{stop:()=>Hn(),status:()=>({connected:q,nodeId:n,cursor:{...ne},inflight:N.size,...Cn(),auth:er(),dormant:Be,removed:qt(),deadLinkMs:xt,deadLinkRedials:Nn,refused:{...nt}}),_tick:()=>{Dn(),Lt()}}}var Z,cn,un,B,Fr,Ur,Bs,js,Fs,ue,Us,Hs,Ks,Ws,Vr,zs,sn,Gs,Vs,Ys,Hr,qs,Kr,Xs,an,Js,Wr,dn=k(()=>{ht();jr();Ht();Xt();Z=(()=>{try{return Ls(import.meta.url)("../package.json").version||null}catch{return null}})(),cn=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||gt.tmpdir(),".bostrat"),un=U.join(cn,"plane-link","removed.json");B=1,Fr=1e3,Ur=3e4,Bs=6e4,js=1500,Fs=500,ue=100,Us=2e3,Hs=25e3,Ks=2.5,Ws=6e4,Vr=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},zs=Vr(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),sn="refused:",Gs={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"},Vs=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},Ys=3e4,Hr=10*6e4,qs=400,Kr=250,Xs=Vr(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),an=4,Js=6e4,Wr=6e4});var qr=k(()=>{Gt()});var no={};Ft(no,{ACTIONABLE_KINDS:()=>bt,INSTALL_ATTEMPTS:()=>Tt,INSTALL_RETRY_STEP_S:()=>Xr,REGISTRY_RETRY_ATTEMPTS:()=>hn,REGISTRY_WAIT_POLLS:()=>fn,REGISTRY_WAIT_STEP_S:()=>pn,RESTART_SIGNAL:()=>Zr,SELF_UPDATE_DIR:()=>_t,SUPERVISOR_PID_FILE:()=>Jr,createAutoUpdater:()=>pi,inFlight:()=>gn,readStatus:()=>yn,restartCommand:()=>Qr,restartStrategy:()=>wn,selfUpdatePlan:()=>eo,settleSelfUpdate:()=>fi,startSelfUpdate:()=>to,underService:()=>mn,updatePolicy:()=>ii});import Ze from"node:fs";import de from"node:fs/promises";import Qs from"node:os";import j from"node:path";import{spawn as ei,execFileSync as ti}from"node:child_process";import{createRequire as ni}from"node:module";function ii({kind:e=Ie(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:bt.has(e)?e==="git-checkout"||mn(t)?"auto":"prompt":"off"}function mn(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function wn({env:e=process.env,platform:t=process.platform,uid:n=typeof process.getuid=="function"?process.getuid():0,serviceName:o=t==="darwin"?"com.bostrat.node":"bostrat-node.service",pidFile:i=Jr,readFile:c=m=>Ze.readFileSync(m,"utf8"),alive:d=ai}={}){let m=t==="darwin"?{mode:"launchd",uid:n,serviceName:o}:{mode:"systemd",serviceName:o};if(mn(e))return m;let h=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(h)&&h>0)){try{h=Number(String(c(i)).trim())}catch{h=NaN}Number.isInteger(h)&&h>0&&d(h)||(h=NaN)}return Number.isInteger(h)&&h>0?{mode:"supervisor",pid:h}:m}function ai(e){try{process.kill(e,0)}catch{return!1}try{let t=ti("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 Qr(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 -${Zr.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function eo({kind:e,to:t,from:n=St,statusFile:o=vt,logFile:i=j.join(_t,"last.log"),port:c=Number(process.env.PORT)||3362,npmPrefix:d=null,serviceName:m=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:h=typeof process.getuid=="function"?process.getuid():0,restart:x=wn({env:{},platform:process.platform,uid:h,serviceName:m,readFile:()=>{throw new Error("no pidfile")}}),liveDir:f=process.env.BOSTRAT_LIVE_CHECKOUT||j.resolve(j.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:T=Date.now(),attempts:$=1}={}){if(!bt.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,S="")=>`write_status ${X(b)} ${S}`,v=Qr(x),M=`
|
|
123
|
+
`),m(0)}var Lr,Xs,wn,Ot,Kr=$(()=>{Lr="wss://plane.bostrat.ai/v1/node",Xs=Ys(import.meta.url)("../package.json").version,wn=`ghcr.io/globocodes/bostrat-node:${Xs}`;Ot=(e,{stdin:t,exec:n}={})=>new Promise((r,s)=>{if(n)return n(e,{stdin:t}).then(r,s);let a=Vs("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,h,m)=>d?s(Object.assign(d,{stdout:h,stderr:m})):r({stdout:h,stderr:m}));t!=null&&a.stdin?.end(t)})});function Gr(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!ei.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 ti(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:Gr(s.from,"from",n),toMs:Gr(s.to,"to",n)}))}return t}var Qs,ei,pu,hu,zr=$(()=>{Qs={"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)."}]},ei=/^\d{4}-\d{2}-\d{2}$/;pu=ti(Qs),hu=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var Vr=$(()=>{zr()});import Yr from"node:fs/promises";import Jr from"node:path";import ni from"node:os";function Qr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function eo(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function to(e){let t=new Date(Qr(e));return t.setDate(t.getDate()+7),t.getTime()}function no(e){let t=new Date(eo(e));return t.setMonth(t.getMonth()+1),t.getTime()}function ai(e=Date.now()){for(let[t,n]of Object.entries(si)){let r=n.startOf(e);if(r!==Rt[t]){Rt[t]=r;for(let s of yn.values())s[t]=0;for(let s of qr)s.includes(`:${t}:`)&&!s.endsWith(`:${r}`)&&qr.delete(s)}}}function ci(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 h=Number(d);if(!Number.isFinite(h)||h<=0)throw new Error(`${n}.${a} must be a positive number or null`);s[a]=h}Object.keys(s).length&&(t[n]=s)}return t}async function ro(e,{source:t="local",updatedAt:n=Date.now()}={}){Be={caps:ci(e),updatedAt:n,source:t};try{await Yr.mkdir(Zr,{recursive:!0}),await Yr.writeFile(ri(),JSON.stringify(Be,null,2))}catch{}return li()}function li(e=Date.now()){ai(e);let t=new Set([...yn.keys(),...Object.keys(Be?.caps||{})]),n={};for(let r of t){let s=yn.get(r);n[r]={weeklyUsd:Xr(s?.weekly||0),monthlyUsd:Xr(s?.monthly||0)}}return{caps:Be?.caps||{},configured:!!Be,seeded:ii,updatedAt:Be?.updatedAt??null,spent:n,windows:{weekly:{start:Rt.weekly,resetsAt:to(e)},monthly:{start:Rt.monthly,resetsAt:no(e)}},warnPct:oi}}var Zr,ri,oi,si,Be,ii,Rt,yn,qr,Xr,oo=$(()=>{kt();Vr();Zr=process.env.BOSTRAT_STATE_DIR||Jr.join(process.env.HOME||ni.tmpdir(),".bostrat"),ri=()=>Jr.join(Zr,"usage-caps.json"),oi=.8;si={weekly:{startOf:Qr,nextStart:to,capKey:"weeklyUsd"},monthly:{startOf:eo,nextStart:no,capKey:"monthlyUsd"}},Be=null,ii=!1,Rt={weekly:0,monthly:0},yn=new Map,qr=new Set;Xr=e=>Math.round(e*1e4)/1e4});var ho={};Xt(ho,{REMOVED_MARKER:()=>vn,detectInstallKind:()=>Fe,detectProviderAuth:()=>fo,maskToken:()=>bn,readRemovedMarker:()=>uo,startPlaneLink:()=>$i,updateCommandFor:()=>ut,versionLt:()=>je});import Le from"node:fs";import lt from"node:fs/promises";import ui from"node:http";import H from"node:path";import Nt from"node:os";import{createRequire as di}from"node:module";import gn from"ws";function bn(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function uo(e=vn){try{let t=JSON.parse(Le.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function Fe({env:e=process.env,pkgDir:t=H.resolve(H.dirname(new URL(import.meta.url).pathname),".."),exists:n=Le.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(H.join(t,"..",".git"))?"git-checkout":"dev"}function je(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 ut(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 fo({home:e=process.env.HOME||Nt.homedir(),env:t=process.env}={}){let n=r=>{try{return Le.statSync(r),!0}catch{return!1}};return{claude:n(H.join(e,".claude",".credentials.json")),codex:n(H.join(t.CODEX_HOME||H.join(e,".codex"),"auth.json")),cursor:n(H.join(t.XDG_CONFIG_HOME||H.join(e,".config"),"cursor","auth.json"))}}function $i({url:e,token:t,nodeId:n=Nt.hostname(),name:r=Nt.hostname(),listTracks:s,detectAgents:a=null,onTracksTransferred:d=null,onTracksMoves:h=null,sampleMetrics:m=null,deliverySample:y=null,onHashKey:f=null,onViewBase:S=null,metricsMs:R=xi,onUpdateAvailable:b=null,onUpdatePolicy:v=null,onHelloRefused:N=null,updatePolicy:k=null,installKind:E=Fe(),selfUrl:A=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:_=null,removedMarkerFile:O=vn,onRemoved:U=null,onDegraded:C=null,onRecovered:K=null,onRefused:he=null,onConnected:$e=null,ingestMode:We=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:Ke=Ti,unackedRetryMs:me=gi,pingMs:Ge=wi,deadLinkMs:ze=Math.round(Ge*yi),maxInflightEvents:ft=vi,httpTimeoutMs:x=Ai,stallBackoffMinMs:ke=bi,fetchImpl:Ee=globalThis.fetch,log:w=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=et(e);let pt=A.replace(/^http/,"ws"),Pn=new Set,Dn=i=>{let l=typeof i.latestNodeVersion=="string"?i.latestNodeVersion:null;if(!(!(l&&ee&&je(ee,l))||Pn.has(l))){Pn.add(l),w.log(`[plane-link] bostrat-node ${l} is available (this node runs ${ee}) \u2014 ${ut(E)}`);try{b?.({current:ee,latest:l,min:i.minNodeVersion??null,installKind:E,required:!!(i.minNodeVersion&&je(ee,i.minNodeVersion))})}catch(c){w.error(`[plane-link] update notice failed: ${c?.message||c}`)}}},we=new Map,ye=new Map,Lt=H.join(_n,"plane-link","cursor.json"),jt=H.join(_n,"plane-link","dead-letter.ndjson"),Cn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),re={},te={},I=new Map,ht=null,ce=null,oe=0,Ve=0,Bn=0,mt={},Ln=new Set,jn=Promise.resolve(),B="ws",Oe=0,Q=!1,ge=0,Ft=!1,Y=de,Re=new Set,le=[],z=null,q=null,X=!1,Ut=!1,Ye=so,qe=null,Ne=null,Ie=null,se=null,Te=0,Fn=0,ie=null,Ht=!1,wt=0,Xe=!1,ue=uo(O);if(ue)if(ue.tokenPreview===bn(t))Xe=!0,on({reason:ue.reason??"removed",at:ue.at??null,nodeId:ue.nodeId??n}),w.error(`[plane-link] this node was REMOVED from the plane (${ue.reason??"removed"}${ue.at?` at ${new Date(ue.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${O} to force a dial.`);else try{Le.unlinkSync(O),w.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function Wt({reason:i="removed",at:l=Date.now(),via:c="ctl"}={}){if(!Xe){Xe=!0,on({reason:i,at:l,nodeId:n,via:c});try{Le.mkdirSync(H.dirname(O),{recursive:!0}),Le.writeFileSync(O,JSON.stringify({at:l,reason:i,via:c,nodeId:n,tokenPreview:bn(t)},null,2))}catch(o){w.error(`[plane-link] could not write ${O}: ${o?.message||o}`)}w.error(`[plane-link] the plane REMOVED this node (${i}, via ${c}) \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{U?.({reason:i,at:l,via:c})}catch{}Jn({bye:!1})}}async function Eo(){try{re=JSON.parse(await lt.readFile(Lt,"utf8"))}catch{re={}}}function Un(){Ht=!0,!Ie&&(Ie=setTimeout(async()=>{if(Ie=null,!!Ht){Ht=!1;try{await lt.mkdir(H.dirname(Lt),{recursive:!0}),await lt.writeFile(Lt,JSON.stringify(re))}catch(i){w.error("[plane-link] cursor flush failed:",i?.message||i)}}},mi),Ie.unref?.())}function L(i){return!q||q.readyState!==gn.OPEN?!1:(q.send(JSON.stringify(i)),!0)}function Je(i){let l=Date.now();for(let{trackId:o,event:u}of i){let p=I.get(u.id);I.set(u.id,{trackId:o,seq:u.seq,event:u,sentAt:l,firstSentAt:p?.firstSentAt??l,retryAt:l+me,tries:(p?.tries??0)+1,nacks:p?.nacks??0})}let c=i.map(({trackId:o,event:u})=>({trackId:o,event:_i(u)}));return B==="http"?(Po(c),!0):L({v:j,ch:"events",type:"append",events:c})}function Oo(i){let l=null;for(let c of I.values())c.trackId===i&&(l==null||c.seq<l)&&(l=c.seq);return l}function Kt(i){let l=te[i];if(l==null)return;let c=Oo(i),o=c==null?l:Math.min(l,c-1);o>(re[i]??0)&&(re[i]=o,Un())}function Ze(){if(ht=Date.now(),ce!=null){let i=Date.now()-ce;w.log(`[plane-link] spine sync recovered after ${Math.round(i/1e3)}s degraded (${oe} stall redial(s))`);let l=ce;ce=null,oe=0,Ve=0,Q=!1,ge=0;try{K?.({since:l,downMs:i})}catch(c){w.error(`[plane-link] onRecovered failed: ${c?.message||c}`)}}}function Gt(i){if(!Array.isArray(i)||!i.length)return;let l=new Set;for(let c of i){let o=I.get(c);o&&(I.delete(c),(te[o.trackId]??0)<o.seq&&(te[o.trackId]=o.seq),l.add(o.trackId))}for(let c of l)Kt(c);Ze()}function Hn(i,l){Bn++;let c={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};w.error(`[plane-link] DEAD-LETTER ${i.trackId} seq ${i.seq} (${c.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${jt}`),jn=jn.then(async()=>{await lt.mkdir(H.dirname(jt),{recursive:!0}),await lt.appendFile(jt,JSON.stringify(c)+`
|
|
124
|
+
`)}).catch(o=>w.error(`[plane-link] dead-letter write failed: ${o?.message||o}`))}function Ro(i,l){if(mt[i]=(mt[i]??0)+1,Ln.has(i))return;Ln.add(i);let c=Si[i]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";w.error(`[plane-link] REFUSED by the plane (${i}) on track ${l}: events are being dropped, not stored \u2014 ${c}`);try{he?.({reason:i,trackId:l,count:mt[i],hint:c})}catch(o){w.error(`[plane-link] onRefused failed: ${o?.message||o}`)}}function zt(i,l,c,o=null){if(!Array.isArray(i)||!i.length)return;let u=new Set,p=Date.now();for(let T of i){let g=I.get(T);g&&(c?(I.delete(T),Hn(g,l),String(l).startsWith(Tn)&&Ro(String(l).slice(Tn.length),g.trackId),(te[g.trackId]??0)<g.seq&&(te[g.trackId]=g.seq),u.add(g.trackId)):(g.nacks++,g.retryAt=p+Math.max(1e3,Number(o)||me)))}for(let T of u)Kt(T);Ze()}function Wn(i=Date.now()){let l=1/0;for(let c of I.values())c.firstSentAt<l&&(l=c.firstSentAt);return l===1/0?0:i-l}function No(i){if(!ze||!i||i!==q||!Te)return!1;let l=Date.now()-Te;if(l<=ze)return!1;Fn++,w.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 Kn(){if(!X||!I.size)return;let i=Date.now(),l=Wn(i);if(l<Ke||ht!=null&&i-ht<Ke||B==="http"&&Q||Ve>i)return;oe++;let c=Math.min(ke*2**(oe-1),ao);if(ce==null){ce=i-l,w.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${I.size} event(s) in flight (${B} door) \u2014 the plane is not answering appends`);try{C?.({since:ce,unacked:I.size,oldestAgeMs:l,mode:B})}catch(o){w.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(B==="http"){Q=!0,ge=i+c,w.error(`[plane-link] ingest circuit OPEN (stall #${oe}); probing /v1/ingest/health in ${Math.round(c/1e3)}s`);return}Ve=i+c,w.error(`[plane-link] closing the link and redialing in ${Math.round(c/1e3)}s (stall redial #${oe})`);try{q?.terminate()}catch{}}function Vt(){if(!X)return;let i=Date.now();if(B==="http"&&Q)return;let l=[...I.values()].filter(o=>o.event&&o.retryAt<=i&&!(B==="http"&&Re.has(o.trackId)));if(!l.length)return;l.sort((o,u)=>o.trackId===u.trackId?o.seq-u.seq:o.trackId<u.trackId?-1:1),w.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let c=B==="http"?Y:de;if(B==="http"){let o=new Map;for(let u of l)(o.get(u.trackId)??o.set(u.trackId,[]).get(u.trackId)).push(u);for(let[,u]of o){if(Oe>=Sn)return;Je(u.slice(0,c).map(p=>({trackId:p.trackId,event:p.event})))}return}for(let o=0;o<l.length;o+=c){let u=l.slice(o,o+c).map(p=>({trackId:p.trackId,event:p.event}));if(!Je(u))return}}async function Io(i=null){for(;;){if(!X)return!1;let l=I.size<ft,c=B!=="http"||Oe<Sn&&!Q&&(!i||!Re.has(i));if(l&&c)return!0;await new Promise(o=>setTimeout(o,100))}}function Yt(){if(z=null,!X||!le.length)return;let i=le;if(le=[],B!=="http"){for(let c=0;c<i.length;c+=de)Je(i.slice(c,c+de));return}let l=new Map;for(let c of i)(l.get(c.trackId)??l.set(c.trackId,[]).get(c.trackId)).push(c);for(let[c,o]of l){if(Re.has(c)||Oe>=Sn||Q){le.push(...o);continue}for(let u=0;u<o.length;u+=Y)Je(o.slice(u,u+Y))}le.length&&!z&&(z=setTimeout(Yt,co),z.unref?.())}let Mo=i=>{let l=new Map;for(let{trackId:c,event:o}of i)(l.get(c)??l.set(c,[]).get(c)).push(o);return[...l].map(([c,o])=>({trackId:c,events:o}))},Se=(i,l,c,{progress:o})=>{let u=Date.now();for(let{event:p}of i){let T=I.get(p.id);T&&(T.nacks++,T.retryAt=u+Math.max(1e3,c||me))}o&&Ze()};async function Po(i){let l=new Set(i.map(c=>c.trackId));for(let c of l)Re.add(c);Oe++;try{let c=await Ee(`${Cn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:Mo(i)}),signal:AbortSignal.timeout(x)}),o=(Number(c.headers.get("retry-after"))||0)*1e3;if(c.status===200){let u=await c.json();Y=de;for(let g of u.results??[]){Gt(g.acked??[]);let P=(ne,G)=>{let yt=new Map;for(let _e of ne??[])(yt.get(_e.reason)??yt.set(_e.reason,[]).get(_e.reason)).push(_e.id);for(let[_e,Zn]of yt)zt(Zn,_e,G,u.retryAfterMs??null)};P(g.rejected,!0),P(g.deferred,!1)}let p=new Set,T=new Map;for(let g of Array.isArray(u.refused)?u.refused:[])!g||typeof g.id!="string"||(p.add(g.id),(T.get(g.reason)??T.set(g.reason,[]).get(g.reason)).push(g.id));for(let[g,P]of T)zt(P,`${Tn}${g}`,!0);Gt((u.discarded??[]).filter(g=>!p.has(g))),Ze();return}if(c.status===429){Se(i,"overloaded",o||5e3,{progress:!0});return}if(c.status===413&&i.length>1){Y=Math.max(1,Math.floor(i.length/2)),w.error(`[plane-link] ingest request too large (${i.length} events) \u2014 halving batches to ${Y}`),Se(i,"too_large",1e3,{progress:!0});return}if(c.status===413){let u=I.get(i[0].event.id);u&&(I.delete(u.event.id),Hn(u,"too_large"),(te[u.trackId]??0)<u.seq&&(te[u.trackId]=u.seq),Kt(u.trackId)),Ze();return}if(c.status===410){Wt({reason:"removed",via:"410"}),Se(i,"http_410",6e4,{progress:!1});return}if(c.status===401||c.status===403){let{tripped:u,holdMs:p}=At();if(u&&w.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>=lo){wt=Date.now();let T="";try{T=(await c.json())?.error??""}catch{}w.error(`[plane-link] plane refused ingest (HTTP ${c.status}${T?`: ${T}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}Se(i,`http_${c.status}`,Math.max(6e4,ot()),{progress:!1});return}if(c.status===400){w.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_${c.status}`,o||5e3,{progress:!1})}catch(c){let o=c?.name==="TimeoutError"||c?.name==="AbortError";o&&i.length>1&&(Y=Math.max(1,Math.floor(i.length/2)),w.error(`[plane-link] ingest request of ${i.length} event(s) outlived its ${x} ms deadline \u2014 halving batches to ${Y}`)),Se(i,o?"timeout":"network",5e3,{progress:!1})}finally{Oe--;for(let c of l)Re.delete(c)}}async function Do(){if(B!=="http"||!Q||!X||Ft)return;let i=Date.now();if(!(ge>i||xt(i))){Ft=!0;try{let l=await Ee(`${Cn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(x)});if(!l.ok)throw new Error(`HTTP ${l.status}`);w.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Q=!1,ge=0,Ve=Date.now()+x+me+1e3;for(let c of I.values())c.retryAt=Math.min(c.retryAt,Date.now());Vt()}catch(l){oe++;let c=Math.min(ke*2**(oe-1),ao);ge=Date.now()+c,w.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(c/1e3)}s`)}finally{Ft=!1}}}function Gn(){let i=Date.now();return{mode:B,unacked:I.size,oldestUnackedAgeMs:Wn(i),lastProgressAt:ht,degradedSince:ce,stallRedials:oe,deadLettered:Bn,http:B==="http"?{inFlight:Oe,circuitOpen:Q,nextProbeInMs:Q?Math.max(0,ge-i):0,batchCap:Y}:null}}async function zn(){if(!m)return;let i;try{i=await m()}catch(c){w.error("[plane-link] metrics sample failed:",c?.message||c);return}let l=null;try{l=y?.()??null}catch{}i&&L({v:j,ch:"ctl",type:"metrics",metrics:{...i,planeLink:Gn(),...l?{delivery:l}:{}}})}function Co(){m&&(ie&&clearInterval(ie),zn(),ie=setInterval(zn,R),ie.unref?.())}async function Bo(){let i;try{i=await s()}catch(l){w.error("[plane-link] backfill listTracks failed:",l?.message||l);return}L({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 Vn(l))return}async function Vn(i){let l;try{l=await $t(i)}catch{return!0}let c=re[i.id]??0,o=l.filter(p=>p.seq>c&&typeof p.id=="string"),u=B==="http"?Y:de;for(let p=0;p<o.length;p+=u){if(!await Io(i.id))return!1;let T=o.slice(p,p+Math.min(u,B==="http"?Y:de)).map(g=>({trackId:i.id,event:g}));if(!Je(T))return!1}return!0}let qt=new Map;async function Yn(i,l){if(qt.get(i)===l)return!1;qt.set(i,l);let c=null;try{c=(await s()).find(T=>T?.id===i)??null}catch{return!1}if(!c)return!1;let o;try{o=await $t(c)}catch{return!1}let u=[...o].reverse().find(T=>(T?.type==="track.transferred"||T?.type==="track.recovered")&&T.payload?.toNode===n);if(!u||!Number.isFinite(u.seq))return!1;let p=u.seq-1;return(re[i]??0)>p&&(re[i]=p,Un()),(te[i]??0)>p&&(te[i]=p),w.log(`[plane-link] re-sending ${i}'s move-commit (seq ${u.seq}, ${u.type}) \u2014 the plane's move record predates this node's adoption`),X?Vn(c):!1}function qn(i){!X||!i?.trackId||typeof i.id!="string"||(le.push({trackId:i.trackId,event:i}),z||(z=setTimeout(Yt,co),z.unref?.()))}let Qe=new Map;async function Lo(i){let{reqId:l,method:c,path:o,headers:u={},body:p}=i,T=Object.fromEntries(Object.entries(u).filter(([,P])=>P!=null)),g=new AbortController;Qe.set(l,g);try{if(i.host){await jo(i,T,g);return}_&&(T["x-bostrat-token"]=_);let P=await fetch(A+o,{method:c,headers:T,body:p?Buffer.from(p,"base64"):void 0,signal:g.signal}),ne=Object.fromEntries(P.headers);for(let G of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete ne[G];if(ne["content-type"]||(ne["content-type"]="application/octet-stream"),L({v:j,ch:"control",type:"http_head",reqId:l,status:P.status,headers:ne}),P.body){for await(let G of P.body)if(!L({v:j,ch:"control",type:"http_data",reqId:l,data:Buffer.from(G).toString("base64")}))break}L({v:j,ch:"control",type:"http_end",reqId:l,error:null})}finally{Qe.delete(l)}}function jo(i,l,c){let{reqId:o,method:u,path:p,body:T}=i,g=new URL(A);return new Promise(P=>{let ne=ui.request({host:g.hostname,port:g.port,method:u,path:p,headers:{...l,host:i.host},signal:c.signal},G=>{let{connection:yt,"keep-alive":_e,"transfer-encoding":Zn,upgrade:_a,...Fo}=G.headers;L({v:j,ch:"control",type:"http_head",reqId:o,status:G.statusCode||502,headers:Fo}),G.on("data",Uo=>{L({v:j,ch:"control",type:"http_data",reqId:o,data:Buffer.from(Uo).toString("base64")})||G.destroy()}),G.on("end",()=>{L({v:j,ch:"control",type:"http_end",reqId:o,error:null}),P()}),G.on("error",()=>{L({v:j,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),P()})});ne.on("error",G=>{L({v:j,ch:"control",type:"http_end",reqId:o,error:G?.message||"view request failed"}),P()}),T&&ne.write(Buffer.from(T,"base64")),ne.end()})}function Xn(){if(Ut||Xe)return;q=new gn(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 c=null;try{c=await a?.()||null}catch{c=null}L({v:j,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:ee,installKind:E,...typeof k=="function"?{updatePolicy:k()}:k?{updatePolicy:k}:{},providers:fo(),...c?{agents:c}:{}})}),q.on("message",c=>{Te=Date.now();let o;try{o=JSON.parse(c)}catch{return}if(o.ch==="ctl"&&o.type==="hello_ok"){qt.clear(),X=!0,Ye=so,qe=null,cr(),w.log(`[plane-link] connected to plane as ${n}`);try{$e?.()}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&&ee&&je(ee,o.minNodeVersion)&&w.error(`[plane-link] this node is bostrat-node ${ee}; the plane asks for \u2265${o.minNodeVersion} \u2014 update with: ${ut(E)}`);try{v?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}Dn(o);let u=o.ingest==="http";B=We==="ws"?"ws":We==="http"||u?"http":"ws",We==="http"&&!u&&w.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),B==="http"&&w.log("[plane-link] spine rides the HTTPS ingest door"),Q=!1,ge=0,Y=de,se&&clearInterval(se),Te=Date.now(),se=setInterval(()=>{No(i)||(L({v:j,ch:"ctl",type:"ping"}),Kn(),Do().catch(()=>{}),Vt(),le.length&&!z&&Yt())},Ge),se.unref?.(),Co(),Bo().catch(p=>w.error("[plane-link] backfill failed:",p?.message||p));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let u=typeof o.minNodeVersion=="string"?o.minNodeVersion:null,p=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;w.error(`[plane-link] plane REFUSED this node: bostrat-node ${ee??"?"} is below its minimum ${u??"?"} \u2014 ${o.fix||ut(E)}`),Ye=io,qe=0;try{N?.({current:ee,min:u,latest:p,fix:o.fix||ut(E),installKind:E})}catch(T){w.error(`[plane-link] refusal handler failed: ${T?.message||T}`)}return}if(o.ch==="ctl"&&o.type==="removed"){L({v:j,ch:"ctl",type:"removed_ack",nodeId:n}),Wt({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"){Dn(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==="usage_caps"){ro(o.caps??{},{source:"plane",updatedAt:o.updatedAt??Date.now()}).then(u=>w.log(`[plane-link] spend caps ${Object.keys(u.caps).length?`updated (${Object.keys(u.caps).join(", ")})`:"cleared"} from plane`)).catch(u=>w.error("[plane-link] spend-caps push rejected:",u?.message||u));return}if(o.ch==="ctl"&&o.type==="transferred"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>d?.(o.tracks)).then(async u=>{for(let p of Array.isArray(u)?u:[])p?.stale&&p.id&&await Yn(p.id,p.since??null)}).catch(u=>w.error("[plane-link] transfer notice failed:",u?.message||u));return}if(o.ch==="ctl"&&o.type==="moves"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>h?.(o.tracks)).then(async u=>{for(let p of Array.isArray(u)?u:[])p?.stale&&p.id&&await Yn(p.id,p.since??null)}).catch(u=>w.error("[plane-link] move-record reconcile failed:",u?.message||u));return}if(o.ch==="events"&&o.type==="ack"&&Array.isArray(o.ids)){Gt(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"){Lo(o).catch(u=>L({v:j,ch:"control",type:"http_end",reqId:o.reqId,error:u?.message||"tunnel error"}));return}if(o.ch==="control"&&o.type==="http_cancel"){Qe.get(o.reqId)?.abort();return}if(o.ch==="attach"&&o.type==="open"){let u=new gn(pt+o.path,Array.isArray(o.protocols)?o.protocols:[],o.host?{headers:{host:o.host}}:void 0);we.set(o.streamId,u),ye.set(o.streamId,[]),u.on("open",()=>{let T=ye.get(o.streamId)||[];ye.delete(o.streamId);for(let{buf:g,bin:P}of T)u.send(g,{binary:P})}),u.on("message",(T,g)=>{let P=g?T:Buffer.from(String(T));L({v:j,ch:"attach",type:"data",streamId:o.streamId,data:P.toString("base64"),...g?{bin:!0}:{}})});let p=()=>{ye.delete(o.streamId),we.delete(o.streamId)&&L({v:j,ch:"attach",type:"close",streamId:o.streamId})};u.on("close",p),u.on("error",p);return}if(o.ch==="attach"&&o.type==="data"){let u=we.get(o.streamId);if(!u)return;let p=Buffer.from(o.data,"base64"),T=o.bin===!0,g=ye.get(o.streamId);g?g.push({buf:p,bin:T}):u.send(p,{binary:T});return}if(o.ch==="attach"&&o.type==="close"){let u=we.get(o.streamId);we.delete(o.streamId),ye.delete(o.streamId),u?.close();return}});let l=()=>{X&&w.log("[plane-link] disconnected from plane"),X=!1,se&&(clearInterval(se),se=null),ie&&(clearInterval(ie),ie=null),I.clear(),te={},le=[],z&&(clearTimeout(z),z=null),Re.clear();for(let u of we.values())u.close();we.clear(),ye.clear();for(let u of Qe.values())u.abort();if(Qe.clear(),Ut||Ne)return;qe==null&&(qe=Date.now());let c=Date.now()-qe<fi,o=Math.max(c?pi+Math.random()*hi:Ye,Ve-Date.now(),ot());Ne=setTimeout(()=>{Ne=null,Xn()},o),Ne.unref?.(),c||(Ye=Math.min(Ye*2,io))};q.on("close",l),q.on("error",c=>{let o=/Unexpected server response: (\d+)/.exec(c?.message||"")?.[1];if(o==="410"){Wt({reason:"removed",via:"410"});return}if(o==="401"||o==="403"){let{tripped:u,holdMs:p}=At();u?w.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>=lo&&(wt=Date.now(),w.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()})}it.on("event",qn),Eo().then(Xn);function Jn({bye:i=!0}={}){Ut=!0,it.off("event",qn),Ne&&clearTimeout(Ne),Ie&&clearTimeout(Ie),se&&clearInterval(se),ie&&clearInterval(ie),z&&clearTimeout(z),i&&L({v:j,ch:"ctl",type:"bye",reason:"shutdown"}),q?.close()}return{stop:()=>Jn(),status:()=>({connected:X,nodeId:n,cursor:{...re},inflight:I.size,...Gn(),auth:lr(),dormant:Xe,removed:sn(),deadLinkMs:ze,deadLinkRedials:Fn,refused:{...mt}}),_tick:()=>{Kn(),Vt()}}}var ee,_n,vn,j,so,io,fi,pi,hi,de,mi,wi,yi,gi,po,Ti,Tn,Si,_i,bi,ao,vi,co,Ai,Sn,xi,lo,An=$(()=>{kt();oo();Zt();an();ee=(()=>{try{return di(import.meta.url)("../package.json").version||null}catch{return null}})(),_n=process.env.BOSTRAT_STATE_DIR||H.join(process.env.HOME||Nt.tmpdir(),".bostrat"),vn=H.join(_n,"plane-link","removed.json");j=1,so=1e3,io=3e4,fi=6e4,pi=1500,hi=500,de=100,mi=2e3,wi=25e3,yi=2.5,gi=6e4,po=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Ti=po(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Tn="refused:",Si={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"},_i=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},bi=3e4,ao=10*6e4,vi=400,co=250,Ai=po(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Sn=4,xi=6e4,lo=6e4});var mo=$(()=>{nn()});var bo={};Xt(bo,{ACTIONABLE_KINDS:()=>Ct,INSTALL_ATTEMPTS:()=>It,INSTALL_RETRY_STEP_S:()=>wo,REGISTRY_RETRY_ATTEMPTS:()=>kn,REGISTRY_WAIT_POLLS:()=>xn,REGISTRY_WAIT_STEP_S:()=>$n,RESTART_SIGNAL:()=>go,SELF_UPDATE_DIR:()=>Pt,SUPERVISOR_PID_FILE:()=>yo,createAutoUpdater:()=>Ui,inFlight:()=>Nn,readStatus:()=>Rn,restartCommand:()=>To,restartStrategy:()=>On,selfUpdatePlan:()=>So,settleSelfUpdate:()=>Fi,startSelfUpdate:()=>_o,underService:()=>En,updatePolicy:()=>Pi});import dt from"node:fs";import fe from"node:fs/promises";import ki from"node:os";import F from"node:path";import{spawn as Ei,execFileSync as Oi}from"node:child_process";import{createRequire as Ri}from"node:module";function Pi({kind:e=Fe(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:Ct.has(e)?e==="git-checkout"||En(t)?"auto":"prompt":"off"}function En(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function On({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=yo,readFile:a=h=>dt.readFileSync(h,"utf8"),alive:d=Di}={}){let h=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(En(e))return h;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}:h}function Di(e){try{process.kill(e,0)}catch{return!1}try{let t=Oi("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 To(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 -${go.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function So({kind:e,to:t,from:n=Mt,statusFile:r=Dt,logFile:s=F.join(Pt,"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:y=On({env:{},platform:process.platform,uid:m,serviceName:h,readFile:()=>{throw new Error("no pidfile")}}),liveDir:f=process.env.BOSTRAT_LIVE_CHECKOUT||F.resolve(F.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:S=Date.now(),attempts:R=1}={}){if(!Ct.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=(A,_="")=>`write_status ${J(A)} ${_}`,v=To(y),N=`
|
|
125
125
|
health() {
|
|
126
126
|
for i in $(seq 1 45); do
|
|
127
127
|
sleep 1
|
|
128
|
-
if curl -sf -o /dev/null "http://127.0.0.1:${
|
|
128
|
+
if curl -sf -o /dev/null "http://127.0.0.1:${a}/api/health"; then return 0; fi
|
|
129
129
|
done
|
|
130
130
|
return 1
|
|
131
|
-
}`,
|
|
131
|
+
}`,k=`#!/usr/bin/env bash
|
|
132
132
|
# bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
|
|
133
|
-
# ${n??"?"} \u2192 ${t} (${e}). Status: ${
|
|
133
|
+
# ${n??"?"} \u2192 ${t} (${e}). Status: ${r}
|
|
134
134
|
set -u
|
|
135
|
-
FROM=${
|
|
136
|
-
TO=${
|
|
137
|
-
STATUS_FILE=${
|
|
138
|
-
STARTED_AT=${Number(
|
|
139
|
-
ATTEMPTS=${Number(
|
|
135
|
+
FROM=${J(n??"")}
|
|
136
|
+
TO=${J(t)}
|
|
137
|
+
STATUS_FILE=${J(r)}
|
|
138
|
+
STARTED_AT=${Number(S)}
|
|
139
|
+
ATTEMPTS=${Number(R)||1}
|
|
140
140
|
write_status() { # <status> [error] [retryable]
|
|
141
141
|
local err="\${2:-}"
|
|
142
142
|
err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
|
|
143
143
|
printf '{"status":"%s","from":"%s","to":"%s","kind":"%s","attempts":%s,"startedAt":%s,"updatedAt":%s%s%s}\\n' \\
|
|
144
|
-
"$1" "$FROM" "$TO" ${
|
|
144
|
+
"$1" "$FROM" "$TO" ${J(e)} "$ATTEMPTS" "$STARTED_AT" "$(date +%s000)" \\
|
|
145
145
|
"\${err:+,\\"error\\":\\"$err\\"}" "\${3:+,\\"retryable\\":true}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
|
|
146
146
|
}
|
|
147
|
-
${
|
|
148
|
-
`;if(e==="npm-global"){let
|
|
149
|
-
`:"",
|
|
147
|
+
${N}
|
|
148
|
+
`;if(e==="npm-global"){let A=d?F.join(d,"bin","npm"):"npm",_=d?`export PATH=${J(F.join(d,"bin"))}:"$PATH"
|
|
149
|
+
`:"",O=d?` --prefix ${J(d)}`:"",U=he=>`${J(A)} install -g "bostrat-node@${he}" --no-audit --no-fund${O}`,C=`
|
|
150
150
|
install_target() {
|
|
151
|
-
for i in $(seq 1 ${
|
|
152
|
-
if ${
|
|
153
|
-
[ "$i" -lt ${
|
|
151
|
+
for i in $(seq 1 ${It}); do
|
|
152
|
+
if ${U("$TO")}; then return 0; fi
|
|
153
|
+
[ "$i" -lt ${It} ] && sleep ${wo}
|
|
154
154
|
done
|
|
155
155
|
return 1
|
|
156
156
|
}`,K=`
|
|
157
157
|
wait_for_registry() {
|
|
158
|
-
for i in $(seq 1 ${
|
|
159
|
-
if [ "$(${
|
|
160
|
-
sleep ${
|
|
158
|
+
for i in $(seq 1 ${xn}); do
|
|
159
|
+
if [ "$(${J(A)} view "bostrat-node@$TO" version --prefer-online 2>/dev/null)" = "$TO" ]; then return 0; fi
|
|
160
|
+
sleep ${$n}
|
|
161
161
|
done
|
|
162
162
|
return 1
|
|
163
|
-
}`;return
|
|
164
|
-
${
|
|
163
|
+
}`;return k+_+K+C+`
|
|
164
|
+
${b("updating",'"" ')}
|
|
165
165
|
if ! wait_for_registry; then
|
|
166
|
-
${
|
|
166
|
+
${b("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(xn*$n/60)} min, attempt $ATTEMPTS of ${kn})" retryable`)}
|
|
167
167
|
exit 1
|
|
168
168
|
fi
|
|
169
169
|
if ! install_target; then
|
|
170
|
-
${
|
|
170
|
+
${b("failed",`"npm install failed (${It} attempts)"`)}
|
|
171
171
|
exit 1
|
|
172
172
|
fi
|
|
173
|
-
${
|
|
173
|
+
${b("restarting")}
|
|
174
174
|
if ! ${v}; then
|
|
175
|
-
${
|
|
175
|
+
${b("failed",`"restart failed (${v.replace(/"/g,"")})"`)}
|
|
176
176
|
exit 1
|
|
177
177
|
fi
|
|
178
178
|
if health; then
|
|
@@ -180,53 +180,53 @@ if health; then
|
|
|
180
180
|
exit 0
|
|
181
181
|
fi
|
|
182
182
|
# \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
|
|
183
|
-
${
|
|
184
|
-
if [ -n "$FROM" ] && ${
|
|
185
|
-
${
|
|
183
|
+
${b("rolling-back",'"agent did not answer on :'+a+' after the update"')}
|
|
184
|
+
if [ -n "$FROM" ] && ${U("$FROM")} && ${v} && health; then
|
|
185
|
+
${b("rolled-back",'"agent did not answer on :'+a+' after the update; rolled back"')}
|
|
186
186
|
exit 1
|
|
187
187
|
fi
|
|
188
|
-
${
|
|
188
|
+
${b("failed",'"agent did not answer after the update AND the rollback"')}
|
|
189
189
|
exit 1
|
|
190
|
-
`}let E=
|
|
191
|
-
LIVE=${
|
|
190
|
+
`}let E=A=>`( cd ${J(f)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${A}" )`;return k+`
|
|
191
|
+
LIVE=${J(f)}
|
|
192
192
|
TMP_SCRIPT="$(mktemp)"
|
|
193
193
|
trap 'rm -f "$TMP_SCRIPT"' EXIT
|
|
194
194
|
# "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
|
|
195
195
|
# restart \u2192 health in one call): the agent it restarts settles "done" on boot,
|
|
196
196
|
# and nothing here may write after that boot or the settle would repeat.
|
|
197
|
-
${
|
|
197
|
+
${b("restarting")}
|
|
198
198
|
if ${E("$TO")}; then
|
|
199
199
|
exit 0
|
|
200
200
|
fi
|
|
201
|
-
${
|
|
201
|
+
${b("rolling-back",'"deploy-pi.sh v$TO failed"')}
|
|
202
202
|
if [ -n "$FROM" ] && ${E("$FROM")}; then
|
|
203
|
-
${
|
|
203
|
+
${b("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
|
|
204
204
|
exit 1
|
|
205
205
|
fi
|
|
206
|
-
${
|
|
206
|
+
${b("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
|
|
207
207
|
exit 1
|
|
208
|
-
`}async function yn(e=vt){try{return JSON.parse(await de.readFile(e,"utf8"))}catch{return null}}async function to({to:e,from:t=St,kind:n=Ie(),reason:o="manual",force:i=!1,statusFile:c=vt,spawnImpl:d=ei,now:m=Date.now,npmPrefix:h=void 0,log:x=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!bt.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Ne(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let f=await yn(c);if(gn(f))return{ok:!1,reason:`an update to ${f.to} is already in flight`,status:f};let T=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&&T<hn))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")?T+1:1;await de.mkdir(j.dirname(c),{recursive:!0});let _=h!==void 0?h:n==="npm-global"?zt(await li())||j.resolve(j.dirname(process.execPath),".."):null,v=wn(),M=eo({kind:n,to:e,from:t,statusFile:c,npmPrefix:_,startedAt:m(),attempts:$,restart:v}),O=j.join(j.dirname(c),`update-${e}.sh`),E=j.join(j.dirname(c),"last.log");await de.writeFile(O,M,{mode:448}),await de.writeFile(c,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:o,attempts:$,startedAt:m(),updatedAt:m()}));let b=Ze.existsSync("/run/systemd/system")&&await ui("systemd-run"),S=b?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",O]]:["bash",[O]],A=async R=>{let K=`could not spawn updater: ${R?.message||R}`;return await de.writeFile(c,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:o,attempts:$,startedAt:m(),updatedAt:m(),error:K})).catch(()=>{}),x.error?.(`[self-update] ${K}`),K},P=null;try{b||(P=Ze.openSync(E,"a"));let R=d(S[0],S[1],{detached:!0,stdio:b?"ignore":["ignore",P,P]});R.on?.("error",K=>{A(K)}),R.unref?.()}catch(R){return{ok:!1,reason:await A(R)}}finally{P!==null&&Ze.closeSync(P)}return x.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${o}, restart via ${v.mode}) started \u2014 status ${c}`),{ok:!0,to:e,from:t,kind:n,scriptFile:O,statusFile:c}}async function li(){try{return await de.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function ui(e){for(let t of String(process.env.PATH||"").split(j.delimiter))try{return await de.access(j.join(t,e),Ze.constants.X_OK),!0}catch{}return!1}async function fi({statusFile:e=vt,current:t=St,now:n=Date.now,staleMs:o=di}={}){let i=await yn(e);if(!i)return null;let c=d=>de.writeFile(e,JSON.stringify(d)).catch(()=>{});if(gn(i)){if(t&&i.to===t){let d={...i,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await c(d),d}if(n()-Number(i.updatedAt||i.startedAt||0)>o){let d={...i,status:"failed",error:`updater went silent while ${i.status} (no status change for ${Math.round(o/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await c(d),d}return null}if(["failed","rolled-back","done"].includes(i.status)&&!i.announced){let d={...i,announced:!0};return await c(d),d}return null}function pi({isBusy:e,start:t=to,onStuck:n=null,onStarted:o=null,tickMs:i=si,stuckMs:c=oi,now:d=Date.now,setIntervalImpl:m=setInterval,clearIntervalImpl:h=clearInterval,log:x=console}={}){let f=null,T=()=>{f?.timer&&h(f.timer),f=null},$=async()=>{if(!f)return;let _=!0;try{_=await e()!==!1}catch{_=!0}if(_){if(!f.stuckFired&&d()-f.since>=c){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let v=f;T();let M=await t({to:v.to,from:v.from,kind:v.kind,reason:"auto"});x.log?.(`[self-update] stasis reached \u2192 ${M.ok?"started":`not started: ${M.reason}`}`);try{await o?.({...v,result:M})}catch{}};return{arm({to:_,from:v=St,kind:M=Ie()}){return f?.to===_?!1:(T(),f={to:_,from:v,kind:M,since:d(),stuckFired:!1,timer:m($,i)},f.timer.unref?.(),!0)},tick:$,cancel:T,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var St,ri,_t,vt,oi,si,fn,pn,hn,Tt,Xr,Jr,Zr,bt,X,ci,gn,di,ro=k(()=>{dn();qr();St=(()=>{try{return ni(import.meta.url)("../package.json").version||null}catch{return null}})(),ri=process.env.BOSTRAT_STATE_DIR||j.join(process.env.HOME||Qs.tmpdir(),".bostrat"),_t=j.join(ri,"self-update"),vt=j.join(_t,"status.json"),oi=1440*6e4,si=6e4,fn=60,pn=15,hn=3,Tt=6,Xr=20,Jr=j.join(_t,"supervisor.pid"),Zr="SIGUSR2",bt=new Set(["npm-global","git-checkout"]);X=e=>`'${String(e).replace(/'/g,"'\\''")}'`;ci=new Set(["updating","restarting","rolling-back"]),gn=e=>!!(e&&ci.has(e.status));di=45*6e4});Ht();Wt();import H from"node:fs";import I from"node:path";import Pe from"node:os";import{createRequire as Tn}from"node:module";import{execFile as hi,spawn as mi}from"node:child_process";import{promisify as wi}from"node:util";import yi from"node:readline/promises";import{randomUUID as gi}from"node:crypto";import{fileURLToPath as Ti}from"node:url";import ds from"node:fs";import mr from"node:path";import fs from"node:os";var ps=()=>process.env.BOSTRAT_STATE_DIR||mr.join(process.env.HOME||fs.tmpdir(),".bostrat"),hs=()=>mr.join(ps(),"plane-link","public-host.json");var qe=null;function ms(){if(qe)return qe;try{let e=JSON.parse(ds.readFileSync(hs(),"utf8"));qe={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{qe={viewBase:null}}return qe}function ws(e,t){let n=String(e||"").trim();if(!n)return null;let o=/^(https?):\/\/(.+?)\/?$/i.exec(n),i=o?o[1].toLowerCase():t,c=(o?o[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return c?{proto:i,host:c}:null}function wr(){return ms().viewBase}function yr(e=process.env.BOSTRAT_PUBLIC_HOST){return ws(e,"https")}function gr(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}var oo=(e,t)=>{let n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);if(n.some(Number.isNaN)||o.some(Number.isNaN))return!1;for(let i=0;i<Math.max(n.length,o.length);i++){let c=(n[i]||0)-(o[i]||0);if(c)return c<0}return!1},fe=wi(hi),Sn=I.dirname(Ti(import.meta.url)),ve=I.resolve(Sn,".."),Si=I.join(Sn,"index.js"),_i="wss://plane.bostrat.ai/v1/node",Me=Tn(import.meta.url)("../package.json").version,F=(e,t)=>({name:e,level:"pass",detail:t}),Q=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),G=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function vi(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?F("node runtime",`${process.version} at ${process.execPath}`):G("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function bi(e){return e.BOSTRAT_OWNER?Q("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"):F("owner stamp","none (the plane infers the owner from the token)")}function Ai(e){let t;try{t=H.statSync(e)}catch{return Q("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?Q("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):F("node.env",`${e} (0600)`)}async function ki(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await fe(t,["-V"],{timeout:5e3});return F("tmux",`${t} (${n.trim()})`)}catch{return G("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function so(e,{required:t=!1}={}){if(await en(e,{loginShell:!0,failOpen:!1}))return F(e,"resolves on the login-shell PATH");let o="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",i=mt[e]?`${mt[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?G(e,o,i):Q(e,o,i)}async function $i(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await fe(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return F("gh (GitHub CLI)",n)}catch{return Q("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",mt.gh)}}async function xi(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>so(t)));return e.some(t=>t.level==="pass")||e.push(G("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 Ei(){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,o])=>await en(t,{failOpen:!1})?F(t,"resolves on the service PATH"):Q(t,`not on the service PATH \u2014 ${n}`,o)))}async function Oi(){try{let t=Tn(I.join(ve,"src","node-cli.js"))("node-pty");return await new Promise((n,o)=>{let i=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),c=setTimeout(()=>o(new Error("spawn timeout")),5e3);i.onExit(()=>{clearTimeout(c),n()})}),F("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${ve} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Tn(I.join(ve,"package.json")),o=I.join(I.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");H.existsSync(o)&&!(H.statSync(o).mode&73)&&(t=`chmod +x ${o} # node-pty ships it non-executable`)}catch{}return G("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function Ri(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(H.existsSync(t))return F("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"?G:Q)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function Ni(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?G("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"):F("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function Ii(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return Q("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,o=Date.now(),i=He(e.BOSTRAT_PLANE_URL);return await new Promise(c=>{let d=new n(i,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),m=null,h=f=>{clearTimeout(x);try{d.close()}catch{}c(m?{...f,viewBase:m}:f)},x=setTimeout(()=>h(G("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-${gi().slice(0,8)}`,ephemeral:!0}))),d.on("message",f=>{try{let T=JSON.parse(f);T.type==="hello_ok"?(typeof T.viewBase=="string"&&T.viewBase&&(m=T.viewBase),T.minNodeVersion&&oo(Me,T.minNodeVersion)?h(G("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${T.minNodeVersion} \u2014 this node is ${Me}; the real link is refused until it updates`,`bostrat-node self-update --to ${T.latestNodeVersion||T.minNodeVersion}`)):T.latestNodeVersion&&oo(Me,T.latestNodeVersion)?h(Q("plane link",`hello_ok in ${Date.now()-o}ms (${i}); bostrat-node ${T.latestNodeVersion} is available (this node: ${Me})`,`bostrat-node self-update --to ${T.latestNodeVersion}`)):h(F("plane link",`hello_ok in ${Date.now()-o}ms (${i})`))):T.type==="error"&&h(G("plane link",`plane said: ${T.code} ${T.message||""}`,"check the token"))}catch{}}),d.on("error",f=>h(G("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function Mi(){let e;try{e=JSON.parse(H.readFileSync(I.join(it,"content-outbox.json"),"utf8"))}catch{return F("content outbox","empty \u2014 every deliverable has reached the plane")}let t=e.ops?.length||0,n=e.parked?.length||0;if(n){let o=e.parked[0];return G("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${o?.op} ${o?.family}/${o?.id}: ${o?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?Q("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"):F("content outbox",t?`${t} op(s) in flight`:"drained")}function Pi(e){return e.BOSTRAT_STATE_REMOTE?F("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):Q("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 Di(e,t){let n=t?.viewBase??null,o=wr(),i=yr(e.BOSTRAT_PUBLIC_HOST),c=(()=>{let d=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(d)return`${d.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let m=gr(e.BOSTRAT_PLANE_URL);return m?`${m}/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 F("public host",`views https://<slug>.${n}/ (plane hello_ok)${d} \xB7 track links ${c}`)}return o?F("public host",`views https://<slug>.${o}/ (persisted from the last hello) \xB7 track links ${c}`):i?F("public host",`views ${i.proto}://<slug>.${i.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${c}`):G("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${c}`,"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 io(e,t={}){let n=[];n.push(await vi()),n.push(Ai(t.envFile||xe())),n.push(await ki(e)),n.push(...await xi()),n.push(await so("git",{required:!0})),n.push(await $i()),n.push(...await Ei()),n.push(await Oi()),n.push(Ri(e)),n.push(Ni(e)),n.push(bi(e));let o=await Ii(e,t);return n.push(o),n.push(Di(e,o)),n.push(Mi()),n.push(Pi(e)),n}function ao(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let c of e)t(`${n[c.level]} ${c.name}: ${c.detail}`),c.fix&&c.level!=="pass"&&t(` fix: ${c.fix}`);let o=e.filter(c=>c.level==="fail").length,i=e.filter(c=>c.level==="warn").length;return t(o?`
|
|
209
|
-
FAIL \u2014 ${
|
|
210
|
-
OK \u2014 0 blocking, ${
|
|
208
|
+
`}async function Rn(e=Dt){try{return JSON.parse(await fe.readFile(e,"utf8"))}catch{return null}}async function _o({to:e,from:t=Mt,kind:n=Fe(),reason:r="manual",force:s=!1,statusFile:a=Dt,spawnImpl:d=Ei,now:h=Date.now,npmPrefix:m=void 0,log:y=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!Ct.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!je(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let f=await Rn(a);if(Nn(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(!s&&f&&f.to===e&&(f.status==="failed"||f.status==="rolled-back")&&!(f.status==="failed"&&f.retryable===!0&&S<kn))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 R=f?.to===e&&(f.status==="failed"||f.status==="rolled-back")?S+1:1;await fe.mkdir(F.dirname(a),{recursive:!0});let b=m!==void 0?m:n==="npm-global"?tn(await Bi())||F.resolve(F.dirname(process.execPath),".."):null,v=On(),N=So({kind:n,to:e,from:t,statusFile:a,npmPrefix:b,startedAt:h(),attempts:R,restart:v}),k=F.join(F.dirname(a),`update-${e}.sh`),E=F.join(F.dirname(a),"last.log");await fe.writeFile(k,N,{mode:448}),await fe.writeFile(a,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:R,startedAt:h(),updatedAt:h()}));let A=dt.existsSync("/run/systemd/system")&&await Li("systemd-run"),_=A?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",k]]:["bash",[k]],O=async C=>{let K=`could not spawn updater: ${C?.message||C}`;return await fe.writeFile(a,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,attempts:R,startedAt:h(),updatedAt:h(),error:K})).catch(()=>{}),y.error?.(`[self-update] ${K}`),K},U=null;try{A||(U=dt.openSync(E,"a"));let C=d(_[0],_[1],{detached:!0,stdio:A?"ignore":["ignore",U,U]});C.on?.("error",K=>{O(K)}),C.unref?.()}catch(C){return{ok:!1,reason:await O(C)}}finally{U!==null&&dt.closeSync(U)}return y.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:k,statusFile:a}}async function Bi(){try{return await fe.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Li(e){for(let t of String(process.env.PATH||"").split(F.delimiter))try{return await fe.access(F.join(t,e),dt.constants.X_OK),!0}catch{}return!1}async function Fi({statusFile:e=Dt,current:t=Mt,now:n=Date.now,staleMs:r=ji}={}){let s=await Rn(e);if(!s)return null;let a=d=>fe.writeFile(e,JSON.stringify(d)).catch(()=>{});if(Nn(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 Ui({isBusy:e,start:t=_o,onStuck:n=null,onStarted:r=null,tickMs:s=Mi,stuckMs:a=Ii,now:d=Date.now,setIntervalImpl:h=setInterval,clearIntervalImpl:m=clearInterval,log:y=console}={}){let f=null,S=()=>{f?.timer&&m(f.timer),f=null},R=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 N=await t({to:v.to,from:v.from,kind:v.kind,reason:"auto"});y.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=Mt,kind:N=Fe()}){return f?.to===b?!1:(S(),f={to:b,from:v,kind:N,since:d(),stuckFired:!1,timer:h(R,s)},f.timer.unref?.(),!0)},tick:R,cancel:S,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var Mt,Ni,Pt,Dt,Ii,Mi,xn,$n,kn,It,wo,yo,go,Ct,J,Ci,Nn,ji,vo=$(()=>{An();mo();Mt=(()=>{try{return Ri(import.meta.url)("../package.json").version||null}catch{return null}})(),Ni=process.env.BOSTRAT_STATE_DIR||F.join(process.env.HOME||ki.tmpdir(),".bostrat"),Pt=F.join(Ni,"self-update"),Dt=F.join(Pt,"status.json"),Ii=1440*6e4,Mi=6e4,xn=60,$n=15,kn=3,It=6,wo=20,yo=F.join(Pt,"supervisor.pid"),go="SIGUSR2",Ct=new Set(["npm-global","git-checkout"]);J=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Ci=new Set(["updating","restarting","rolling-back"]),Nn=e=>!!(e&&Ci.has(e.status));ji=45*6e4});Zt();en();dn();import W from"node:fs";import M from"node:path";import He from"node:os";import{createRequire as In}from"node:module";import{execFile as Hi,spawn as Wi}from"node:child_process";import{promisify as Ki}from"node:util";import Gi from"node:readline/promises";import{randomUUID as zi}from"node:crypto";import{fileURLToPath as Vi}from"node:url";import Bs from"node:fs";import Rr from"node:path";import Ls from"node:os";var js=()=>process.env.BOSTRAT_STATE_DIR||Rr.join(process.env.HOME||Ls.tmpdir(),".bostrat"),Fs=()=>Rr.join(js(),"plane-link","public-host.json");var ct=null;function Us(){if(ct)return ct;try{let e=JSON.parse(Bs.readFileSync(Fs(),"utf8"));ct={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{ct={viewBase:null}}return ct}function Hs(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 Nr(){return Us().viewBase}function Ir(e=process.env.BOSTRAT_PUBLIC_HOST){return Hs(e,"https")}function Mr(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}ln();import Ws from"node:fs";import Ks from"node:os";import Pr from"node:path";var Dr=3*6e4;function hn(e=process.env){let t=e.BOSTRAT_STATE_DIR||Pr.join(e.HOME||Ks.tmpdir(),".bostrat");return Pr.join(t,"heartbeat.json")}function Cr(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return Dr;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):Dr}function Br(e=hn()){try{let t=JSON.parse(Ws.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}}var Ao=(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},pe=Ki(Hi),Mn=M.dirname(Vi(import.meta.url)),xe=M.resolve(Mn,".."),Yi=M.join(Mn,"index.js"),qi="wss://plane.bostrat.ai/v1/node",Ue=In(import.meta.url)("../package.json").version,D=(e,t)=>({name:e,level:"pass",detail:t}),Z=(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 Xi(){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 Ji(e){return e.BOSTRAT_OWNER?Z("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 Zi(e){let t;try{t=W.statSync(e)}catch{return Z("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?Z("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 Qi(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await pe(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 pn(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=Et[e]?`${Et[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):Z(e,r,s)}async function ea(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await pe(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 Z("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",Et.gh)}}async function ta(){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 na(){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 pn(t,{failOpen:!1})?D(t,"resolves on the service PATH"):Z(t,`not on the service PATH \u2014 ${n}`,r)))}async function ra(){try{let t=In(M.join(xe,"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 ${xe} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=In(M.join(xe,"package.json")),r=M.join(M.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");W.existsSync(r)&&!(W.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 oa(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(W.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:Z)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function sa(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 ia(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return Z("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=et(e.BOSTRAT_PLANE_URL);return await new Promise(a=>{let d=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),h=null,m=f=>{clearTimeout(y);try{d.close()}catch{}a(h?{...f,viewBase:h}:f)},y=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-${zi().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&&Ao(Ue,S.minNodeVersion)?m(V("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${S.minNodeVersion} \u2014 this node is ${Ue}; the real link is refused until it updates`,`bostrat-node self-update --to ${S.latestNodeVersion||S.minNodeVersion}`)):S.latestNodeVersion&&Ao(Ue,S.latestNodeVersion)?m(Z("plane link",`hello_ok in ${Date.now()-r}ms (${s}); bostrat-node ${S.latestNodeVersion} is available (this node: ${Ue})`,`bostrat-node self-update --to ${S.latestNodeVersion}`)):m(D("plane link",`hello_ok in ${Date.now()-r}ms (${s})`))):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 aa(){let e;try{e=JSON.parse(W.readFileSync(M.join(Tt,"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?Z("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 ca(e){let t=await vr({env:e}),n=Ar(t);return t.available?D("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?Z("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)}function la(e){return e.BOSTRAT_STATE_REMOTE?D("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):Z("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 ua(e,t){let n=t?.viewBase??null,r=Nr(),s=Ir(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=Mr(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=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 $o(e,t={}){let n=[];n.push(await Xi()),n.push(Zi(t.envFile||Me())),n.push(await Qi(e)),n.push(await ca(e)),n.push(...await ta()),n.push(await xo("git",{required:!0})),n.push(await ea()),n.push(...await na()),n.push(await ra()),n.push(oa(e)),n.push(sa(e)),n.push(Ji(e));let r=await ia(e,t);return n.push(r),n.push(ua(e,r)),n.push(aa()),n.push(la(e)),n}function ko(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let a of e)t(`${n[a.level]} ${a.name}: ${a.detail}`),a.fix&&a.level!=="pass"&&t(` fix: ${a.fix}`);let r=e.filter(a=>a.level==="fail").length,s=e.filter(a=>a.level==="warn").length;return t(r?`
|
|
209
|
+
FAIL \u2014 ${r} blocking, ${s} warnings`:`
|
|
210
|
+
OK \u2014 0 blocking, ${s} warnings`),r===0}async function da({envFile:e=Me(),input:t=process.stdin,output:n=process.stdout}={}){let r=St(e),s=Gi.createInterface({input:t,output:n}),a=async(A,_)=>(await s.question(_?`${A} [${_}]: `:`${A}: `)).trim()||_||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
|
|
211
211
|
you type those inside each box, later (box-auth-policy).
|
|
212
212
|
|
|
213
|
-
`);let d=await
|
|
214
|
-
`);let
|
|
215
|
-
`);let
|
|
213
|
+
`);let d=await a("Plane URL",r.BOSTRAT_PLANE_URL||qi),h=et(d);h!==d.trim()&&n.write(` \u2192 using ${h}
|
|
214
|
+
`);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 y=await a("Node name",r.BOSTRAT_NODE_NAME||He.hostname().split(".")[0]),f=await a("Repos root",r.BOSTRAT_REPOS_ROOT||M.join(He.homedir(),"Documents")),S=await a("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),R=(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");R&&n.write(`
|
|
216
216
|
BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
|
|
217
217
|
injected per box, stored 0600 in node.env, never sent to the plane.
|
|
218
218
|
\u2022 create/copy a key: https://console.anthropic.com/settings/keys
|
|
219
219
|
\u2022 set a monthly spend limit while you're there \u2014 the key is live.
|
|
220
220
|
|
|
221
|
-
`);let
|
|
222
|
-
`),
|
|
221
|
+
`);let b=R?await a("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";R&&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.
|
|
222
|
+
`),s.close();let v={...tr(),...r,BOSTRAT_PLANE_URL:h,BOSTRAT_PLANE_TOKEN:m,BOSTRAT_NODE_NAME:y,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||y,BOSTRAT_REPOS_ROOT:f,BOSTRAT_STATE_REMOTE:S,BOSTRAT_CLAUDE_USE_API_KEY:R?"1":"0",ANTHROPIC_API_KEY:R?b:r.ANTHROPIC_API_KEY};delete v.BOSTRAT_OWNER,er(e,v,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
|
|
223
223
|
0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
|
|
224
224
|
Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
|
|
225
225
|
wrote ${e}
|
|
226
226
|
|
|
227
|
-
`);let
|
|
228
|
-
`));return E&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:E,results:
|
|
229
|
-
`)}catch{}let
|
|
227
|
+
`);let N={...v,...process.env},k=await $o(N,{envFile:e}),E=ko(k,A=>n.write(A+`
|
|
228
|
+
`));return E&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:E,results:k}}var fa="SIGUSR2",pa=5*6e4,ha=1e4,Bt=M.join(Tt,"self-update","supervisor.pid");function ma({spawnChild:e,exit:t=y=>process.exit(y),now:n=Date.now,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:s=clearTimeout,killGraceMs:a=15e3,rollbackGraceMs:d=pa,stall:h=null,log:m=console}={}){let y=null,f=0,S=!1,R="update",b=0,v=null,N=null,k=null,E=0,A=0,_=!1,O=h&&h.staleMs>0?h.staleMs:0,U=h?.checkMs>0?h.checkMs:ha,C=()=>{v&&s(v),v=null},K=()=>{y.kill("SIGTERM"),N=r(()=>y?.kill("SIGKILL"),a),N.unref?.()},he=null,$e=0,We=()=>{let x=null;try{x=h.readHeartbeat()}catch{}return x&&x.pid===y.pid&&Number.isFinite(x.ts)&&x.ts!==he&&(he=x.ts,$e=Math.max($e,Math.min(x.ts,n()))),n()-$e},Ke=()=>{if(!y||_||S||!O)return!1;let x=We();return x<O?!1:(A++,m.error?.(`[bostrat-node] the agent (pid ${y.pid}) has written no heartbeat for ${Math.round(x/1e3)} s \u2014 stalled; relaunching it in place (boxes keep running on the host tmux server; stall relaunch #${A})`),R="stall",S=!0,K(),!0)},me=()=>{O&&(k&&s(k),k=r(()=>{k=null,Ke(),me()},U),k.unref?.())},Ge=()=>{let x=e();return y=x,f=n(),he=null,$e=f,x.on("exit",(ke,Ee)=>ze(x,ke,Ee)),k||me(),x},ze=(x,ke,Ee)=>{if(x!==y)return;if(y=null,N&&s(N),N=null,S){S=!1,ft(R);return}let w=Ee?1:ke??1;if(!_&&w!==0&&n()<b){let pt=b-n();m.error?.(`[bostrat-node] the agent exited (code ${w}) right after a self-update restart \u2014 holding ${Math.ceil(pt/1e3)} s for the updater's rollback signal`),v=r(()=>t(w),pt);return}t(w)},ft=(x="update")=>{E++,x==="stall"?m.log?.(`[bostrat-node] relaunched the agent after a stall (restart #${E}, stall relaunch #${A})`):(b=n()+d,m.log?.(`[bostrat-node] restarting the agent (self-update, restart #${E})`)),R="update",Ge()};return{start:Ge,restart(){if(_=!1,C(),R="update",!y){ft("update");return}S||(S=!0,K())},checkStall:Ke,forward(x){_=!0,y?y.kill(x):(C(),t(1))},get child(){return y},get state(){return{alive:!!y,restartPending:S,restartReason:R,holding:!!v,restarts:E,stallRelaunches:A,stopping:_}}}}function wa({envFile:e=Me()}={}){Qn(e),process.title="bostrat-node";let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n={...process.env,BOSTRAT_RUN_SUPERVISOR_PID:String(process.pid)};try{W.mkdirSync(M.dirname(Bt),{recursive:!0}),W.writeFileSync(Bt,`${process.pid}
|
|
229
|
+
`)}catch{}let r=Cr(process.env),s=hn(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=ma({spawnChild:()=>Wi(t,[Yi],{cwd:xe,stdio:"inherit",env:n}),stall:r?{readHeartbeat:()=>Br(s),staleMs:r}:null});for(let d of["SIGINT","SIGTERM"])process.on(d,()=>a.forward(d));return process.on(fa,()=>a.restart()),process.on("exit",()=>{try{W.readFileSync(Bt,"utf8").trim()===String(process.pid)&&W.rmSync(Bt,{force:!0})}catch{}}),a.start()}function ya({agentDir:e=xe,nodeBin:t=process.execPath,envFile:n=Me(),home:r=He.homedir()}={}){let s=M.dirname(t),a=M.join(M.basename(Mn),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
|
|
230
230
|
# ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
|
|
231
231
|
[Unit]
|
|
232
232
|
Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
|
|
@@ -236,17 +236,17 @@ After=default.target
|
|
|
236
236
|
Type=simple
|
|
237
237
|
WorkingDirectory=${e}
|
|
238
238
|
# Pinned runtime: node-pty is compiled against exactly this node (SEGV trap).
|
|
239
|
-
ExecStart=${t} --disable-warning=ExperimentalWarning ${
|
|
239
|
+
ExecStart=${t} --disable-warning=ExperimentalWarning ${a}
|
|
240
240
|
EnvironmentFile=${n}
|
|
241
241
|
# systemd's user PATH omits ~/.local/bin (cursor-agent, bostrat-view) and the
|
|
242
242
|
# nvm bin dir \u2014 both are load-bearing for box spawning.
|
|
243
|
-
Environment=PATH=${
|
|
243
|
+
Environment=PATH=${r}/.local/bin:${s}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
|
244
244
|
Restart=on-failure
|
|
245
245
|
RestartSec=2
|
|
246
246
|
|
|
247
247
|
[Install]
|
|
248
248
|
WantedBy=default.target
|
|
249
|
-
`}function
|
|
249
|
+
`}function ga({agentDir:e=xe,nodeBin:t=process.execPath,home:n=He.homedir()}={}){let r=M.dirname(t),s=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
|
|
250
250
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
251
251
|
<plist version="1.0">
|
|
252
252
|
<dict>
|
|
@@ -260,15 +260,15 @@ WantedBy=default.target
|
|
|
260
260
|
<key>WorkingDirectory</key><string>${e}</string>
|
|
261
261
|
<key>EnvironmentVariables</key>
|
|
262
262
|
<dict>
|
|
263
|
-
<key>PATH</key><string>${n}/.local/bin:${
|
|
263
|
+
<key>PATH</key><string>${n}/.local/bin:${r}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
|
|
264
264
|
</dict>
|
|
265
265
|
<key>RunAtLoad</key><true/>
|
|
266
266
|
<key>KeepAlive</key><true/>
|
|
267
|
-
<key>StandardOutPath</key><string>${
|
|
268
|
-
<key>StandardErrorPath</key><string>${
|
|
267
|
+
<key>StandardOutPath</key><string>${s}/node.out.log</string>
|
|
268
|
+
<key>StandardErrorPath</key><string>${s}/node.err.log</string>
|
|
269
269
|
</dict>
|
|
270
270
|
</plist>
|
|
271
|
-
`}function
|
|
271
|
+
`}function Ta(e=process.platform,t=He.homedir()){return e==="darwin"?{kind:"launchd",file:M.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:M.join(t,".config","systemd","user","bostrat-node.service")}}async function Sa({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:s=xe}={}){let{kind:a,file:d}=Ta(n);if(!e&&s.split(M.sep).includes("_npx"))return r("\u2717 running from the npx cache \u2014 a service must point at a durable install."),r(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){a==="systemd"?(await pe("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),W.rmSync(d,{force:!0}),await pe("systemctl",["--user","daemon-reload"])):(await pe("launchctl",["unload","-w",d]).catch(()=>{}),W.rmSync(d,{force:!0})),r(`removed ${d}`);return}W.mkdirSync(M.dirname(d),{recursive:!0}),a==="systemd"?(W.writeFileSync(d,ya()),await pe("systemctl",["--user","daemon-reload"]),t&&await pe("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${d}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(W.mkdirSync(M.join(He.homedir(),"Library","Logs","bostrat"),{recursive:!0}),W.writeFileSync(d,ga()),t&&await pe("launchctl",["load","-w",d]),r(`installed ${d}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function pd(e=process.argv.slice(2)){let t=e[0],n=Me();if(t==="--version"||t==="-v"||t==="version")return console.log(Ue),0;if(t==="init")return(await da({envFile:n})).ok?0:1;if(t==="doctor"){let r={...St(n),...process.env};return ko(await $o(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return wa({envFile:n}),null;if(t==="install-service")return await Sa({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(Kr(),Wr));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:s,updatePolicy:a}=await Promise.resolve().then(()=>(vo(),bo)),{detectInstallKind:d}=await Promise.resolve().then(()=>(An(),ho)),h=d(),m=e.indexOf("--to"),y=m>=0?String(e[m+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Ue,installKind:h,policy:a({kind:h}),status:await s()},null,2)),0;if(!y)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:y,kind:h,reason:"cli",force:!0});return f.ok?(console.log(`\u2713 self-update ${f.from??"?"} \u2192 ${f.to} started (${f.kind}) \u2014 status: ${f.statusFile}; the node restarts when the install completes`),0):(console.error(`\u2717 not started: ${f.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
|
|
272
272
|
|
|
273
273
|
usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
|
|
274
274
|
|
|
@@ -277,4 +277,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
|
|
|
277
277
|
run start the node in the foreground (sources node.env)
|
|
278
278
|
install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
|
|
279
279
|
fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
|
|
280
|
-
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{
|
|
280
|
+
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{fa as RESTART_SIGNAL,pa as ROLLBACK_GRACE_MS,ha as STALL_CHECK_MS,Bt as SUPERVISOR_PID_FILE,ma as createRunSupervisor,da as init,Sa as installService,ga as launchdPlist,pd as main,ko as printDoctor,wa as runAgent,$o as runDoctor,Ta as servicePaths,ya as systemdUnit};
|