bostrat-node 1.11.5 → 1.11.7

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