bostrat-node 1.14.10 → 1.14.11

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