bostrat-node 1.11.7 → 1.12.1

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 +26 -26
  2. package/dist/index.js +228 -223
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
- var ho=Object.defineProperty;var b=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var It=(e,t)=>{for(var n in t)ho(e,n,{get:t[n],enumerable:!0})};import tt from"node:fs";import Mt from"node:path";import mo 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}`,r;try{r=new URL(n)}catch{return t}let i={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return i?(r.protocol=i,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function nt(e){let t;try{t=tt.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
1
+ var mo=Object.defineProperty;var v=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var It=(e,t)=>{for(var n in t)mo(e,n,{get:t[n],enumerable:!0})};import tt from"node:fs";import Mt from"node:path";import wo 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}`,r;try{r=new URL(n)}catch{return t}let i={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return i?(r.protocol=i,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function nt(e){let t;try{t=tt.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
2
2
  `)){let i=r.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 Mn(e,t=process.env){let n=nt(e);for(let[r,i]of Object.entries(n))r in t||(t[r]=i);return n}function Pn(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
3
3
  `).map(i=>i?`# ${i}`:"#"));for(let[i,c]of Object.entries(t))c==null||c===""||r.push(`${i}=${c}`);tt.mkdirSync(Mt.dirname(e),{recursive:!0}),tt.writeFileSync(e,r.join(`
4
4
  `)+`
5
- `,{mode:384}),tt.chmodSync(e,384)}function Dn(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 Pt,$e,Dt=b(()=>{Pt=process.env.BOSTRAT_STATE_DIR||Mt.join(process.env.HOME||mo.tmpdir(),".bostrat"),$e=()=>Mt.join(Pt,"node.env")});var we,rt,ot=b(()=>{we="BOSTRAT_HOOK_TOKEN",rt="x-bostrat-hook"});var Ln=b(()=>{ot()});var wo,Bi,Bn=b(()=>{wo="check_for_update_on_startup",Bi=`${wo} = false`});import yo from"node:os";import Cn from"node:path";var go,Hi,Ki,Lt=b(()=>{Bt();go=process.env.BOSTRAT_DEBUG_DIR||Cn.join(yo.homedir(),".bostrat","debug"),Hi=Cn.join(go,"handoff.jsonl"),Ki=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as _o}from"node:child_process";import{promisify as So}from"node:util";function Ct(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var qi,Xi,Ji,Zi,jt=b(()=>{Lt();qi=So(_o),Xi=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Ji=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,Zi=Promise.resolve()});var jn=b(()=>{});import Ft from"node:path";import{execFile as bo}from"node:child_process";import{promisify as vo}from"node:util";var oa,Fn,Ao,sa,ia,Un=b(()=>{oa=vo(bo),Fn=process.env.HOME||"/home/globo",Ao=Ft.join(process.env.BOSTRAT_STATE_DIR||Ft.join(Fn,".bostrat"),"repos"),sa=[...(process.env.BOSTRAT_REPOS_ROOT||Ft.join(Fn,"Documents")).split(","),Ao].map(e=>e.trim()).filter(Boolean),ia=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 Hn(){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 Ut(e={}){ge={at:Date.now(),...e},ye=1/0}function Ht(){return ge}function Kn(e=Date.now()){return{held:ct(e),holdMs:ge?null:Ke(e),holds:it,removed:ge?{...ge}:null}}var ko,st,Ue,He,it,ye,ge,Kt=b(()=>{ko={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},st={...ko},Ue=0,He=0,it=0,ye=0,ge=null});import Wn from"node:path";import $o from"node:os";import{execFile as xo}from"node:child_process";import{promisify as Eo}from"node:util";var wa,Oo,ya,ga,Ta,Wt=b(()=>{Un();Kt();wa=Eo(xo),Oo=process.env.BOSTRAT_STATE_DIR||Wn.join(process.env.HOME||$o.tmpdir(),".bostrat"),ya=Wn.join(Oo,"repos"),ga=5*6e4,Ta=10*6e4});var zn=b(()=>{Wt()});import No from"node:fs/promises";import We from"node:path";import Io from"node:os";import{EventEmitter as Mo}from"node:events";function Po(e){return e?.cwd?We.join(e.cwd,".bostrat","events"):We.join(Yn,"events")}async function zt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?We.join(Yn,"events"):Po(e));let i;try{i=await No.readFile(Do(n,r),"utf8")}catch{return[]}let c=[];for(let d of i.split(`
6
- `))if(d.trim())try{c.push(JSON.parse(Bo(d)?Co(d):d))}catch{}return c}var ze,Yn,Do,Lo,Bo,Co,lt=b(()=>{ze=new Mo;ze.setMaxListeners(0);Yn=process.env.BOSTRAT_STATE_DIR||We.join(process.env.HOME||Io.tmpdir(),".bostrat");Do=(e,t)=>We.join(e,`${t}.ndjson`),Lo=/(?<!\\)((?:\\\\)*)\\u0000/g,Bo=e=>e.includes("\\u0000"),Co=e=>e.replace(Lo,"$1\\ufffd")});import Fo from"node:os";import Uo from"node:path";import{execFile as Ho}from"node:child_process";import{promisify as Ko}from"node:util";var La,Ba,Ca,ja,Fa,Ua,Gn=b(()=>{zn();lt();La=Ko(Ho),Ba=process.env.BOSTRAT_STATE_DIR||Uo.join(process.env.HOME||Fo.tmpdir(),".bostrat"),Ca=25*1024,ja=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,Fa=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,Ua=Promise.resolve()});var Vn=b(()=>{});var Ga,qn=b(()=>{Wt();Vn();Ga=60*6e4});var Xn=b(()=>{qn()});import Jn from"node:path";import Wo from"node:os";var ut,zo,sc,Zn,ic,ac,Qn=b(()=>{ot();ut="BOSTRAT_NODE_URL",zo=process.env.BOSTRAT_STATE_DIR||Jn.join(process.env.HOME||Wo.tmpdir(),".bostrat"),sc=Jn.join(zo,"git-hooks"),Zn=`#!/bin/sh
5
+ `,{mode:384}),tt.chmodSync(e,384)}function Dn(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 Pt,$e,Dt=v(()=>{Pt=process.env.BOSTRAT_STATE_DIR||Mt.join(process.env.HOME||wo.tmpdir(),".bostrat"),$e=()=>Mt.join(Pt,"node.env")});var we,rt,ot=v(()=>{we="BOSTRAT_HOOK_TOKEN",rt="x-bostrat-hook"});var Cn=v(()=>{ot()});var yo,Li,Bn=v(()=>{yo="check_for_update_on_startup",Li=`${yo} = false`});import go from"node:os";import Ln from"node:path";var To,Ki,Wi,Ct=v(()=>{Bt();To=process.env.BOSTRAT_DEBUG_DIR||Ln.join(go.homedir(),".bostrat","debug"),Ki=Ln.join(To,"handoff.jsonl"),Wi=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as So}from"node:child_process";import{promisify as vo}from"node:util";function Lt(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Xi,Ji,Zi,Qi,jt=v(()=>{Ct();Xi=vo(So),Ji=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Zi=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,Qi=Promise.resolve()});var jn=v(()=>{});import Ft from"node:path";import{execFile as bo}from"node:child_process";import{promisify as Ao}from"node:util";var sa,Fn,ko,ia,aa,Un=v(()=>{sa=Ao(bo),Fn=process.env.HOME||"/home/globo",ko=Ft.join(process.env.BOSTRAT_STATE_DIR||Ft.join(Fn,".bostrat"),"repos"),ia=[...(process.env.BOSTRAT_REPOS_ROOT||Ft.join(Fn,"Documents")).split(","),ko].map(e=>e.trim()).filter(Boolean),aa=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 Hn(){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 Ut(e={}){ge={at:Date.now(),...e},ye=1/0}function Ht(){return ge}function Kn(e=Date.now()){return{held:ct(e),holdMs:ge?null:Ke(e),holds:it,removed:ge?{...ge}:null}}var $o,st,Ue,He,it,ye,ge,Kt=v(()=>{$o={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},st={...$o},Ue=0,He=0,it=0,ye=0,ge=null});import Wn from"node:path";import xo from"node:os";import{execFile as Eo}from"node:child_process";import{promisify as Oo}from"node:util";var ya,Ro,ga,Ta,_a,Wt=v(()=>{Un();Kt();ya=Oo(Eo),Ro=process.env.BOSTRAT_STATE_DIR||Wn.join(process.env.HOME||xo.tmpdir(),".bostrat"),ga=Wn.join(Ro,"repos"),Ta=5*6e4,_a=10*6e4});var zn=v(()=>{Wt()});import Io from"node:fs/promises";import We from"node:path";import Mo from"node:os";import{EventEmitter as Po}from"node:events";function Do(e){return e?.cwd?We.join(e.cwd,".bostrat","events"):We.join(Vn,"events")}async function zt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?We.join(Vn,"events"):Do(e));let i;try{i=await Io.readFile(Co(n,r),"utf8")}catch{return[]}let c=[];for(let d of i.split(`
6
+ `))if(d.trim())try{c.push(JSON.parse(Lo(d)?jo(d):d))}catch{}return c}var ze,Vn,Co,Bo,Lo,jo,lt=v(()=>{ze=new Po;ze.setMaxListeners(0);Vn=process.env.BOSTRAT_STATE_DIR||We.join(process.env.HOME||Mo.tmpdir(),".bostrat");Co=(e,t)=>We.join(e,`${t}.ndjson`),Bo=/(?<!\\)((?:\\\\)*)\\u0000/g,Lo=e=>e.includes("\\u0000"),jo=e=>e.replace(Bo,"$1\\ufffd")});import Uo from"node:os";import Ho from"node:path";import{execFile as Ko}from"node:child_process";import{promisify as Wo}from"node:util";var Ba,La,ja,Fa,Ua,Ha,Yn=v(()=>{zn();lt();Ba=Wo(Ko),La=process.env.BOSTRAT_STATE_DIR||Ho.join(process.env.HOME||Uo.tmpdir(),".bostrat"),ja=25*1024,Fa=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,Ua=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,Ha=Promise.resolve()});var Gn=v(()=>{});var Ga,qn=v(()=>{Wt();Gn();Ga=60*6e4});var Xn=v(()=>{qn()});import Jn from"node:path";import zo from"node:os";var ut,Vo,ic,Zn,ac,cc,Qn=v(()=>{ot();ut="BOSTRAT_NODE_URL",Vo=process.env.BOSTRAT_STATE_DIR||Jn.join(process.env.HOME||zo.tmpdir(),".bostrat"),ic=Jn.join(Vo,"git-hooks"),Zn=`#!/bin/sh
7
7
  # bostrat git hook shim (agent/src/git-hooks.js) \u2014 chains to the repo's own hook,
8
8
  # then stamps/reports for rework attribution when running inside a bostrat box.
9
9
  hook=$(basename "$0")
@@ -18,7 +18,7 @@ esac
18
18
  if [ -x "$orig/$hook" ] && [ "$orig/$hook" != "$0" ]; then
19
19
  "$orig/$hook" "$@" || exit $?
20
20
  fi
21
- `,ic=`${Zn}
21
+ `,ac=`${Zn}
22
22
  # \u2500\u2500 bostrat: append provenance trailers (Layer 0). Skipped for merge commits
23
23
  # (nobody "wrote" a merge) and outside a box (no token / no node url).
24
24
  [ -z "$${we}" ] && exit 0
@@ -30,7 +30,7 @@ printf '%s\\n' "$trailers" | while IFS= read -r line; do
30
30
  [ -n "$line" ] && git interpret-trailers --in-place --if-exists addIfDifferent --trailer "$line" "$1" >/dev/null 2>&1 || true
31
31
  done
32
32
  exit 0
33
- `,ac=`${Zn}
33
+ `,cc=`${Zn}
34
34
  # \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
35
35
  [ -z "$${we}" ] && exit 0
36
36
  [ -z "$${ut}" ] && exit 0
@@ -39,7 +39,7 @@ cwd=$(git rev-parse --show-toplevel 2>/dev/null)
39
39
  printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${ut}/api/git/committed" \\
40
40
  -H 'content-type: application/json' -H "${rt}: $${we}" --data-binary @- >/dev/null 2>&1 || true
41
41
  exit 0
42
- `});import{execFile as Yo}from"node:child_process";import{promisify as Go}from"node:util";import Vo from"node:fs";function nr(e){return`/tmp/tmux-${e}/default`}function Xo({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let i=nr(r);return t?i:n?`${n}/bostrat/tmux-default`:i}async function Gt(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Zo(e,{loginShell:t});return r===rr?!0:r===Yt?!1:n}async function Zo(e,{loginShell:t=!1,timeoutMs:n=Jo}={}){if(!e)return Yt;let r=t?process.env.SHELL||"/bin/sh":"sh",i=t?"-lic":"-c";try{return await qo(r,[i,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),rr}catch(c){return c?.killed||c?.signal?tr:c?.code===1||c?.code===127?Yt:tr}}var qo,Ic,er,Mc,Pc,Dc,Lc,rr,Yt,tr,Jo,dt,Bc,Cc,jc,Fc,Uc,Bt=b(()=>{Ln();Bn();jt();jn();Gn();Xn();Lt();ot();Qn();qo=Go(Yo),Ic=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";er=typeof process.getuid=="function"?process.getuid():0,Mc=Xo({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Vo.existsSync(nr(er))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:er}),Pc=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Dc=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Lc=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]);rr="present",Yt="absent",tr="unknown",Jo=5e3;dt={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"},Bc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Cc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,jc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Fc=Number(process.env.BOSTRAT_BOX_COLS)||120,Uc=Number(process.env.BOSTRAT_BOX_ROWS)||40});var pr={};It(pr,{NODE_IMAGE:()=>qt,commandPlan:()=>ur,flyToml:()=>lr,flyWizard:()=>fs,parseFlyFlags:()=>dr,stageConfig:()=>fr});import Vt from"node:fs";import Te from"node:path";import ss from"node:os";import is from"node:readline/promises";import{execFile as as}from"node:child_process";import{createRequire as cs}from"node:module";import{randomUUID as ls}from"node:crypto";function lr({app:e,region:t,nodeName:n=e,planeUrl:r=cr,image:i=qt}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
42
+ `});import{execFile as Yo}from"node:child_process";import{promisify as Go}from"node:util";import nr from"node:fs";import qo from"node:os";function rr(e){return`/tmp/tmux-${e}/default`}function Jo({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let i=rr(r);return t?i:n?`${n}/bostrat/tmux-default`:i}async function Yt(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Qo(e,{loginShell:t});return r===or?!0:r===Vt?!1:n}async function Qo(e,{loginShell:t=!1,timeoutMs:n=Zo}={}){if(!e)return Vt;let r=t?process.env.SHELL||"/bin/sh":"sh",i=t?"-lic":"-c";try{return await Xo(r,[i,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),or}catch(c){return c?.killed||c?.signal?tr:c?.code===1||c?.code===127?Vt:tr}}var Xo,Pc,er,Dc,Cc,Bc,Lc,jc,or,Vt,tr,Zo,dt,Fc,Uc,Hc,Kc,Wc,zc,Bt=v(()=>{Cn();Bn();jt();jn();Yn();Xn();Ct();ot();Qn();Xo=Go(Yo),Pc=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";er=typeof process.getuid=="function"?process.getuid():0,Dc=Jo({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return nr.existsSync(rr(er))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:er}),Cc=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Bc=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Lc=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),jc=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);or="present",Vt="absent",tr="unknown",Zo=5e3;dt={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"},Fc=(()=>{try{let e=qo.homedir();if(e&&nr.existsSync(e))return e}catch{}return"/"})(),Uc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Hc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Kc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Wc=Number(process.env.BOSTRAT_BOX_COLS)||120,zc=Number(process.env.BOSTRAT_BOX_ROWS)||40});var hr={};It(hr,{NODE_IMAGE:()=>qt,commandPlan:()=>dr,flyToml:()=>ur,flyWizard:()=>ps,parseFlyFlags:()=>fr,stageConfig:()=>pr});import Gt from"node:fs";import Te from"node:path";import is from"node:os";import as from"node:readline/promises";import{execFile as cs}from"node:child_process";import{createRequire as ls}from"node:module";import{randomUUID as us}from"node:crypto";function ur({app:e,region:t,nodeName:n=e,planeUrl:r=lr,image:i=qt}){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,20 +79,20 @@ 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 ur({app:e,org:t,region:n,sizeGb:r,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(r),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${r} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted> via stdin`,stdin:d.join(`
82
+ `}function dr({app:e,org:t,region:n,sizeGb:r,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(r),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${r} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted> via stdin`,stdin:d.join(`
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 dr(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--image":"image"};for(let r=0;r<e.length;r++){let i=e[r];if(i==="--yes"||i==="-y")t.yes=!0;else if(n[i])t[n[i]]=e[++r]??"";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 fr({app:e,dest:t,toml:n}){let r=t||Te.join(ss.homedir(),".bostrat","fly",e);Vt.mkdirSync(r,{recursive:!0});for(let i of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])Vt.rmSync(Te.join(r,i),{recursive:!0,force:!0});return Vt.writeFileSync(Te.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function ds({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:i}=await ft(["orgs","list","--json"],{exec:n}),c=JSON.parse(i),d=Array.isArray(c)?c.map(p=>p.Slug||p.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 fs({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:i}={}){let c=dr(e),d=is.createInterface({input:t,output:n}),p=async(S,j)=>(await d.question(j?`${S} [${j}]: `:`${S}: `)).trim()||j||"",T=S=>(d.close(),S);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
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 fr(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--image":"image"};for(let r=0;r<e.length;r++){let i=e[r];if(i==="--yes"||i==="-y")t.yes=!0;else if(n[i])t[n[i]]=e[++r]??"";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 pr({app:e,dest:t,toml:n}){let r=t||Te.join(is.homedir(),".bostrat","fly",e);Gt.mkdirSync(r,{recursive:!0});for(let i of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])Gt.rmSync(Te.join(r,i),{recursive:!0,force:!0});return Gt.writeFileSync(Te.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function fs({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:i}=await ft(["orgs","list","--json"],{exec:n}),c=JSON.parse(i),d=Array.isArray(c)?c.map(p=>p.Slug||p.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 ps({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:i}={}){let c=fr(e),d=as.createInterface({input:t,output:n}),p=async(S,j)=>(await d.question(j?`${S} [${j}]: `:`${S}: `)).trim()||j||"",T=S=>(d.close(),S);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
88
  `);try{await ft(["version"],{exec:r})}catch{return n.write("\u2717 `fly` (flyctl) is not installed or not on PATH.\n install: https://fly.io/docs/flyctl/install/ \u2014 then re-run `bostrat-node fly`\n"),T(1)}try{let{stdout:S}=await ft(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${S.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"),T(1)}let O=await ds({ask:p,output:n,exec:r,flag:c.org}),f=c.app||await p("App name",`bostrat-node-${ls().slice(0,4)}`),g=c.region||await p("Region (see `fly platform regions`)","iad"),_=c.sizeGb||Number(await p("Volume size GB (logins + repos live here)","10"))||10,x=c.name||f,R=c.planeUrl||cr,v=c.token||await p("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!v)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
- `),T(1);let N=c.image||qt,{dir:A}=fr({app:f,dest:i,toml:lr({app:f,region:g,nodeName:x,planeUrl:R,image:N})});n.write(`
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"),T(1)}let O=await fs({ask:p,output:n,exec:r,flag:c.org}),f=c.app||await p("App name",`bostrat-node-${us().slice(0,4)}`),g=c.region||await p("Region (see `fly platform regions`)","iad"),_=c.sizeGb||Number(await p("Volume size GB (logins + repos live here)","10"))||10,x=c.name||f,R=c.planeUrl||lr,b=c.token||await p("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!b)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
+ `),T(1);let N=c.image||qt,{dir:A}=pr({app:f,dest:i,toml:ur({app:f,region:g,nodeName:x,planeUrl:R,image:N})});n.write(`
91
91
  wrote ${Te.join(A,"fly.toml")} \u2014 deploys the prebuilt node image ${N}
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 k=ur({app:f,org:O,region:g,sizeGb:_,token:v,dir:A});for(let S of k)n.write(` $ ${S.display}
95
+ `);let k=dr({app:f,org:O,region:g,sizeGb:_,token:b,dir:A});for(let S of k)n.write(` $ ${S.display}
96
96
  `);if(!c.yes&&(await p(`
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
98
  `),T(1);for(let S of k){n.write(`
@@ -112,15 +112,15 @@ Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u201
112
112
  redeploy: fly deploy ${A} -c ${Te.join(A,"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
- `),T(0)}var cr,us,qt,ft,hr=b(()=>{cr="wss://plane.bostrat.ai/v1/node",us=cs(import.meta.url)("../package.json").version,qt=`ghcr.io/globocodes/bostrat-node:${us}`;ft=(e,{stdin:t,exec:n}={})=>new Promise((r,i)=>{if(n)return n(e,{stdin:t}).then(r,i);let c=as("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,p,T)=>d?i(Object.assign(d,{stdout:p,stderr:T})):r({stdout:p,stderr:T}));t!=null&&c.stdin?.end(t)})});function mr(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!hs.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let r=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(r))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return r}function ms(e){let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||r.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=r.map(i=>({...i,fromMs:mr(i.from,"from",n),toMs:mr(i.to,"to",n)}))}return t}var ps,hs,el,tl,wr=b(()=>{ps={"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)."}]},hs=/^\d{4}-\d{2}-\d{2}$/;el=ms(ps),tl=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var yr=b(()=>{wr()});import gr from"node:fs/promises";import Sr from"node:path";import ws from"node:os";function vr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Ar(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function kr(e){let t=new Date(vr(e));return t.setDate(t.getDate()+7),t.getTime()}function $r(e){let t=new Date(Ar(e));return t.setMonth(t.getMonth()+1),t.getTime()}function Ss(e=Date.now()){for(let[t,n]of Object.entries(Ts)){let r=n.startOf(e);if(r!==pt[t]){pt[t]=r;for(let i of Xt.values())i[t]=0;for(let i of Tr)i.includes(`:${t}:`)&&!i.endsWith(`:${r}`)&&Tr.delete(i)}}}function bs(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let i={};for(let c of["weeklyUsd","monthlyUsd"]){let d=r?.[c];if(d==null||d==="")continue;let p=Number(d);if(!Number.isFinite(p)||p<=0)throw new Error(`${n}.${c} must be a positive number or null`);i[c]=p}Object.keys(i).length&&(t[n]=i)}return t}async function xr(e,{source:t="local",updatedAt:n=Date.now()}={}){xe={caps:bs(e),updatedAt:n,source:t};try{await gr.mkdir(br,{recursive:!0}),await gr.writeFile(ys(),JSON.stringify(xe,null,2))}catch{}return vs()}function vs(e=Date.now()){Ss(e);let t=new Set([...Xt.keys(),...Object.keys(xe?.caps||{})]),n={};for(let r of t){let i=Xt.get(r);n[r]={weeklyUsd:_r(i?.weekly||0),monthlyUsd:_r(i?.monthly||0)}}return{caps:xe?.caps||{},configured:!!xe,seeded:_s,updatedAt:xe?.updatedAt??null,spent:n,windows:{weekly:{start:pt.weekly,resetsAt:kr(e)},monthly:{start:pt.monthly,resetsAt:$r(e)}},warnPct:gs}}var br,ys,gs,Ts,xe,_s,pt,Xt,Tr,_r,Er=b(()=>{lt();yr();br=process.env.BOSTRAT_STATE_DIR||Sr.join(process.env.HOME||ws.tmpdir(),".bostrat"),ys=()=>Sr.join(br,"usage-caps.json"),gs=.8;Ts={weekly:{startOf:vr,nextStart:kr,capKey:"weeklyUsd"},monthly:{startOf:Ar,nextStart:$r,capKey:"monthlyUsd"}},xe=null,_s=!1,pt={weekly:0,monthly:0},Xt=new Map,Tr=new Set;_r=e=>Math.round(e*1e4)/1e4});var Br={};It(Br,{REMOVED_MARKER:()=>nn,detectInstallKind:()=>Re,detectProviderAuth:()=>Dr,maskToken:()=>tn,readRemovedMarker:()=>Pr,startPlaneLink:()=>Fs,updateCommandFor:()=>Ve,versionLt:()=>Oe});import Ee from"node:fs";import Ge from"node:fs/promises";import As from"node:http";import C from"node:path";import ht from"node:os";import{createRequire as ks}from"node:module";import Jt from"ws";function tn(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function Pr(e=nn){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=C.resolve(C.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ee.existsSync}={}){let r=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(r)?r:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(C.join(t,"..",".git"))?"git-checkout":"dev"}function Oe(e,t){let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let i=0;i<Math.max(n.length,r.length);i++){let c=(n[i]||0)-(r[i]||0);if(c)return c<0}return!1}function Ve(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 Dr({home:e=process.env.HOME||ht.homedir(),env:t=process.env}={}){let n=r=>{try{return Ee.statSync(r),!0}catch{return!1}};return{claude:n(C.join(e,".claude",".credentials.json")),codex:n(C.join(t.CODEX_HOME||C.join(e,".codex"),"auth.json")),cursor:n(C.join(t.XDG_CONFIG_HOME||C.join(e,".config"),"cursor","auth.json"))}}function Fs({url:e,token:t,nodeId:n=ht.hostname(),name:r=ht.hostname(),listTracks:i,detectAgents:c=null,onTracksTransferred:d=null,sampleMetrics:p=null,deliverySample:T=null,onHashKey:O=null,onViewBase:f=null,metricsMs:g=js,onUpdateAvailable:_=null,onUpdatePolicy:x=null,onHelloRefused:R=null,updatePolicy:v=null,installKind:N=Re(),selfUrl:A=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:k=null,removedMarkerFile:S=nn,onRemoved:j=null,onDegraded:te=null,onRecovered:Se=null,onRefused:gt=null,onConnected:qr=null,ingestMode:Tt=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:pn=Ms,unackedRetryMs:qe=Is,pingMs:hn=Rs,deadLinkMs:_t=Math.round(hn*Ns),maxInflightEvents:Xr=Bs,httpTimeoutMs:Xe=Cs,stallBackoffMinMs:mn=Ls,fetchImpl:wn=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=Fe(e);let Jr=A.replace(/^http/,"ws"),yn=new Set,gn=s=>{let l=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(!(!(l&&V&&Oe(V,l))||yn.has(l))){yn.add(l),w.log(`[plane-link] bostrat-node ${l} is available (this node runs ${V}) \u2014 ${Ve(N)}`);try{_?.({current:V,latest:l,min:s.minNodeVersion??null,installKind:N,required:!!(s.minNodeVersion&&Oe(V,s.minNodeVersion))})}catch(a){w.error(`[plane-link] update notice failed: ${a?.message||a}`)}}},le=new Map,ue=new Map,St=C.join(en,"plane-link","cursor.json"),bt=C.join(en,"plane-link","dead-letter.ndjson"),Tn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),de={},ne={},E=new Map,Je=null,re=null,Z=0,Me=0,_n=0,Ze={},Sn=new Set,bn=Promise.resolve(),I="ws",be=0,Y=!1,fe=0,vt=!1,W=ie,ve=new Set,oe=[],H=null,z=null,G=!1,At=!1,Pe=Or,De=null,Ae=null,ke=null,Q=null,pe=0,vn=0,ee=null,kt=!1,Qe=0,Le=!1,se=Pr(S);if(se)if(se.tokenPreview===tn(t))Le=!0,Ut({reason:se.reason??"removed",at:se.at??null,nodeId:se.nodeId??n}),w.error(`[plane-link] this node was REMOVED from the plane (${se.reason??"removed"}${se.at?` at ${new Date(se.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${S} to force a dial.`);else try{Ee.unlinkSync(S),w.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function $t({reason:s="removed",at:l=Date.now(),via:a="ctl"}={}){if(!Le){Le=!0,Ut({reason:s,at:l,nodeId:n,via:a});try{Ee.mkdirSync(C.dirname(S),{recursive:!0}),Ee.writeFileSync(S,JSON.stringify({at:l,reason:s,via:a,nodeId:n,tokenPreview:tn(t)},null,2))}catch(o){w.error(`[plane-link] could not write ${S}: ${o?.message||o}`)}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{j?.({reason:s,at:l,via:a})}catch{}Nn({bye:!1})}}async function Zr(){try{de=JSON.parse(await Ge.readFile(St,"utf8"))}catch{de={}}}function Qr(){kt=!0,!ke&&(ke=setTimeout(async()=>{if(ke=null,!!kt){kt=!1;try{await Ge.mkdir(C.dirname(St),{recursive:!0}),await Ge.writeFile(St,JSON.stringify(de))}catch(s){w.error("[plane-link] cursor flush failed:",s?.message||s)}}},Os),ke.unref?.())}function M(s){return!z||z.readyState!==Jt.OPEN?!1:(z.send(JSON.stringify(s)),!0)}function Be(s){let l=Date.now();for(let{trackId:o,event:u}of s){let y=E.get(u.id);E.set(u.id,{trackId:o,seq:u.seq,event:u,sentAt:l,firstSentAt:y?.firstSentAt??l,retryAt:l+qe,tries:(y?.tries??0)+1,nacks:y?.nacks??0})}let a=s.map(({trackId:o,event:u})=>({trackId:o,event:Ds(u)}));return I==="http"?(so(a),!0):M({v:P,ch:"events",type:"append",events:a})}function eo(s){let l=null;for(let a of E.values())a.trackId===s&&(l==null||a.seq<l)&&(l=a.seq);return l}function xt(s){let l=ne[s];if(l==null)return;let a=eo(s),o=a==null?l:Math.min(l,a-1);o>(de[s]??0)&&(de[s]=o,Qr())}function Ce(){if(Je=Date.now(),re!=null){let s=Date.now()-re;w.log(`[plane-link] spine sync recovered after ${Math.round(s/1e3)}s degraded (${Z} stall redial(s))`);let l=re;re=null,Z=0,Me=0,Y=!1,fe=0;try{Se?.({since:l,downMs:s})}catch(a){w.error(`[plane-link] onRecovered failed: ${a?.message||a}`)}}}function Et(s){if(!Array.isArray(s)||!s.length)return;let l=new Set;for(let a of s){let o=E.get(a);o&&(E.delete(a),(ne[o.trackId]??0)<o.seq&&(ne[o.trackId]=o.seq),l.add(o.trackId))}for(let a of l)xt(a);Ce()}function An(s,l){_n++;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 ${bt}`),bn=bn.then(async()=>{await Ge.mkdir(C.dirname(bt),{recursive:!0}),await Ge.appendFile(bt,JSON.stringify(a)+`
116
- `)}).catch(o=>w.error(`[plane-link] dead-letter write failed: ${o?.message||o}`))}function to(s,l){if(Ze[s]=(Ze[s]??0)+1,Sn.has(s))return;Sn.add(s);let a=Ps[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{gt?.({reason:s,trackId:l,count:Ze[s],hint:a})}catch(o){w.error(`[plane-link] onRefused failed: ${o?.message||o}`)}}function Ot(s,l,a,o=null){if(!Array.isArray(s)||!s.length)return;let u=new Set,y=Date.now();for(let m of s){let h=E.get(m);h&&(a?(E.delete(m),An(h,l),String(l).startsWith(Zt)&&to(String(l).slice(Zt.length),h.trackId),(ne[h.trackId]??0)<h.seq&&(ne[h.trackId]=h.seq),u.add(h.trackId)):(h.nacks++,h.retryAt=y+Math.max(1e3,Number(o)||qe)))}for(let m of u)xt(m);Ce()}function kn(s=Date.now()){let l=1/0;for(let a of E.values())a.firstSentAt<l&&(l=a.firstSentAt);return l===1/0?0:s-l}function no(s){if(!_t||!s||s!==z||!pe)return!1;let l=Date.now()-pe;if(l<=_t)return!1;vn++,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 $n(){if(!G||!E.size)return;let s=Date.now(),l=kn(s);if(l<pn||Je!=null&&s-Je<pn||I==="http"&&Y||Me>s)return;Z++;let a=Math.min(mn*2**(Z-1),Nr);if(re==null){re=s-l,w.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${E.size} event(s) in flight (${I} door) \u2014 the plane is not answering appends`);try{te?.({since:re,unacked:E.size,oldestAgeMs:l,mode:I})}catch(o){w.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(I==="http"){Y=!0,fe=s+a,w.error(`[plane-link] ingest circuit OPEN (stall #${Z}); 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 #${Z})`);try{z?.terminate()}catch{}}function Rt(){if(!G)return;let s=Date.now();if(I==="http"&&Y)return;let l=[...E.values()].filter(o=>o.event&&o.retryAt<=s&&!(I==="http"&&ve.has(o.trackId)));if(!l.length)return;l.sort((o,u)=>o.trackId===u.trackId?o.seq-u.seq:o.trackId<u.trackId?-1:1),w.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let a=I==="http"?W:ie;if(I==="http"){let o=new Map;for(let u of l)(o.get(u.trackId)??o.set(u.trackId,[]).get(u.trackId)).push(u);for(let[,u]of o){if(be>=Qt)return;Be(u.slice(0,a).map(y=>({trackId:y.trackId,event:y.event})))}return}for(let o=0;o<l.length;o+=a){let u=l.slice(o,o+a).map(y=>({trackId:y.trackId,event:y.event}));if(!Be(u))return}}async function ro(s=null){for(;;){if(!G)return!1;let l=E.size<Xr,a=I!=="http"||be<Qt&&!Y&&(!s||!ve.has(s));if(l&&a)return!0;await new Promise(o=>setTimeout(o,100))}}function Nt(){if(H=null,!G||!oe.length)return;let s=oe;if(oe=[],I!=="http"){for(let a=0;a<s.length;a+=ie)Be(s.slice(a,a+ie));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,o]of l){if(ve.has(a)||be>=Qt||Y){oe.push(...o);continue}for(let u=0;u<o.length;u+=W)Be(o.slice(u,u+W))}oe.length&&!H&&(H=setTimeout(Nt,Ir),H.unref?.())}let oo=s=>{let l=new Map;for(let{trackId:a,event:o}of s)(l.get(a)??l.set(a,[]).get(a)).push(o);return[...l].map(([a,o])=>({trackId:a,events:o}))},he=(s,l,a,{progress:o})=>{let u=Date.now();for(let{event:y}of s){let m=E.get(y.id);m&&(m.nacks++,m.retryAt=u+Math.max(1e3,a||qe))}o&&Ce()};async function so(s){let l=new Set(s.map(a=>a.trackId));for(let a of l)ve.add(a);be++;try{let a=await wn(`${Tn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:oo(s)}),signal:AbortSignal.timeout(Xe)}),o=(Number(a.headers.get("retry-after"))||0)*1e3;if(a.status===200){let u=await a.json();W=ie;for(let h of u.results??[]){Et(h.acked??[]);let $=(J,F)=>{let et=new Map;for(let me of J??[])(et.get(me.reason)??et.set(me.reason,[]).get(me.reason)).push(me.id);for(let[me,In]of et)Ot(In,me,F,u.retryAfterMs??null)};$(h.rejected,!0),$(h.deferred,!1)}let y=new Set,m=new Map;for(let h of Array.isArray(u.refused)?u.refused:[])!h||typeof h.id!="string"||(y.add(h.id),(m.get(h.reason)??m.set(h.reason,[]).get(h.reason)).push(h.id));for(let[h,$]of m)Ot($,`${Zt}${h}`,!0);Et((u.discarded??[]).filter(h=>!y.has(h))),Ce();return}if(a.status===429){he(s,"overloaded",o||5e3,{progress:!0});return}if(a.status===413&&s.length>1){W=Math.max(1,Math.floor(s.length/2)),w.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=E.get(s[0].event.id);u&&(E.delete(u.event.id),An(u,"too_large"),(ne[u.trackId]??0)<u.seq&&(ne[u.trackId]=u.seq),xt(u.trackId)),Ce();return}if(a.status===410){$t({reason:"removed",via:"410"}),he(s,"http_410",6e4,{progress:!1});return}if(a.status===401||a.status===403){let{tripped:u,holdMs:y}=at();if(u&&w.error(`[plane-link] holding every plane call for ${Math.round(y/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Qe>=Mr){Qe=Date.now();let m="";try{m=(await a.json())?.error??""}catch{}w.error(`[plane-link] plane refused ingest (HTTP ${a.status}${m?`: ${m}`:""}) \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){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`),he(s,"http_400",6e4,{progress:!1});return}he(s,`http_${a.status}`,o||5e3,{progress:!1})}catch(a){let o=a?.name==="TimeoutError"||a?.name==="AbortError";o&&s.length>1&&(W=Math.max(1,Math.floor(s.length/2)),w.error(`[plane-link] ingest request of ${s.length} event(s) outlived its ${Xe} ms deadline \u2014 halving batches to ${W}`)),he(s,o?"timeout":"network",5e3,{progress:!1})}finally{be--;for(let a of l)ve.delete(a)}}async function io(){if(I!=="http"||!Y||!G||vt)return;let s=Date.now();if(!(fe>s||ct(s))){vt=!0;try{let l=await wn(`${Tn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(Xe)});if(!l.ok)throw new Error(`HTTP ${l.status}`);w.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Y=!1,fe=0,Me=Date.now()+Xe+qe+1e3;for(let a of E.values())a.retryAt=Math.min(a.retryAt,Date.now());Rt()}catch(l){Z++;let a=Math.min(mn*2**(Z-1),Nr);fe=Date.now()+a,w.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(a/1e3)}s`)}finally{vt=!1}}}function xn(){let s=Date.now();return{mode:I,unacked:E.size,oldestUnackedAgeMs:kn(s),lastProgressAt:Je,degradedSince:re,stallRedials:Z,deadLettered:_n,http:I==="http"?{inFlight:be,circuitOpen:Y,nextProbeInMs:Y?Math.max(0,fe-s):0,batchCap:W}:null}}async function En(){if(!p)return;let s;try{s=await p()}catch(a){w.error("[plane-link] metrics sample failed:",a?.message||a);return}let l=null;try{l=T?.()??null}catch{}s&&M({v:P,ch:"ctl",type:"metrics",metrics:{...s,planeLink:xn(),...l?{delivery:l}:{}}})}function ao(){p&&(ee&&clearInterval(ee),En(),ee=setInterval(En,g),ee.unref?.())}async function co(){let s;try{s=await i()}catch(l){w.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(!G)return;let a;try{a=await zt(l)}catch{continue}let o=de[l.id]??0,u=a.filter(m=>m.seq>o&&typeof m.id=="string"),y=I==="http"?W:ie;for(let m=0;m<u.length;m+=y){if(!await ro(l.id))return;let h=u.slice(m,m+Math.min(y,I==="http"?W:ie)).map($=>({trackId:l.id,event:$}));if(!Be(h))return}}}function On(s){!G||!s?.trackId||typeof s.id!="string"||(oe.push({trackId:s.trackId,event:s}),H||(H=setTimeout(Nt,Ir),H.unref?.()))}let je=new Map;async function lo(s){let{reqId:l,method:a,path:o,headers:u={},body:y}=s,m=Object.fromEntries(Object.entries(u).filter(([,$])=>$!=null)),h=new AbortController;je.set(l,h);try{if(s.host){await uo(s,m,h);return}k&&(m["x-bostrat-token"]=k);let $=await fetch(A+o,{method:a,headers:m,body:y?Buffer.from(y,"base64"):void 0,signal:h.signal}),J=Object.fromEntries($.headers);for(let F of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete J[F];if(J["content-type"]||(J["content-type"]="application/octet-stream"),M({v:P,ch:"control",type:"http_head",reqId:l,status:$.status,headers:J}),$.body){for await(let F of $.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 uo(s,l,a){let{reqId:o,method:u,path:y,body:m}=s,h=new URL(A);return new Promise($=>{let J=As.request({host:h.hostname,port:h.port,method:u,path:y,headers:{...l,host:s.host},signal:a.signal},F=>{let{connection:et,"keep-alive":me,"transfer-encoding":In,upgrade:Ei,...fo}=F.headers;M({v:P,ch:"control",type:"http_head",reqId:o,status:F.statusCode||502,headers:fo}),F.on("data",po=>{M({v:P,ch:"control",type:"http_data",reqId:o,data:Buffer.from(po).toString("base64")})||F.destroy()}),F.on("end",()=>{M({v:P,ch:"control",type:"http_end",reqId:o,error:null}),$()}),F.on("error",()=>{M({v:P,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),$()})});J.on("error",F=>{M({v:P,ch:"control",type:"http_end",reqId:o,error:F?.message||"view request failed"}),$()}),m&&J.write(Buffer.from(m,"base64")),J.end()})}function Rn(){if(At||Le)return;z=new Jt(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:r,platform:process.platform,version:V,installKind:N,...typeof v=="function"?{updatePolicy:v()}:v?{updatePolicy:v}:{},providers:Dr(),...a?{agents:a}:{}})}),z.on("message",a=>{pe=Date.now();let o;try{o=JSON.parse(a)}catch{return}if(o.ch==="ctl"&&o.type==="hello_ok"){G=!0,Pe=Or,De=null,Hn(),w.log(`[plane-link] connected to plane as ${n}`);try{qr?.()}catch{}if(typeof o.hashKey=="string"&&o.hashKey)try{O?.(o.hashKey)}catch{}try{f?.(typeof o.viewBase=="string"&&o.viewBase?o.viewBase:null)}catch{}o.minNodeVersion&&V&&Oe(V,o.minNodeVersion)&&w.error(`[plane-link] this node is bostrat-node ${V}; the plane asks for \u2265${o.minNodeVersion} \u2014 update with: ${Ve(N)}`);try{x?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}gn(o);let u=o.ingest==="http";I=Tt==="ws"?"ws":Tt==="http"||u?"http":"ws",Tt==="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"),I==="http"&&w.log("[plane-link] spine rides the HTTPS ingest door"),Y=!1,fe=0,W=ie,Q&&clearInterval(Q),pe=Date.now(),Q=setInterval(()=>{no(s)||(M({v:P,ch:"ctl",type:"ping"}),$n(),io().catch(()=>{}),Rt(),oe.length&&!H&&Nt())},hn),Q.unref?.(),ao(),co().catch(y=>w.error("[plane-link] backfill failed:",y?.message||y));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let u=typeof o.minNodeVersion=="string"?o.minNodeVersion:null,y=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;w.error(`[plane-link] plane REFUSED this node: bostrat-node ${V??"?"} is below its minimum ${u??"?"} \u2014 ${o.fix||Ve(N)}`),Pe=Rr,De=0;try{R?.({current:V,min:u,latest:y,fix:o.fix||Ve(N),installKind:N})}catch(m){w.error(`[plane-link] refusal handler failed: ${m?.message||m}`)}return}if(o.ch==="ctl"&&o.type==="removed"){M({v:P,ch:"ctl",type:"removed_ack",nodeId:n}),$t({reason:typeof o.reason=="string"?o.reason:"removed",at:Number(o.at)||Date.now(),via:"ctl"});return}if(o.ch==="ctl"&&o.type==="update_available"){gn(o);return}if(o.ch==="ctl"&&o.type==="update_policy"){try{x?.(typeof o.mode=="string"?o.mode:null)}catch{}return}if(o.ch==="ctl"&&o.type==="usage_caps"){xr(o.caps??{},{source:"plane",updatedAt:o.updatedAt??Date.now()}).then(u=>w.log(`[plane-link] spend caps ${Object.keys(u.caps).length?`updated (${Object.keys(u.caps).join(", ")})`:"cleared"} from plane`)).catch(u=>w.error("[plane-link] spend-caps push rejected:",u?.message||u));return}if(o.ch==="ctl"&&o.type==="transferred"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>d?.(o.tracks)).catch(u=>w.error("[plane-link] transfer notice failed:",u?.message||u));return}if(o.ch==="events"&&o.type==="ack"&&Array.isArray(o.ids)){Et(o.ids);return}if(o.ch==="events"&&o.type==="nack"&&Array.isArray(o.ids)){Ot(o.ids,o.reason,o.permanent===!0,o.retryAfterMs??null);return}if(o.ch==="control"&&o.type==="http_open"){lo(o).catch(u=>M({v:P,ch:"control",type:"http_end",reqId:o.reqId,error:u?.message||"tunnel error"}));return}if(o.ch==="control"&&o.type==="http_cancel"){je.get(o.reqId)?.abort();return}if(o.ch==="attach"&&o.type==="open"){let u=new Jt(Jr+o.path,Array.isArray(o.protocols)?o.protocols:[],o.host?{headers:{host:o.host}}:void 0);le.set(o.streamId,u),ue.set(o.streamId,[]),u.on("open",()=>{let m=ue.get(o.streamId)||[];ue.delete(o.streamId);for(let{buf:h,bin:$}of m)u.send(h,{binary:$})}),u.on("message",(m,h)=>{let $=h?m:Buffer.from(String(m));M({v:P,ch:"attach",type:"data",streamId:o.streamId,data:$.toString("base64"),...h?{bin:!0}:{}})});let y=()=>{ue.delete(o.streamId),le.delete(o.streamId)&&M({v:P,ch:"attach",type:"close",streamId:o.streamId})};u.on("close",y),u.on("error",y);return}if(o.ch==="attach"&&o.type==="data"){let u=le.get(o.streamId);if(!u)return;let y=Buffer.from(o.data,"base64"),m=o.bin===!0,h=ue.get(o.streamId);h?h.push({buf:y,bin:m}):u.send(y,{binary:m});return}if(o.ch==="attach"&&o.type==="close"){let u=le.get(o.streamId);le.delete(o.streamId),ue.delete(o.streamId),u?.close();return}});let l=()=>{G&&w.log("[plane-link] disconnected from plane"),G=!1,Q&&(clearInterval(Q),Q=null),ee&&(clearInterval(ee),ee=null),E.clear(),ne={},oe=[],H&&(clearTimeout(H),H=null),ve.clear();for(let u of le.values())u.close();le.clear(),ue.clear();for(let u of je.values())u.abort();if(je.clear(),At||Ae)return;De==null&&(De=Date.now());let a=Date.now()-De<$s,o=Math.max(a?xs+Math.random()*Es:Pe,Me-Date.now(),Ke());Ae=setTimeout(()=>{Ae=null,Rn()},o),Ae.unref?.(),a||(Pe=Math.min(Pe*2,Rr))};z.on("close",l),z.on("error",a=>{let o=/Unexpected server response: (\d+)/.exec(a?.message||"")?.[1];if(o==="410"){$t({reason:"removed",via:"410"});return}if(o==="401"||o==="403"){let{tripped:u,holdMs:y}=at();u?w.error(`[plane-link] holding every plane call for ${Math.round(y/6e4)} min \u2014 three credential refusals in a row (HTTP ${o}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(y/6e4)} min.`):Date.now()-Qe>=Mr&&(Qe=Date.now(),w.error(`[plane-link] plane refused this node's credentials (HTTP ${o}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`))}l()})}ze.on("event",On),Zr().then(Rn);function Nn({bye:s=!0}={}){At=!0,ze.off("event",On),Ae&&clearTimeout(Ae),ke&&clearTimeout(ke),Q&&clearInterval(Q),ee&&clearInterval(ee),H&&clearTimeout(H),s&&M({v:P,ch:"ctl",type:"bye",reason:"shutdown"}),z?.close()}return{stop:()=>Nn(),status:()=>({connected:G,nodeId:n,cursor:{...de},inflight:E.size,...xn(),auth:Kn(),dormant:Le,removed:Ht(),deadLinkMs:_t,deadLinkRedials:vn,refused:{...Ze}}),_tick:()=>{$n(),Rt()}}}var V,en,nn,P,Or,Rr,$s,xs,Es,ie,Os,Rs,Ns,Is,Lr,Ms,Zt,Ps,Ds,Ls,Nr,Bs,Ir,Cs,Qt,js,Mr,rn=b(()=>{lt();Er();Dt();Kt();V=(()=>{try{return ks(import.meta.url)("../package.json").version||null}catch{return null}})(),en=process.env.BOSTRAT_STATE_DIR||C.join(process.env.HOME||ht.tmpdir(),".bostrat"),nn=C.join(en,"plane-link","removed.json");P=1,Or=1e3,Rr=3e4,$s=6e4,xs=1500,Es=500,ie=100,Os=2e3,Rs=25e3,Ns=2.5,Is=6e4,Lr=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Ms=Lr(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Zt="refused:",Ps={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"},Ds=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},Ls=3e4,Nr=10*6e4,Bs=400,Ir=250,Cs=Lr(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Qt=4,js=6e4,Mr=6e4});var Cr=b(()=>{jt()});var Kr={};It(Kr,{ACTIONABLE_KINDS:()=>yt,REGISTRY_RETRY_ATTEMPTS:()=>cn,REGISTRY_WAIT_POLLS:()=>on,REGISTRY_WAIT_STEP_S:()=>sn,SELF_UPDATE_DIR:()=>an,createAutoUpdater:()=>Qs,inFlight:()=>un,readStatus:()=>ln,selfUpdatePlan:()=>Ur,settleSelfUpdate:()=>Zs,startSelfUpdate:()=>Hr,underService:()=>Fr,updatePolicy:()=>Gs});import jr from"node:fs";import ae from"node:fs/promises";import Us from"node:os";import L from"node:path";import{spawn as Hs}from"node:child_process";import{createRequire as Ks}from"node:module";function Gs({kind:e=Re(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:yt.has(e)?e==="git-checkout"||Fr(t)?"auto":"prompt":"off"}function Fr(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Ur({kind:e,to:t,from:n=mt,statusFile:r=wt,logFile:i=L.join(an,"last.log"),port:c=Number(process.env.PORT)||3362,npmPrefix:d=null,serviceName:p=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:T=typeof process.getuid=="function"?process.getuid():0,liveDir:O=process.env.BOSTRAT_LIVE_CHECKOUT||L.resolve(L.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:f=Date.now(),attempts:g=1}={}){if(!yt.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 _=(A,k="")=>`write_status ${U(A)} ${k}`,x=process.platform==="darwin"?`launchctl kickstart -k gui/${T}/${p}`:`systemctl --user restart ${U(p)}`,R=`
115
+ `),T(0)}var lr,ds,qt,ft,mr=v(()=>{lr="wss://plane.bostrat.ai/v1/node",ds=ls(import.meta.url)("../package.json").version,qt=`ghcr.io/globocodes/bostrat-node:${ds}`;ft=(e,{stdin:t,exec:n}={})=>new Promise((r,i)=>{if(n)return n(e,{stdin:t}).then(r,i);let c=cs("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,p,T)=>d?i(Object.assign(d,{stdout:p,stderr:T})):r({stdout:p,stderr:T}));t!=null&&c.stdin?.end(t)})});function wr(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!ms.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let r=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(r))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return r}function ws(e){let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||r.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=r.map(i=>({...i,fromMs:wr(i.from,"from",n),toMs:wr(i.to,"to",n)}))}return t}var hs,ms,ol,sl,yr=v(()=>{hs={"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)."}]},ms=/^\d{4}-\d{2}-\d{2}$/;ol=ws(hs),sl=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var gr=v(()=>{yr()});import Tr from"node:fs/promises";import vr from"node:path";import ys from"node:os";function Ar(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function kr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function $r(e){let t=new Date(Ar(e));return t.setDate(t.getDate()+7),t.getTime()}function xr(e){let t=new Date(kr(e));return t.setMonth(t.getMonth()+1),t.getTime()}function vs(e=Date.now()){for(let[t,n]of Object.entries(_s)){let r=n.startOf(e);if(r!==pt[t]){pt[t]=r;for(let i of Xt.values())i[t]=0;for(let i of _r)i.includes(`:${t}:`)&&!i.endsWith(`:${r}`)&&_r.delete(i)}}}function bs(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let i={};for(let c of["weeklyUsd","monthlyUsd"]){let d=r?.[c];if(d==null||d==="")continue;let p=Number(d);if(!Number.isFinite(p)||p<=0)throw new Error(`${n}.${c} must be a positive number or null`);i[c]=p}Object.keys(i).length&&(t[n]=i)}return t}async function Er(e,{source:t="local",updatedAt:n=Date.now()}={}){xe={caps:bs(e),updatedAt:n,source:t};try{await Tr.mkdir(br,{recursive:!0}),await Tr.writeFile(gs(),JSON.stringify(xe,null,2))}catch{}return As()}function As(e=Date.now()){vs(e);let t=new Set([...Xt.keys(),...Object.keys(xe?.caps||{})]),n={};for(let r of t){let i=Xt.get(r);n[r]={weeklyUsd:Sr(i?.weekly||0),monthlyUsd:Sr(i?.monthly||0)}}return{caps:xe?.caps||{},configured:!!xe,seeded:Ss,updatedAt:xe?.updatedAt??null,spent:n,windows:{weekly:{start:pt.weekly,resetsAt:$r(e)},monthly:{start:pt.monthly,resetsAt:xr(e)}},warnPct:Ts}}var br,gs,Ts,_s,xe,Ss,pt,Xt,_r,Sr,Or=v(()=>{lt();gr();br=process.env.BOSTRAT_STATE_DIR||vr.join(process.env.HOME||ys.tmpdir(),".bostrat"),gs=()=>vr.join(br,"usage-caps.json"),Ts=.8;_s={weekly:{startOf:Ar,nextStart:$r,capKey:"weeklyUsd"},monthly:{startOf:kr,nextStart:xr,capKey:"monthlyUsd"}},xe=null,Ss=!1,pt={weekly:0,monthly:0},Xt=new Map,_r=new Set;Sr=e=>Math.round(e*1e4)/1e4});var Lr={};It(Lr,{REMOVED_MARKER:()=>nn,detectInstallKind:()=>Re,detectProviderAuth:()=>Cr,maskToken:()=>tn,readRemovedMarker:()=>Dr,startPlaneLink:()=>Us,updateCommandFor:()=>Ge,versionLt:()=>Oe});import Ee from"node:fs";import Ye from"node:fs/promises";import ks from"node:http";import L from"node:path";import ht from"node:os";import{createRequire as $s}from"node:module";import Jt from"ws";function tn(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function Dr(e=nn){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=L.resolve(L.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ee.existsSync}={}){let r=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(r)?r:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(L.join(t,"..",".git"))?"git-checkout":"dev"}function Oe(e,t){let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let i=0;i<Math.max(n.length,r.length);i++){let c=(n[i]||0)-(r[i]||0);if(c)return c<0}return!1}function Ge(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 Cr({home:e=process.env.HOME||ht.homedir(),env:t=process.env}={}){let n=r=>{try{return Ee.statSync(r),!0}catch{return!1}};return{claude:n(L.join(e,".claude",".credentials.json")),codex:n(L.join(t.CODEX_HOME||L.join(e,".codex"),"auth.json")),cursor:n(L.join(t.XDG_CONFIG_HOME||L.join(e,".config"),"cursor","auth.json"))}}function Us({url:e,token:t,nodeId:n=ht.hostname(),name:r=ht.hostname(),listTracks:i,detectAgents:c=null,onTracksTransferred:d=null,sampleMetrics:p=null,deliverySample:T=null,onHashKey:O=null,onViewBase:f=null,metricsMs:g=Fs,onUpdateAvailable:_=null,onUpdatePolicy:x=null,onHelloRefused:R=null,updatePolicy:b=null,installKind:N=Re(),selfUrl:A=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:k=null,removedMarkerFile:S=nn,onRemoved:j=null,onDegraded:te=null,onRecovered:Se=null,onRefused:gt=null,onConnected:Xr=null,ingestMode:Tt=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:pn=Ps,unackedRetryMs:qe=Ms,pingMs:hn=Ns,deadLinkMs:_t=Math.round(hn*Is),maxInflightEvents:Jr=Ls,httpTimeoutMs:Xe=js,stallBackoffMinMs:mn=Bs,fetchImpl:wn=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=Fe(e);let Zr=A.replace(/^http/,"ws"),yn=new Set,gn=s=>{let l=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(!(!(l&&G&&Oe(G,l))||yn.has(l))){yn.add(l),w.log(`[plane-link] bostrat-node ${l} is available (this node runs ${G}) \u2014 ${Ge(N)}`);try{_?.({current:G,latest:l,min:s.minNodeVersion??null,installKind:N,required:!!(s.minNodeVersion&&Oe(G,s.minNodeVersion))})}catch(a){w.error(`[plane-link] update notice failed: ${a?.message||a}`)}}},le=new Map,ue=new Map,St=L.join(en,"plane-link","cursor.json"),vt=L.join(en,"plane-link","dead-letter.ndjson"),Tn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),de={},ne={},E=new Map,Je=null,re=null,Z=0,Me=0,_n=0,Ze={},Sn=new Set,vn=Promise.resolve(),I="ws",ve=0,V=!1,fe=0,bt=!1,W=ie,be=new Set,oe=[],H=null,z=null,Y=!1,At=!1,Pe=Rr,De=null,Ae=null,ke=null,Q=null,pe=0,bn=0,ee=null,kt=!1,Qe=0,Ce=!1,se=Dr(S);if(se)if(se.tokenPreview===tn(t))Ce=!0,Ut({reason:se.reason??"removed",at:se.at??null,nodeId:se.nodeId??n}),w.error(`[plane-link] this node was REMOVED from the plane (${se.reason??"removed"}${se.at?` at ${new Date(se.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${S} to force a dial.`);else try{Ee.unlinkSync(S),w.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function $t({reason:s="removed",at:l=Date.now(),via:a="ctl"}={}){if(!Ce){Ce=!0,Ut({reason:s,at:l,nodeId:n,via:a});try{Ee.mkdirSync(L.dirname(S),{recursive:!0}),Ee.writeFileSync(S,JSON.stringify({at:l,reason:s,via:a,nodeId:n,tokenPreview:tn(t)},null,2))}catch(o){w.error(`[plane-link] could not write ${S}: ${o?.message||o}`)}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{j?.({reason:s,at:l,via:a})}catch{}Nn({bye:!1})}}async function Qr(){try{de=JSON.parse(await Ye.readFile(St,"utf8"))}catch{de={}}}function eo(){kt=!0,!ke&&(ke=setTimeout(async()=>{if(ke=null,!!kt){kt=!1;try{await Ye.mkdir(L.dirname(St),{recursive:!0}),await Ye.writeFile(St,JSON.stringify(de))}catch(s){w.error("[plane-link] cursor flush failed:",s?.message||s)}}},Rs),ke.unref?.())}function M(s){return!z||z.readyState!==Jt.OPEN?!1:(z.send(JSON.stringify(s)),!0)}function Be(s){let l=Date.now();for(let{trackId:o,event:u}of s){let y=E.get(u.id);E.set(u.id,{trackId:o,seq:u.seq,event:u,sentAt:l,firstSentAt:y?.firstSentAt??l,retryAt:l+qe,tries:(y?.tries??0)+1,nacks:y?.nacks??0})}let a=s.map(({trackId:o,event:u})=>({trackId:o,event:Cs(u)}));return I==="http"?(io(a),!0):M({v:P,ch:"events",type:"append",events:a})}function to(s){let l=null;for(let a of E.values())a.trackId===s&&(l==null||a.seq<l)&&(l=a.seq);return l}function xt(s){let l=ne[s];if(l==null)return;let a=to(s),o=a==null?l:Math.min(l,a-1);o>(de[s]??0)&&(de[s]=o,eo())}function Le(){if(Je=Date.now(),re!=null){let s=Date.now()-re;w.log(`[plane-link] spine sync recovered after ${Math.round(s/1e3)}s degraded (${Z} stall redial(s))`);let l=re;re=null,Z=0,Me=0,V=!1,fe=0;try{Se?.({since:l,downMs:s})}catch(a){w.error(`[plane-link] onRecovered failed: ${a?.message||a}`)}}}function Et(s){if(!Array.isArray(s)||!s.length)return;let l=new Set;for(let a of s){let o=E.get(a);o&&(E.delete(a),(ne[o.trackId]??0)<o.seq&&(ne[o.trackId]=o.seq),l.add(o.trackId))}for(let a of l)xt(a);Le()}function An(s,l){_n++;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 ${vt}`),vn=vn.then(async()=>{await Ye.mkdir(L.dirname(vt),{recursive:!0}),await Ye.appendFile(vt,JSON.stringify(a)+`
116
+ `)}).catch(o=>w.error(`[plane-link] dead-letter write failed: ${o?.message||o}`))}function no(s,l){if(Ze[s]=(Ze[s]??0)+1,Sn.has(s))return;Sn.add(s);let a=Ds[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{gt?.({reason:s,trackId:l,count:Ze[s],hint:a})}catch(o){w.error(`[plane-link] onRefused failed: ${o?.message||o}`)}}function Ot(s,l,a,o=null){if(!Array.isArray(s)||!s.length)return;let u=new Set,y=Date.now();for(let m of s){let h=E.get(m);h&&(a?(E.delete(m),An(h,l),String(l).startsWith(Zt)&&no(String(l).slice(Zt.length),h.trackId),(ne[h.trackId]??0)<h.seq&&(ne[h.trackId]=h.seq),u.add(h.trackId)):(h.nacks++,h.retryAt=y+Math.max(1e3,Number(o)||qe)))}for(let m of u)xt(m);Le()}function kn(s=Date.now()){let l=1/0;for(let a of E.values())a.firstSentAt<l&&(l=a.firstSentAt);return l===1/0?0:s-l}function ro(s){if(!_t||!s||s!==z||!pe)return!1;let l=Date.now()-pe;if(l<=_t)return!1;bn++,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 $n(){if(!Y||!E.size)return;let s=Date.now(),l=kn(s);if(l<pn||Je!=null&&s-Je<pn||I==="http"&&V||Me>s)return;Z++;let a=Math.min(mn*2**(Z-1),Ir);if(re==null){re=s-l,w.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${E.size} event(s) in flight (${I} door) \u2014 the plane is not answering appends`);try{te?.({since:re,unacked:E.size,oldestAgeMs:l,mode:I})}catch(o){w.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(I==="http"){V=!0,fe=s+a,w.error(`[plane-link] ingest circuit OPEN (stall #${Z}); 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 #${Z})`);try{z?.terminate()}catch{}}function Rt(){if(!Y)return;let s=Date.now();if(I==="http"&&V)return;let l=[...E.values()].filter(o=>o.event&&o.retryAt<=s&&!(I==="http"&&be.has(o.trackId)));if(!l.length)return;l.sort((o,u)=>o.trackId===u.trackId?o.seq-u.seq:o.trackId<u.trackId?-1:1),w.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let a=I==="http"?W:ie;if(I==="http"){let o=new Map;for(let u of l)(o.get(u.trackId)??o.set(u.trackId,[]).get(u.trackId)).push(u);for(let[,u]of o){if(ve>=Qt)return;Be(u.slice(0,a).map(y=>({trackId:y.trackId,event:y.event})))}return}for(let o=0;o<l.length;o+=a){let u=l.slice(o,o+a).map(y=>({trackId:y.trackId,event:y.event}));if(!Be(u))return}}async function oo(s=null){for(;;){if(!Y)return!1;let l=E.size<Jr,a=I!=="http"||ve<Qt&&!V&&(!s||!be.has(s));if(l&&a)return!0;await new Promise(o=>setTimeout(o,100))}}function Nt(){if(H=null,!Y||!oe.length)return;let s=oe;if(oe=[],I!=="http"){for(let a=0;a<s.length;a+=ie)Be(s.slice(a,a+ie));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,o]of l){if(be.has(a)||ve>=Qt||V){oe.push(...o);continue}for(let u=0;u<o.length;u+=W)Be(o.slice(u,u+W))}oe.length&&!H&&(H=setTimeout(Nt,Mr),H.unref?.())}let so=s=>{let l=new Map;for(let{trackId:a,event:o}of s)(l.get(a)??l.set(a,[]).get(a)).push(o);return[...l].map(([a,o])=>({trackId:a,events:o}))},he=(s,l,a,{progress:o})=>{let u=Date.now();for(let{event:y}of s){let m=E.get(y.id);m&&(m.nacks++,m.retryAt=u+Math.max(1e3,a||qe))}o&&Le()};async function io(s){let l=new Set(s.map(a=>a.trackId));for(let a of l)be.add(a);ve++;try{let a=await wn(`${Tn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:so(s)}),signal:AbortSignal.timeout(Xe)}),o=(Number(a.headers.get("retry-after"))||0)*1e3;if(a.status===200){let u=await a.json();W=ie;for(let h of u.results??[]){Et(h.acked??[]);let $=(J,F)=>{let et=new Map;for(let me of J??[])(et.get(me.reason)??et.set(me.reason,[]).get(me.reason)).push(me.id);for(let[me,In]of et)Ot(In,me,F,u.retryAfterMs??null)};$(h.rejected,!0),$(h.deferred,!1)}let y=new Set,m=new Map;for(let h of Array.isArray(u.refused)?u.refused:[])!h||typeof h.id!="string"||(y.add(h.id),(m.get(h.reason)??m.set(h.reason,[]).get(h.reason)).push(h.id));for(let[h,$]of m)Ot($,`${Zt}${h}`,!0);Et((u.discarded??[]).filter(h=>!y.has(h))),Le();return}if(a.status===429){he(s,"overloaded",o||5e3,{progress:!0});return}if(a.status===413&&s.length>1){W=Math.max(1,Math.floor(s.length/2)),w.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=E.get(s[0].event.id);u&&(E.delete(u.event.id),An(u,"too_large"),(ne[u.trackId]??0)<u.seq&&(ne[u.trackId]=u.seq),xt(u.trackId)),Le();return}if(a.status===410){$t({reason:"removed",via:"410"}),he(s,"http_410",6e4,{progress:!1});return}if(a.status===401||a.status===403){let{tripped:u,holdMs:y}=at();if(u&&w.error(`[plane-link] holding every plane call for ${Math.round(y/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Qe>=Pr){Qe=Date.now();let m="";try{m=(await a.json())?.error??""}catch{}w.error(`[plane-link] plane refused ingest (HTTP ${a.status}${m?`: ${m}`:""}) \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){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`),he(s,"http_400",6e4,{progress:!1});return}he(s,`http_${a.status}`,o||5e3,{progress:!1})}catch(a){let o=a?.name==="TimeoutError"||a?.name==="AbortError";o&&s.length>1&&(W=Math.max(1,Math.floor(s.length/2)),w.error(`[plane-link] ingest request of ${s.length} event(s) outlived its ${Xe} ms deadline \u2014 halving batches to ${W}`)),he(s,o?"timeout":"network",5e3,{progress:!1})}finally{ve--;for(let a of l)be.delete(a)}}async function ao(){if(I!=="http"||!V||!Y||bt)return;let s=Date.now();if(!(fe>s||ct(s))){bt=!0;try{let l=await wn(`${Tn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(Xe)});if(!l.ok)throw new Error(`HTTP ${l.status}`);w.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),V=!1,fe=0,Me=Date.now()+Xe+qe+1e3;for(let a of E.values())a.retryAt=Math.min(a.retryAt,Date.now());Rt()}catch(l){Z++;let a=Math.min(mn*2**(Z-1),Ir);fe=Date.now()+a,w.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(a/1e3)}s`)}finally{bt=!1}}}function xn(){let s=Date.now();return{mode:I,unacked:E.size,oldestUnackedAgeMs:kn(s),lastProgressAt:Je,degradedSince:re,stallRedials:Z,deadLettered:_n,http:I==="http"?{inFlight:ve,circuitOpen:V,nextProbeInMs:V?Math.max(0,fe-s):0,batchCap:W}:null}}async function En(){if(!p)return;let s;try{s=await p()}catch(a){w.error("[plane-link] metrics sample failed:",a?.message||a);return}let l=null;try{l=T?.()??null}catch{}s&&M({v:P,ch:"ctl",type:"metrics",metrics:{...s,planeLink:xn(),...l?{delivery:l}:{}}})}function co(){p&&(ee&&clearInterval(ee),En(),ee=setInterval(En,g),ee.unref?.())}async function lo(){let s;try{s=await i()}catch(l){w.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(!Y)return;let a;try{a=await zt(l)}catch{continue}let o=de[l.id]??0,u=a.filter(m=>m.seq>o&&typeof m.id=="string"),y=I==="http"?W:ie;for(let m=0;m<u.length;m+=y){if(!await oo(l.id))return;let h=u.slice(m,m+Math.min(y,I==="http"?W:ie)).map($=>({trackId:l.id,event:$}));if(!Be(h))return}}}function On(s){!Y||!s?.trackId||typeof s.id!="string"||(oe.push({trackId:s.trackId,event:s}),H||(H=setTimeout(Nt,Mr),H.unref?.()))}let je=new Map;async function uo(s){let{reqId:l,method:a,path:o,headers:u={},body:y}=s,m=Object.fromEntries(Object.entries(u).filter(([,$])=>$!=null)),h=new AbortController;je.set(l,h);try{if(s.host){await fo(s,m,h);return}k&&(m["x-bostrat-token"]=k);let $=await fetch(A+o,{method:a,headers:m,body:y?Buffer.from(y,"base64"):void 0,signal:h.signal}),J=Object.fromEntries($.headers);for(let F of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete J[F];if(J["content-type"]||(J["content-type"]="application/octet-stream"),M({v:P,ch:"control",type:"http_head",reqId:l,status:$.status,headers:J}),$.body){for await(let F of $.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 fo(s,l,a){let{reqId:o,method:u,path:y,body:m}=s,h=new URL(A);return new Promise($=>{let J=ks.request({host:h.hostname,port:h.port,method:u,path:y,headers:{...l,host:s.host},signal:a.signal},F=>{let{connection:et,"keep-alive":me,"transfer-encoding":In,upgrade:Oi,...po}=F.headers;M({v:P,ch:"control",type:"http_head",reqId:o,status:F.statusCode||502,headers:po}),F.on("data",ho=>{M({v:P,ch:"control",type:"http_data",reqId:o,data:Buffer.from(ho).toString("base64")})||F.destroy()}),F.on("end",()=>{M({v:P,ch:"control",type:"http_end",reqId:o,error:null}),$()}),F.on("error",()=>{M({v:P,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),$()})});J.on("error",F=>{M({v:P,ch:"control",type:"http_end",reqId:o,error:F?.message||"view request failed"}),$()}),m&&J.write(Buffer.from(m,"base64")),J.end()})}function Rn(){if(At||Ce)return;z=new Jt(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:r,platform:process.platform,version:G,installKind:N,...typeof b=="function"?{updatePolicy:b()}:b?{updatePolicy:b}:{},providers:Cr(),...a?{agents:a}:{}})}),z.on("message",a=>{pe=Date.now();let o;try{o=JSON.parse(a)}catch{return}if(o.ch==="ctl"&&o.type==="hello_ok"){Y=!0,Pe=Rr,De=null,Hn(),w.log(`[plane-link] connected to plane as ${n}`);try{Xr?.()}catch{}if(typeof o.hashKey=="string"&&o.hashKey)try{O?.(o.hashKey)}catch{}try{f?.(typeof o.viewBase=="string"&&o.viewBase?o.viewBase:null)}catch{}o.minNodeVersion&&G&&Oe(G,o.minNodeVersion)&&w.error(`[plane-link] this node is bostrat-node ${G}; the plane asks for \u2265${o.minNodeVersion} \u2014 update with: ${Ge(N)}`);try{x?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}gn(o);let u=o.ingest==="http";I=Tt==="ws"?"ws":Tt==="http"||u?"http":"ws",Tt==="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"),I==="http"&&w.log("[plane-link] spine rides the HTTPS ingest door"),V=!1,fe=0,W=ie,Q&&clearInterval(Q),pe=Date.now(),Q=setInterval(()=>{ro(s)||(M({v:P,ch:"ctl",type:"ping"}),$n(),ao().catch(()=>{}),Rt(),oe.length&&!H&&Nt())},hn),Q.unref?.(),co(),lo().catch(y=>w.error("[plane-link] backfill failed:",y?.message||y));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let u=typeof o.minNodeVersion=="string"?o.minNodeVersion:null,y=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;w.error(`[plane-link] plane REFUSED this node: bostrat-node ${G??"?"} is below its minimum ${u??"?"} \u2014 ${o.fix||Ge(N)}`),Pe=Nr,De=0;try{R?.({current:G,min:u,latest:y,fix:o.fix||Ge(N),installKind:N})}catch(m){w.error(`[plane-link] refusal handler failed: ${m?.message||m}`)}return}if(o.ch==="ctl"&&o.type==="removed"){M({v:P,ch:"ctl",type:"removed_ack",nodeId:n}),$t({reason:typeof o.reason=="string"?o.reason:"removed",at:Number(o.at)||Date.now(),via:"ctl"});return}if(o.ch==="ctl"&&o.type==="update_available"){gn(o);return}if(o.ch==="ctl"&&o.type==="update_policy"){try{x?.(typeof o.mode=="string"?o.mode:null)}catch{}return}if(o.ch==="ctl"&&o.type==="usage_caps"){Er(o.caps??{},{source:"plane",updatedAt:o.updatedAt??Date.now()}).then(u=>w.log(`[plane-link] spend caps ${Object.keys(u.caps).length?`updated (${Object.keys(u.caps).join(", ")})`:"cleared"} from plane`)).catch(u=>w.error("[plane-link] spend-caps push rejected:",u?.message||u));return}if(o.ch==="ctl"&&o.type==="transferred"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>d?.(o.tracks)).catch(u=>w.error("[plane-link] transfer notice failed:",u?.message||u));return}if(o.ch==="events"&&o.type==="ack"&&Array.isArray(o.ids)){Et(o.ids);return}if(o.ch==="events"&&o.type==="nack"&&Array.isArray(o.ids)){Ot(o.ids,o.reason,o.permanent===!0,o.retryAfterMs??null);return}if(o.ch==="control"&&o.type==="http_open"){uo(o).catch(u=>M({v:P,ch:"control",type:"http_end",reqId:o.reqId,error:u?.message||"tunnel error"}));return}if(o.ch==="control"&&o.type==="http_cancel"){je.get(o.reqId)?.abort();return}if(o.ch==="attach"&&o.type==="open"){let u=new Jt(Zr+o.path,Array.isArray(o.protocols)?o.protocols:[],o.host?{headers:{host:o.host}}:void 0);le.set(o.streamId,u),ue.set(o.streamId,[]),u.on("open",()=>{let m=ue.get(o.streamId)||[];ue.delete(o.streamId);for(let{buf:h,bin:$}of m)u.send(h,{binary:$})}),u.on("message",(m,h)=>{let $=h?m:Buffer.from(String(m));M({v:P,ch:"attach",type:"data",streamId:o.streamId,data:$.toString("base64"),...h?{bin:!0}:{}})});let y=()=>{ue.delete(o.streamId),le.delete(o.streamId)&&M({v:P,ch:"attach",type:"close",streamId:o.streamId})};u.on("close",y),u.on("error",y);return}if(o.ch==="attach"&&o.type==="data"){let u=le.get(o.streamId);if(!u)return;let y=Buffer.from(o.data,"base64"),m=o.bin===!0,h=ue.get(o.streamId);h?h.push({buf:y,bin:m}):u.send(y,{binary:m});return}if(o.ch==="attach"&&o.type==="close"){let u=le.get(o.streamId);le.delete(o.streamId),ue.delete(o.streamId),u?.close();return}});let l=()=>{Y&&w.log("[plane-link] disconnected from plane"),Y=!1,Q&&(clearInterval(Q),Q=null),ee&&(clearInterval(ee),ee=null),E.clear(),ne={},oe=[],H&&(clearTimeout(H),H=null),be.clear();for(let u of le.values())u.close();le.clear(),ue.clear();for(let u of je.values())u.abort();if(je.clear(),At||Ae)return;De==null&&(De=Date.now());let a=Date.now()-De<xs,o=Math.max(a?Es+Math.random()*Os:Pe,Me-Date.now(),Ke());Ae=setTimeout(()=>{Ae=null,Rn()},o),Ae.unref?.(),a||(Pe=Math.min(Pe*2,Nr))};z.on("close",l),z.on("error",a=>{let o=/Unexpected server response: (\d+)/.exec(a?.message||"")?.[1];if(o==="410"){$t({reason:"removed",via:"410"});return}if(o==="401"||o==="403"){let{tripped:u,holdMs:y}=at();u?w.error(`[plane-link] holding every plane call for ${Math.round(y/6e4)} min \u2014 three credential refusals in a row (HTTP ${o}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(y/6e4)} min.`):Date.now()-Qe>=Pr&&(Qe=Date.now(),w.error(`[plane-link] plane refused this node's credentials (HTTP ${o}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`))}l()})}ze.on("event",On),Qr().then(Rn);function Nn({bye:s=!0}={}){At=!0,ze.off("event",On),Ae&&clearTimeout(Ae),ke&&clearTimeout(ke),Q&&clearInterval(Q),ee&&clearInterval(ee),H&&clearTimeout(H),s&&M({v:P,ch:"ctl",type:"bye",reason:"shutdown"}),z?.close()}return{stop:()=>Nn(),status:()=>({connected:Y,nodeId:n,cursor:{...de},inflight:E.size,...xn(),auth:Kn(),dormant:Ce,removed:Ht(),deadLinkMs:_t,deadLinkRedials:bn,refused:{...Ze}}),_tick:()=>{$n(),Rt()}}}var G,en,nn,P,Rr,Nr,xs,Es,Os,ie,Rs,Ns,Is,Ms,Br,Ps,Zt,Ds,Cs,Bs,Ir,Ls,Mr,js,Qt,Fs,Pr,rn=v(()=>{lt();Or();Dt();Kt();G=(()=>{try{return $s(import.meta.url)("../package.json").version||null}catch{return null}})(),en=process.env.BOSTRAT_STATE_DIR||L.join(process.env.HOME||ht.tmpdir(),".bostrat"),nn=L.join(en,"plane-link","removed.json");P=1,Rr=1e3,Nr=3e4,xs=6e4,Es=1500,Os=500,ie=100,Rs=2e3,Ns=25e3,Is=2.5,Ms=6e4,Br=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Ps=Br(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Zt="refused:",Ds={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"},Cs=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},Bs=3e4,Ir=10*6e4,Ls=400,Mr=250,js=Br(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Qt=4,Fs=6e4,Pr=6e4});var jr=v(()=>{jt()});var Wr={};It(Wr,{ACTIONABLE_KINDS:()=>yt,REGISTRY_RETRY_ATTEMPTS:()=>cn,REGISTRY_WAIT_POLLS:()=>on,REGISTRY_WAIT_STEP_S:()=>sn,SELF_UPDATE_DIR:()=>an,createAutoUpdater:()=>ei,inFlight:()=>un,readStatus:()=>ln,selfUpdatePlan:()=>Hr,settleSelfUpdate:()=>Qs,startSelfUpdate:()=>Kr,underService:()=>Ur,updatePolicy:()=>Gs});import Fr from"node:fs";import ae from"node:fs/promises";import Hs from"node:os";import C from"node:path";import{spawn as Ks}from"node:child_process";import{createRequire as Ws}from"node:module";function Gs({kind:e=Re(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:yt.has(e)?e==="git-checkout"||Ur(t)?"auto":"prompt":"off"}function Ur(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Hr({kind:e,to:t,from:n=mt,statusFile:r=wt,logFile:i=C.join(an,"last.log"),port:c=Number(process.env.PORT)||3362,npmPrefix:d=null,serviceName:p=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:T=typeof process.getuid=="function"?process.getuid():0,liveDir:O=process.env.BOSTRAT_LIVE_CHECKOUT||C.resolve(C.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:f=Date.now(),attempts:g=1}={}){if(!yt.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 _=(A,k="")=>`write_status ${U(A)} ${k}`,x=process.platform==="darwin"?`launchctl kickstart -k gui/${T}/${p}`:`systemctl --user restart ${U(p)}`,R=`
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
- }`,v=`#!/usr/bin/env bash
123
+ }`,b=`#!/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: ${r}
126
126
  set -u
@@ -137,7 +137,7 @@ write_status() { # <status> [error] [retryable]
137
137
  "\${err:+,\\"error\\":\\"$err\\"}" "\${3:+,\\"retryable\\":true}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
138
138
  }
139
139
  ${R}
140
- `;if(e==="npm-global"){let A=d?L.join(d,"bin","npm"):"npm",k=d?`export PATH=${U(L.join(d,"bin"))}:"$PATH"
140
+ `;if(e==="npm-global"){let A=d?C.join(d,"bin","npm"):"npm",k=d?`export PATH=${U(C.join(d,"bin"))}:"$PATH"
141
141
  `:"",S=d?` --prefix ${U(d)}`:"",j=Se=>`${U(A)} install -g "bostrat-node@${Se}" --no-audit --no-fund${S}`,te=`
142
142
  wait_for_registry() {
143
143
  for i in $(seq 1 ${on}); do
@@ -145,7 +145,7 @@ wait_for_registry() {
145
145
  sleep ${sn}
146
146
  done
147
147
  return 1
148
- }`;return v+k+te+`
148
+ }`;return b+k+te+`
149
149
  ${_("updating",'"" ')}
150
150
  if ! wait_for_registry; then
151
151
  ${_("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(on*sn/60)} min, attempt $ATTEMPTS of ${cn})" retryable`)}
@@ -172,7 +172,7 @@ if [ -n "$FROM" ] && ${j("$FROM")} && ${x} && health; then
172
172
  fi
173
173
  ${_("failed",'"agent did not answer after the update AND the rollback"')}
174
174
  exit 1
175
- `}let N=A=>`( cd ${U(O)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${A}" )`;return v+`
175
+ `}let N=A=>`( cd ${U(O)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${A}" )`;return b+`
176
176
  LIVE=${U(O)}
177
177
  TMP_SCRIPT="$(mktemp)"
178
178
  trap 'rm -f "$TMP_SCRIPT"' EXIT
@@ -190,12 +190,12 @@ if [ -n "$FROM" ] && ${N("$FROM")}; then
190
190
  fi
191
191
  ${_("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
192
192
  exit 1
193
- `}async function ln(e=wt){try{return JSON.parse(await ae.readFile(e,"utf8"))}catch{return null}}async function Hr({to:e,from:t=mt,kind:n=Re(),reason:r="manual",force:i=!1,statusFile:c=wt,spawnImpl:d=Hs,now:p=Date.now,npmPrefix:T=void 0,log:O=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!yt.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 ln(c);if(un(f))return{ok:!1,reason:`an update to ${f.to} is already in flight`,status:f};let g=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&&g<cn))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")?g+1:1;await ae.mkdir(L.dirname(c),{recursive:!0});let x=T!==void 0?T:n==="npm-global"?Ct(await qs())||L.resolve(L.dirname(process.execPath),".."):null,R=Ur({kind:n,to:e,from:t,statusFile:c,npmPrefix:x,startedAt:p(),attempts:_}),v=L.join(L.dirname(c),`update-${e}.sh`),N=L.join(L.dirname(c),"last.log");await ae.writeFile(v,R,{mode:448}),await ae.writeFile(c,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:_,startedAt:p(),updatedAt:p()}));let A=jr.existsSync("/run/systemd/system")&&await Xs("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",v]]:["setsid",["-f","bash","-c",`exec bash ${U(v)} >> ${U(N)} 2>&1`]];try{d(A[0],A[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(k){return await ae.writeFile(c,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,startedAt:p(),updatedAt:p(),error:`could not spawn updater: ${k?.message||k}`})),{ok:!1,reason:`could not spawn updater: ${k?.message||k}`}}return O.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${c}`),{ok:!0,to:e,from:t,kind:n,scriptFile:v,statusFile:c}}async function qs(){try{return await ae.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Xs(e){for(let t of String(process.env.PATH||"").split(L.delimiter))try{return await ae.access(L.join(t,e),jr.constants.X_OK),!0}catch{}return!1}async function Zs({statusFile:e=wt,current:t=mt,now:n=Date.now,staleMs:r=Js}={}){let i=await ln(e);if(!i)return null;let c=d=>ae.writeFile(e,JSON.stringify(d)).catch(()=>{});if(un(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)>r){let d={...i,status:"failed",error:`updater went silent while ${i.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await 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 Qs({isBusy:e,start:t=Hr,onStuck:n=null,onStarted:r=null,tickMs:i=Ys,stuckMs:c=zs,now:d=Date.now,setIntervalImpl:p=setInterval,clearIntervalImpl:T=clearInterval,log:O=console}={}){let f=null,g=()=>{f?.timer&&T(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 R=f;g();let v=await t({to:R.to,from:R.from,kind:R.kind,reason:"auto"});O.log?.(`[self-update] stasis reached \u2192 ${v.ok?"started":`not started: ${v.reason}`}`);try{await r?.({...R,result:v})}catch{}};return{arm({to:x,from:R=mt,kind:v=Re()}){return f?.to===x?!1:(g(),f={to:x,from:R,kind:v,since:d(),stuckFired:!1,timer:p(_,i)},f.timer.unref?.(),!0)},tick:_,cancel:g,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var mt,Ws,an,wt,zs,Ys,on,sn,cn,yt,U,Vs,un,Js,Wr=b(()=>{rn();Cr();mt=(()=>{try{return Ks(import.meta.url)("../package.json").version||null}catch{return null}})(),Ws=process.env.BOSTRAT_STATE_DIR||L.join(process.env.HOME||Us.tmpdir(),".bostrat"),an=L.join(Ws,"self-update"),wt=L.join(an,"status.json"),zs=1440*6e4,Ys=6e4,on=60,sn=15,cn=3,yt=new Set(["npm-global","git-checkout"]);U=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Vs=new Set(["updating","restarting","rolling-back"]),un=e=>!!(e&&Vs.has(e.status));Js=45*6e4});Dt();Bt();import q from"node:fs";import D from"node:path";import Ie from"node:os";import{createRequire as dn}from"node:module";import{execFile as ei,spawn as ti}from"node:child_process";import{promisify as ni}from"node:util";import ri from"node:readline/promises";import{randomUUID as oi}from"node:crypto";import{fileURLToPath as si}from"node:url";import Qo from"node:fs";import or from"node:path";import es from"node:os";var ts=()=>process.env.BOSTRAT_STATE_DIR||or.join(process.env.HOME||es.tmpdir(),".bostrat"),ns=()=>or.join(ts(),"plane-link","public-host.json");var Ye=null;function rs(){if(Ye)return Ye;try{let e=JSON.parse(Qo.readFileSync(ns(),"utf8"));Ye={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{Ye={viewBase:null}}return Ye}function os(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),i=r?r[1].toLowerCase():t,c=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return c?{proto:i,host:c}:null}function sr(){return rs().viewBase}function ir(e=process.env.BOSTRAT_PUBLIC_HOST){return os(e,"https")}function ar(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 zr=(e,t)=>{let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let i=0;i<Math.max(n.length,r.length);i++){let c=(n[i]||0)-(r[i]||0);if(c)return c<0}return!1},ce=ni(ei),fn=D.dirname(si(import.meta.url)),_e=D.resolve(fn,".."),ii=D.join(fn,"index.js"),ai="wss://plane.bostrat.ai/v1/node",Ne=dn(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 ci(){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 li(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 ui(e){let t;try{t=q.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 di(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await ce(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 Yr(e,{required:t=!1}={}){if(await Gt(e,{loginShell:!0,failOpen:!1}))return B(e,"resolves on the login-shell PATH");let r="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",i=dt[e]?`${dt[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,r,i):X(e,r,i)}async function fi(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await ce(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",dt.gh)}}async function pi(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Yr(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 hi(){let e=[...process.platform==="linux"?[["fuser","stopped views can't free their ports (they leak, and the port can't be reused)","apt install psmisc"]]:[],["pgrep","agent-swap can't detect an idle pane shell \u2014 swaps may misfire","apt install procps"],["npm","codex auto-update and `npm run` views are unavailable","install Node.js with npm on the service PATH"]];return Promise.all(e.map(async([t,n,r])=>await Gt(t,{failOpen:!1})?B(t,"resolves on the service PATH"):X(t,`not on the service PATH \u2014 ${n}`,r)))}async function mi(){try{let t=dn(D.join(_e,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let i=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),c=setTimeout(()=>r(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=dn(D.join(_e,"package.json")),r=D.join(D.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");q.existsSync(r)&&!(q.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return K("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function wi(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(q.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 yi(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 gi(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,r=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}`}}),p=null,T=f=>{clearTimeout(O);try{d.close()}catch{}c(p?{...f,viewBase:p}:f)},O=setTimeout(()=>T(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-${oi().slice(0,8)}`,ephemeral:!0}))),d.on("message",f=>{try{let g=JSON.parse(f);g.type==="hello_ok"?(typeof g.viewBase=="string"&&g.viewBase&&(p=g.viewBase),g.minNodeVersion&&zr(Ne,g.minNodeVersion)?T(K("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${g.minNodeVersion} \u2014 this node is ${Ne}; the real link is refused until it updates`,`bostrat-node self-update --to ${g.latestNodeVersion||g.minNodeVersion}`)):g.latestNodeVersion&&zr(Ne,g.latestNodeVersion)?T(X("plane link",`hello_ok in ${Date.now()-r}ms (${i}); bostrat-node ${g.latestNodeVersion} is available (this node: ${Ne})`,`bostrat-node self-update --to ${g.latestNodeVersion}`)):T(B("plane link",`hello_ok in ${Date.now()-r}ms (${i})`))):g.type==="error"&&T(K("plane link",`plane said: ${g.code} ${g.message||""}`,"check the token"))}catch{}}),d.on("error",f=>T(K("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function Ti(){let e;try{e=JSON.parse(q.readFileSync(D.join(Pt,"content-outbox.json"),"utf8"))}catch{return B("content outbox","empty \u2014 every deliverable has reached the plane")}let t=e.ops?.length||0,n=e.parked?.length||0;if(n){let r=e.parked[0];return K("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?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 _i(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 Si(e,t){let n=t?.viewBase??null,r=sr(),i=ir(e.BOSTRAT_PUBLIC_HOST),c=(()=>{let d=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(d)return`${d.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let p=ar(e.BOSTRAT_PLANE_URL);return p?`${p}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let d=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 r?B("public host",`views https://<slug>.${r}/ (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 Gr(e,t={}){let n=[];n.push(await ci()),n.push(ui(t.envFile||$e())),n.push(await di(e)),n.push(...await pi()),n.push(await Yr("git",{required:!0})),n.push(await fi()),n.push(...await hi()),n.push(await mi()),n.push(wi(e)),n.push(yi(e)),n.push(li(e));let r=await gi(e,t);return n.push(r),n.push(Si(e,r)),n.push(Ti()),n.push(_i(e)),n}function Vr(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 r=e.filter(c=>c.level==="fail").length,i=e.filter(c=>c.level==="warn").length;return t(r?`
193
+ `}async function ln(e=wt){try{return JSON.parse(await ae.readFile(e,"utf8"))}catch{return null}}async function Kr({to:e,from:t=mt,kind:n=Re(),reason:r="manual",force:i=!1,statusFile:c=wt,spawnImpl:d=Ks,now:p=Date.now,npmPrefix:T=void 0,log:O=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!yt.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 ln(c);if(un(f))return{ok:!1,reason:`an update to ${f.to} is already in flight`,status:f};let g=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&&g<cn))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")?g+1:1;await ae.mkdir(C.dirname(c),{recursive:!0});let x=T!==void 0?T:n==="npm-global"?Lt(await Xs())||C.resolve(C.dirname(process.execPath),".."):null,R=Hr({kind:n,to:e,from:t,statusFile:c,npmPrefix:x,startedAt:p(),attempts:_}),b=C.join(C.dirname(c),`update-${e}.sh`),N=C.join(C.dirname(c),"last.log");await ae.writeFile(b,R,{mode:448}),await ae.writeFile(c,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:_,startedAt:p(),updatedAt:p()}));let A=Fr.existsSync("/run/systemd/system")&&await Js("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",b]]:["setsid",["-f","bash","-c",`exec bash ${U(b)} >> ${U(N)} 2>&1`]];try{d(A[0],A[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(k){return await ae.writeFile(c,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,startedAt:p(),updatedAt:p(),error:`could not spawn updater: ${k?.message||k}`})),{ok:!1,reason:`could not spawn updater: ${k?.message||k}`}}return O.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${c}`),{ok:!0,to:e,from:t,kind:n,scriptFile:b,statusFile:c}}async function Xs(){try{return await ae.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Js(e){for(let t of String(process.env.PATH||"").split(C.delimiter))try{return await ae.access(C.join(t,e),Fr.constants.X_OK),!0}catch{}return!1}async function Qs({statusFile:e=wt,current:t=mt,now:n=Date.now,staleMs:r=Zs}={}){let i=await ln(e);if(!i)return null;let c=d=>ae.writeFile(e,JSON.stringify(d)).catch(()=>{});if(un(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)>r){let d={...i,status:"failed",error:`updater went silent while ${i.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await 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 ei({isBusy:e,start:t=Kr,onStuck:n=null,onStarted:r=null,tickMs:i=Ys,stuckMs:c=Vs,now:d=Date.now,setIntervalImpl:p=setInterval,clearIntervalImpl:T=clearInterval,log:O=console}={}){let f=null,g=()=>{f?.timer&&T(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 R=f;g();let b=await t({to:R.to,from:R.from,kind:R.kind,reason:"auto"});O.log?.(`[self-update] stasis reached \u2192 ${b.ok?"started":`not started: ${b.reason}`}`);try{await r?.({...R,result:b})}catch{}};return{arm({to:x,from:R=mt,kind:b=Re()}){return f?.to===x?!1:(g(),f={to:x,from:R,kind:b,since:d(),stuckFired:!1,timer:p(_,i)},f.timer.unref?.(),!0)},tick:_,cancel:g,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var mt,zs,an,wt,Vs,Ys,on,sn,cn,yt,U,qs,un,Zs,zr=v(()=>{rn();jr();mt=(()=>{try{return Ws(import.meta.url)("../package.json").version||null}catch{return null}})(),zs=process.env.BOSTRAT_STATE_DIR||C.join(process.env.HOME||Hs.tmpdir(),".bostrat"),an=C.join(zs,"self-update"),wt=C.join(an,"status.json"),Vs=1440*6e4,Ys=6e4,on=60,sn=15,cn=3,yt=new Set(["npm-global","git-checkout"]);U=e=>`'${String(e).replace(/'/g,"'\\''")}'`;qs=new Set(["updating","restarting","rolling-back"]),un=e=>!!(e&&qs.has(e.status));Zs=45*6e4});Dt();Bt();import q from"node:fs";import D from"node:path";import Ie from"node:os";import{createRequire as dn}from"node:module";import{execFile as ti,spawn as ni}from"node:child_process";import{promisify as ri}from"node:util";import oi from"node:readline/promises";import{randomUUID as si}from"node:crypto";import{fileURLToPath as ii}from"node:url";import es from"node:fs";import sr from"node:path";import ts from"node:os";var ns=()=>process.env.BOSTRAT_STATE_DIR||sr.join(process.env.HOME||ts.tmpdir(),".bostrat"),rs=()=>sr.join(ns(),"plane-link","public-host.json");var Ve=null;function os(){if(Ve)return Ve;try{let e=JSON.parse(es.readFileSync(rs(),"utf8"));Ve={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{Ve={viewBase:null}}return Ve}function ss(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),i=r?r[1].toLowerCase():t,c=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return c?{proto:i,host:c}:null}function ir(){return os().viewBase}function ar(e=process.env.BOSTRAT_PUBLIC_HOST){return ss(e,"https")}function cr(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 Vr=(e,t)=>{let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let i=0;i<Math.max(n.length,r.length);i++){let c=(n[i]||0)-(r[i]||0);if(c)return c<0}return!1},ce=ri(ti),fn=D.dirname(ii(import.meta.url)),_e=D.resolve(fn,".."),ai=D.join(fn,"index.js"),ci="wss://plane.bostrat.ai/v1/node",Ne=dn(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 li(){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 ui(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 di(e){let t;try{t=q.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 fi(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await ce(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 Yr(e,{required:t=!1}={}){if(await Yt(e,{loginShell:!0,failOpen:!1}))return B(e,"resolves on the login-shell PATH");let r="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",i=dt[e]?`${dt[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,r,i):X(e,r,i)}async function pi(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await ce(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",dt.gh)}}async function hi(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Yr(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 mi(){let e=[...process.platform==="linux"?[["fuser","stopped views can't free their ports (they leak, and the port can't be reused)","apt install psmisc"]]:[],["pgrep","agent-swap can't detect an idle pane shell \u2014 swaps may misfire","apt install procps"],["npm","codex auto-update and `npm run` views are unavailable","install Node.js with npm on the service PATH"]];return Promise.all(e.map(async([t,n,r])=>await Yt(t,{failOpen:!1})?B(t,"resolves on the service PATH"):X(t,`not on the service PATH \u2014 ${n}`,r)))}async function wi(){try{let t=dn(D.join(_e,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let i=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),c=setTimeout(()=>r(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=dn(D.join(_e,"package.json")),r=D.join(D.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");q.existsSync(r)&&!(q.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return K("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function yi(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(q.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 gi(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 Ti(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,r=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}`}}),p=null,T=f=>{clearTimeout(O);try{d.close()}catch{}c(p?{...f,viewBase:p}:f)},O=setTimeout(()=>T(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-${si().slice(0,8)}`,ephemeral:!0}))),d.on("message",f=>{try{let g=JSON.parse(f);g.type==="hello_ok"?(typeof g.viewBase=="string"&&g.viewBase&&(p=g.viewBase),g.minNodeVersion&&Vr(Ne,g.minNodeVersion)?T(K("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${g.minNodeVersion} \u2014 this node is ${Ne}; the real link is refused until it updates`,`bostrat-node self-update --to ${g.latestNodeVersion||g.minNodeVersion}`)):g.latestNodeVersion&&Vr(Ne,g.latestNodeVersion)?T(X("plane link",`hello_ok in ${Date.now()-r}ms (${i}); bostrat-node ${g.latestNodeVersion} is available (this node: ${Ne})`,`bostrat-node self-update --to ${g.latestNodeVersion}`)):T(B("plane link",`hello_ok in ${Date.now()-r}ms (${i})`))):g.type==="error"&&T(K("plane link",`plane said: ${g.code} ${g.message||""}`,"check the token"))}catch{}}),d.on("error",f=>T(K("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function _i(){let e;try{e=JSON.parse(q.readFileSync(D.join(Pt,"content-outbox.json"),"utf8"))}catch{return B("content outbox","empty \u2014 every deliverable has reached the plane")}let t=e.ops?.length||0,n=e.parked?.length||0;if(n){let r=e.parked[0];return K("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?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 Si(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 vi(e,t){let n=t?.viewBase??null,r=ir(),i=ar(e.BOSTRAT_PUBLIC_HOST),c=(()=>{let d=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(d)return`${d.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let p=cr(e.BOSTRAT_PLANE_URL);return p?`${p}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let d=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 r?B("public host",`views https://<slug>.${r}/ (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 Gr(e,t={}){let n=[];n.push(await li()),n.push(di(t.envFile||$e())),n.push(await fi(e)),n.push(...await hi()),n.push(await Yr("git",{required:!0})),n.push(await pi()),n.push(...await mi()),n.push(await wi()),n.push(yi(e)),n.push(gi(e)),n.push(ui(e));let r=await Ti(e,t);return n.push(r),n.push(vi(e,r)),n.push(_i()),n.push(Si(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 r=e.filter(c=>c.level==="fail").length,i=e.filter(c=>c.level==="warn").length;return t(r?`
194
194
  FAIL \u2014 ${r} blocking, ${i} warnings`:`
195
- OK \u2014 0 blocking, ${i} warnings`),r===0}async function bi({envFile:e=$e(),input:t=process.stdin,output:n=process.stdout}={}){let r=nt(e),i=ri.createInterface({input:t,output:n}),c=async(k,S)=>(await i.question(S?`${k} [${S}]: `:`${k}: `)).trim()||S||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
195
+ OK \u2014 0 blocking, ${i} warnings`),r===0}async function bi({envFile:e=$e(),input:t=process.stdin,output:n=process.stdout}={}){let r=nt(e),i=oi.createInterface({input:t,output:n}),c=async(k,S)=>(await i.question(S?`${k} [${S}]: `:`${k}: `)).trim()||S||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
196
196
  you type those inside each box, later (box-auth-policy).
197
197
 
198
- `);let d=await c("Plane URL",r.BOSTRAT_PLANE_URL||ai),p=Fe(d);p!==d.trim()&&n.write(` \u2192 using ${p}
198
+ `);let d=await c("Plane URL",r.BOSTRAT_PLANE_URL||ci),p=Fe(d);p!==d.trim()&&n.write(` \u2192 using ${p}
199
199
  `);let T=await c("Node token (minted plane-side; stored 0600)",r.BOSTRAT_PLANE_TOKEN);r.BOSTRAT_OWNER&&n.write(` \u2192 dropping BOSTRAT_OWNER from node.env \u2014 the plane infers the owner from the token; a stale id here got every event refused.
200
200
  `);let O=await c("Node name",r.BOSTRAT_NODE_NAME||Ie.hostname().split(".")[0]),f=await c("Repos root",r.BOSTRAT_REPOS_ROOT||D.join(Ie.homedir(),"Documents")),g=await c("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),_=(await c("Route NEW claude boxes through a BYO API key? (y/N)",r.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");_&&n.write(`
201
201
  BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
@@ -209,8 +209,8 @@ injected per box, stored 0600 in node.env, never sent to the plane.
209
209
  Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
210
210
  wrote ${e}
211
211
 
212
- `);let v={...R,...process.env},N=await Gr(v,{envFile:e}),A=Vr(N,k=>n.write(k+`
213
- `));return A&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:A,results:N}}function vi({envFile:e=$e()}={}){Mn(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=ti(t,[ii],{cwd:_e,stdio:"inherit",env:process.env});for(let r of["SIGINT","SIGTERM"])process.on(r,()=>n.kill(r));return n.on("exit",(r,i)=>process.exit(i?1:r??1)),n}function Ai({agentDir:e=_e,nodeBin:t=process.execPath,envFile:n=$e(),home:r=Ie.homedir()}={}){let i=D.dirname(t),c=D.join(D.basename(fn),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
212
+ `);let b={...R,...process.env},N=await Gr(b,{envFile:e}),A=qr(N,k=>n.write(k+`
213
+ `));return A&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:A,results:N}}function Ai({envFile:e=$e()}={}){Mn(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=ni(t,[ai],{cwd:_e,stdio:"inherit",env:process.env});for(let r of["SIGINT","SIGTERM"])process.on(r,()=>n.kill(r));return n.on("exit",(r,i)=>process.exit(i?1:r??1)),n}function ki({agentDir:e=_e,nodeBin:t=process.execPath,envFile:n=$e(),home:r=Ie.homedir()}={}){let i=D.dirname(t),c=D.join(D.basename(fn),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
214
214
  # ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
215
215
  [Unit]
216
216
  Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
@@ -230,7 +230,7 @@ RestartSec=2
230
230
 
231
231
  [Install]
232
232
  WantedBy=default.target
233
- `}function ki({agentDir:e=_e,nodeBin:t=process.execPath,home:n=Ie.homedir()}={}){let r=D.dirname(t),i=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
233
+ `}function $i({agentDir:e=_e,nodeBin:t=process.execPath,home:n=Ie.homedir()}={}){let r=D.dirname(t),i=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
234
234
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
235
235
  <plist version="1.0">
236
236
  <dict>
@@ -252,7 +252,7 @@ WantedBy=default.target
252
252
  <key>StandardErrorPath</key><string>${i}/node.err.log</string>
253
253
  </dict>
254
254
  </plist>
255
- `}function $i(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 xi({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:i=_e}={}){let{kind:c,file:d}=$i(n);if(!e&&i.split(D.sep).includes("_npx"))return r("\u2717 running from the npx cache \u2014 a service must point at a durable install."),r(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){c==="systemd"?(await ce("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),q.rmSync(d,{force:!0}),await ce("systemctl",["--user","daemon-reload"])):(await ce("launchctl",["unload","-w",d]).catch(()=>{}),q.rmSync(d,{force:!0})),r(`removed ${d}`);return}q.mkdirSync(D.dirname(d),{recursive:!0}),c==="systemd"?(q.writeFileSync(d,Ai()),await ce("systemctl",["--user","daemon-reload"]),t&&await ce("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${d}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(q.mkdirSync(D.join(Ie.homedir(),"Library","Logs","bostrat"),{recursive:!0}),q.writeFileSync(d,ki()),t&&await ce("launchctl",["load","-w",d]),r(`installed ${d}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function Zl(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 bi({envFile:n})).ok?0:1;if(t==="doctor"){let r={...nt(n),...process.env};return Vr(await Gr(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return vi({envFile:n}),null;if(t==="install-service")return await xi({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(hr(),pr));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:i,updatePolicy:c}=await Promise.resolve().then(()=>(Wr(),Kr)),{detectInstallKind:d}=await Promise.resolve().then(()=>(rn(),Br)),p=d(),T=e.indexOf("--to"),O=T>=0?String(e[T+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Ne,installKind:p,policy:c({kind:p}),status:await i()},null,2)),0;if(!O)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let f=await r({to:O,kind:p,reason:"cli",force:!0});return f.ok?(console.log(`\u2713 self-update ${f.from??"?"} \u2192 ${f.to} started (${f.kind}) \u2014 status: ${f.statusFile}; the 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)
255
+ `}function xi(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 Ei({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:i=_e}={}){let{kind:c,file:d}=xi(n);if(!e&&i.split(D.sep).includes("_npx"))return r("\u2717 running from the npx cache \u2014 a service must point at a durable install."),r(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){c==="systemd"?(await ce("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),q.rmSync(d,{force:!0}),await ce("systemctl",["--user","daemon-reload"])):(await ce("launchctl",["unload","-w",d]).catch(()=>{}),q.rmSync(d,{force:!0})),r(`removed ${d}`);return}q.mkdirSync(D.dirname(d),{recursive:!0}),c==="systemd"?(q.writeFileSync(d,ki()),await ce("systemctl",["--user","daemon-reload"]),t&&await ce("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${d}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(q.mkdirSync(D.join(Ie.homedir(),"Library","Logs","bostrat"),{recursive:!0}),q.writeFileSync(d,$i()),t&&await ce("launchctl",["load","-w",d]),r(`installed ${d}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function nu(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 bi({envFile:n})).ok?0:1;if(t==="doctor"){let r={...nt(n),...process.env};return qr(await Gr(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return Ai({envFile:n}),null;if(t==="install-service")return await Ei({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(mr(),hr));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:i,updatePolicy:c}=await Promise.resolve().then(()=>(zr(),Wr)),{detectInstallKind:d}=await Promise.resolve().then(()=>(rn(),Lr)),p=d(),T=e.indexOf("--to"),O=T>=0?String(e[T+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Ne,installKind:p,policy:c({kind:p}),status:await i()},null,2)),0;if(!O)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let f=await r({to:O,kind:p,reason:"cli",force:!0});return f.ok?(console.log(`\u2713 self-update ${f.from??"?"} \u2192 ${f.to} started (${f.kind}) \u2014 status: ${f.statusFile}; the 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)
256
256
 
257
257
  usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
258
258
 
@@ -261,4 +261,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
261
261
  run start the node in the foreground (sources node.env)
262
262
  install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
263
263
  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{bi as init,xi as installService,ki as launchdPlist,Zl as main,Vr as printDoctor,vi as runAgent,Gr as runDoctor,$i as servicePaths,Ai as systemdUnit};
264
+ self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{bi as init,Ei as installService,$i as launchdPlist,nu as main,qr as printDoctor,Ai as runAgent,Gr as runDoctor,xi as servicePaths,ki as systemdUnit};