bostrat-node 1.16.0 → 1.16.2

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