bostrat-node 1.11.5 → 1.11.6

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 +83 -71
  2. package/dist/index.js +243 -231
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
- var no=Object.defineProperty;var v=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Et=(e,t)=>{for(var n in t)no(e,n,{get:t[n],enumerable:!0})};import et from"node:fs";import Ot from"node:path";import ro 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 tt(e){let t;try{t=et.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 u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),n[c[1]]=u}return n}function An(e,t=process.env){let n=tt(e);for(let[r,s]of Object.entries(n))r in t||(t[r]=s);return n}function kn(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}`);et.mkdirSync(Ot.dirname(e),{recursive:!0}),et.writeFileSync(e,r.join(`
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(`
4
4
  `)+`
5
- `,{mode:384}),et.chmodSync(e,384)}function xn(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 Rt,ke,Nt=v(()=>{Rt=process.env.BOSTRAT_STATE_DIR||Ot.join(process.env.HOME||ro.tmpdir(),".bostrat"),ke=()=>Ot.join(Rt,"node.env")});var me,nt,rt=v(()=>{me="BOSTRAT_HOOK_TOKEN",nt="x-bostrat-hook"});var $n=v(()=>{rt()});var oo,ki,En=v(()=>{oo="check_for_update_on_startup",ki=`${oo} = false`});import so from"node:os";import On from"node:path";var io,Ri,Ni,It=v(()=>{Mt();io=process.env.BOSTRAT_DEBUG_DIR||On.join(so.homedir(),".bostrat","debug"),Ri=On.join(io,"handoff.jsonl"),Ni=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as co}from"node:child_process";import{promisify as lo}from"node:util";function Pt(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Li,Bi,ji,Fi,Dt=v(()=>{It();Li=lo(co),Bi=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,ji=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,Fi=Promise.resolve()});var Rn=v(()=>{});import Ct from"node:path";import{execFile as uo}from"node:child_process";import{promisify as fo}from"node:util";var Yi,Nn,po,Gi,Vi,In=v(()=>{Yi=fo(uo),Nn=process.env.HOME||"/home/globo",po=Ct.join(process.env.BOSTRAT_STATE_DIR||Ct.join(Nn,".bostrat"),"repos"),Gi=[...(process.env.BOSTRAT_REPOS_ROOT||Ct.join(Nn,"Documents")).split(","),po].map(e=>e.trim()).filter(Boolean),Vi=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function it(e=Date.now()){if(ye)return{tripped:!1,holdMs:1/0};if(we>e)return{tripped:!1,holdMs:we-e};if((!He||e-He>=ot.windowMs)&&(He=e,Ue=0),Ue++,Ue<ot.trip)return{tripped:!1,holdMs:0};st++;let t=Math.min(ot.minMs*2**(st-1),ot.maxMs);return we=e+t,Ue=0,He=0,{tripped:!0,holdMs:t}}function Mn(){Ue=0,He=0,st=0,we=0}function Ke(e=Date.now()){return ye?1/0:we>e?we-e:0}function at(e=Date.now()){return Ke(e)>0}function Lt(e={}){ye={at:Date.now(),...e},we=1/0}function Bt(){return ye}function Pn(e=Date.now()){return{held:at(e),holdMs:ye?null:Ke(e),holds:st,removed:ye?{...ye}:null}}var ho,ot,Ue,He,st,we,ye,jt=v(()=>{ho={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},ot={...ho},Ue=0,He=0,st=0,we=0,ye=null});import Dn from"node:path";import mo from"node:os";import{execFile as wo}from"node:child_process";import{promisify as yo}from"node:util";var oa,go,sa,ia,aa,Ft=v(()=>{In();jt();oa=yo(wo),go=process.env.BOSTRAT_STATE_DIR||Dn.join(process.env.HOME||mo.tmpdir(),".bostrat"),sa=Dn.join(go,"repos"),ia=5*6e4,aa=10*6e4});var Cn=v(()=>{Ft()});import _o from"node:fs/promises";import We from"node:path";import So from"node:os";import{EventEmitter as vo}from"node:events";function bo(e){return e?.cwd?We.join(e.cwd,".bostrat","events"):We.join(Ln,"events")}async function Ut(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(Ln,"events"):bo(e));let s;try{s=await _o.readFile(Ao(n,r),"utf8")}catch{return[]}let c=[];for(let u of s.split(`
6
- `))if(u.trim())try{c.push(JSON.parse(xo(u)?$o(u):u))}catch{}return c}var ze,Ln,Ao,ko,xo,$o,ct=v(()=>{ze=new vo;ze.setMaxListeners(0);Ln=process.env.BOSTRAT_STATE_DIR||We.join(process.env.HOME||So.tmpdir(),".bostrat");Ao=(e,t)=>We.join(e,`${t}.ndjson`),ko=/(?<!\\)((?:\\\\)*)\\u0000/g,xo=e=>e.includes("\\u0000"),$o=e=>e.replace(ko,"$1\\ufffd")});import Oo from"node:os";import Ro from"node:path";import{execFile as No}from"node:child_process";import{promisify as Io}from"node:util";var Aa,ka,xa,$a,Ea,Oa,Bn=v(()=>{Cn();ct();Aa=Io(No),ka=process.env.BOSTRAT_STATE_DIR||Ro.join(process.env.HOME||Oo.tmpdir(),".bostrat"),xa=25*1024,$a=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,Ea=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,Oa=Promise.resolve()});var jn=v(()=>{});var Da,Fn=v(()=>{Ft();jn();Da=60*6e4});var Un=v(()=>{Fn()});import Hn from"node:path";import Mo from"node:os";var lt,Po,Ga,Kn,Va,qa,Wn=v(()=>{rt();lt="BOSTRAT_NODE_URL",Po=process.env.BOSTRAT_STATE_DIR||Hn.join(process.env.HOME||Mo.tmpdir(),".bostrat"),Ga=Hn.join(Po,"git-hooks"),Kn=`#!/bin/sh
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
7
7
  # bostrat git hook shim (agent/src/git-hooks.js) \u2014 chains to the repo's own hook,
8
8
  # then stamps/reports for rework attribution when running inside a bostrat box.
9
9
  hook=$(basename "$0")
@@ -18,28 +18,28 @@ esac
18
18
  if [ -x "$orig/$hook" ] && [ "$orig/$hook" != "$0" ]; then
19
19
  "$orig/$hook" "$@" || exit $?
20
20
  fi
21
- `,Va=`${Kn}
21
+ `,sc=`${Jn}
22
22
  # \u2500\u2500 bostrat: append provenance trailers (Layer 0). Skipped for merge commits
23
23
  # (nobody "wrote" a merge) and outside a box (no token / no node url).
24
- [ -z "$${me}" ] && exit 0
25
- [ -z "$${lt}" ] && exit 0
24
+ [ -z "$${we}" ] && exit 0
25
+ [ -z "$${ut}" ] && exit 0
26
26
  [ "$2" = "merge" ] && exit 0
27
- trailers=$(curl -sS -m 3 -H "${nt}: $${me}" "$${lt}/api/git/trailers" 2>/dev/null) || exit 0
27
+ trailers=$(curl -sS -m 3 -H "${rt}: $${we}" "$${ut}/api/git/trailers" 2>/dev/null) || exit 0
28
28
  [ -z "$trailers" ] && exit 0
29
29
  printf '%s\\n' "$trailers" | while IFS= read -r line; do
30
30
  [ -n "$line" ] && git interpret-trailers --in-place --if-exists addIfDifferent --trailer "$line" "$1" >/dev/null 2>&1 || true
31
31
  done
32
32
  exit 0
33
- `,qa=`${Kn}
33
+ `,ic=`${Jn}
34
34
  # \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
35
- [ -z "$${me}" ] && exit 0
36
- [ -z "$${lt}" ] && exit 0
35
+ [ -z "$${we}" ] && exit 0
36
+ [ -z "$${ut}" ] && exit 0
37
37
  sha=$(git rev-parse HEAD 2>/dev/null) || exit 0
38
38
  cwd=$(git rev-parse --show-toplevel 2>/dev/null)
39
- printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${lt}/api/git/committed" \\
40
- -H 'content-type: application/json' -H "${nt}: $${me}" --data-binary @- >/dev/null 2>&1 || true
39
+ printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${ut}/api/git/committed" \\
40
+ -H 'content-type: application/json' -H "${rt}: $${we}" --data-binary @- >/dev/null 2>&1 || true
41
41
  exit 0
42
- `});import{execFile as Do}from"node:child_process";import{promisify as Co}from"node:util";import Lo from"node:fs";function Gn(e){return`/tmp/tmux-${e}/default`}function jo({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let s=Gn(r);return t?s:n?`${n}/bostrat/tmux-default`:s}async function Kt(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Uo(e,{loginShell:t});return r===Vn?!0:r===Ht?!1:n}async function Uo(e,{loginShell:t=!1,timeoutMs:n=Fo}={}){if(!e)return Ht;let r=t?process.env.SHELL||"/bin/sh":"sh",s=t?"-lic":"-c";try{return await Bo(r,[s,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),Vn}catch(c){return c?.killed||c?.signal?Yn:c?.code===1||c?.code===127?Ht:Yn}}var Bo,_c,zn,Sc,vc,bc,Ac,Vn,Ht,Yn,Fo,ut,kc,xc,$c,Ec,Oc,Mt=v(()=>{$n();En();Dt();Rn();Bn();Un();It();rt();Wn();Bo=Co(Do),_c=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";zn=typeof process.getuid=="function"?process.getuid():0,Sc=jo({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Lo.existsSync(Gn(zn))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:zn}),vc=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",bc=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Ac=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]);Vn="present",Ht="absent",Yn="unknown",Fo=5e3;ut={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"},kc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,xc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,$c=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Ec=Number(process.env.BOSTRAT_BOX_COLS)||120,Oc=Number(process.env.BOSTRAT_BOX_ROWS)||40});var or={};Et(or,{NODE_IMAGE:()=>zt,commandPlan:()=>tr,flyToml:()=>er,flyWizard:()=>ts,parseFlyFlags:()=>nr,stageConfig:()=>rr});import Wt from"node:fs";import ge from"node:path";import Vo from"node:os";import qo from"node:readline/promises";import{execFile as Jo}from"node:child_process";import{createRequire as Xo}from"node:module";import{randomUUID as Zo}from"node:crypto";function er({app:e,region:t,nodeName:n=e,planeUrl:r=Qn,image:s=zt}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
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\`.
43
43
  # Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
44
44
  # No [http_service] and none should be added: the node dials OUT to the plane;
45
45
  # nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
@@ -79,48 +79,48 @@ 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 tr({app:e,org:t,region:n,sizeGb:r,token:s,owner:c,dir:u}){let h=[`BOSTRAT_PLANE_TOKEN=${s}`,...c?[`BOSTRAT_OWNER=${c}`]:[]];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>${c?" BOSTRAT_OWNER=\u2026":""} via stdin`,stdin:h.join(`
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(`
83
83
  `)+`
84
- `},{argv:["deploy",u,"-c",ge.join(u,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${u} -c ${ge.join(u,"fly.toml")} -a ${e} --ha=false`}]}function nr(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--owner":"owner","--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,...u]=s.split("=");n[c]?t[n[c]]=u.join("="):c==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function rr({app:e,dest:t,toml:n}){let r=t||ge.join(Vo.homedir(),".bostrat","fly",e);Wt.mkdirSync(r,{recursive:!0});for(let s of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])Wt.rmSync(ge.join(r,s),{recursive:!0,force:!0});return Wt.writeFileSync(ge.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function es({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:s}=await dt(["orgs","list","--json"],{exec:n}),c=JSON.parse(s),u=Array.isArray(c)?c.map(h=>h.Slug||h.slug).filter(Boolean):Object.keys(c);if(u.length===1)return t.write(`Org: ${u[0]} (your only org)
85
- `),u[0];if(u.length>1)return await e(`Fly org (${u.join(" / ")})`,u[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function ts({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:s}={}){let c=nr(e),u=qo.createInterface({input:t,output:n}),h=async(b,G)=>(await u.question(G?`${b} [${G}]: `:`${b}: `)).trim()||G||"",g=b=>(u.close(),b);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 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.
86
86
  bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
87
87
 
88
- `);try{await dt(["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"),g(1)}try{let{stdout:b}=await dt(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${b.trim()}
89
- `)}catch{return n.write("\u2717 not signed in to Fly. Run `fly auth login` (or `fly auth signup`) and re-run `bostrat-node fly`.\n"),g(1)}let T=await es({ask:h,output:n,exec:r,flag:c.org}),f=c.app||await h("App name",`bostrat-node-${Zo().slice(0,4)}`),m=c.region||await h("Region (see `fly platform regions`)","iad"),C=c.sizeGb||Number(await h("Volume size GB (logins + repos live here)","10"))||10,A=c.name||f,k=c.planeUrl||Qn,S=c.token||await h("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!S)return n.write(`\u2717 a node token is required \u2014 mint one in the bostrat setup chat (Connect a node \u2192 Fly), then re-run with it.
90
- `),g(1);let M=c.owner??await h("Owner userId (shown next to the token; empty = infer from token)",""),j=c.image||zt,{dir:K}=rr({app:f,dest:s,toml:er({app:f,region:m,nodeName:A,planeUrl:k,image:j})});n.write(`
91
- wrote ${ge.join(K,"fly.toml")} \u2014 deploys the prebuilt node image ${j}
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}
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 P=tr({app:f,org:T,region:m,sizeGb:C,token:S,owner:M,dir:K});for(let b of P)n.write(` $ ${b.display}
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
96
  `);if(!c.yes&&(await h(`
97
97
  Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u2014 nothing was created. Re-run any time; the staged context is kept.
98
- `),g(1);for(let b of P){n.write(`
99
- \u2192 ${b.display}
100
- `);try{let{stdout:G,stderr:_e}=await dt(b.argv,{stdin:b.stdin,exec:r}),qe=`${G||""}${_e||""}`.trim();qe&&n.write(qe.split(`
101
- `).map(Ie=>` ${Ie}`).join(`
98
+ `),_(1);for(let S of C){n.write(`
99
+ \u2192 ${S.display}
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
+ `).map(gt=>` ${gt}`).join(`
102
102
  `)+`
103
- `)}catch(G){let _e=`${G?.stdout||""}${G?.stderr||""}${G?.message||""}`;if(b.tolerate&&b.tolerate.test(_e)){n.write(` (already exists \u2014 continuing)
104
- `);continue}return n.write(`\u2717 failed: ${_e.trim().split(`
103
+ `)}catch(j){let te=`${j?.stdout||""}${j?.stderr||""}${j?.message||""}`;if(S.tolerate&&S.tolerate.test(te)){n.write(` (already exists \u2014 continuing)
104
+ `);continue}return n.write(`\u2717 failed: ${te.trim().split(`
105
105
  `).slice(-4).join(`
106
106
  `)}
107
107
  fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
108
- `),g(1)}}return n.write(`
108
+ `),_(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 ${K} -c ${ge.join(K,"fly.toml")} -a ${f} --ha=false
112
+ redeploy: fly deploy ${v} -c ${Te.join(v,"fly.toml")} -a ${f} --ha=false
113
113
  Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
114
114
  boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
115
- `),g(0)}var Qn,Qo,zt,dt,sr=v(()=>{Qn="wss://plane.bostrat.ai/v1/node",Qo=Xo(import.meta.url)("../package.json").version,zt=`ghcr.io/globocodes/bostrat-node:${Qo}`;dt=(e,{stdin:t,exec:n}={})=>new Promise((r,s)=>{if(n)return n(e,{stdin:t}).then(r,s);let c=Jo("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(u,h,g)=>u?s(Object.assign(u,{stdout:h,stderr:g})):r({stdout:h,stderr:g}));t!=null&&c.stdin?.end(t)})});function ir(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!rs.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 os(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:ir(s.from,"from",n),toMs:ir(s.to,"to",n)}))}return t}var ns,rs,Hc,Kc,ar=v(()=>{ns={"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)."}]},rs=/^\d{4}-\d{2}-\d{2}$/;Hc=os(ns),Kc=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var cr=v(()=>{ar()});import lr from"node:fs/promises";import fr from"node:path";import ss from"node:os";function hr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function mr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function wr(e){let t=new Date(hr(e));return t.setDate(t.getDate()+7),t.getTime()}function yr(e){let t=new Date(mr(e));return t.setMonth(t.getMonth()+1),t.getTime()}function us(e=Date.now()){for(let[t,n]of Object.entries(cs)){let r=n.startOf(e);if(r!==ft[t]){ft[t]=r;for(let s of Yt.values())s[t]=0;for(let s of ur)s.includes(`:${t}:`)&&!s.endsWith(`:${r}`)&&ur.delete(s)}}}function ds(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 u=r?.[c];if(u==null||u==="")continue;let h=Number(u);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 gr(e,{source:t="local",updatedAt:n=Date.now()}={}){xe={caps:ds(e),updatedAt:n,source:t};try{await lr.mkdir(pr,{recursive:!0}),await lr.writeFile(is(),JSON.stringify(xe,null,2))}catch{}return fs()}function fs(e=Date.now()){us(e);let t=new Set([...Yt.keys(),...Object.keys(xe?.caps||{})]),n={};for(let r of t){let s=Yt.get(r);n[r]={weeklyUsd:dr(s?.weekly||0),monthlyUsd:dr(s?.monthly||0)}}return{caps:xe?.caps||{},configured:!!xe,seeded:ls,updatedAt:xe?.updatedAt??null,spent:n,windows:{weekly:{start:ft.weekly,resetsAt:wr(e)},monthly:{start:ft.monthly,resetsAt:yr(e)}},warnPct:as}}var pr,is,as,cs,xe,ls,ft,Yt,ur,dr,Tr=v(()=>{ct();cr();pr=process.env.BOSTRAT_STATE_DIR||fr.join(process.env.HOME||ss.tmpdir(),".bostrat"),is=()=>fr.join(pr,"usage-caps.json"),as=.8;cs={weekly:{startOf:hr,nextStart:wr,capKey:"weeklyUsd"},monthly:{startOf:mr,nextStart:yr,capKey:"monthlyUsd"}},xe=null,ls=!1,ft={weekly:0,monthly:0},Yt=new Map,ur=new Set;dr=e=>Math.round(e*1e4)/1e4});var Er={};Et(Er,{REMOVED_MARKER:()=>Xt,detectInstallKind:()=>Oe,detectProviderAuth:()=>xr,maskToken:()=>Jt,readRemovedMarker:()=>kr,startPlaneLink:()=>$s,updateCommandFor:()=>Ve,versionLt:()=>Ee});import $e from"node:fs";import Ge from"node:fs/promises";import ps from"node:http";import B from"node:path";import pt from"node:os";import{createRequire as hs}from"node:module";import Gt from"ws";function Jt(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function kr(e=Xt){try{let t=JSON.parse($e.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function Oe({env:e=process.env,pkgDir:t=B.resolve(B.dirname(new URL(import.meta.url).pathname),".."),exists:n=$e.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 Ee(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 xr({home:e=process.env.HOME||pt.homedir(),env:t=process.env}={}){let n=r=>{try{return $e.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 $s({url:e,token:t,nodeId:n=pt.hostname(),name:r=pt.hostname(),listTracks:s,detectAgents:c=null,onTracksTransferred:u=null,sampleMetrics:h=null,deliverySample:g=null,onHashKey:T=null,onViewBase:f=null,metricsMs:m=xs,onUpdateAvailable:C=null,onUpdatePolicy:A=null,onHelloRefused:k=null,updatePolicy:S=null,installKind:M=Oe(),selfUrl:j=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:K=null,removedMarkerFile:P=Xt,onRemoved:b=null,onDegraded:G=null,onRecovered:_e=null,onConnected:qe=null,ingestMode:Ie=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:on=vs,unackedRetryMs:Je=Ss,pingMs:sn=Ts,deadLinkMs:yt=Math.round(sn*_s),maxInflightEvents:Fr=As,httpTimeoutMs:Xe=ks,stallBackoffMinMs:an=bs,fetchImpl:cn=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 Ur=j.replace(/^http/,"ws"),ln=new Set,le=new Map,ue=new Map,gt=B.join(qt,"plane-link","cursor.json"),Tt=B.join(qt,"plane-link","dead-letter.ndjson"),un=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),de={},ne={},x=new Map,Ze=null,re=null,Q=0,Me=0,dn=0,fn=Promise.resolve(),E="ws",Se=0,V=!1,fe=0,_t=!1,W=ie,ve=new Set,oe=[],F=null,z=null,q=!1,St=!1,Pe=_r,De=null,be=null,Ae=null,ee=null,pe=0,pn=0,te=null,vt=!1,Qe=0,Ce=!1,se=kr(P);if(se)if(se.tokenPreview===Jt(t))Ce=!0,Lt({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 ${P} to force a dial.`);else try{$e.unlinkSync(P),w.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function bt({reason:i="removed",at:l=Date.now(),via:a="ctl"}={}){if(!Ce){Ce=!0,Lt({reason:i,at:l,nodeId:n,via:a});try{$e.mkdirSync(B.dirname(P),{recursive:!0}),$e.writeFileSync(P,JSON.stringify({at:l,reason:i,via:a,nodeId:n,tokenPreview:Jt(t)},null,2))}catch(o){w.error(`[plane-link] could not write ${P}: ${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{b?.({reason:i,at:l,via:a})}catch{}vn({bye:!1})}}async function Hr(){try{de=JSON.parse(await Ge.readFile(gt,"utf8"))}catch{de={}}}function Kr(){vt=!0,!Ae&&(Ae=setTimeout(async()=>{if(Ae=null,!!vt){vt=!1;try{await Ge.mkdir(B.dirname(gt),{recursive:!0}),await Ge.writeFile(gt,JSON.stringify(de))}catch(i){w.error("[plane-link] cursor flush failed:",i?.message||i)}}},gs),Ae.unref?.())}function O(i){return!z||z.readyState!==Gt.OPEN?!1:(z.send(JSON.stringify(i)),!0)}function Le(i){let l=Date.now();for(let{trackId:a,event:o}of i){let d=x.get(o.id);x.set(o.id,{trackId:a,seq:o.seq,event:o,sentAt:l,firstSentAt:d?.firstSentAt??l,retryAt:l+Je,tries:(d?.tries??0)+1,nacks:d?.nacks??0})}return E==="http"?(Vr(i),!0):O({v:N,ch:"events",type:"append",events:i})}function Wr(i){let l=null;for(let a of x.values())a.trackId===i&&(l==null||a.seq<l)&&(l=a.seq);return l}function At(i){let l=ne[i];if(l==null)return;let a=Wr(i),o=a==null?l:Math.min(l,a-1);o>(de[i]??0)&&(de[i]=o,Kr())}function Be(){if(Ze=Date.now(),re!=null){let i=Date.now()-re;w.log(`[plane-link] spine sync recovered after ${Math.round(i/1e3)}s degraded (${Q} stall redial(s))`);let l=re;re=null,Q=0,Me=0,V=!1,fe=0;try{_e?.({since:l,downMs:i})}catch(a){w.error(`[plane-link] onRecovered failed: ${a?.message||a}`)}}}function kt(i){if(!Array.isArray(i)||!i.length)return;let l=new Set;for(let a of i){let o=x.get(a);o&&(x.delete(a),(ne[o.trackId]??0)<o.seq&&(ne[o.trackId]=o.seq),l.add(o.trackId))}for(let a of l)At(a);Be()}function hn(i,l){dn++;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 ${Tt}`),fn=fn.then(async()=>{await Ge.mkdir(B.dirname(Tt),{recursive:!0}),await Ge.appendFile(Tt,JSON.stringify(a)+`
116
- `)}).catch(o=>w.error(`[plane-link] dead-letter write failed: ${o?.message||o}`))}function mn(i,l,a,o=null){if(!Array.isArray(i)||!i.length)return;let d=new Set,y=Date.now();for(let p of i){let _=x.get(p);_&&(a?(x.delete(p),hn(_,l),(ne[_.trackId]??0)<_.seq&&(ne[_.trackId]=_.seq),d.add(_.trackId)):(_.nacks++,_.retryAt=y+Math.max(1e3,Number(o)||Je)))}for(let p of d)At(p);Be()}function wn(i=Date.now()){let l=1/0;for(let a of x.values())a.firstSentAt<l&&(l=a.firstSentAt);return l===1/0?0:i-l}function zr(i){if(!yt||!i||i!==z||!pe)return!1;let l=Date.now()-pe;if(l<=yt)return!1;pn++,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 yn(){if(!q||!x.size)return;let i=Date.now(),l=wn(i);if(l<on||Ze!=null&&i-Ze<on||E==="http"&&V||Me>i)return;Q++;let a=Math.min(an*2**(Q-1),vr);if(re==null){re=i-l,w.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${x.size} event(s) in flight (${E} door) \u2014 the plane is not answering appends`);try{G?.({since:re,unacked:x.size,oldestAgeMs:l,mode:E})}catch(o){w.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(E==="http"){V=!0,fe=i+a,w.error(`[plane-link] ingest circuit OPEN (stall #${Q}); 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 #${Q})`);try{z?.terminate()}catch{}}function xt(){if(!q)return;let i=Date.now();if(E==="http"&&V)return;let l=[...x.values()].filter(o=>o.event&&o.retryAt<=i&&!(E==="http"&&ve.has(o.trackId)));if(!l.length)return;l.sort((o,d)=>o.trackId===d.trackId?o.seq-d.seq:o.trackId<d.trackId?-1:1),w.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let a=E==="http"?W:ie;if(E==="http"){let o=new Map;for(let d of l)(o.get(d.trackId)??o.set(d.trackId,[]).get(d.trackId)).push(d);for(let[,d]of o){if(Se>=Vt)return;Le(d.slice(0,a).map(y=>({trackId:y.trackId,event:y.event})))}return}for(let o=0;o<l.length;o+=a){let d=l.slice(o,o+a).map(y=>({trackId:y.trackId,event:y.event}));if(!Le(d))return}}async function Yr(i=null){for(;;){if(!q)return!1;let l=x.size<Fr,a=E!=="http"||Se<Vt&&!V&&(!i||!ve.has(i));if(l&&a)return!0;await new Promise(o=>setTimeout(o,100))}}function $t(){if(F=null,!q||!oe.length)return;let i=oe;if(oe=[],E!=="http"){for(let a=0;a<i.length;a+=ie)Le(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)||Se>=Vt||V){oe.push(...o);continue}for(let d=0;d<o.length;d+=W)Le(o.slice(d,d+W))}oe.length&&!F&&(F=setTimeout($t,br),F.unref?.())}let Gr=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 d=Date.now();for(let{event:y}of i){let p=x.get(y.id);p&&(p.nacks++,p.retryAt=d+Math.max(1e3,a||Je))}o&&Be()};async function Vr(i){let l=new Set(i.map(a=>a.trackId));for(let a of l)ve.add(a);Se++;try{let a=await cn(`${un}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:Gr(i)}),signal:AbortSignal.timeout(Xe)}),o=(Number(a.headers.get("retry-after"))||0)*1e3;if(a.status===200){let d=await a.json();W=ie;for(let y of d.results??[]){kt(y.acked??[]);let p=(_,R)=>{let Y=new Map;for(let $ of _??[])(Y.get($.reason)??Y.set($.reason,[]).get($.reason)).push($.id);for(let[$,bn]of Y)mn(bn,$,R,d.retryAfterMs??null)};p(y.rejected,!0),p(y.deferred,!1)}kt(d.discarded??[]),Be();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 d=x.get(i[0].event.id);d&&(x.delete(d.event.id),hn(d,"too_large"),(ne[d.trackId]??0)<d.seq&&(ne[d.trackId]=d.seq),At(d.trackId)),Be();return}if(a.status===410){bt({reason:"removed",via:"410"}),he(i,"http_410",6e4,{progress:!1});return}if(a.status===401||a.status===403){let{tripped:d,holdMs:y}=it();if(d&&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>=Ar){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{Se--;for(let a of l)ve.delete(a)}}async function qr(){if(E!=="http"||!V||!q||_t)return;let i=Date.now();if(!(fe>i||at(i))){_t=!0;try{let l=await cn(`${un}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(Xe)});if(!l.ok)throw new Error(`HTTP ${l.status}`);w.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),V=!1,fe=0,Me=Date.now()+Xe+Je+1e3;for(let a of x.values())a.retryAt=Math.min(a.retryAt,Date.now());xt()}catch(l){Q++;let a=Math.min(an*2**(Q-1),vr);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{_t=!1}}}function gn(){let i=Date.now();return{mode:E,unacked:x.size,oldestUnackedAgeMs:wn(i),lastProgressAt:Ze,degradedSince:re,stallRedials:Q,deadLettered:dn,http:E==="http"?{inFlight:Se,circuitOpen:V,nextProbeInMs:V?Math.max(0,fe-i):0,batchCap:W}:null}}async function Tn(){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=g?.()??null}catch{}i&&O({v:N,ch:"ctl",type:"metrics",metrics:{...i,planeLink:gn(),...l?{delivery:l}:{}}})}function Jr(){h&&(te&&clearInterval(te),Tn(),te=setInterval(Tn,m),te.unref?.())}async function Xr(){let i;try{i=await s()}catch(l){w.error("[plane-link] backfill listTracks failed:",l?.message||l);return}O({v:N,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(!q)return;let a;try{a=await Ut(l)}catch{continue}let o=de[l.id]??0,d=a.filter(p=>p.seq>o&&typeof p.id=="string"),y=E==="http"?W:ie;for(let p=0;p<d.length;p+=y){if(!await Yr(l.id))return;let _=d.slice(p,p+Math.min(y,E==="http"?W:ie)).map(R=>({trackId:l.id,event:R}));if(!Le(_))return}}}function _n(i){!q||!i?.trackId||typeof i.id!="string"||(oe.push({trackId:i.trackId,event:i}),F||(F=setTimeout($t,br),F.unref?.()))}let je=new Map;async function Zr(i){let{reqId:l,method:a,path:o,headers:d={},body:y}=i,p=Object.fromEntries(Object.entries(d).filter(([,R])=>R!=null)),_=new AbortController;je.set(l,_);try{if(i.host){await Qr(i,p,_);return}K&&(p["x-bostrat-token"]=K);let R=await fetch(j+o,{method:a,headers:p,body:y?Buffer.from(y,"base64"):void 0,signal:_.signal}),Y=Object.fromEntries(R.headers);for(let $ of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete Y[$];if(Y["content-type"]||(Y["content-type"]="application/octet-stream"),O({v:N,ch:"control",type:"http_head",reqId:l,status:R.status,headers:Y}),R.body){for await(let $ of R.body)if(!O({v:N,ch:"control",type:"http_data",reqId:l,data:Buffer.from($).toString("base64")}))break}O({v:N,ch:"control",type:"http_end",reqId:l,error:null})}finally{je.delete(l)}}function Qr(i,l,a){let{reqId:o,method:d,path:y,body:p}=i,_=new URL(j);return new Promise(R=>{let Y=ps.request({host:_.hostname,port:_.port,method:d,path:y,headers:{...l,host:i.host},signal:a.signal},$=>{let{connection:bn,"keep-alive":hi,"transfer-encoding":mi,upgrade:wi,...eo}=$.headers;O({v:N,ch:"control",type:"http_head",reqId:o,status:$.statusCode||502,headers:eo}),$.on("data",to=>{O({v:N,ch:"control",type:"http_data",reqId:o,data:Buffer.from(to).toString("base64")})||$.destroy()}),$.on("end",()=>{O({v:N,ch:"control",type:"http_end",reqId:o,error:null}),R()}),$.on("error",()=>{O({v:N,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),R()})});Y.on("error",$=>{O({v:N,ch:"control",type:"http_end",reqId:o,error:$?.message||"view request failed"}),R()}),p&&Y.write(Buffer.from(p,"base64")),Y.end()})}function Sn(){if(St||Ce)return;z=new Gt(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}O({v:N,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:J,installKind:M,...typeof S=="function"?{updatePolicy:S()}:S?{updatePolicy:S}:{},providers:xr(),...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"){q=!0,Pe=_r,De=null,Mn(),w.log(`[plane-link] connected to plane as ${n}`);try{qe?.()}catch{}if(typeof o.hashKey=="string"&&o.hashKey)try{T?.(o.hashKey)}catch{}try{f?.(typeof o.viewBase=="string"&&o.viewBase?o.viewBase:null)}catch{}o.minNodeVersion&&J&&Ee(J,o.minNodeVersion)&&w.error(`[plane-link] this node is bostrat-node ${J}; the plane asks for \u2265${o.minNodeVersion} \u2014 update with: ${Ve(M)}`);try{A?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}let d=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;if(d&&J&&Ee(J,d)&&!ln.has(d)){ln.add(d),w.log(`[plane-link] bostrat-node ${d} is available (this node runs ${J}) \u2014 ${Ve(M)}`);try{C?.({current:J,latest:d,min:o.minNodeVersion??null,installKind:M,required:!!(o.minNodeVersion&&Ee(J,o.minNodeVersion))})}catch(p){w.error(`[plane-link] update notice failed: ${p?.message||p}`)}}let y=o.ingest==="http";E=Ie==="ws"?"ws":Ie==="http"||y?"http":"ws",Ie==="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"),E==="http"&&w.log("[plane-link] spine rides the HTTPS ingest door"),V=!1,fe=0,W=ie,ee&&clearInterval(ee),pe=Date.now(),ee=setInterval(()=>{zr(i)||(O({v:N,ch:"ctl",type:"ping"}),yn(),qr().catch(()=>{}),xt(),oe.length&&!F&&$t())},sn),ee.unref?.(),Jr(),Xr().catch(p=>w.error("[plane-link] backfill failed:",p?.message||p));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let d=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 ${J??"?"} is below its minimum ${d??"?"} \u2014 ${o.fix||Ve(M)}`),Pe=Sr,De=0;try{k?.({current:J,min:d,latest:y,fix:o.fix||Ve(M),installKind:M})}catch(p){w.error(`[plane-link] refusal handler failed: ${p?.message||p}`)}return}if(o.ch==="ctl"&&o.type==="removed"){O({v:N,ch:"ctl",type:"removed_ack",nodeId:n}),bt({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{A?.(typeof o.mode=="string"?o.mode:null)}catch{}return}if(o.ch==="ctl"&&o.type==="usage_caps"){gr(o.caps??{},{source:"plane",updatedAt:o.updatedAt??Date.now()}).then(d=>w.log(`[plane-link] spend caps ${Object.keys(d.caps).length?`updated (${Object.keys(d.caps).join(", ")})`:"cleared"} from plane`)).catch(d=>w.error("[plane-link] spend-caps push rejected:",d?.message||d));return}if(o.ch==="ctl"&&o.type==="transferred"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>u?.(o.tracks)).catch(d=>w.error("[plane-link] transfer notice failed:",d?.message||d));return}if(o.ch==="events"&&o.type==="ack"&&Array.isArray(o.ids)){kt(o.ids);return}if(o.ch==="events"&&o.type==="nack"&&Array.isArray(o.ids)){mn(o.ids,o.reason,o.permanent===!0,o.retryAfterMs??null);return}if(o.ch==="control"&&o.type==="http_open"){Zr(o).catch(d=>O({v:N,ch:"control",type:"http_end",reqId:o.reqId,error:d?.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 d=new Gt(Ur+o.path,Array.isArray(o.protocols)?o.protocols:[],o.host?{headers:{host:o.host}}:void 0);le.set(o.streamId,d),ue.set(o.streamId,[]),d.on("open",()=>{let p=ue.get(o.streamId)||[];ue.delete(o.streamId);for(let{buf:_,bin:R}of p)d.send(_,{binary:R})}),d.on("message",(p,_)=>{let R=_?p:Buffer.from(String(p));O({v:N,ch:"attach",type:"data",streamId:o.streamId,data:R.toString("base64"),..._?{bin:!0}:{}})});let y=()=>{ue.delete(o.streamId),le.delete(o.streamId)&&O({v:N,ch:"attach",type:"close",streamId:o.streamId})};d.on("close",y),d.on("error",y);return}if(o.ch==="attach"&&o.type==="data"){let d=le.get(o.streamId);if(!d)return;let y=Buffer.from(o.data,"base64"),p=o.bin===!0,_=ue.get(o.streamId);_?_.push({buf:y,bin:p}):d.send(y,{binary:p});return}if(o.ch==="attach"&&o.type==="close"){let d=le.get(o.streamId);le.delete(o.streamId),ue.delete(o.streamId),d?.close();return}});let l=()=>{q&&w.log("[plane-link] disconnected from plane"),q=!1,ee&&(clearInterval(ee),ee=null),te&&(clearInterval(te),te=null),x.clear(),ne={},oe=[],F&&(clearTimeout(F),F=null),ve.clear();for(let d of le.values())d.close();le.clear(),ue.clear();for(let d of je.values())d.abort();if(je.clear(),St||be)return;De==null&&(De=Date.now());let a=Date.now()-De<ms,o=Math.max(a?ws+Math.random()*ys:Pe,Me-Date.now(),Ke());be=setTimeout(()=>{be=null,Sn()},o),be.unref?.(),a||(Pe=Math.min(Pe*2,Sr))};z.on("close",l),z.on("error",a=>{let o=/Unexpected server response: (\d+)/.exec(a?.message||"")?.[1];if(o==="410"){bt({reason:"removed",via:"410"});return}if(o==="401"||o==="403"){let{tripped:d,holdMs:y}=it();d?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>=Ar&&(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",_n),Hr().then(Sn);function vn({bye:i=!0}={}){St=!0,ze.off("event",_n),be&&clearTimeout(be),Ae&&clearTimeout(Ae),ee&&clearInterval(ee),te&&clearInterval(te),F&&clearTimeout(F),i&&O({v:N,ch:"ctl",type:"bye",reason:"shutdown"}),z?.close()}return{stop:()=>vn(),status:()=>({connected:q,nodeId:n,cursor:{...de},inflight:x.size,...gn(),auth:Pn(),dormant:Ce,removed:Bt(),deadLinkMs:yt,deadLinkRedials:pn}),_tick:()=>{yn(),xt()}}}var J,qt,Xt,N,_r,Sr,ms,ws,ys,ie,gs,Ts,_s,Ss,$r,vs,bs,vr,As,br,ks,Vt,xs,Ar,Zt=v(()=>{ct();Tr();Nt();jt();J=(()=>{try{return hs(import.meta.url)("../package.json").version||null}catch{return null}})(),qt=process.env.BOSTRAT_STATE_DIR||B.join(process.env.HOME||pt.tmpdir(),".bostrat"),Xt=B.join(qt,"plane-link","removed.json");N=1,_r=1e3,Sr=3e4,ms=6e4,ws=1500,ys=500,ie=100,gs=2e3,Ts=25e3,_s=2.5,Ss=6e4,$r=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},vs=$r(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),bs=3e4,vr=10*6e4,As=400,br=250,ks=$r(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Vt=4,xs=6e4,Ar=6e4});var Or=v(()=>{Dt()});var Pr={};Et(Pr,{ACTIONABLE_KINDS:()=>wt,SELF_UPDATE_DIR:()=>Qt,createAutoUpdater:()=>Fs,inFlight:()=>tn,readStatus:()=>en,selfUpdatePlan:()=>Ir,settleSelfUpdate:()=>js,startSelfUpdate:()=>Mr,underService:()=>Nr,updatePolicy:()=>Ps});import Rr from"node:fs";import ae from"node:fs/promises";import Es from"node:os";import D from"node:path";import{spawn as Os}from"node:child_process";import{createRequire as Rs}from"node:module";function Ps({kind:e=Oe(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:wt.has(e)?e==="git-checkout"||Nr(t)?"auto":"prompt":"off"}function Nr(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Ir({kind:e,to:t,from:n=ht,statusFile:r=mt,logFile:s=D.join(Qt,"last.log"),port:c=Number(process.env.PORT)||3362,npmPrefix:u=null,serviceName:h=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:g=typeof process.getuid=="function"?process.getuid():0,liveDir:T=process.env.BOSTRAT_LIVE_CHECKOUT||D.resolve(D.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:f=Date.now()}={}){if(!wt.has(e))throw new Error(`self-update: install kind "${e}" is not actionable here`);if(!/^\d+\.\d+\.\d+$/.test(String(t)))throw new Error(`self-update: bad target version "${t}"`);if(n&&!/^\d+\.\d+\.\d+$/.test(String(n)))throw new Error(`self-update: bad current version "${n}"`);let m=(M,j="")=>`write_status ${U(M)} ${j}`,C=process.platform==="darwin"?`launchctl kickstart -k gui/${g}/${h}`:`systemctl --user restart ${U(h)}`,A=`
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=`
117
117
  health() {
118
118
  for i in $(seq 1 45); do
119
119
  sleep 1
120
120
  if curl -sf -o /dev/null "http://127.0.0.1:${c}/api/health"; then return 0; fi
121
121
  done
122
122
  return 1
123
- }`,k=`#!/usr/bin/env bash
123
+ }`,E=`#!/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,24 +128,36 @@ FROM=${U(n??"")}
128
128
  TO=${U(t)}
129
129
  STATUS_FILE=${U(r)}
130
130
  STARTED_AT=${Number(f)}
131
- write_status() { # <status> [error]
131
+ ATTEMPTS=${Number(T)||1}
132
+ write_status() { # <status> [error] [retryable]
132
133
  local err="\${2:-}"
133
134
  err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
134
- printf '{"status":"%s","from":"%s","to":"%s","kind":"%s","startedAt":%s,"updatedAt":%s%s}\\n' \\
135
- "$1" "$FROM" "$TO" ${U(e)} "$STARTED_AT" "$(date +%s000)" \\
136
- "\${err:+,\\"error\\":\\"$err\\"}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
135
+ printf '{"status":"%s","from":"%s","to":"%s","kind":"%s","attempts":%s,"startedAt":%s,"updatedAt":%s%s%s}\\n' \\
136
+ "$1" "$FROM" "$TO" ${U(e)} "$ATTEMPTS" "$STARTED_AT" "$(date +%s000)" \\
137
+ "\${err:+,\\"error\\":\\"$err\\"}" "\${3:+,\\"retryable\\":true}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
137
138
  }
138
- ${A}
139
- `;if(e==="npm-global"){let M=u?D.join(u,"bin","npm"):"npm",j=u?`export PATH=${U(D.join(u,"bin"))}:"$PATH"
140
- `:"",K=u?` --prefix ${U(u)}`:"",P=b=>`${U(M)} install -g "bostrat-node@${b}" --no-audit --no-fund${K}`;return k+j+`
141
- ${m("updating",'"" ')}
142
- if ! ${P("$TO")}; then
143
- ${m("failed",'"npm install failed"')}
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=`
142
+ wait_for_registry() {
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
145
+ sleep ${sn}
146
+ done
147
+ return 1
148
+ }`;return E+C+te+`
149
+ ${b("updating",'"" ')}
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`)}
152
+ exit 1
153
+ fi
154
+ if ! ${j("$TO")}; then
155
+ ${b("failed",'"npm install failed"')}
144
156
  exit 1
145
157
  fi
146
- ${m("restarting")}
147
- if ! ${C}; then
148
- ${m("failed",'"service restart failed"')}
158
+ ${b("restarting")}
159
+ if ! ${x}; then
160
+ ${b("failed",'"service restart failed"')}
149
161
  exit 1
150
162
  fi
151
163
  if health; then
@@ -153,52 +165,52 @@ if health; then
153
165
  exit 0
154
166
  fi
155
167
  # \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
156
- ${m("rolling-back",'"agent did not answer on :'+c+' after the update"')}
157
- if [ -n "$FROM" ] && ${P("$FROM")} && ${C} && health; then
158
- ${m("rolled-back",'"agent did not answer on :'+c+' after the update; rolled back"')}
168
+ ${b("rolling-back",'"agent did not answer on :'+c+' after the update"')}
169
+ if [ -n "$FROM" ] && ${j("$FROM")} && ${x} && health; then
170
+ ${b("rolled-back",'"agent did not answer on :'+c+' after the update; rolled back"')}
159
171
  exit 1
160
172
  fi
161
- ${m("failed",'"agent did not answer after the update AND the rollback"')}
173
+ ${b("failed",'"agent did not answer after the update AND the rollback"')}
162
174
  exit 1
163
- `}let S=M=>`( cd ${U(T)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${M}" )`;return k+`
164
- LIVE=${U(T)}
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)}
165
177
  TMP_SCRIPT="$(mktemp)"
166
178
  trap 'rm -f "$TMP_SCRIPT"' EXIT
167
179
  # "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
168
180
  # restart \u2192 health in one call): the agent it restarts settles "done" on boot,
169
181
  # and nothing here may write after that boot or the settle would repeat.
170
- ${m("restarting")}
171
- if ${S("$TO")}; then
182
+ ${b("restarting")}
183
+ if ${R("$TO")}; then
172
184
  exit 0
173
185
  fi
174
- ${m("rolling-back",'"deploy-pi.sh v$TO failed"')}
175
- if [ -n "$FROM" ] && ${S("$FROM")}; then
176
- ${m("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
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"')}
177
189
  exit 1
178
190
  fi
179
- ${m("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
191
+ ${b("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
180
192
  exit 1
181
- `}async function en(e=mt){try{return JSON.parse(await ae.readFile(e,"utf8"))}catch{return null}}async function Mr({to:e,from:t=ht,kind:n=Oe(),reason:r="manual",statusFile:s=mt,spawnImpl:c=Os,now:u=Date.now,npmPrefix:h=void 0,log:g=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!wt.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Ee(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let T=await en(s);if(tn(T))return{ok:!1,reason:`an update to ${T.to} is already in flight`,status:T};if(T&&T.to===e&&(T.status==="failed"||T.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${T.status} (${T.error||"no detail"}) \u2014 retried when a newer release exists`,status:T};await ae.mkdir(D.dirname(s),{recursive:!0});let f=h!==void 0?h:n==="npm-global"?Pt(await Cs())||D.resolve(D.dirname(process.execPath),".."):null,m=Ir({kind:n,to:e,from:t,statusFile:s,npmPrefix:f,startedAt:u()}),C=D.join(D.dirname(s),`update-${e}.sh`),A=D.join(D.dirname(s),"last.log");await ae.writeFile(C,m,{mode:448}),await ae.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,startedAt:u(),updatedAt:u()}));let k=Rr.existsSync("/run/systemd/system")&&await Ls("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",C]]:["setsid",["-f","bash","-c",`exec bash ${U(C)} >> ${U(A)} 2>&1`]];try{c(k[0],k[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(S){return await ae.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,startedAt:u(),updatedAt:u(),error:`could not spawn updater: ${S?.message||S}`})),{ok:!1,reason:`could not spawn updater: ${S?.message||S}`}}return g.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:C,statusFile:s}}async function Cs(){try{return await ae.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Ls(e){for(let t of String(process.env.PATH||"").split(D.delimiter))try{return await ae.access(D.join(t,e),Rr.constants.X_OK),!0}catch{}return!1}async function js({statusFile:e=mt,current:t=ht,now:n=Date.now,staleMs:r=Bs}={}){let s=await en(e);if(!s)return null;let c=u=>ae.writeFile(e,JSON.stringify(u)).catch(()=>{});if(tn(s)){if(t&&s.to===t){let u={...s,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await c(u),u}if(n()-Number(s.updatedAt||s.startedAt||0)>r){let u={...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(u),u}return null}if(["failed","rolled-back","done"].includes(s.status)&&!s.announced){let u={...s,announced:!0};return await c(u),u}return null}function Fs({isBusy:e,start:t=Mr,onStuck:n=null,onStarted:r=null,tickMs:s=Ms,stuckMs:c=Is,now:u=Date.now,setIntervalImpl:h=setInterval,clearIntervalImpl:g=clearInterval,log:T=console}={}){let f=null,m=()=>{f?.timer&&g(f.timer),f=null},C=async()=>{if(!f)return;let A=!0;try{A=await e()!==!1}catch{A=!0}if(A){if(!f.stuckFired&&u()-f.since>=c){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let k=f;m();let S=await t({to:k.to,from:k.from,kind:k.kind,reason:"auto"});T.log?.(`[self-update] stasis reached \u2192 ${S.ok?"started":`not started: ${S.reason}`}`);try{await r?.({...k,result:S})}catch{}};return{arm({to:A,from:k=ht,kind:S=Oe()}){return f?.to===A?!1:(m(),f={to:A,from:k,kind:S,since:u(),stuckFired:!1,timer:h(C,s)},f.timer.unref?.(),!0)},tick:C,cancel:m,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var ht,Ns,Qt,mt,Is,Ms,wt,U,Ds,tn,Bs,Dr=v(()=>{Zt();Or();ht=(()=>{try{return Rs(import.meta.url)("../package.json").version||null}catch{return null}})(),Ns=process.env.BOSTRAT_STATE_DIR||D.join(process.env.HOME||Es.tmpdir(),".bostrat"),Qt=D.join(Ns,"self-update"),mt=D.join(Qt,"status.json"),Is=1440*6e4,Ms=6e4,wt=new Set(["npm-global","git-checkout"]);U=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Ds=new Set(["updating","restarting","rolling-back"]),tn=e=>!!(e&&Ds.has(e.status));Bs=45*6e4});Nt();Mt();import X from"node:fs";import I from"node:path";import Ne from"node:os";import{createRequire as nn}from"node:module";import{execFile as Us,spawn as Hs}from"node:child_process";import{promisify as Ks}from"node:util";import Ws from"node:readline/promises";import{randomUUID as zs}from"node:crypto";import{fileURLToPath as Ys}from"node:url";import Ho from"node:fs";import qn from"node:path";import Ko from"node:os";var Wo=()=>process.env.BOSTRAT_STATE_DIR||qn.join(process.env.HOME||Ko.tmpdir(),".bostrat"),zo=()=>qn.join(Wo(),"plane-link","public-host.json");var Ye=null;function Yo(){if(Ye)return Ye;try{let e=JSON.parse(Ho.readFileSync(zo(),"utf8"));Ye={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{Ye={viewBase:null}}return Ye}function Go(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 Jn(){return Yo().viewBase}function Xn(e=process.env.BOSTRAT_PUBLIC_HOST){return Go(e,"https")}function Zn(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 Cr=(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=Ks(Us),rn=I.dirname(Ys(import.meta.url)),Te=I.resolve(rn,".."),Gs=I.join(rn,"index.js"),Vs="wss://plane.bostrat.ai/v1/node",Re=nn(import.meta.url)("../package.json").version,L=(e,t)=>({name:e,level:"pass",detail:t}),Z=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),H=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function qs(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?L("node runtime",`${process.version} at ${process.execPath}`):H("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Js(e){let t;try{t=X.statSync(e)}catch{return Z("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?Z("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):L("node.env",`${e} (0600)`)}async function Xs(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 H("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Lr(e,{required:t=!1}={}){if(await Kt(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=ut[e]?`${ut[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?H(e,r,s):Z(e,r,s)}async function Zs(){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 Z("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",ut.gh)}}async function Qs(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Lr(t)));return e.some(t=>t.level==="pass")||e.push(H("agent CLIs","no agent CLI found at all \u2014 a node with nothing to drive","install at least one of claude / codex / cursor-agent")),e}async function ei(){let e=[...process.platform==="linux"?[["fuser","stopped views can't free their ports (they leak, and the port can't be reused)","apt install psmisc"]]:[],["pgrep","agent-swap can't detect an idle pane shell \u2014 swaps may misfire","apt install procps"],["npm","codex auto-update and `npm run` views are unavailable","install Node.js with npm on the service PATH"]];return Promise.all(e.map(async([t,n,r])=>await Kt(t,{failOpen:!1})?L(t,"resolves on the service PATH"):Z(t,`not on the service PATH \u2014 ${n}`,r)))}async function ti(){try{let t=nn(I.join(Te,"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 ${Te} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=nn(I.join(Te,"package.json")),r=I.join(I.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");X.existsSync(r)&&!(X.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return H("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function ni(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(X.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"?H:Z)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function ri(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?H("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 oi(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return Z("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),s=Fe(e.BOSTRAT_PLANE_URL);return await new Promise(c=>{let u=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),h=null,g=f=>{clearTimeout(T);try{u.close()}catch{}c(h?{...f,viewBase:h}:f)},T=setTimeout(()=>g(H("plane link",`no hello_ok within 5s from ${s}`,"check the URL, the token, and the plane's IP gate")),5e3);u.on("open",()=>u.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${zs().slice(0,8)}`,ephemeral:!0}))),u.on("message",f=>{try{let m=JSON.parse(f);m.type==="hello_ok"?(typeof m.viewBase=="string"&&m.viewBase&&(h=m.viewBase),m.minNodeVersion&&Cr(Re,m.minNodeVersion)?g(H("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${m.minNodeVersion} \u2014 this node is ${Re}; the real link is refused until it updates`,`bostrat-node self-update --to ${m.latestNodeVersion||m.minNodeVersion}`)):m.latestNodeVersion&&Cr(Re,m.latestNodeVersion)?g(Z("plane link",`hello_ok in ${Date.now()-r}ms (${s}); bostrat-node ${m.latestNodeVersion} is available (this node: ${Re})`,`bostrat-node self-update --to ${m.latestNodeVersion}`)):g(L("plane link",`hello_ok in ${Date.now()-r}ms (${s})`))):m.type==="error"&&g(H("plane link",`plane said: ${m.code} ${m.message||""}`,"check the token"))}catch{}}),u.on("error",f=>g(H("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function si(){let e;try{e=JSON.parse(X.readFileSync(I.join(Rt,"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 H("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?Z("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):L("content outbox",t?`${t} op(s) in flight`:"drained")}function ii(e){return e.BOSTRAT_STATE_REMOTE?L("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):Z("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}function ai(e,t){let n=t?.viewBase??null,r=Jn(),s=Xn(e.BOSTRAT_PUBLIC_HOST),c=(()=>{let u=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(u)return`${u.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let h=Zn(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 u=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)${u} \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}`):H("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 Br(e,t={}){let n=[];n.push(await qs()),n.push(Js(t.envFile||ke())),n.push(await Xs(e)),n.push(...await Qs()),n.push(await Lr("git",{required:!0})),n.push(await Zs()),n.push(...await ei()),n.push(await ti()),n.push(ni(e)),n.push(ri(e));let r=await oi(e,t);return n.push(r),n.push(ai(e,r)),n.push(si()),n.push(ii(e)),n}function jr(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?`
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?`
182
194
  FAIL \u2014 ${r} blocking, ${s} warnings`:`
183
- OK \u2014 0 blocking, ${s} warnings`),r===0}async function ci({envFile:e=ke(),input:t=process.stdin,output:n=process.stdout}={}){let r=tt(e),s=Ws.createInterface({input:t,output:n}),c=async(P,b)=>(await s.question(b?`${P} [${b}]: `:`${P}: `)).trim()||b||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
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:
184
196
  you type those inside each box, later (box-auth-policy).
185
197
 
186
- `);let u=await c("Plane URL",r.BOSTRAT_PLANE_URL||Vs),h=Fe(u);h!==u.trim()&&n.write(` \u2192 using ${h}
187
- `);let g=await c("Node token (minted plane-side; stored 0600)",r.BOSTRAT_PLANE_TOKEN),T=await c("Owner userId (just press Enter \u2014 the plane infers it from your token)",r.BOSTRAT_OWNER||"");T&&!/^user_[A-Za-z0-9]+$/.test(T)&&n.write(` ! that doesn't look like a Clerk userId (user_\u2026) \u2014 leave it empty next time and the plane infers the owner from the token; saved as typed.
188
- `);let f=await c("Node name",r.BOSTRAT_NODE_NAME||Ne.hostname().split(".")[0]),m=await c("Repos root",r.BOSTRAT_REPOS_ROOT||I.join(Ne.homedir(),"Documents")),C=await c("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),A=(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");A&&n.write(`
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(`
189
201
  BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
190
202
  injected per box, stored 0600 in node.env, never sent to the plane.
191
203
  \u2022 create/copy a key: https://console.anthropic.com/settings/keys
192
204
  \u2022 set a monthly spend limit while you're there \u2014 the key is live.
193
205
 
194
- `);let k=A?await c("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";A&&k&&!/^sk-ant-/.test(k)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
195
- `),s.close();let S={...xn(),...r,BOSTRAT_PLANE_URL:h,BOSTRAT_PLANE_TOKEN:g,BOSTRAT_OWNER:T,BOSTRAT_NODE_NAME:f,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||f,BOSTRAT_REPOS_ROOT:m,BOSTRAT_STATE_REMOTE:C,BOSTRAT_CLAUDE_USE_API_KEY:A?"1":"0",ANTHROPIC_API_KEY:A?k:r.ANTHROPIC_API_KEY};kn(e,S,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
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()}
196
208
  0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
197
209
  Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
198
210
  wrote ${e}
199
211
 
200
- `);let M={...S,...process.env},j=await Br(M,{envFile:e}),K=jr(j,P=>n.write(P+`
201
- `));return K&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:K,results:j}}function li({envFile:e=ke()}={}){An(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=Hs(t,[Gs],{cwd:Te,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 ui({agentDir:e=Te,nodeBin:t=process.execPath,envFile:n=ke(),home:r=Ne.homedir()}={}){let s=I.dirname(t),c=I.join(I.basename(rn),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
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
202
214
  # ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
203
215
  [Unit]
204
216
  Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
@@ -218,7 +230,7 @@ RestartSec=2
218
230
 
219
231
  [Install]
220
232
  WantedBy=default.target
221
- `}function di({agentDir:e=Te,nodeBin:t=process.execPath,home:n=Ne.homedir()}={}){let r=I.dirname(t),s=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
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"?>
222
234
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
223
235
  <plist version="1.0">
224
236
  <dict>
@@ -240,7 +252,7 @@ WantedBy=default.target
240
252
  <key>StandardErrorPath</key><string>${s}/node.err.log</string>
241
253
  </dict>
242
254
  </plist>
243
- `}function fi(e=process.platform,t=Ne.homedir()){return e==="darwin"?{kind:"launchd",file:I.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:I.join(t,".config","systemd","user","bostrat-node.service")}}async function pi({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:s=Te}={}){let{kind:c,file:u}=fi(n);if(!e&&s.split(I.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(()=>{}),X.rmSync(u,{force:!0}),await ce("systemctl",["--user","daemon-reload"])):(await ce("launchctl",["unload","-w",u]).catch(()=>{}),X.rmSync(u,{force:!0})),r(`removed ${u}`);return}X.mkdirSync(I.dirname(u),{recursive:!0}),c==="systemd"?(X.writeFileSync(u,ui()),await ce("systemctl",["--user","daemon-reload"]),t&&await ce("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${u}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(X.mkdirSync(I.join(Ne.homedir(),"Library","Logs","bostrat"),{recursive:!0}),X.writeFileSync(u,di()),t&&await ce("launchctl",["load","-w",u]),r(`installed ${u}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function Fl(e=process.argv.slice(2)){let t=e[0],n=ke();if(t==="--version"||t==="-v"||t==="version")return console.log(Re),0;if(t==="init")return(await ci({envFile:n})).ok?0:1;if(t==="doctor"){let r={...tt(n),...process.env};return jr(await Br(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return li({envFile:n}),null;if(t==="install-service")return await pi({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(sr(),or));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:s,updatePolicy:c}=await Promise.resolve().then(()=>(Dr(),Pr)),{detectInstallKind:u}=await Promise.resolve().then(()=>(Zt(),Er)),h=u(),g=e.indexOf("--to"),T=g>=0?String(e[g+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Re,installKind:h,policy:c({kind:h}),status:await s()},null,2)),0;if(!T)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:T,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 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)
244
256
 
245
257
  usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
246
258
 
@@ -249,4 +261,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
249
261
  run start the node in the foreground (sources node.env)
250
262
  install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
251
263
  fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
252
- self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{ci as init,pi as installService,di as launchdPlist,Fl as main,jr as printDoctor,li as runAgent,Br as runDoctor,fi as servicePaths,ui as systemdUnit};
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};