bostrat-node 1.11.6 → 1.11.7

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 +62 -62
  2. package/dist/index.js +187 -187
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
- var po=Object.defineProperty;var A=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var It=(e,t)=>{for(var n in t)po(e,n,{get:t[n],enumerable:!0})};import tt from"node:fs";import Mt from"node:path";import ho 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 s={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return s?(r.protocol=s,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function nt(e){let t;try{t=tt.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
2
- `)){let s=r.trim();if(!s||s.startsWith("#"))continue;let c=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(s);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 In(e,t=process.env){let n=nt(e);for(let[r,s]of Object.entries(n))r in t||(t[r]=s);return n}function Mn(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
3
- `).map(s=>s?`# ${s}`:"#"));for(let[s,c]of Object.entries(t))c==null||c===""||r.push(`${s}=${c}`);tt.mkdirSync(Mt.dirname(e),{recursive:!0}),tt.writeFileSync(e,r.join(`
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(`
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
+ `).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 Pn(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=A(()=>{Pt=process.env.BOSTRAT_STATE_DIR||Mt.join(process.env.HOME||ho.tmpdir(),".bostrat"),$e=()=>Mt.join(Pt,"node.env")});var we,rt,ot=A(()=>{we="BOSTRAT_HOOK_TOKEN",rt="x-bostrat-hook"});var Dn=A(()=>{ot()});var mo,Li,Ln=A(()=>{mo="check_for_update_on_startup",Li=`${mo} = false`});import wo from"node:os";import Bn from"node:path";var yo,Ui,Hi,Lt=A(()=>{Bt();yo=process.env.BOSTRAT_DEBUG_DIR||Bn.join(wo.homedir(),".bostrat","debug"),Ui=Bn.join(yo,"handoff.jsonl"),Hi=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as To}from"node:child_process";import{promisify as _o}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 Vi,qi,Xi,Ji,jt=A(()=>{Lt();Vi=_o(To),qi=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Xi=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,Ji=Promise.resolve()});var Cn=A(()=>{});import Ft from"node:path";import{execFile as So}from"node:child_process";import{promisify as bo}from"node:util";var ra,jn,vo,oa,sa,Fn=A(()=>{ra=bo(So),jn=process.env.HOME||"/home/globo",vo=Ft.join(process.env.BOSTRAT_STATE_DIR||Ft.join(jn,".bostrat"),"repos"),oa=[...(process.env.BOSTRAT_REPOS_ROOT||Ft.join(jn,"Documents")).split(","),vo].map(e=>e.trim()).filter(Boolean),sa=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 Un(){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 Hn(e=Date.now()){return{held:ct(e),holdMs:ge?null:Ke(e),holds:it,removed:ge?{...ge}:null}}var Ao,st,Ue,He,it,ye,ge,Kt=A(()=>{Ao={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},st={...Ao},Ue=0,He=0,it=0,ye=0,ge=null});import Kn from"node:path";import ko from"node:os";import{execFile as $o}from"node:child_process";import{promisify as xo}from"node:util";var ma,Eo,wa,ya,ga,Wt=A(()=>{Fn();Kt();ma=xo($o),Eo=process.env.BOSTRAT_STATE_DIR||Kn.join(process.env.HOME||ko.tmpdir(),".bostrat"),wa=Kn.join(Eo,"repos"),ya=5*6e4,ga=10*6e4});var Wn=A(()=>{Wt()});import Ro from"node:fs/promises";import We from"node:path";import No from"node:os";import{EventEmitter as Io}from"node:events";function Mo(e){return e?.cwd?We.join(e.cwd,".bostrat","events"):We.join(zn,"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(zn,"events"):Mo(e));let s;try{s=await Ro.readFile(Po(n,r),"utf8")}catch{return[]}let c=[];for(let d of s.split(`
6
- `))if(d.trim())try{c.push(JSON.parse(Lo(d)?Bo(d):d))}catch{}return c}var ze,zn,Po,Do,Lo,Bo,lt=A(()=>{ze=new Io;ze.setMaxListeners(0);zn=process.env.BOSTRAT_STATE_DIR||We.join(process.env.HOME||No.tmpdir(),".bostrat");Po=(e,t)=>We.join(e,`${t}.ndjson`),Do=/(?<!\\)((?:\\\\)*)\\u0000/g,Lo=e=>e.includes("\\u0000"),Bo=e=>e.replace(Do,"$1\\ufffd")});import jo from"node:os";import Fo from"node:path";import{execFile as Uo}from"node:child_process";import{promisify as Ho}from"node:util";var Da,La,Ba,Ca,ja,Fa,Yn=A(()=>{Wn();lt();Da=Ho(Uo),La=process.env.BOSTRAT_STATE_DIR||Fo.join(process.env.HOME||jo.tmpdir(),".bostrat"),Ba=25*1024,Ca=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,ja=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,Fa=Promise.resolve()});var Gn=A(()=>{});var Ya,Vn=A(()=>{Wt();Gn();Ya=60*6e4});var qn=A(()=>{Vn()});import Xn from"node:path";import Ko from"node:os";var ut,Wo,oc,Jn,sc,ic,Zn=A(()=>{ot();ut="BOSTRAT_NODE_URL",Wo=process.env.BOSTRAT_STATE_DIR||Xn.join(process.env.HOME||Ko.tmpdir(),".bostrat"),oc=Xn.join(Wo,"git-hooks"),Jn=`#!/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=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
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
- `,sc=`${Jn}
21
+ `,ic=`${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
- `,ic=`${Jn}
33
+ `,ac=`${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 zo}from"node:child_process";import{promisify as Yo}from"node:util";import Go from"node:fs";function tr(e){return`/tmp/tmux-${e}/default`}function qo({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let s=tr(r);return t?s:n?`${n}/bostrat/tmux-default`:s}async function Gt(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Jo(e,{loginShell:t});return r===nr?!0:r===Yt?!1:n}async function Jo(e,{loginShell:t=!1,timeoutMs:n=Xo}={}){if(!e)return Yt;let r=t?process.env.SHELL||"/bin/sh":"sh",s=t?"-lic":"-c";try{return await Vo(r,[s,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),nr}catch(c){return c?.killed||c?.signal?er:c?.code===1||c?.code===127?Yt:er}}var Vo,Nc,Qn,Ic,Mc,Pc,Dc,nr,Yt,er,Xo,dt,Lc,Bc,Cc,jc,Fc,Bt=A(()=>{Dn();Ln();jt();Cn();Yn();qn();Lt();ot();Zn();Vo=Yo(zo),Nc=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";Qn=typeof process.getuid=="function"?process.getuid():0,Ic=qo({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Go.existsSync(tr(Qn))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:Qn}),Mc=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Pc=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Dc=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]);nr="present",Yt="absent",er="unknown",Xo=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"},Lc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Bc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Cc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,jc=Number(process.env.BOSTRAT_BOX_COLS)||120,Fc=Number(process.env.BOSTRAT_BOX_ROWS)||40});var fr={};It(fr,{NODE_IMAGE:()=>qt,commandPlan:()=>lr,flyToml:()=>cr,flyWizard:()=>ds,parseFlyFlags:()=>ur,stageConfig:()=>dr});import Vt from"node:fs";import Te from"node:path";import os from"node:os";import ss from"node:readline/promises";import{execFile as is}from"node:child_process";import{createRequire as as}from"node:module";import{randomUUID as cs}from"node:crypto";function cr({app:e,region:t,nodeName:n=e,planeUrl:r=ar,image:s=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 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\`.
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.
@@ -54,7 +54,7 @@ swap_size_mb = 1024
54
54
  # The published node image (claude + cursor-agent + codex baked in, logged
55
55
  # out), pinned to the bostrat-node version that wrote this file. Update with:
56
56
  # npm i -g bostrat-node && bostrat-node fly (re-run is safe), or bump the tag.
57
- image = "${s}"
57
+ image = "${i}"
58
58
 
59
59
  [env]
60
60
  PORT = "3362"
@@ -79,23 +79,23 @@ 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 lr({app:e,org:t,region:n,sizeGb:r,token:s,dir:c}){let d=[`BOSTRAT_PLANE_TOKEN=${s}`];return[{argv:["apps","create",e,"-o",t],display:`fly apps create ${e} -o ${t}`,tolerate:/already|taken|exists/i},{argv:["volumes","create","node_data","-a",e,"-r",n,"-s",String(r),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${r} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted> via stdin`,stdin:d.join(`
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(`
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 ur(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--image":"image"};for(let r=0;r<e.length;r++){let s=e[r];if(s==="--yes"||s==="-y")t.yes=!0;else if(n[s])t[n[s]]=e[++r]??"";else if(s.startsWith("--")&&s.includes("=")){let[c,...d]=s.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 dr({app:e,dest:t,toml:n}){let r=t||Te.join(os.homedir(),".bostrat","fly",e);Vt.mkdirSync(r,{recursive:!0});for(let s of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])Vt.rmSync(Te.join(r,s),{recursive:!0,force:!0});return Vt.writeFileSync(Te.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function us({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:s}=await ft(["orgs","list","--json"],{exec:n}),c=JSON.parse(s),d=Array.isArray(c)?c.map(h=>h.Slug||h.slug).filter(Boolean):Object.keys(c);if(d.length===1)return t.write(`Org: ${d[0]} (your only org)
85
- `),d[0];if(d.length>1)return await e(`Fly org (${d.join(" / ")})`,d[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function ds({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:s}={}){let c=ur(e),d=ss.createInterface({input:t,output:n}),h=async(S,j)=>(await d.question(j?`${S} [${j}]: `:`${S}: `)).trim()||j||"",_=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 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.
86
86
  bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
87
87
 
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"),_(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"),_(1)}let g=await us({ask:h,output:n,exec:r,flag:c.org}),f=c.app||await h("App name",`bostrat-node-${cs().slice(0,4)}`),T=c.region||await h("Region (see `fly platform regions`)","iad"),b=c.sizeGb||Number(await h("Volume size GB (logins + repos live here)","10"))||10,x=c.name||f,k=c.planeUrl||ar,E=c.token||await h("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!E)return n.write(`\u2717 a node token is required \u2014 mint one in the bostrat setup chat (Connect a node \u2192 Fly), then re-run with it.
90
- `),_(1);let R=c.image||qt,{dir:v}=dr({app:f,dest:s,toml:cr({app:f,region:T,nodeName:x,planeUrl:k,image:R})});n.write(`
91
- wrote ${Te.join(v,"fly.toml")} \u2014 deploys the prebuilt node image ${R}
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(`
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 C=lr({app:f,org:g,region:T,sizeGb:b,token:E,dir:v});for(let S of C)n.write(` $ ${S.display}
96
- `);if(!c.yes&&(await h(`
95
+ `);let k=ur({app:f,org:O,region:g,sizeGb:_,token:v,dir:A});for(let S of k)n.write(` $ ${S.display}
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
- `),_(1);for(let S of C){n.write(`
98
+ `),T(1);for(let S of k){n.write(`
99
99
  \u2192 ${S.display}
100
100
  `);try{let{stdout:j,stderr:te}=await ft(S.argv,{stdin:S.stdin,exec:r}),Se=`${j||""}${te||""}`.trim();Se&&n.write(Se.split(`
101
101
  `).map(gt=>` ${gt}`).join(`
@@ -105,22 +105,22 @@ Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u201
105
105
  `).slice(-4).join(`
106
106
  `)}
107
107
  fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
108
- `),_(1)}}return n.write(`
108
+ `),T(1)}}return n.write(`
109
109
  \u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
110
110
  chat: the node step advances on its own within a minute.
111
111
  logs: fly logs -a ${f}
112
- redeploy: fly deploy ${v} -c ${Te.join(v,"fly.toml")} -a ${f} --ha=false
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
- `),_(0)}var ar,ls,qt,ft,pr=A(()=>{ar="wss://plane.bostrat.ai/v1/node",ls=as(import.meta.url)("../package.json").version,qt=`ghcr.io/globocodes/bostrat-node:${ls}`;ft=(e,{stdin:t,exec:n}={})=>new Promise((r,s)=>{if(n)return n(e,{stdin:t}).then(r,s);let c=is("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,h,_)=>d?s(Object.assign(d,{stdout:h,stderr:_})):r({stdout:h,stderr:_}));t!=null&&c.stdin?.end(t)})});function hr(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!ps.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 hs(e){let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||r.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=r.map(s=>({...s,fromMs:hr(s.from,"from",n),toMs:hr(s.to,"to",n)}))}return t}var fs,ps,Qc,el,mr=A(()=>{fs={"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)."}]},ps=/^\d{4}-\d{2}-\d{2}$/;Qc=hs(fs),el=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var wr=A(()=>{mr()});import yr from"node:fs/promises";import _r from"node:path";import ms from"node:os";function br(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function vr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Ar(e){let t=new Date(br(e));return t.setDate(t.getDate()+7),t.getTime()}function kr(e){let t=new Date(vr(e));return t.setMonth(t.getMonth()+1),t.getTime()}function _s(e=Date.now()){for(let[t,n]of Object.entries(gs)){let r=n.startOf(e);if(r!==pt[t]){pt[t]=r;for(let s of Xt.values())s[t]=0;for(let s of gr)s.includes(`:${t}:`)&&!s.endsWith(`:${r}`)&&gr.delete(s)}}}function Ss(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let s={};for(let c of["weeklyUsd","monthlyUsd"]){let d=r?.[c];if(d==null||d==="")continue;let h=Number(d);if(!Number.isFinite(h)||h<=0)throw new Error(`${n}.${c} must be a positive number or null`);s[c]=h}Object.keys(s).length&&(t[n]=s)}return t}async function $r(e,{source:t="local",updatedAt:n=Date.now()}={}){xe={caps:Ss(e),updatedAt:n,source:t};try{await yr.mkdir(Sr,{recursive:!0}),await yr.writeFile(ws(),JSON.stringify(xe,null,2))}catch{}return bs()}function bs(e=Date.now()){_s(e);let t=new Set([...Xt.keys(),...Object.keys(xe?.caps||{})]),n={};for(let r of t){let s=Xt.get(r);n[r]={weeklyUsd:Tr(s?.weekly||0),monthlyUsd:Tr(s?.monthly||0)}}return{caps:xe?.caps||{},configured:!!xe,seeded:Ts,updatedAt:xe?.updatedAt??null,spent:n,windows:{weekly:{start:pt.weekly,resetsAt:Ar(e)},monthly:{start:pt.monthly,resetsAt:kr(e)}},warnPct:ys}}var Sr,ws,ys,gs,xe,Ts,pt,Xt,gr,Tr,xr=A(()=>{lt();wr();Sr=process.env.BOSTRAT_STATE_DIR||_r.join(process.env.HOME||ms.tmpdir(),".bostrat"),ws=()=>_r.join(Sr,"usage-caps.json"),ys=.8;gs={weekly:{startOf:br,nextStart:Ar,capKey:"weeklyUsd"},monthly:{startOf:vr,nextStart:kr,capKey:"monthlyUsd"}},xe=null,Ts=!1,pt={weekly:0,monthly:0},Xt=new Map,gr=new Set;Tr=e=>Math.round(e*1e4)/1e4});var Lr={};It(Lr,{REMOVED_MARKER:()=>nn,detectInstallKind:()=>Re,detectProviderAuth:()=>Pr,maskToken:()=>tn,readRemovedMarker:()=>Mr,startPlaneLink:()=>js,updateCommandFor:()=>Ve,versionLt:()=>Oe});import Ee from"node:fs";import Ge from"node:fs/promises";import vs from"node:http";import B from"node:path";import ht from"node:os";import{createRequire as As}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 Mr(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=B.resolve(B.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(B.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 s=0;s<Math.max(n.length,r.length);s++){let c=(n[s]||0)-(r[s]||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 Pr({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(B.join(e,".claude",".credentials.json")),codex:n(B.join(t.CODEX_HOME||B.join(e,".codex"),"auth.json")),cursor:n(B.join(t.XDG_CONFIG_HOME||B.join(e,".config"),"cursor","auth.json"))}}function js({url:e,token:t,nodeId:n=ht.hostname(),name:r=ht.hostname(),listTracks:s,detectAgents:c=null,onTracksTransferred:d=null,sampleMetrics:h=null,deliverySample:_=null,onHashKey:g=null,onViewBase:f=null,metricsMs:T=Cs,onUpdateAvailable:b=null,onUpdatePolicy:x=null,onHelloRefused:k=null,updatePolicy:E=null,installKind:R=Re(),selfUrl:v=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:C=null,removedMarkerFile:S=nn,onRemoved:j=null,onDegraded:te=null,onRecovered:Se=null,onRefused:gt=null,onConnected:Vr=null,ingestMode:Tt=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:pn=Is,unackedRetryMs:qe=Ns,pingMs:hn=Os,deadLinkMs:_t=Math.round(hn*Rs),maxInflightEvents:qr=Ls,httpTimeoutMs:Xe=Bs,stallBackoffMinMs:mn=Ds,fetchImpl:wn=globalThis.fetch,log:w=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof s!="function")throw new Error("plane-link: listTracks is required");e=Fe(e);let Xr=v.replace(/^http/,"ws"),yn=new Set,le=new Map,ue=new Map,St=B.join(en,"plane-link","cursor.json"),bt=B.join(en,"plane-link","dead-letter.ndjson"),gn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),de={},ne={},O=new Map,Je=null,re=null,Z=0,Me=0,Tn=0,Ze={},_n=new Set,Sn=Promise.resolve(),N="ws",be=0,Y=!1,fe=0,vt=!1,W=ie,ve=new Set,oe=[],H=null,z=null,G=!1,At=!1,Pe=Er,De=null,Ae=null,ke=null,Q=null,pe=0,bn=0,ee=null,kt=!1,Qe=0,Le=!1,se=Mr(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:i="removed",at:l=Date.now(),via:a="ctl"}={}){if(!Le){Le=!0,Ut({reason:i,at:l,nodeId:n,via:a});try{Ee.mkdirSync(B.dirname(S),{recursive:!0}),Ee.writeFileSync(S,JSON.stringify({at:l,reason:i,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 (${i}, 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:i,at:l,via:a})}catch{}Rn({bye:!1})}}async function Jr(){try{de=JSON.parse(await Ge.readFile(St,"utf8"))}catch{de={}}}function Zr(){kt=!0,!ke&&(ke=setTimeout(async()=>{if(ke=null,!!kt){kt=!1;try{await Ge.mkdir(B.dirname(St),{recursive:!0}),await Ge.writeFile(St,JSON.stringify(de))}catch(i){w.error("[plane-link] cursor flush failed:",i?.message||i)}}},Es),ke.unref?.())}function I(i){return!z||z.readyState!==Jt.OPEN?!1:(z.send(JSON.stringify(i)),!0)}function Be(i){let l=Date.now();for(let{trackId:o,event:u}of i){let y=O.get(u.id);O.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=i.map(({trackId:o,event:u})=>({trackId:o,event:Ps(u)}));return N==="http"?(oo(a),!0):I({v:M,ch:"events",type:"append",events:a})}function Qr(i){let l=null;for(let a of O.values())a.trackId===i&&(l==null||a.seq<l)&&(l=a.seq);return l}function xt(i){let l=ne[i];if(l==null)return;let a=Qr(i),o=a==null?l:Math.min(l,a-1);o>(de[i]??0)&&(de[i]=o,Zr())}function Ce(){if(Je=Date.now(),re!=null){let i=Date.now()-re;w.log(`[plane-link] spine sync recovered after ${Math.round(i/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:i})}catch(a){w.error(`[plane-link] onRecovered failed: ${a?.message||a}`)}}}function Et(i){if(!Array.isArray(i)||!i.length)return;let l=new Set;for(let a of i){let o=O.get(a);o&&(O.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 vn(i,l){Tn++;let a={at:Date.now(),trackId:i.trackId,seq:i.seq,id:i.event?.id??null,type:i.event?.type??null,reason:l,event:i.event??null};w.error(`[plane-link] DEAD-LETTER ${i.trackId} seq ${i.seq} (${a.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${bt}`),Sn=Sn.then(async()=>{await Ge.mkdir(B.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 eo(i,l){if(Ze[i]=(Ze[i]??0)+1,_n.has(i))return;_n.add(i);let a=Ms[i]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";w.error(`[plane-link] REFUSED by the plane (${i}) on track ${l}: events are being dropped, not stored \u2014 ${a}`);try{gt?.({reason:i,trackId:l,count:Ze[i],hint:a})}catch(o){w.error(`[plane-link] onRefused failed: ${o?.message||o}`)}}function Ot(i,l,a,o=null){if(!Array.isArray(i)||!i.length)return;let u=new Set,y=Date.now();for(let p of i){let m=O.get(p);m&&(a?(O.delete(p),vn(m,l),String(l).startsWith(Zt)&&eo(String(l).slice(Zt.length),m.trackId),(ne[m.trackId]??0)<m.seq&&(ne[m.trackId]=m.seq),u.add(m.trackId)):(m.nacks++,m.retryAt=y+Math.max(1e3,Number(o)||qe)))}for(let p of u)xt(p);Ce()}function An(i=Date.now()){let l=1/0;for(let a of O.values())a.firstSentAt<l&&(l=a.firstSentAt);return l===1/0?0:i-l}function to(i){if(!_t||!i||i!==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{i.terminate()}catch{}return!0}function kn(){if(!G||!O.size)return;let i=Date.now(),l=An(i);if(l<pn||Je!=null&&i-Je<pn||N==="http"&&Y||Me>i)return;Z++;let a=Math.min(mn*2**(Z-1),Rr);if(re==null){re=i-l,w.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${O.size} event(s) in flight (${N} door) \u2014 the plane is not answering appends`);try{te?.({since:re,unacked:O.size,oldestAgeMs:l,mode:N})}catch(o){w.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(N==="http"){Y=!0,fe=i+a,w.error(`[plane-link] ingest circuit OPEN (stall #${Z}); probing /v1/ingest/health in ${Math.round(a/1e3)}s`);return}Me=i+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 i=Date.now();if(N==="http"&&Y)return;let l=[...O.values()].filter(o=>o.event&&o.retryAt<=i&&!(N==="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=N==="http"?W:ie;if(N==="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 no(i=null){for(;;){if(!G)return!1;let l=O.size<qr,a=N!=="http"||be<Qt&&!Y&&(!i||!ve.has(i));if(l&&a)return!0;await new Promise(o=>setTimeout(o,100))}}function Nt(){if(H=null,!G||!oe.length)return;let i=oe;if(oe=[],N!=="http"){for(let a=0;a<i.length;a+=ie)Be(i.slice(a,a+ie));return}let l=new Map;for(let a of i)(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,Nr),H.unref?.())}let ro=i=>{let l=new Map;for(let{trackId:a,event:o}of i)(l.get(a)??l.set(a,[]).get(a)).push(o);return[...l].map(([a,o])=>({trackId:a,events:o}))},he=(i,l,a,{progress:o})=>{let u=Date.now();for(let{event:y}of i){let p=O.get(y.id);p&&(p.nacks++,p.retryAt=u+Math.max(1e3,a||qe))}o&&Ce()};async function oo(i){let l=new Set(i.map(a=>a.trackId));for(let a of l)ve.add(a);be++;try{let a=await wn(`${gn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:ro(i)}),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 m of u.results??[]){Et(m.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,Nn]of et)Ot(Nn,me,F,u.retryAfterMs??null)};$(m.rejected,!0),$(m.deferred,!1)}let y=new Set,p=new Map;for(let m of Array.isArray(u.refused)?u.refused:[])!m||typeof m.id!="string"||(y.add(m.id),(p.get(m.reason)??p.set(m.reason,[]).get(m.reason)).push(m.id));for(let[m,$]of p)Ot($,`${Zt}${m}`,!0);Et((u.discarded??[]).filter(m=>!y.has(m))),Ce();return}if(a.status===429){he(i,"overloaded",o||5e3,{progress:!0});return}if(a.status===413&&i.length>1){W=Math.max(1,Math.floor(i.length/2)),w.error(`[plane-link] ingest request too large (${i.length} events) \u2014 halving batches to ${W}`),he(i,"too_large",1e3,{progress:!0});return}if(a.status===413){let u=O.get(i[0].event.id);u&&(O.delete(u.event.id),vn(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(i,"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>=Ir){Qe=Date.now();let p="";try{p=(await a.json())?.error??""}catch{}w.error(`[plane-link] plane refused ingest (HTTP ${a.status}${p?`: ${p}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}he(i,`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 ${i.length} event(s) for retry; this is a bug, not data`),he(i,"http_400",6e4,{progress:!1});return}he(i,`http_${a.status}`,o||5e3,{progress:!1})}catch(a){let o=a?.name==="TimeoutError"||a?.name==="AbortError";o&&i.length>1&&(W=Math.max(1,Math.floor(i.length/2)),w.error(`[plane-link] ingest request of ${i.length} event(s) outlived its ${Xe} ms deadline \u2014 halving batches to ${W}`)),he(i,o?"timeout":"network",5e3,{progress:!1})}finally{be--;for(let a of l)ve.delete(a)}}async function so(){if(N!=="http"||!Y||!G||vt)return;let i=Date.now();if(!(fe>i||ct(i))){vt=!0;try{let l=await wn(`${gn}/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 O.values())a.retryAt=Math.min(a.retryAt,Date.now());Rt()}catch(l){Z++;let a=Math.min(mn*2**(Z-1),Rr);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 $n(){let i=Date.now();return{mode:N,unacked:O.size,oldestUnackedAgeMs:An(i),lastProgressAt:Je,degradedSince:re,stallRedials:Z,deadLettered:Tn,http:N==="http"?{inFlight:be,circuitOpen:Y,nextProbeInMs:Y?Math.max(0,fe-i):0,batchCap:W}:null}}async function xn(){if(!h)return;let i;try{i=await h()}catch(a){w.error("[plane-link] metrics sample failed:",a?.message||a);return}let l=null;try{l=_?.()??null}catch{}i&&I({v:M,ch:"ctl",type:"metrics",metrics:{...i,planeLink:$n(),...l?{delivery:l}:{}}})}function io(){h&&(ee&&clearInterval(ee),xn(),ee=setInterval(xn,T),ee.unref?.())}async function ao(){let i;try{i=await s()}catch(l){w.error("[plane-link] backfill listTracks failed:",l?.message||l);return}I({v:M,ch:"ctl",type:"tracks",ids:i.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of i){if(!G)return;let a;try{a=await zt(l)}catch{continue}let o=de[l.id]??0,u=a.filter(p=>p.seq>o&&typeof p.id=="string"),y=N==="http"?W:ie;for(let p=0;p<u.length;p+=y){if(!await no(l.id))return;let m=u.slice(p,p+Math.min(y,N==="http"?W:ie)).map($=>({trackId:l.id,event:$}));if(!Be(m))return}}}function En(i){!G||!i?.trackId||typeof i.id!="string"||(oe.push({trackId:i.trackId,event:i}),H||(H=setTimeout(Nt,Nr),H.unref?.()))}let je=new Map;async function co(i){let{reqId:l,method:a,path:o,headers:u={},body:y}=i,p=Object.fromEntries(Object.entries(u).filter(([,$])=>$!=null)),m=new AbortController;je.set(l,m);try{if(i.host){await lo(i,p,m);return}C&&(p["x-bostrat-token"]=C);let $=await fetch(v+o,{method:a,headers:p,body:y?Buffer.from(y,"base64"):void 0,signal:m.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"),I({v:M,ch:"control",type:"http_head",reqId:l,status:$.status,headers:J}),$.body){for await(let F of $.body)if(!I({v:M,ch:"control",type:"http_data",reqId:l,data:Buffer.from(F).toString("base64")}))break}I({v:M,ch:"control",type:"http_end",reqId:l,error:null})}finally{je.delete(l)}}function lo(i,l,a){let{reqId:o,method:u,path:y,body:p}=i,m=new URL(v);return new Promise($=>{let J=vs.request({host:m.hostname,port:m.port,method:u,path:y,headers:{...l,host:i.host},signal:a.signal},F=>{let{connection:et,"keep-alive":me,"transfer-encoding":Nn,upgrade:xi,...uo}=F.headers;I({v:M,ch:"control",type:"http_head",reqId:o,status:F.statusCode||502,headers:uo}),F.on("data",fo=>{I({v:M,ch:"control",type:"http_data",reqId:o,data:Buffer.from(fo).toString("base64")})||F.destroy()}),F.on("end",()=>{I({v:M,ch:"control",type:"http_end",reqId:o,error:null}),$()}),F.on("error",()=>{I({v:M,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),$()})});J.on("error",F=>{I({v:M,ch:"control",type:"http_end",reqId:o,error:F?.message||"view request failed"}),$()}),p&&J.write(Buffer.from(p,"base64")),J.end()})}function On(){if(At||Le)return;z=new Jt(e,{headers:{authorization:`Bearer ${t}`}});let i=z;pe=0,i.on("ping",()=>{pe=Date.now()}),i.on("pong",()=>{pe=Date.now()}),z.on("open",async()=>{let a=null;try{a=await c?.()||null}catch{a=null}I({v:M,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:V,installKind:R,...typeof E=="function"?{updatePolicy:E()}:E?{updatePolicy:E}:{},providers:Pr(),...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=Er,De=null,Un(),w.log(`[plane-link] connected to plane as ${n}`);try{Vr?.()}catch{}if(typeof o.hashKey=="string"&&o.hashKey)try{g?.(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(R)}`);try{x?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}let u=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;if(u&&V&&Oe(V,u)&&!yn.has(u)){yn.add(u),w.log(`[plane-link] bostrat-node ${u} is available (this node runs ${V}) \u2014 ${Ve(R)}`);try{b?.({current:V,latest:u,min:o.minNodeVersion??null,installKind:R,required:!!(o.minNodeVersion&&Oe(V,o.minNodeVersion))})}catch(p){w.error(`[plane-link] update notice failed: ${p?.message||p}`)}}let y=o.ingest==="http";N=Tt==="ws"?"ws":Tt==="http"||y?"http":"ws",Tt==="http"&&!y&&w.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),N==="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(()=>{to(i)||(I({v:M,ch:"ctl",type:"ping"}),kn(),so().catch(()=>{}),Rt(),oe.length&&!H&&Nt())},hn),Q.unref?.(),io(),ao().catch(p=>w.error("[plane-link] backfill failed:",p?.message||p));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let u=typeof o.minNodeVersion=="string"?o.minNodeVersion:null,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(R)}`),Pe=Or,De=0;try{k?.({current:V,min:u,latest:y,fix:o.fix||Ve(R),installKind:R})}catch(p){w.error(`[plane-link] refusal handler failed: ${p?.message||p}`)}return}if(o.ch==="ctl"&&o.type==="removed"){I({v:M,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_policy"){try{x?.(typeof o.mode=="string"?o.mode:null)}catch{}return}if(o.ch==="ctl"&&o.type==="usage_caps"){$r(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"){co(o).catch(u=>I({v:M,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(Xr+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 p=ue.get(o.streamId)||[];ue.delete(o.streamId);for(let{buf:m,bin:$}of p)u.send(m,{binary:$})}),u.on("message",(p,m)=>{let $=m?p:Buffer.from(String(p));I({v:M,ch:"attach",type:"data",streamId:o.streamId,data:$.toString("base64"),...m?{bin:!0}:{}})});let y=()=>{ue.delete(o.streamId),le.delete(o.streamId)&&I({v:M,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"),p=o.bin===!0,m=ue.get(o.streamId);m?m.push({buf:y,bin:p}):u.send(y,{binary:p});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),O.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<ks,o=Math.max(a?$s+Math.random()*xs:Pe,Me-Date.now(),Ke());Ae=setTimeout(()=>{Ae=null,On()},o),Ae.unref?.(),a||(Pe=Math.min(Pe*2,Or))};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>=Ir&&(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",En),Jr().then(On);function Rn({bye:i=!0}={}){At=!0,ze.off("event",En),Ae&&clearTimeout(Ae),ke&&clearTimeout(ke),Q&&clearInterval(Q),ee&&clearInterval(ee),H&&clearTimeout(H),i&&I({v:M,ch:"ctl",type:"bye",reason:"shutdown"}),z?.close()}return{stop:()=>Rn(),status:()=>({connected:G,nodeId:n,cursor:{...de},inflight:O.size,...$n(),auth:Hn(),dormant:Le,removed:Ht(),deadLinkMs:_t,deadLinkRedials:bn,refused:{...Ze}}),_tick:()=>{kn(),Rt()}}}var V,en,nn,M,Er,Or,ks,$s,xs,ie,Es,Os,Rs,Ns,Dr,Is,Zt,Ms,Ps,Ds,Rr,Ls,Nr,Bs,Qt,Cs,Ir,rn=A(()=>{lt();xr();Dt();Kt();V=(()=>{try{return As(import.meta.url)("../package.json").version||null}catch{return null}})(),en=process.env.BOSTRAT_STATE_DIR||B.join(process.env.HOME||ht.tmpdir(),".bostrat"),nn=B.join(en,"plane-link","removed.json");M=1,Er=1e3,Or=3e4,ks=6e4,$s=1500,xs=500,ie=100,Es=2e3,Os=25e3,Rs=2.5,Ns=6e4,Dr=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Is=Dr(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Zt="refused:",Ms={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"},Ps=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},Ds=3e4,Rr=10*6e4,Ls=400,Nr=250,Bs=Dr(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Qt=4,Cs=6e4,Ir=6e4});var Br=A(()=>{jt()});var Hr={};It(Hr,{ACTIONABLE_KINDS:()=>yt,REGISTRY_RETRY_ATTEMPTS:()=>cn,REGISTRY_WAIT_POLLS:()=>on,REGISTRY_WAIT_STEP_S:()=>sn,SELF_UPDATE_DIR:()=>an,createAutoUpdater:()=>Zs,inFlight:()=>un,readStatus:()=>ln,selfUpdatePlan:()=>Fr,settleSelfUpdate:()=>Js,startSelfUpdate:()=>Ur,underService:()=>jr,updatePolicy:()=>Ys});import Cr from"node:fs";import ae from"node:fs/promises";import Fs from"node:os";import D from"node:path";import{spawn as Us}from"node:child_process";import{createRequire as Hs}from"node:module";function Ys({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"||jr(t)?"auto":"prompt":"off"}function jr(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Fr({kind:e,to:t,from:n=mt,statusFile:r=wt,logFile:s=D.join(an,"last.log"),port:c=Number(process.env.PORT)||3362,npmPrefix:d=null,serviceName:h=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:_=typeof process.getuid=="function"?process.getuid():0,liveDir:g=process.env.BOSTRAT_LIVE_CHECKOUT||D.resolve(D.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:f=Date.now(),attempts:T=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 b=(v,C="")=>`write_status ${U(v)} ${C}`,x=process.platform==="darwin"?`launchctl kickstart -k gui/${_}/${h}`:`systemctl --user restart ${U(h)}`,k=`
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=`
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
- }`,E=`#!/usr/bin/env bash
123
+ }`,v=`#!/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
@@ -128,7 +128,7 @@ FROM=${U(n??"")}
128
128
  TO=${U(t)}
129
129
  STATUS_FILE=${U(r)}
130
130
  STARTED_AT=${Number(f)}
131
- ATTEMPTS=${Number(T)||1}
131
+ ATTEMPTS=${Number(g)||1}
132
132
  write_status() { # <status> [error] [retryable]
133
133
  local err="\${2:-}"
134
134
  err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
@@ -136,28 +136,28 @@ write_status() { # <status> [error] [retryable]
136
136
  "$1" "$FROM" "$TO" ${U(e)} "$ATTEMPTS" "$STARTED_AT" "$(date +%s000)" \\
137
137
  "\${err:+,\\"error\\":\\"$err\\"}" "\${3:+,\\"retryable\\":true}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
138
138
  }
139
- ${k}
140
- `;if(e==="npm-global"){let v=d?D.join(d,"bin","npm"):"npm",C=d?`export PATH=${U(D.join(d,"bin"))}:"$PATH"
141
- `:"",S=d?` --prefix ${U(d)}`:"",j=Se=>`${U(v)} install -g "bostrat-node@${Se}" --no-audit --no-fund${S}`,te=`
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"
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
144
- if [ "$(${U(v)} view "bostrat-node@$TO" version --prefer-online 2>/dev/null)" = "$TO" ]; then return 0; fi
144
+ if [ "$(${U(A)} view "bostrat-node@$TO" version --prefer-online 2>/dev/null)" = "$TO" ]; then return 0; fi
145
145
  sleep ${sn}
146
146
  done
147
147
  return 1
148
- }`;return E+C+te+`
149
- ${b("updating",'"" ')}
148
+ }`;return v+k+te+`
149
+ ${_("updating",'"" ')}
150
150
  if ! wait_for_registry; then
151
- ${b("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(on*sn/60)} min, attempt $ATTEMPTS of ${cn})" retryable`)}
151
+ ${_("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(on*sn/60)} min, attempt $ATTEMPTS of ${cn})" retryable`)}
152
152
  exit 1
153
153
  fi
154
154
  if ! ${j("$TO")}; then
155
- ${b("failed",'"npm install failed"')}
155
+ ${_("failed",'"npm install failed"')}
156
156
  exit 1
157
157
  fi
158
- ${b("restarting")}
158
+ ${_("restarting")}
159
159
  if ! ${x}; then
160
- ${b("failed",'"service restart failed"')}
160
+ ${_("failed",'"service restart failed"')}
161
161
  exit 1
162
162
  fi
163
163
  if health; then
@@ -165,52 +165,52 @@ if health; then
165
165
  exit 0
166
166
  fi
167
167
  # \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
168
- ${b("rolling-back",'"agent did not answer on :'+c+' after the update"')}
168
+ ${_("rolling-back",'"agent did not answer on :'+c+' after the update"')}
169
169
  if [ -n "$FROM" ] && ${j("$FROM")} && ${x} && health; then
170
- ${b("rolled-back",'"agent did not answer on :'+c+' after the update; rolled back"')}
170
+ ${_("rolled-back",'"agent did not answer on :'+c+' after the update; rolled back"')}
171
171
  exit 1
172
172
  fi
173
- ${b("failed",'"agent did not answer after the update AND the rollback"')}
173
+ ${_("failed",'"agent did not answer after the update AND the rollback"')}
174
174
  exit 1
175
- `}let R=v=>`( cd ${U(g)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${v}" )`;return E+`
176
- LIVE=${U(g)}
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+`
176
+ LIVE=${U(O)}
177
177
  TMP_SCRIPT="$(mktemp)"
178
178
  trap 'rm -f "$TMP_SCRIPT"' EXIT
179
179
  # "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
180
180
  # restart \u2192 health in one call): the agent it restarts settles "done" on boot,
181
181
  # and nothing here may write after that boot or the settle would repeat.
182
- ${b("restarting")}
183
- if ${R("$TO")}; then
182
+ ${_("restarting")}
183
+ if ${N("$TO")}; then
184
184
  exit 0
185
185
  fi
186
- ${b("rolling-back",'"deploy-pi.sh v$TO failed"')}
187
- if [ -n "$FROM" ] && ${R("$FROM")}; then
188
- ${b("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
186
+ ${_("rolling-back",'"deploy-pi.sh v$TO failed"')}
187
+ if [ -n "$FROM" ] && ${N("$FROM")}; then
188
+ ${_("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
189
189
  exit 1
190
190
  fi
191
- ${b("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
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 Ur({to:e,from:t=mt,kind:n=Re(),reason:r="manual",statusFile:s=wt,spawnImpl:c=Us,now:d=Date.now,npmPrefix:h=void 0,log:_=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 g=await ln(s);if(un(g))return{ok:!1,reason:`an update to ${g.to} is already in flight`,status:g};let f=g?.to===e?Number(g.attempts)||1:0;if(g&&g.to===e&&(g.status==="failed"||g.status==="rolled-back")&&!(g.status==="failed"&&g.retryable===!0&&f<cn))return{ok:!1,reason:`update to ${e} already ${g.status} (${g.error||"no detail"}) \u2014 retried when a newer release exists`,status:g};let T=g?.to===e&&g.status==="failed"?f+1:1;await ae.mkdir(D.dirname(s),{recursive:!0});let b=h!==void 0?h:n==="npm-global"?Ct(await Vs())||D.resolve(D.dirname(process.execPath),".."):null,x=Fr({kind:n,to:e,from:t,statusFile:s,npmPrefix:b,startedAt:d(),attempts:T}),k=D.join(D.dirname(s),`update-${e}.sh`),E=D.join(D.dirname(s),"last.log");await ae.writeFile(k,x,{mode:448}),await ae.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:T,startedAt:d(),updatedAt:d()}));let R=Cr.existsSync("/run/systemd/system")&&await qs("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",k]]:["setsid",["-f","bash","-c",`exec bash ${U(k)} >> ${U(E)} 2>&1`]];try{c(R[0],R[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(v){return await ae.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,startedAt:d(),updatedAt:d(),error:`could not spawn updater: ${v?.message||v}`})),{ok:!1,reason:`could not spawn updater: ${v?.message||v}`}}return _.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:k,statusFile:s}}async function Vs(){try{return await ae.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function qs(e){for(let t of String(process.env.PATH||"").split(D.delimiter))try{return await ae.access(D.join(t,e),Cr.constants.X_OK),!0}catch{}return!1}async function Js({statusFile:e=wt,current:t=mt,now:n=Date.now,staleMs:r=Xs}={}){let s=await ln(e);if(!s)return null;let c=d=>ae.writeFile(e,JSON.stringify(d)).catch(()=>{});if(un(s)){if(t&&s.to===t){let d={...s,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await c(d),d}if(n()-Number(s.updatedAt||s.startedAt||0)>r){let d={...s,status:"failed",error:`updater went silent while ${s.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await c(d),d}return null}if(["failed","rolled-back","done"].includes(s.status)&&!s.announced){let d={...s,announced:!0};return await c(d),d}return null}function Zs({isBusy:e,start:t=Ur,onStuck:n=null,onStarted:r=null,tickMs:s=zs,stuckMs:c=Ws,now:d=Date.now,setIntervalImpl:h=setInterval,clearIntervalImpl:_=clearInterval,log:g=console}={}){let f=null,T=()=>{f?.timer&&_(f.timer),f=null},b=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 k=f;T();let E=await t({to:k.to,from:k.from,kind:k.kind,reason:"auto"});g.log?.(`[self-update] stasis reached \u2192 ${E.ok?"started":`not started: ${E.reason}`}`);try{await r?.({...k,result:E})}catch{}};return{arm({to:x,from:k=mt,kind:E=Re()}){return f?.to===x?!1:(T(),f={to:x,from:k,kind:E,since:d(),stuckFired:!1,timer:h(b,s)},f.timer.unref?.(),!0)},tick:b,cancel:T,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var mt,Ks,an,wt,Ws,zs,on,sn,cn,yt,U,Gs,un,Xs,Kr=A(()=>{rn();Br();mt=(()=>{try{return Hs(import.meta.url)("../package.json").version||null}catch{return null}})(),Ks=process.env.BOSTRAT_STATE_DIR||D.join(process.env.HOME||Fs.tmpdir(),".bostrat"),an=D.join(Ks,"self-update"),wt=D.join(an,"status.json"),Ws=1440*6e4,zs=6e4,on=60,sn=15,cn=3,yt=new Set(["npm-global","git-checkout"]);U=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Gs=new Set(["updating","restarting","rolling-back"]),un=e=>!!(e&&Gs.has(e.status));Xs=45*6e4});Dt();Bt();import q from"node:fs";import P from"node:path";import Ie from"node:os";import{createRequire as dn}from"node:module";import{execFile as Qs,spawn as ei}from"node:child_process";import{promisify as ti}from"node:util";import ni from"node:readline/promises";import{randomUUID as ri}from"node:crypto";import{fileURLToPath as oi}from"node:url";import Zo from"node:fs";import rr from"node:path";import Qo from"node:os";var es=()=>process.env.BOSTRAT_STATE_DIR||rr.join(process.env.HOME||Qo.tmpdir(),".bostrat"),ts=()=>rr.join(es(),"plane-link","public-host.json");var Ye=null;function ns(){if(Ye)return Ye;try{let e=JSON.parse(Zo.readFileSync(ts(),"utf8"));Ye={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{Ye={viewBase:null}}return Ye}function rs(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),s=r?r[1].toLowerCase():t,c=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return c?{proto:s,host:c}:null}function or(){return ns().viewBase}function sr(e=process.env.BOSTRAT_PUBLIC_HOST){return rs(e,"https")}function ir(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 Wr=(e,t)=>{let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let s=0;s<Math.max(n.length,r.length);s++){let c=(n[s]||0)-(r[s]||0);if(c)return c<0}return!1},ce=ti(Qs),fn=P.dirname(oi(import.meta.url)),_e=P.resolve(fn,".."),si=P.join(fn,"index.js"),ii="wss://plane.bostrat.ai/v1/node",Ne=dn(import.meta.url)("../package.json").version,L=(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 ai(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?L("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 ci(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"):L("owner stamp","none (the plane infers the owner from the token)")}function li(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}`):L("node.env",`${e} (0600)`)}async function ui(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await ce(t,["-V"],{timeout:5e3});return L("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 zr(e,{required:t=!1}={}){if(await Gt(e,{loginShell:!0,failOpen:!1}))return L(e,"resolves on the login-shell PATH");let r="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",s=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,s):X(e,r,s)}async function di(){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 L("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 fi(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>zr(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 pi(){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})?L(t,"resolves on the service PATH"):X(t,`not on the service PATH \u2014 ${n}`,r)))}async function hi(){try{let t=dn(P.join(_e,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let s=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),c=setTimeout(()=>r(new Error("spawn timeout")),5e3);s.onExit(()=>{clearTimeout(c),n()})}),L("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(P.join(_e,"package.json")),r=P.join(P.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 mi(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(q.existsSync(t))return L("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 wi(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"):L("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function yi(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(),s=Fe(e.BOSTRAT_PLANE_URL);return await new Promise(c=>{let d=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),h=null,_=f=>{clearTimeout(g);try{d.close()}catch{}c(h?{...f,viewBase:h}:f)},g=setTimeout(()=>_(K("plane link",`no hello_ok within 5s from ${s}`,"check the URL, the token, and the plane's IP gate")),5e3);d.on("open",()=>d.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${ri().slice(0,8)}`,ephemeral:!0}))),d.on("message",f=>{try{let T=JSON.parse(f);T.type==="hello_ok"?(typeof T.viewBase=="string"&&T.viewBase&&(h=T.viewBase),T.minNodeVersion&&Wr(Ne,T.minNodeVersion)?_(K("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${T.minNodeVersion} \u2014 this node is ${Ne}; the real link is refused until it updates`,`bostrat-node self-update --to ${T.latestNodeVersion||T.minNodeVersion}`)):T.latestNodeVersion&&Wr(Ne,T.latestNodeVersion)?_(X("plane link",`hello_ok in ${Date.now()-r}ms (${s}); bostrat-node ${T.latestNodeVersion} is available (this node: ${Ne})`,`bostrat-node self-update --to ${T.latestNodeVersion}`)):_(L("plane link",`hello_ok in ${Date.now()-r}ms (${s})`))):T.type==="error"&&_(K("plane link",`plane said: ${T.code} ${T.message||""}`,"check the token"))}catch{}}),d.on("error",f=>_(K("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function gi(){let e;try{e=JSON.parse(q.readFileSync(P.join(Pt,"content-outbox.json"),"utf8"))}catch{return L("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"):L("content outbox",t?`${t} op(s) in flight`:"drained")}function Ti(e){return e.BOSTRAT_STATE_REMOTE?L("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):X("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}function _i(e,t){let n=t?.viewBase??null,r=or(),s=sr(e.BOSTRAT_PUBLIC_HOST),c=(()=>{let d=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(d)return`${d.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let h=ir(e.BOSTRAT_PLANE_URL);return h?`${h}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let d=s&&s.host!==n?`; BOSTRAT_PUBLIC_HOST=${s.host} is set but the plane's value wins`:"";return L("public host",`views https://<slug>.${n}/ (plane hello_ok)${d} \xB7 track links ${c}`)}return r?L("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${c}`):s?L("public host",`views ${s.proto}://<slug>.${s.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 Yr(e,t={}){let n=[];n.push(await ai()),n.push(li(t.envFile||$e())),n.push(await ui(e)),n.push(...await fi()),n.push(await zr("git",{required:!0})),n.push(await di()),n.push(...await pi()),n.push(await hi()),n.push(mi(e)),n.push(wi(e)),n.push(ci(e));let r=await yi(e,t);return n.push(r),n.push(_i(e,r)),n.push(gi()),n.push(Ti(e)),n}function Gr(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,s=e.filter(c=>c.level==="warn").length;return t(r?`
194
- FAIL \u2014 ${r} blocking, ${s} warnings`:`
195
- OK \u2014 0 blocking, ${s} warnings`),r===0}async function Si({envFile:e=$e(),input:t=process.stdin,output:n=process.stdout}={}){let r=nt(e),s=ni.createInterface({input:t,output:n}),c=async(C,S)=>(await s.question(S?`${C} [${S}]: `:`${C}: `)).trim()||S||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
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?`
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:
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||ii),h=Fe(d);h!==d.trim()&&n.write(` \u2192 using ${h}
199
- `);let _=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
- `);let g=await c("Node name",r.BOSTRAT_NODE_NAME||Ie.hostname().split(".")[0]),f=await c("Repos root",r.BOSTRAT_REPOS_ROOT||P.join(Ie.homedir(),"Documents")),T=await c("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),b=(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");b&&n.write(`
198
+ `);let d=await c("Plane URL",r.BOSTRAT_PLANE_URL||ai),p=Fe(d);p!==d.trim()&&n.write(` \u2192 using ${p}
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
+ `);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,
202
202
  injected per box, stored 0600 in node.env, never sent to the plane.
203
203
  \u2022 create/copy a key: https://console.anthropic.com/settings/keys
204
204
  \u2022 set a monthly spend limit while you're there \u2014 the key is live.
205
205
 
206
- `);let x=b?await c("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";b&&x&&!/^sk-ant-/.test(x)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
207
- `),s.close();let k={...Pn(),...r,BOSTRAT_PLANE_URL:h,BOSTRAT_PLANE_TOKEN:_,BOSTRAT_NODE_NAME:g,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||g,BOSTRAT_REPOS_ROOT:f,BOSTRAT_STATE_REMOTE:T,BOSTRAT_CLAUDE_USE_API_KEY:b?"1":"0",ANTHROPIC_API_KEY:b?x:r.ANTHROPIC_API_KEY};delete k.BOSTRAT_OWNER,Mn(e,k,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
206
+ `);let x=_?await c("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";_&&x&&!/^sk-ant-/.test(x)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
207
+ `),i.close();let R={...Dn(),...r,BOSTRAT_PLANE_URL:p,BOSTRAT_PLANE_TOKEN:T,BOSTRAT_NODE_NAME:O,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||O,BOSTRAT_REPOS_ROOT:f,BOSTRAT_STATE_REMOTE:g,BOSTRAT_CLAUDE_USE_API_KEY:_?"1":"0",ANTHROPIC_API_KEY:_?x:r.ANTHROPIC_API_KEY};delete R.BOSTRAT_OWNER,Pn(e,R,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
208
208
  0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
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 E={...k,...process.env},R=await Yr(E,{envFile:e}),v=Gr(R,C=>n.write(C+`
213
- `));return v&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:v,results:R}}function bi({envFile:e=$e()}={}){In(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=ei(t,[si],{cwd:_e,stdio:"inherit",env:process.env});for(let r of["SIGINT","SIGTERM"])process.on(r,()=>n.kill(r));return n.on("exit",(r,s)=>process.exit(s?1:r??1)),n}function vi({agentDir:e=_e,nodeBin:t=process.execPath,envFile:n=$e(),home:r=Ie.homedir()}={}){let s=P.dirname(t),c=P.join(P.basename(fn),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
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
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)
@@ -224,13 +224,13 @@ ExecStart=${t} --disable-warning=ExperimentalWarning ${c}
224
224
  EnvironmentFile=${n}
225
225
  # systemd's user PATH omits ~/.local/bin (cursor-agent, bostrat-view) and the
226
226
  # nvm bin dir \u2014 both are load-bearing for box spawning.
227
- Environment=PATH=${r}/.local/bin:${s}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
227
+ Environment=PATH=${r}/.local/bin:${i}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
228
228
  Restart=on-failure
229
229
  RestartSec=2
230
230
 
231
231
  [Install]
232
232
  WantedBy=default.target
233
- `}function Ai({agentDir:e=_e,nodeBin:t=process.execPath,home:n=Ie.homedir()}={}){let r=P.dirname(t),s=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
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"?>
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>
@@ -248,11 +248,11 @@ WantedBy=default.target
248
248
  </dict>
249
249
  <key>RunAtLoad</key><true/>
250
250
  <key>KeepAlive</key><true/>
251
- <key>StandardOutPath</key><string>${s}/node.out.log</string>
252
- <key>StandardErrorPath</key><string>${s}/node.err.log</string>
251
+ <key>StandardOutPath</key><string>${i}/node.out.log</string>
252
+ <key>StandardErrorPath</key><string>${i}/node.err.log</string>
253
253
  </dict>
254
254
  </plist>
255
- `}function ki(e=process.platform,t=Ie.homedir()){return e==="darwin"?{kind:"launchd",file:P.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:P.join(t,".config","systemd","user","bostrat-node.service")}}async function $i({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:s=_e}={}){let{kind:c,file:d}=ki(n);if(!e&&s.split(P.sep).includes("_npx"))return r("\u2717 running from the npx cache \u2014 a service must point at a durable install."),r(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){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(P.dirname(d),{recursive:!0}),c==="systemd"?(q.writeFileSync(d,vi()),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(P.join(Ie.homedir(),"Library","Logs","bostrat"),{recursive:!0}),q.writeFileSync(d,Ai()),t&&await ce("launchctl",["load","-w",d]),r(`installed ${d}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function Jl(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 Si({envFile:n})).ok?0:1;if(t==="doctor"){let r={...nt(n),...process.env};return Gr(await Yr(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return bi({envFile:n}),null;if(t==="install-service")return await $i({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(pr(),fr));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:s,updatePolicy:c}=await Promise.resolve().then(()=>(Kr(),Hr)),{detectInstallKind:d}=await Promise.resolve().then(()=>(rn(),Lr)),h=d(),_=e.indexOf("--to"),g=_>=0?String(e[_+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Ne,installKind:h,policy:c({kind:h}),status:await s()},null,2)),0;if(!g)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:g,kind:h,reason:"cli"});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 $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)
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{Si as init,$i as installService,Ai as launchdPlist,Jl as main,Gr as printDoctor,bi as runAgent,Yr as runDoctor,ki as servicePaths,vi 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,xi as installService,ki as launchdPlist,Zl as main,Vr as printDoctor,vi as runAgent,Gr as runDoctor,$i as servicePaths,Ai as systemdUnit};