bostrat-node 1.13.0 → 1.13.2

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