bostrat-node 1.8.0 → 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.js +109 -72
  2. package/dist/index.js +220 -175
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,9 +1,45 @@
1
- var Tn=Object.defineProperty;var S=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Re=(e,t)=>{for(var n in t)Tn(e,n,{get:t[n],enumerable:!0})};import we from"node:fs";import Ne from"node:path";import bn 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 o={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return o?(r.protocol=o,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function ye(e){let t;try{t=we.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
2
- `)){let o=r.trim();if(!o||o.startsWith("#"))continue;let i=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!i)continue;let a=i[2].trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n[i[1]]=a}return n}function rt(e,t=process.env){let n=ye(e);for(let[r,o]of Object.entries(n))r in t||(t[r]=o);return n}function ot(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
3
- `).map(o=>o?`# ${o}`:"#"));for(let[o,i]of Object.entries(t))i==null||i===""||r.push(`${o}=${i}`);we.mkdirSync(Ne.dirname(e),{recursive:!0}),we.writeFileSync(e,r.join(`
1
+ var gr=Object.defineProperty;var v=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ut=(e,t)=>{for(var n in t)gr(e,n,{get:t[n],enumerable:!0})};import He from"node:fs";import dt from"node:path";import Tr from"node:os";function Pe(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,o;try{o=new URL(n)}catch{return t}let s={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[o.protocol];return s?(o.protocol=s,(o.pathname===""||o.pathname==="/")&&(o.pathname="/v1/node"),o.toString()):t}function Ke(e){let t;try{t=He.readFileSync(e,"utf8")}catch{return{}}let n={};for(let o of t.split(`
2
+ `)){let s=o.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 zt(e,t=process.env){let n=Ke(e);for(let[o,s]of Object.entries(n))o in t||(t[o]=s);return n}function Yt(e,t,{header:n=""}={}){let o=[];n&&o.push(...n.split(`
3
+ `).map(s=>s?`# ${s}`:"#"));for(let[s,c]of Object.entries(t))c==null||c===""||o.push(`${s}=${c}`);He.mkdirSync(dt.dirname(e),{recursive:!0}),He.writeFileSync(e,o.join(`
4
4
  `)+`
5
- `,{mode:384}),we.chmodSync(e,384)}function st(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 Ie,re,Pe=S(()=>{Ie=process.env.BOSTRAT_STATE_DIR||Ne.join(process.env.HOME||bn.tmpdir(),".bostrat"),re=()=>Ne.join(Ie,"node.env")});var Me=S(()=>{});var it=S(()=>{Me()});var at=S(()=>{});var ct=S(()=>{});import De from"node:path";import{execFile as Sn}from"node:child_process";import{promisify as vn}from"node:util";var Po,lt,An,Mo,Do,ut=S(()=>{Po=vn(Sn),lt=process.env.HOME||"/home/globo",An=De.join(process.env.BOSTRAT_STATE_DIR||De.join(lt,".bostrat"),"repos"),Mo=[...(process.env.BOSTRAT_REPOS_ROOT||De.join(lt,"Documents")).split(","),An].map(e=>e.trim()).filter(Boolean),Do=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});import dt from"node:path";import xn from"node:os";import{execFile as kn}from"node:child_process";import{promisify as On}from"node:util";var Ko,$n,Wo,zo,Yo,je=S(()=>{ut();Ko=On(kn),$n=process.env.BOSTRAT_STATE_DIR||dt.join(process.env.HOME||xn.tmpdir(),".bostrat"),Wo=dt.join($n,"repos"),zo=5*6e4,Yo=10*6e4});var ft=S(()=>{je()});import Rn from"node:fs/promises";import pe from"node:path";import Nn from"node:os";import{EventEmitter as In}from"node:events";function Pn(e){return e?.cwd?pe.join(e.cwd,".bostrat","events"):pe.join(pt,"events")}async function Ce(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?pe.join(pt,"events"):Pn(e));let o;try{o=await Rn.readFile(Mn(n,r),"utf8")}catch{return[]}let i=[];for(let a of o.split(`
6
- `))if(a.trim())try{i.push(JSON.parse(a))}catch{}return i}var me,pt,Mn,ge=S(()=>{me=new In;me.setMaxListeners(0);pt=process.env.BOSTRAT_STATE_DIR||pe.join(process.env.HOME||Nn.tmpdir(),".bostrat");Mn=(e,t)=>pe.join(e,`${t}.ndjson`)});import jn from"node:os";import Cn from"node:path";import{execFile as Fn}from"node:child_process";import{promisify as Bn}from"node:util";var ls,us,ds,fs,ps,ms,mt=S(()=>{ft();ge();ls=Bn(Fn),us=process.env.BOSTRAT_STATE_DIR||Cn.join(process.env.HOME||jn.tmpdir(),".bostrat"),ds=25*1024,fs=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,ps=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,ms=Promise.resolve()});var ht=S(()=>{});var bs,wt=S(()=>{je();ht();bs=60*6e4});var yt=S(()=>{wt()});import Ln from"node:os";import gt from"node:path";var Un,Is,Ps,Fe=S(()=>{Be();Un=process.env.BOSTRAT_DEBUG_DIR||gt.join(Ln.homedir(),".bostrat","debug"),Is=gt.join(Un,"handoff.jsonl"),Ps=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as Kn}from"node:child_process";import{promisify as Wn}from"node:util";import zn from"node:fs";function _t(e){return`/tmp/tmux-${e}/default`}function qn({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=_t(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function Ue(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Gn(e,{loginShell:t});return r===St?!0:r===Le?!1:n}async function Gn(e,{loginShell:t=!1,timeoutMs:n=Vn}={}){if(!e)return Le;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await Yn(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),St}catch(i){return i?.killed||i?.signal?bt:i?.code===1||i?.code===127?Le:bt}}var Yn,Qs,Tt,ei,ti,ni,St,Le,bt,Vn,Te,ri,oi,si,ii,ai,Be=S(()=>{it();at();ct();mt();yt();Fe();Me();Yn=Wn(Kn),Qs=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";Tt=typeof process.getuid=="function"?process.getuid():0,ei=qn({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return zn.existsSync(_t(Tt))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:Tt}),ti=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",ni=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions";St="present",Le="absent",bt="unknown",Vn=5e3;Te={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"},ri=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,oi=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,si=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,ii=Number(process.env.BOSTRAT_BOX_COLS)||120,ai=Number(process.env.BOSTRAT_BOX_ROWS)||40});var $t={};Re($t,{NODE_IMAGE:()=>Ke,commandPlan:()=>xt,flyToml:()=>At,flyWizard:()=>rr,parseFlyFlags:()=>kt,stageConfig:()=>Ot});import He from"node:fs";import Q from"node:path";import Jn from"node:os";import Xn from"node:readline/promises";import{execFile as Zn}from"node:child_process";import{createRequire as Qn}from"node:module";import{randomUUID as er}from"node:crypto";function At({app:e,region:t,nodeName:n=e,planeUrl:r=vt,image:o=Ke}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
5
+ `,{mode:384}),He.chmodSync(e,384)}function qt(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 ft,be,pt=v(()=>{ft=process.env.BOSTRAT_STATE_DIR||dt.join(process.env.HOME||Tr.tmpdir(),".bostrat"),be=()=>dt.join(ft,"node.env")});var pe,We,ze=v(()=>{pe="BOSTRAT_HOOK_TOKEN",We="x-bostrat-hook"});var Gt=v(()=>{ze()});var Vt=v(()=>{});var Jt=v(()=>{});import ht from"node:path";import{execFile as _r}from"node:child_process";import{promisify as br}from"node:util";var js,Xt,Sr,Cs,Fs,Zt=v(()=>{js=br(_r),Xt=process.env.HOME||"/home/globo",Sr=ht.join(process.env.BOSTRAT_STATE_DIR||ht.join(Xt,".bostrat"),"repos"),Cs=[...(process.env.BOSTRAT_REPOS_ROOT||ht.join(Xt,"Documents")).split(","),Sr].map(e=>e.trim()).filter(Boolean),Fs=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});import Qt from"node:path";import vr from"node:os";import{execFile as kr}from"node:child_process";import{promisify as Ar}from"node:util";var Ys,$r,qs,Gs,Vs,mt=v(()=>{Zt();Ys=Ar(kr),$r=process.env.BOSTRAT_STATE_DIR||Qt.join(process.env.HOME||vr.tmpdir(),".bostrat"),qs=Qt.join($r,"repos"),Gs=5*6e4,Vs=10*6e4});var en=v(()=>{mt()});import Er from"node:fs/promises";import De from"node:path";import Or from"node:os";import{EventEmitter as Rr}from"node:events";function Nr(e){return e?.cwd?De.join(e.cwd,".bostrat","events"):De.join(tn,"events")}async function wt(e,t){let n,o;typeof e=="string"&&t?(n=e,o=t):(o=typeof e=="string"?e:e?.id,n=typeof e=="string"?De.join(tn,"events"):Nr(e));let s;try{s=await Er.readFile(Ir(n,o),"utf8")}catch{return[]}let c=[];for(let u of s.split(`
6
+ `))if(u.trim())try{c.push(JSON.parse(Pr(u)?Dr(u):u))}catch{}return c}var je,tn,Ir,Mr,Pr,Dr,Ye=v(()=>{je=new Rr;je.setMaxListeners(0);tn=process.env.BOSTRAT_STATE_DIR||De.join(process.env.HOME||Or.tmpdir(),".bostrat");Ir=(e,t)=>De.join(e,`${t}.ndjson`),Mr=/(?<!\\)((?:\\\\)*)\\u0000/g,Pr=e=>e.includes("\\u0000"),Dr=e=>e.replace(Mr,"$1\\ufffd")});import Cr from"node:os";import Fr from"node:path";import{execFile as Lr}from"node:child_process";import{promisify as Br}from"node:util";var fi,pi,hi,mi,wi,yi,nn=v(()=>{en();Ye();fi=Br(Lr),pi=process.env.BOSTRAT_STATE_DIR||Fr.join(process.env.HOME||Cr.tmpdir(),".bostrat"),hi=25*1024,mi=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,wi=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,yi=Promise.resolve()});var rn=v(()=>{});var vi,on=v(()=>{mt();rn();vi=60*6e4});var sn=v(()=>{on()});import Ur from"node:os";import an from"node:path";var Hr,Di,ji,yt=v(()=>{gt();Hr=process.env.BOSTRAT_DEBUG_DIR||an.join(Ur.homedir(),".bostrat","debug"),Di=an.join(Hr,"handoff.jsonl"),ji=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import cn from"node:path";import Kr from"node:os";var qe,Wr,Hi,ln,Ki,Wi,un=v(()=>{ze();qe="BOSTRAT_NODE_URL",Wr=process.env.BOSTRAT_STATE_DIR||cn.join(process.env.HOME||Kr.tmpdir(),".bostrat"),Hi=cn.join(Wr,"git-hooks"),ln=`#!/bin/sh
7
+ # bostrat git hook shim (agent/src/git-hooks.js) \u2014 chains to the repo's own hook,
8
+ # then stamps/reports for rework attribution when running inside a bostrat box.
9
+ hook=$(basename "$0")
10
+ common=$(git rev-parse --git-common-dir 2>/dev/null)
11
+ orig=$(git config --local --get core.hooksPath 2>/dev/null)
12
+ [ -z "$orig" ] && orig=$(git config --global --get core.hooksPath 2>/dev/null)
13
+ [ -z "$orig" ] && orig="$common/hooks"
14
+ case "$orig" in
15
+ /*) ;;
16
+ *) top=$(git rev-parse --show-toplevel 2>/dev/null); [ -n "$top" ] && orig="$top/$orig" ;;
17
+ esac
18
+ if [ -x "$orig/$hook" ] && [ "$orig/$hook" != "$0" ]; then
19
+ "$orig/$hook" "$@" || exit $?
20
+ fi
21
+ `,Ki=`${ln}
22
+ # \u2500\u2500 bostrat: append provenance trailers (Layer 0). Skipped for merge commits
23
+ # (nobody "wrote" a merge) and outside a box (no token / no node url).
24
+ [ -z "$${pe}" ] && exit 0
25
+ [ -z "$${qe}" ] && exit 0
26
+ [ "$2" = "merge" ] && exit 0
27
+ trailers=$(curl -sS -m 3 -H "${We}: $${pe}" "$${qe}/api/git/trailers" 2>/dev/null) || exit 0
28
+ [ -z "$trailers" ] && exit 0
29
+ printf '%s\\n' "$trailers" | while IFS= read -r line; do
30
+ [ -n "$line" ] && git interpret-trailers --in-place --if-exists addIfDifferent --trailer "$line" "$1" >/dev/null 2>&1 || true
31
+ done
32
+ exit 0
33
+ `,Wi=`${ln}
34
+ # \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
35
+ [ -z "$${pe}" ] && exit 0
36
+ [ -z "$${qe}" ] && exit 0
37
+ sha=$(git rev-parse HEAD 2>/dev/null) || exit 0
38
+ cwd=$(git rev-parse --show-toplevel 2>/dev/null)
39
+ printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${qe}/api/git/committed" \\
40
+ -H 'content-type: application/json' -H "${We}: $${pe}" --data-binary @- >/dev/null 2>&1 || true
41
+ exit 0
42
+ `});import{execFile as Yr}from"node:child_process";import{promisify as qr}from"node:util";import Gr from"node:fs";function pn(e){return`/tmp/tmux-${e}/default`}function Jr({explicit:e,legacyExists:t,runtimeDir:n,uid:o}){if(e)return e;let s=pn(o);return t?s:n?`${n}/bostrat/tmux-default`:s}async function _t(e,{loginShell:t=!1,failOpen:n=!1}={}){let o=await Zr(e,{loginShell:t});return o===hn?!0:o===Tt?!1:n}async function Zr(e,{loginShell:t=!1,timeoutMs:n=Xr}={}){if(!e)return Tt;let o=t?process.env.SHELL||"/bin/sh":"sh",s=t?"-lic":"-c";try{return await Vr(o,[s,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),hn}catch(c){return c?.killed||c?.signal?fn:c?.code===1||c?.code===127?Tt:fn}}var Vr,fa,dn,pa,ha,ma,hn,Tt,fn,Xr,Ge,wa,ya,ga,Ta,_a,gt=v(()=>{Gt();Vt();Jt();nn();sn();yt();ze();un();Vr=qr(Yr),fa=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";dn=typeof process.getuid=="function"?process.getuid():0,pa=Jr({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Gr.existsSync(pn(dn))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:dn}),ha=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",ma=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions";hn="present",Tt="absent",fn="unknown",Xr=5e3;Ge={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"},wa=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,ya=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,ga=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Ta=Number(process.env.BOSTRAT_BOX_COLS)||120,_a=Number(process.env.BOSTRAT_BOX_ROWS)||40});var _n={};ut(_n,{NODE_IMAGE:()=>St,commandPlan:()=>yn,flyToml:()=>wn,flyWizard:()=>io,parseFlyFlags:()=>gn,stageConfig:()=>Tn});import bt from"node:fs";import he from"node:path";import Qr from"node:os";import eo from"node:readline/promises";import{execFile as to}from"node:child_process";import{createRequire as no}from"node:module";import{randomUUID as ro}from"node:crypto";function wn({app:e,region:t,nodeName:n=e,planeUrl:o=mn,image:s=St}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
7
43
  # Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
8
44
  # No [http_service] and none should be added: the node dials OUT to the plane;
9
45
  # nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
@@ -18,14 +54,14 @@ swap_size_mb = 1024
18
54
  # The published node image (claude + cursor-agent + codex baked in, logged
19
55
  # out), pinned to the bostrat-node version that wrote this file. Update with:
20
56
  # npm i -g bostrat-node && bostrat-node fly (re-run is safe), or bump the tag.
21
- image = "${o}"
57
+ image = "${s}"
22
58
 
23
59
  [env]
24
60
  PORT = "3362"
25
61
  # $HOME on the volume: your agent logins, repos, and node state survive
26
62
  # machine replacement (the "your login stays on your node" promise).
27
63
  HOME = "/data/home"
28
- BOSTRAT_PLANE_URL = "${r}"
64
+ BOSTRAT_PLANE_URL = "${o}"
29
65
  BOSTRAT_NODE_ID = "${e}"
30
66
  BOSTRAT_NODE_NAME = "${n}"
31
67
  BOSTRAT_REPOS_ROOT = "/data/home/repos"
@@ -43,72 +79,73 @@ swap_size_mb = 1024
43
79
  # Scale later with: fly scale memory 4096 -a ${e}
44
80
  size = "shared-cpu-2x"
45
81
  memory = "2gb"
46
- `}function xt({app:e,org:t,region:n,sizeGb:r,token:o,owner:i,dir:a}){let d=[`BOSTRAT_PLANE_TOKEN=${o}`,...i?[`BOSTRAT_OWNER=${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>${i?" BOSTRAT_OWNER=\u2026":""} via stdin`,stdin:d.join(`
82
+ `}function yn({app:e,org:t,region:n,sizeGb:o,token:s,owner:c,dir:u}){let p=[`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(o),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${o} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted>${c?" BOSTRAT_OWNER=\u2026":""} via stdin`,stdin:p.join(`
47
83
  `)+`
48
- `},{argv:["deploy",a,"-c",Q.join(a,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${a} -c ${Q.join(a,"fly.toml")} -a ${e} --ha=false`}]}function kt(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 o=e[r];if(o==="--yes"||o==="-y")t.yes=!0;else if(n[o])t[n[o]]=e[++r]??"";else if(o.startsWith("--")&&o.includes("=")){let[i,...a]=o.split("=");n[i]?t[n[i]]=a.join("="):i==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function Ot({app:e,dest:t,toml:n}){let r=t||Q.join(Jn.homedir(),".bostrat","fly",e);He.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])He.rmSync(Q.join(r,o),{recursive:!0,force:!0});return He.writeFileSync(Q.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function nr({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await be(["orgs","list","--json"],{exec:n}),i=JSON.parse(o),a=Array.isArray(i)?i.map(d=>d.Slug||d.slug).filter(Boolean):Object.keys(i);if(a.length===1)return t.write(`Org: ${a[0]} (your only org)
49
- `),a[0];if(a.length>1)return await e(`Fly org (${a.join(" / ")})`,a[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function rr({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:o}={}){let i=kt(e),a=Xn.createInterface({input:t,output:n}),d=async(g,O)=>(await a.question(O?`${g} [${O}]: `:`${g}: `)).trim()||O||"",T=g=>(a.close(),g);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
84
+ `},{argv:["deploy",u,"-c",he.join(u,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${u} -c ${he.join(u,"fly.toml")} -a ${e} --ha=false`}]}function gn(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 o=0;o<e.length;o++){let s=e[o];if(s==="--yes"||s==="-y")t.yes=!0;else if(n[s])t[n[s]]=e[++o]??"";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 Tn({app:e,dest:t,toml:n}){let o=t||he.join(Qr.homedir(),".bostrat","fly",e);bt.mkdirSync(o,{recursive:!0});for(let s of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])bt.rmSync(he.join(o,s),{recursive:!0,force:!0});return bt.writeFileSync(he.join(o,"fly.toml"),n),{dir:o,manifest:["fly.toml"]}}async function so({ask:e,output:t,exec:n,flag:o}){if(o)return o;try{let{stdout:s}=await Ve(["orgs","list","--json"],{exec:n}),c=JSON.parse(s),u=Array.isArray(c)?c.map(p=>p.Slug||p.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 io({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:o,stageDest:s}={}){let c=gn(e),u=eo.createInterface({input:t,output:n}),p=async(S,z)=>(await u.question(z?`${S} [${z}]: `:`${S}: `)).trim()||z||"",T=S=>(u.close(),S);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
50
86
  bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
51
87
 
52
- `);try{await be(["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:g}=await be(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${g.trim()}
53
- `)}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 m=await nr({ask:d,output:n,exec:r,flag:i.org}),l=i.app||await d("App name",`bostrat-node-${er().slice(0,4)}`),b=i.region||await d("Region (see `fly platform regions`)","iad"),v=i.sizeGb||Number(await d("Volume size GB (logins + repos live here)","10"))||10,y=i.name||l,_=i.planeUrl||vt,p=i.token||await d("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!p)return n.write(`\u2717 a node token is required \u2014 mint one in the bostrat setup chat (Connect a node \u2192 Fly), then re-run with it.
54
- `),T(1);let F=i.owner??await d("Owner userId (shown next to the token; empty = infer from token)",""),M=i.image||Ke,{dir:k}=Ot({app:l,dest:o,toml:At({app:l,region:b,nodeName:y,planeUrl:_,image:M})});n.write(`
55
- wrote ${Q.join(k,"fly.toml")} \u2014 deploys the prebuilt node image ${M}
88
+ `);try{await Ve(["version"],{exec:o})}catch{return n.write("\u2717 `fly` (flyctl) is not installed or not on PATH.\n install: https://fly.io/docs/flyctl/install/ \u2014 then re-run `bostrat-node fly`\n"),T(1)}try{let{stdout:S}=await Ve(["auth","whoami"],{exec:o});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 m=await so({ask:p,output:n,exec:o,flag:c.org}),f=c.app||await p("App name",`bostrat-node-${ro().slice(0,4)}`),_=c.region||await p("Region (see `fly platform regions`)","iad"),x=c.sizeGb||Number(await p("Volume size GB (logins + repos live here)","10"))||10,g=c.name||f,k=c.planeUrl||mn,A=c.token||await p("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!A)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 W=c.owner??await p("Owner userId (shown next to the token; empty = infer from token)",""),j=c.image||St,{dir:B}=Tn({app:f,dest:s,toml:wn({app:f,region:_,nodeName:g,planeUrl:k,image:j})});n.write(`
91
+ wrote ${he.join(B,"fly.toml")} \u2014 deploys the prebuilt node image ${j}
56
92
  (claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
57
93
 
58
94
  Plan (your flyctl, your org, your bill):
59
- `);let A=xt({app:l,org:m,region:b,sizeGb:v,token:p,owner:F,dir:k});for(let g of A)n.write(` $ ${g.display}
60
- `);if(!i.yes&&(await d(`
95
+ `);let P=yn({app:f,org:m,region:_,sizeGb:x,token:A,owner:W,dir:B});for(let S of P)n.write(` $ ${S.display}
96
+ `);if(!c.yes&&(await p(`
61
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.
62
- `),T(1);for(let g of A){n.write(`
63
- \u2192 ${g.display}
64
- `);try{let{stdout:O,stderr:z}=await be(g.argv,{stdin:g.stdin,exec:r}),B=`${O||""}${z||""}`.trim();B&&n.write(B.split(`
65
- `).map(L=>` ${L}`).join(`
98
+ `),T(1);for(let S of P){n.write(`
99
+ \u2192 ${S.display}
100
+ `);try{let{stdout:z,stderr:Q}=await Ve(S.argv,{stdin:S.stdin,exec:o}),xe=`${z||""}${Q||""}`.trim();xe&&n.write(xe.split(`
101
+ `).map(Le=>` ${Le}`).join(`
66
102
  `)+`
67
- `)}catch(O){let z=`${O?.stdout||""}${O?.stderr||""}${O?.message||""}`;if(g.tolerate&&g.tolerate.test(z)){n.write(` (already exists \u2014 continuing)
68
- `);continue}return n.write(`\u2717 failed: ${z.trim().split(`
103
+ `)}catch(z){let Q=`${z?.stdout||""}${z?.stderr||""}${z?.message||""}`;if(S.tolerate&&S.tolerate.test(Q)){n.write(` (already exists \u2014 continuing)
104
+ `);continue}return n.write(`\u2717 failed: ${Q.trim().split(`
69
105
  `).slice(-4).join(`
70
106
  `)}
71
107
  fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
72
108
  `),T(1)}}return n.write(`
73
109
  \u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
74
110
  chat: the node step advances on its own within a minute.
75
- logs: fly logs -a ${l}
76
- redeploy: fly deploy ${k} -c ${Q.join(k,"fly.toml")} -a ${l} --ha=false
111
+ logs: fly logs -a ${f}
112
+ redeploy: fly deploy ${B} -c ${he.join(B,"fly.toml")} -a ${f} --ha=false
77
113
  Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
78
114
  boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
79
- `),T(0)}var vt,tr,Ke,be,Et=S(()=>{vt="wss://plane.bostrat.ai/v1/node",tr=Qn(import.meta.url)("../package.json").version,Ke=`ghcr.io/globocodes/bostrat-node:${tr}`;be=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let i=Zn("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(a,d,T)=>a?o(Object.assign(a,{stdout:d,stderr:T})):r({stdout:d,stderr:T}));t!=null&&i.stdin?.end(t)})});function Rt(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!sr.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 ir(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(o=>({...o,fromMs:Rt(o.from,"from",n),toMs:Rt(o.to,"to",n)}))}return t}var or,sr,wi,yi,Nt=S(()=>{or={"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":[{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:null,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)."}],"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)."}]},sr=/^\d{4}-\d{2}-\d{2}$/;wi=ir(or),yi=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var It=S(()=>{Nt()});import Pt from"node:fs/promises";import jt from"node:path";import ar from"node:os";function Ft(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Bt(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Lt(e){let t=new Date(Ft(e));return t.setDate(t.getDate()+7),t.getTime()}function Ut(e){let t=new Date(Bt(e));return t.setMonth(t.getMonth()+1),t.getTime()}function fr(e=Date.now()){for(let[t,n]of Object.entries(ur)){let r=n.startOf(e);if(r!==_e[t]){_e[t]=r;for(let o of We.values())o[t]=0;for(let o of Mt)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&Mt.delete(o)}}}function pr(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 o={};for(let i of["weeklyUsd","monthlyUsd"]){let a=r?.[i];if(a==null||a==="")continue;let d=Number(a);if(!Number.isFinite(d)||d<=0)throw new Error(`${n}.${i} must be a positive number or null`);o[i]=d}Object.keys(o).length&&(t[n]=o)}return t}async function Ht(e,{source:t="local",updatedAt:n=Date.now()}={}){oe={caps:pr(e),updatedAt:n,source:t};try{await Pt.mkdir(Ct,{recursive:!0}),await Pt.writeFile(cr(),JSON.stringify(oe,null,2))}catch{}return mr()}function mr(e=Date.now()){fr(e);let t=new Set([...We.keys(),...Object.keys(oe?.caps||{})]),n={};for(let r of t){let o=We.get(r);n[r]={weeklyUsd:Dt(o?.weekly||0),monthlyUsd:Dt(o?.monthly||0)}}return{caps:oe?.caps||{},configured:!!oe,seeded:dr,updatedAt:oe?.updatedAt??null,spent:n,windows:{weekly:{start:_e.weekly,resetsAt:Lt(e)},monthly:{start:_e.monthly,resetsAt:Ut(e)}},warnPct:lr}}var Ct,cr,lr,ur,oe,dr,_e,We,Mt,Dt,Kt=S(()=>{ge();It();Ct=process.env.BOSTRAT_STATE_DIR||jt.join(process.env.HOME||ar.tmpdir(),".bostrat"),cr=()=>jt.join(Ct,"usage-caps.json"),lr=.8;ur={weekly:{startOf:Ft,nextStart:Lt,capKey:"weeklyUsd"},monthly:{startOf:Bt,nextStart:Ut,capKey:"monthlyUsd"}},oe=null,dr=!1,_e={weekly:0,monthly:0},We=new Map,Mt=new Set;Dt=e=>Math.round(e*1e4)/1e4});var Vt={};Re(Vt,{detectInstallKind:()=>ie,detectProviderAuth:()=>qt,startPlaneLink:()=>kr,updateCommandFor:()=>he,versionLt:()=>se});import Yt from"node:fs";import ze from"node:fs/promises";import hr from"node:http";import V from"node:path";import ve from"node:os";import{createRequire as wr}from"node:module";import Ye from"ws";function ie({env:e=process.env,pkgDir:t=V.resolve(V.dirname(new URL(import.meta.url).pathname),".."),exists:n=Yt.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(V.join(t,"..",".git"))?"git-checkout":"dev"}function se(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 o=0;o<Math.max(n.length,r.length);o++){let i=(n[o]||0)-(r[o]||0);if(i)return i<0}return!1}function he(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 qt({home:e=process.env.HOME||ve.homedir(),env:t=process.env}={}){let n=r=>{try{return Yt.statSync(r),!0}catch{return!1}};return{claude:n(V.join(e,".claude",".credentials.json")),codex:n(V.join(t.CODEX_HOME||V.join(e,".codex"),"auth.json"))}}function kr({url:e,token:t,nodeId:n=ve.hostname(),name:r=ve.hostname(),listTracks:o,detectAgents:i=null,onTracksTransferred:a=null,sampleMetrics:d=null,metricsMs:T=Ar,onUpdateAvailable:m=null,onUpdatePolicy:l=null,onHelloRefused:b=null,updatePolicy:v=null,installKind:y=ie(),selfUrl:_=`http://127.0.0.1:${process.env.PORT||3362}`,log:p=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof o!="function")throw new Error("plane-link: listTracks is required");e=fe(e);let F=_.replace(/^http/,"ws"),M=new Set,k=new Map,A=new Map,g=V.join(yr,"plane-link","cursor.json"),O={},z={},B=new Map,L=null,Z=!1,Oe=!1,le=Wt,ue=null,te=null,ne=null,Y=null,q=null,$e=!1,Qe=0;async function cn(){try{O=JSON.parse(await ze.readFile(g,"utf8"))}catch{O={}}}function ln(){$e=!0,!ne&&(ne=setTimeout(async()=>{if(ne=null,!!$e){$e=!1;try{await ze.mkdir(V.dirname(g),{recursive:!0}),await ze.writeFile(g,JSON.stringify(O))}catch(f){p.error("[plane-link] cursor flush failed:",f?.message||f)}}},_r),ne.unref?.())}function $(f){return!L||L.readyState!==Ye.OPEN?!1:(L.send(JSON.stringify(f)),!0)}function Ee(f){let u=Date.now();for(let{trackId:s,event:c}of f){let h=B.get(c.id);B.set(c.id,{trackId:s,seq:c.seq,event:c,sentAt:u,tries:(h?.tries??0)+1})}return $({v:E,ch:"events",type:"append",events:f})}function un(f){let u=null;for(let s of B.values())s.trackId===f&&(u==null||s.seq<u)&&(u=s.seq);return u}function dn(f){let u=z[f];if(u==null)return;let s=un(f),c=s==null?u:Math.min(u,s-1);c>(O[f]??0)&&(O[f]=c,ln())}function fn(){if(!Z)return;let f=Date.now(),u=[...B.values()].filter(s=>s.event&&f-s.sentAt>=vr);if(u.length){u.sort((s,c)=>s.trackId===c.trackId?s.seq-c.seq:s.trackId<c.trackId?-1:1),p.log(`[plane-link] re-sending ${u.length} unacked event(s) the plane never confirmed`);for(let s=0;s<u.length;s+=Se){let c=u.slice(s,s+Se).map(h=>({trackId:h.trackId,event:h.event}));if(!Ee(c))return}}}async function et(){if(!d)return;let f;try{f=await d()}catch(u){p.error("[plane-link] metrics sample failed:",u?.message||u);return}f&&$({v:E,ch:"ctl",type:"metrics",metrics:f})}function pn(){d&&(q&&clearInterval(q),et(),q=setInterval(et,T),q.unref?.())}async function mn(){let f;try{f=await o()}catch(u){p.error("[plane-link] backfill listTracks failed:",u?.message||u);return}$({v:E,ch:"ctl",type:"tracks",ids:f.filter(u=>!u.transferredTo).map(u=>u.id).filter(u=>typeof u=="string")});for(let u of f){if(!Z)return;let s;try{s=await Ce(u)}catch{continue}let c=O[u.id]??0,h=s.filter(w=>w.seq>c&&typeof w.id=="string");for(let w=0;w<h.length;w+=Se){let N=h.slice(w,w+Se).map(D=>({trackId:u.id,event:D}));if(!Ee(N))return}}}function tt(f){!Z||!f?.trackId||typeof f.id!="string"||Ee([{trackId:f.trackId,event:f}])}let de=new Map;async function hn(f){let{reqId:u,method:s,path:c,headers:h={},body:w}=f,N=Object.fromEntries(Object.entries(h).filter(([,K])=>K!=null)),D=new AbortController;de.set(u,D);try{if(f.host){await wn(f,N,D);return}let K=await fetch(_+c,{method:s,headers:N,body:w?Buffer.from(w,"base64"):void 0,signal:D.signal}),G=Object.fromEntries(K.headers);for(let j of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete G[j];if(G["content-type"]||(G["content-type"]="application/octet-stream"),$({v:E,ch:"control",type:"http_head",reqId:u,status:K.status,headers:G}),K.body){for await(let j of K.body)if(!$({v:E,ch:"control",type:"http_data",reqId:u,data:Buffer.from(j).toString("base64")}))break}$({v:E,ch:"control",type:"http_end",reqId:u,error:null})}finally{de.delete(u)}}function wn(f,u,s){let{reqId:c,method:h,path:w,body:N}=f,D=new URL(_);return new Promise(K=>{let G=hr.request({host:D.hostname,port:D.port,method:h,path:w,headers:{...u,host:f.host},signal:s.signal},j=>{let{connection:ho,"keep-alive":wo,"transfer-encoding":yo,upgrade:go,...yn}=j.headers;$({v:E,ch:"control",type:"http_head",reqId:c,status:j.statusCode||502,headers:yn}),j.on("data",gn=>{$({v:E,ch:"control",type:"http_data",reqId:c,data:Buffer.from(gn).toString("base64")})||j.destroy()}),j.on("end",()=>{$({v:E,ch:"control",type:"http_end",reqId:c,error:null}),K()}),j.on("error",()=>{$({v:E,ch:"control",type:"http_end",reqId:c,error:"view upstream error"}),K()})});G.on("error",j=>{$({v:E,ch:"control",type:"http_end",reqId:c,error:j?.message||"view request failed"}),K()}),N&&G.write(Buffer.from(N,"base64")),G.end()})}function nt(){if(Oe)return;L=new Ye(e,{headers:{authorization:`Bearer ${t}`}}),L.on("open",async()=>{let u=null;try{u=await i?.()||null}catch{u=null}$({v:E,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:U,installKind:y,...typeof v=="function"?{updatePolicy:v()}:v?{updatePolicy:v}:{},providers:qt(),...u?{agents:u}:{}})}),L.on("message",u=>{let s;try{s=JSON.parse(u)}catch{return}if(s.ch==="ctl"&&s.type==="hello_ok"){Z=!0,le=Wt,ue=null,p.log(`[plane-link] connected to plane as ${n}`),s.minNodeVersion&&U&&se(U,s.minNodeVersion)&&p.error(`[plane-link] this node is bostrat-node ${U}; the plane asks for \u2265${s.minNodeVersion} \u2014 update with: ${he(y)}`);try{l?.(typeof s.updatePolicy=="string"?s.updatePolicy:null)}catch{}let c=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(c&&U&&se(U,c)&&!M.has(c)){M.add(c),p.log(`[plane-link] bostrat-node ${c} is available (this node runs ${U}) \u2014 ${he(y)}`);try{m?.({current:U,latest:c,min:s.minNodeVersion??null,installKind:y,required:!!(s.minNodeVersion&&se(U,s.minNodeVersion))})}catch(h){p.error(`[plane-link] update notice failed: ${h?.message||h}`)}}Y&&clearInterval(Y),Y=setInterval(()=>{$({v:E,ch:"ctl",type:"ping"}),fn()},Sr),Y.unref?.(),pn(),mn().catch(h=>p.error("[plane-link] backfill failed:",h?.message||h));return}if(s.ch==="ctl"&&s.type==="hello_refused"){let c=typeof s.minNodeVersion=="string"?s.minNodeVersion:null,h=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;p.error(`[plane-link] plane REFUSED this node: bostrat-node ${U??"?"} is below its minimum ${c??"?"} \u2014 ${s.fix||he(y)}`),le=zt,ue=0;try{b?.({current:U,min:c,latest:h,fix:s.fix||he(y),installKind:y})}catch(w){p.error(`[plane-link] refusal handler failed: ${w?.message||w}`)}return}if(s.ch==="ctl"&&s.type==="update_policy"){try{l?.(typeof s.mode=="string"?s.mode:null)}catch{}return}if(s.ch==="ctl"&&s.type==="usage_caps"){Ht(s.caps??{},{source:"plane",updatedAt:s.updatedAt??Date.now()}).then(c=>p.log(`[plane-link] spend caps ${Object.keys(c.caps).length?`updated (${Object.keys(c.caps).join(", ")})`:"cleared"} from plane`)).catch(c=>p.error("[plane-link] spend-caps push rejected:",c?.message||c));return}if(s.ch==="ctl"&&s.type==="transferred"&&Array.isArray(s.tracks)){Promise.resolve().then(()=>a?.(s.tracks)).catch(c=>p.error("[plane-link] transfer notice failed:",c?.message||c));return}if(s.ch==="events"&&s.type==="ack"&&Array.isArray(s.ids)){let c=new Set;for(let h of s.ids){let w=B.get(h);w&&(B.delete(h),(z[w.trackId]??0)<w.seq&&(z[w.trackId]=w.seq),c.add(w.trackId))}for(let h of c)dn(h);return}if(s.ch==="control"&&s.type==="http_open"){hn(s).catch(c=>$({v:E,ch:"control",type:"http_end",reqId:s.reqId,error:c?.message||"tunnel error"}));return}if(s.ch==="control"&&s.type==="http_cancel"){de.get(s.reqId)?.abort();return}if(s.ch==="attach"&&s.type==="open"){let c=new Ye(F+s.path,Array.isArray(s.protocols)?s.protocols:[],s.host?{headers:{host:s.host}}:void 0);k.set(s.streamId,c),A.set(s.streamId,[]),c.on("open",()=>{let w=A.get(s.streamId)||[];A.delete(s.streamId);for(let{buf:N,bin:D}of w)c.send(N,{binary:D})}),c.on("message",(w,N)=>{let D=N?w:Buffer.from(String(w));$({v:E,ch:"attach",type:"data",streamId:s.streamId,data:D.toString("base64"),...N?{bin:!0}:{}})});let h=()=>{A.delete(s.streamId),k.delete(s.streamId)&&$({v:E,ch:"attach",type:"close",streamId:s.streamId})};c.on("close",h),c.on("error",h);return}if(s.ch==="attach"&&s.type==="data"){let c=k.get(s.streamId);if(!c)return;let h=Buffer.from(s.data,"base64"),w=s.bin===!0,N=A.get(s.streamId);N?N.push({buf:h,bin:w}):c.send(h,{binary:w});return}if(s.ch==="attach"&&s.type==="close"){let c=k.get(s.streamId);k.delete(s.streamId),A.delete(s.streamId),c?.close();return}});let f=()=>{Z&&p.log("[plane-link] disconnected from plane"),Z=!1,Y&&(clearInterval(Y),Y=null),q&&(clearInterval(q),q=null),B.clear(),z={};for(let c of k.values())c.close();k.clear(),A.clear();for(let c of de.values())c.abort();if(de.clear(),Oe||te)return;ue==null&&(ue=Date.now());let u=Date.now()-ue<gr,s=u?Tr+Math.random()*br:le;te=setTimeout(()=>{te=null,nt()},s),te.unref?.(),u||(le=Math.min(le*2,zt))};L.on("close",f),L.on("error",u=>{let s=/Unexpected server response: (\d+)/.exec(u?.message||"")?.[1];(s==="401"||s==="403")&&Date.now()-Qe>=xr&&(Qe=Date.now(),p.error(`[plane-link] plane refused this node's credentials (HTTP ${s}) \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)`)),f()})}return me.on("event",tt),cn().then(nt),{stop:()=>{Oe=!0,me.off("event",tt),te&&clearTimeout(te),ne&&clearTimeout(ne),Y&&clearInterval(Y),q&&clearInterval(q),$({v:E,ch:"ctl",type:"bye",reason:"shutdown"}),L?.close()},status:()=>({connected:Z,nodeId:n,cursor:{...O},inflight:B.size})}}var U,yr,E,Wt,zt,gr,Tr,br,Se,_r,Sr,vr,Ar,xr,qe=S(()=>{ge();Kt();Pe();U=(()=>{try{return wr(import.meta.url)("../package.json").version||null}catch{return null}})(),yr=process.env.BOSTRAT_STATE_DIR||V.join(process.env.HOME||ve.tmpdir(),".bostrat");E=1,Wt=1e3,zt=3e4,gr=6e4,Tr=1500,br=500,Se=100,_r=2e3,Sr=25e3,vr=6e4,Ar=6e4,xr=6e4});import{execFile as Or}from"node:child_process";import{promisify as $r}from"node:util";function Gt(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Ki,Wi,zi,Jt=S(()=>{Fe();Ki=$r(Or),Wi=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,zi=Promise.resolve()});var tn={};Re(tn,{ACTIONABLE_KINDS:()=>ke,SELF_UPDATE_DIR:()=>Ve,createAutoUpdater:()=>Ur,inFlight:()=>Je,readStatus:()=>Ge,selfUpdatePlan:()=>Qt,settleSelfUpdate:()=>Lr,startSelfUpdate:()=>en,underService:()=>Zt,updatePolicy:()=>Dr});import Xt from"node:fs";import J from"node:fs/promises";import Er from"node:os";import R from"node:path";import{spawn as Rr}from"node:child_process";import{createRequire as Nr}from"node:module";function Dr({kind:e=ie(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:ke.has(e)?e==="git-checkout"||Zt(t)?"auto":"prompt":"off"}function Zt(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Qt({kind:e,to:t,from:n=Ae,statusFile:r=xe,logFile:o=R.join(Ve,"last.log"),port:i=Number(process.env.PORT)||3362,npmPrefix:a=null,serviceName:d=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:T=typeof process.getuid=="function"?process.getuid():0,liveDir:m=process.env.BOSTRAT_LIVE_CHECKOUT||R.resolve(R.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:l=Date.now()}={}){if(!ke.has(e))throw new Error(`self-update: install kind "${e}" is not actionable here`);if(!/^\d+\.\d+\.\d+$/.test(String(t)))throw new Error(`self-update: bad target version "${t}"`);if(n&&!/^\d+\.\d+\.\d+$/.test(String(n)))throw new Error(`self-update: bad current version "${n}"`);let b=(F,M="")=>`write_status ${I(F)} ${M}`,v=process.platform==="darwin"?`launchctl kickstart -k gui/${T}/${d}`:`systemctl --user restart ${I(d)}`,y=`
115
+ `),T(0)}var mn,oo,St,Ve,bn=v(()=>{mn="wss://plane.bostrat.ai/v1/node",oo=no(import.meta.url)("../package.json").version,St=`ghcr.io/globocodes/bostrat-node:${oo}`;Ve=(e,{stdin:t,exec:n}={})=>new Promise((o,s)=>{if(n)return n(e,{stdin:t}).then(o,s);let c=to("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(u,p,T)=>u?s(Object.assign(u,{stdout:p,stderr:T})):o({stdout:p,stderr:T}));t!=null&&c.stdin?.end(t)})});function Sn(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!co.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let o=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(o))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return o}function lo(e){let t={};for(let[n,o]of Object.entries(e)){if(!Array.isArray(o)||o.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=o.map(s=>({...s,fromMs:Sn(s.from,"from",n),toMs:Sn(s.to,"to",n)}))}return t}var ao,co,Oa,Ra,vn=v(()=>{ao={"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":[{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:null,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)."}],"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)."}]},co=/^\d{4}-\d{2}-\d{2}$/;Oa=lo(ao),Ra=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var kn=v(()=>{vn()});import An from"node:fs/promises";import En from"node:path";import uo from"node:os";function Rn(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Nn(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function In(e){let t=new Date(Rn(e));return t.setDate(t.getDate()+7),t.getTime()}function Mn(e){let t=new Date(Nn(e));return t.setMonth(t.getMonth()+1),t.getTime()}function wo(e=Date.now()){for(let[t,n]of Object.entries(ho)){let o=n.startOf(e);if(o!==Je[t]){Je[t]=o;for(let s of vt.values())s[t]=0;for(let s of $n)s.includes(`:${t}:`)&&!s.endsWith(`:${o}`)&&$n.delete(s)}}}function yo(e){let t={};for(let[n,o]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let s={};for(let c of["weeklyUsd","monthlyUsd"]){let u=o?.[c];if(u==null||u==="")continue;let p=Number(u);if(!Number.isFinite(p)||p<=0)throw new Error(`${n}.${c} must be a positive number or null`);s[c]=p}Object.keys(s).length&&(t[n]=s)}return t}async function Pn(e,{source:t="local",updatedAt:n=Date.now()}={}){Se={caps:yo(e),updatedAt:n,source:t};try{await An.mkdir(On,{recursive:!0}),await An.writeFile(fo(),JSON.stringify(Se,null,2))}catch{}return go()}function go(e=Date.now()){wo(e);let t=new Set([...vt.keys(),...Object.keys(Se?.caps||{})]),n={};for(let o of t){let s=vt.get(o);n[o]={weeklyUsd:xn(s?.weekly||0),monthlyUsd:xn(s?.monthly||0)}}return{caps:Se?.caps||{},configured:!!Se,seeded:mo,updatedAt:Se?.updatedAt??null,spent:n,windows:{weekly:{start:Je.weekly,resetsAt:In(e)},monthly:{start:Je.monthly,resetsAt:Mn(e)}},warnPct:po}}var On,fo,po,ho,Se,mo,Je,vt,$n,xn,Dn=v(()=>{Ye();kn();On=process.env.BOSTRAT_STATE_DIR||En.join(process.env.HOME||uo.tmpdir(),".bostrat"),fo=()=>En.join(On,"usage-caps.json"),po=.8;ho={weekly:{startOf:Rn,nextStart:In,capKey:"weeklyUsd"},monthly:{startOf:Nn,nextStart:Mn,capKey:"monthlyUsd"}},Se=null,mo=!1,Je={weekly:0,monthly:0},vt=new Map,$n=new Set;xn=e=>Math.round(e*1e4)/1e4});var zn={};ut(zn,{detectInstallKind:()=>ke,detectProviderAuth:()=>Kn,startPlaneLink:()=>Io,updateCommandFor:()=>Fe,versionLt:()=>ve});import Hn from"node:fs";import Ce from"node:fs/promises";import To from"node:http";import V from"node:path";import Xe from"node:os";import{createRequire as _o}from"node:module";import kt from"ws";function ke({env:e=process.env,pkgDir:t=V.resolve(V.dirname(new URL(import.meta.url).pathname),".."),exists:n=Hn.existsSync}={}){let o=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(o)?o:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(V.join(t,"..",".git"))?"git-checkout":"dev"}function ve(e,t){let n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);if(n.some(Number.isNaN)||o.some(Number.isNaN))return!1;for(let s=0;s<Math.max(n.length,o.length);s++){let c=(n[s]||0)-(o[s]||0);if(c)return c<0}return!1}function Fe(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 Kn({home:e=process.env.HOME||Xe.homedir(),env:t=process.env}={}){let n=o=>{try{return Hn.statSync(o),!0}catch{return!1}};return{claude:n(V.join(e,".claude",".credentials.json")),codex:n(V.join(t.CODEX_HOME||V.join(e,".codex"),"auth.json"))}}function Io({url:e,token:t,nodeId:n=Xe.hostname(),name:o=Xe.hostname(),listTracks:s,detectAgents:c=null,onTracksTransferred:u=null,sampleMetrics:p=null,metricsMs:T=No,onUpdateAvailable:m=null,onUpdatePolicy:f=null,onHelloRefused:_=null,updatePolicy:x=null,installKind:g=ke(),selfUrl:k=`http://127.0.0.1:${process.env.PORT||3362}`,onDegraded:A=null,onRecovered:W=null,ingestMode:j=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:B=xo,unackedRetryMs:P=$o,pingMs:S=Ao,maxInflightEvents:z=Oo,httpTimeoutMs:Q=Ro,stallBackoffMinMs:xe=Eo,fetchImpl:Le=globalThis.fetch,log:y=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=Pe(e);let or=k.replace(/^http/,"ws"),It=new Set,le=new Map,ue=new Map,tt=V.join(jn,"plane-link","cursor.json"),nt=V.join(jn,"plane-link","dead-letter.ndjson"),Mt=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),de={},re={},$=new Map,Be=null,oe=null,ee=0,Ee=0,Pt=0,Dt=Promise.resolve(),O="ws",we=0,Y=!1,fe=0,rt=!1,U=ie,ye=new Set,se=[],C=null,X=null,q=!1,ot=!1,Oe=Cn,Re=null,ge=null,Te=null,te=null,ne=null,st=!1,Ue=0;async function sr(){try{de=JSON.parse(await Ce.readFile(tt,"utf8"))}catch{de={}}}function ir(){st=!0,!Te&&(Te=setTimeout(async()=>{if(Te=null,!!st){st=!1;try{await Ce.mkdir(V.dirname(tt),{recursive:!0}),await Ce.writeFile(tt,JSON.stringify(de))}catch(a){y.error("[plane-link] cursor flush failed:",a?.message||a)}}},ko),Te.unref?.())}function N(a){return!X||X.readyState!==kt.OPEN?!1:(X.send(JSON.stringify(a)),!0)}function Ne(a){let l=Date.now();for(let{trackId:r,event:i}of a){let d=$.get(i.id);$.set(i.id,{trackId:r,seq:i.seq,event:i,sentAt:l,firstSentAt:d?.firstSentAt??l,retryAt:l+P,tries:(d?.tries??0)+1,nacks:d?.nacks??0})}return O==="http"?(ur(a),!0):N({v:I,ch:"events",type:"append",events:a})}function ar(a){let l=null;for(let r of $.values())r.trackId===a&&(l==null||r.seq<l)&&(l=r.seq);return l}function it(a){let l=re[a];if(l==null)return;let r=ar(a),i=r==null?l:Math.min(l,r-1);i>(de[a]??0)&&(de[a]=i,ir())}function Ie(){if(Be=Date.now(),oe!=null){let a=Date.now()-oe;y.log(`[plane-link] spine sync recovered after ${Math.round(a/1e3)}s degraded (${ee} stall redial(s))`);let l=oe;oe=null,ee=0,Ee=0,Y=!1,fe=0;try{W?.({since:l,downMs:a})}catch(r){y.error(`[plane-link] onRecovered failed: ${r?.message||r}`)}}}function at(a){if(!Array.isArray(a)||!a.length)return;let l=new Set;for(let r of a){let i=$.get(r);i&&($.delete(r),(re[i.trackId]??0)<i.seq&&(re[i.trackId]=i.seq),l.add(i.trackId))}for(let r of l)it(r);Ie()}function jt(a,l){Pt++;let r={at:Date.now(),trackId:a.trackId,seq:a.seq,id:a.event?.id??null,type:a.event?.type??null,reason:l,event:a.event??null};y.error(`[plane-link] DEAD-LETTER ${a.trackId} seq ${a.seq} (${r.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${nt}`),Dt=Dt.then(async()=>{await Ce.mkdir(V.dirname(nt),{recursive:!0}),await Ce.appendFile(nt,JSON.stringify(r)+`
116
+ `)}).catch(i=>y.error(`[plane-link] dead-letter write failed: ${i?.message||i}`))}function Ct(a,l,r,i=null){if(!Array.isArray(a)||!a.length)return;let d=new Set,h=Date.now();for(let w of a){let b=$.get(w);b&&(r?($.delete(w),jt(b,l),(re[b.trackId]??0)<b.seq&&(re[b.trackId]=b.seq),d.add(b.trackId)):(b.nacks++,b.retryAt=h+Math.max(1e3,Number(i)||P)))}for(let w of d)it(w);Ie()}function Ft(a=Date.now()){let l=1/0;for(let r of $.values())r.firstSentAt<l&&(l=r.firstSentAt);return l===1/0?0:a-l}function Lt(){if(!q||!$.size)return;let a=Date.now(),l=Ft(a);if(l<B||Be!=null&&a-Be<B||O==="http"&&Y||Ee>a)return;ee++;let r=Math.min(xe*2**(ee-1),Ln);if(oe==null){oe=a-l,y.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${$.size} event(s) in flight (${O} door) \u2014 the plane is not answering appends`);try{A?.({since:oe,unacked:$.size,oldestAgeMs:l,mode:O})}catch(i){y.error(`[plane-link] onDegraded failed: ${i?.message||i}`)}}if(O==="http"){Y=!0,fe=a+r,y.error(`[plane-link] ingest circuit OPEN (stall #${ee}); probing /v1/ingest/health in ${Math.round(r/1e3)}s`);return}Ee=a+r,y.error(`[plane-link] closing the link and redialing in ${Math.round(r/1e3)}s (stall redial #${ee})`);try{X?.terminate()}catch{}}function ct(){if(!q)return;let a=Date.now();if(O==="http"&&Y)return;let l=[...$.values()].filter(i=>i.event&&i.retryAt<=a&&!(O==="http"&&ye.has(i.trackId)));if(!l.length)return;l.sort((i,d)=>i.trackId===d.trackId?i.seq-d.seq:i.trackId<d.trackId?-1:1),y.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let r=O==="http"?U:ie;if(O==="http"){let i=new Map;for(let d of l)(i.get(d.trackId)??i.set(d.trackId,[]).get(d.trackId)).push(d);for(let[,d]of i){if(we>=At)return;Ne(d.slice(0,r).map(h=>({trackId:h.trackId,event:h.event})))}return}for(let i=0;i<l.length;i+=r){let d=l.slice(i,i+r).map(h=>({trackId:h.trackId,event:h.event}));if(!Ne(d))return}}async function cr(a=null){for(;;){if(!q)return!1;let l=$.size<z,r=O!=="http"||we<At&&!Y&&(!a||!ye.has(a));if(l&&r)return!0;await new Promise(i=>setTimeout(i,100))}}function lt(){if(C=null,!q||!se.length)return;let a=se;if(se=[],O!=="http"){for(let r=0;r<a.length;r+=ie)Ne(a.slice(r,r+ie));return}let l=new Map;for(let r of a)(l.get(r.trackId)??l.set(r.trackId,[]).get(r.trackId)).push(r);for(let[r,i]of l){if(ye.has(r)||we>=At||Y){se.push(...i);continue}for(let d=0;d<i.length;d+=U)Ne(i.slice(d,d+U))}se.length&&!C&&(C=setTimeout(lt,Bn),C.unref?.())}let lr=a=>{let l=new Map;for(let{trackId:r,event:i}of a)(l.get(r)??l.set(r,[]).get(r)).push(i);return[...l].map(([r,i])=>({trackId:r,events:i}))},_e=(a,l,r,{progress:i})=>{let d=Date.now();for(let{event:h}of a){let w=$.get(h.id);w&&(w.nacks++,w.retryAt=d+Math.max(1e3,r||P))}i&&Ie()};async function ur(a){let l=new Set(a.map(r=>r.trackId));for(let r of l)ye.add(r);we++;try{let r=await Le(`${Mt}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:lr(a)}),signal:AbortSignal.timeout(Q)}),i=(Number(r.headers.get("retry-after"))||0)*1e3;if(r.status===200){let d=await r.json();U=ie;for(let h of d.results??[]){at(h.acked??[]);let w=(b,D)=>{let H=new Map;for(let E of b??[])(H.get(E.reason)??H.set(E.reason,[]).get(E.reason)).push(E.id);for(let[E,Wt]of H)Ct(Wt,E,D,d.retryAfterMs??null)};w(h.rejected,!0),w(h.deferred,!1)}at(d.discarded??[]),Ie();return}if(r.status===429){_e(a,"overloaded",i||5e3,{progress:!0});return}if(r.status===413&&a.length>1){U=Math.max(1,Math.floor(a.length/2)),y.error(`[plane-link] ingest request too large (${a.length} events) \u2014 halving batches to ${U}`),_e(a,"too_large",1e3,{progress:!0});return}if(r.status===413){let d=$.get(a[0].event.id);d&&($.delete(d.event.id),jt(d,"too_large"),(re[d.trackId]??0)<d.seq&&(re[d.trackId]=d.seq),it(d.trackId)),Ie();return}if(r.status===401||r.status===403){if(Date.now()-Ue>=Un){Ue=Date.now();let d="";try{d=(await r.json())?.error??""}catch{}y.error(`[plane-link] plane refused ingest (HTTP ${r.status}${d?`: ${d}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}_e(a,`http_${r.status}`,6e4,{progress:!1});return}if(r.status===400){y.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${a.length} event(s) for retry; this is a bug, not data`),_e(a,"http_400",6e4,{progress:!1});return}_e(a,`http_${r.status}`,i||5e3,{progress:!1})}catch(r){let i=r?.name==="TimeoutError"||r?.name==="AbortError";i&&a.length>1&&(U=Math.max(1,Math.floor(a.length/2)),y.error(`[plane-link] ingest request of ${a.length} event(s) outlived its ${Q} ms deadline \u2014 halving batches to ${U}`)),_e(a,i?"timeout":"network",5e3,{progress:!1})}finally{we--;for(let r of l)ye.delete(r)}}async function dr(){if(O!=="http"||!Y||!q||rt)return;let a=Date.now();if(!(fe>a)){rt=!0;try{let l=await Le(`${Mt}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(Q)});if(!l.ok)throw new Error(`HTTP ${l.status}`);y.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Y=!1,fe=0,Ee=Date.now()+Q+P+1e3;for(let r of $.values())r.retryAt=Math.min(r.retryAt,Date.now());ct()}catch(l){ee++;let r=Math.min(xe*2**(ee-1),Ln);fe=Date.now()+r,y.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(r/1e3)}s`)}finally{rt=!1}}}function Bt(){let a=Date.now();return{mode:O,unacked:$.size,oldestUnackedAgeMs:Ft(a),lastProgressAt:Be,degradedSince:oe,stallRedials:ee,deadLettered:Pt,http:O==="http"?{inFlight:we,circuitOpen:Y,nextProbeInMs:Y?Math.max(0,fe-a):0,batchCap:U}:null}}async function Ut(){if(!p)return;let a;try{a=await p()}catch(l){y.error("[plane-link] metrics sample failed:",l?.message||l);return}a&&N({v:I,ch:"ctl",type:"metrics",metrics:{...a,planeLink:Bt()}})}function fr(){p&&(ne&&clearInterval(ne),Ut(),ne=setInterval(Ut,T),ne.unref?.())}async function pr(){let a;try{a=await s()}catch(l){y.error("[plane-link] backfill listTracks failed:",l?.message||l);return}N({v:I,ch:"ctl",type:"tracks",ids:a.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of a){if(!q)return;let r;try{r=await wt(l)}catch{continue}let i=de[l.id]??0,d=r.filter(w=>w.seq>i&&typeof w.id=="string"),h=O==="http"?U:ie;for(let w=0;w<d.length;w+=h){if(!await cr(l.id))return;let b=d.slice(w,w+Math.min(h,O==="http"?U:ie)).map(D=>({trackId:l.id,event:D}));if(!Ne(b))return}}}function Ht(a){!q||!a?.trackId||typeof a.id!="string"||(se.push({trackId:a.trackId,event:a}),C||(C=setTimeout(lt,Bn),C.unref?.()))}let Me=new Map;async function hr(a){let{reqId:l,method:r,path:i,headers:d={},body:h}=a,w=Object.fromEntries(Object.entries(d).filter(([,D])=>D!=null)),b=new AbortController;Me.set(l,b);try{if(a.host){await mr(a,w,b);return}let D=await fetch(k+i,{method:r,headers:w,body:h?Buffer.from(h,"base64"):void 0,signal:b.signal}),H=Object.fromEntries(D.headers);for(let E of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete H[E];if(H["content-type"]||(H["content-type"]="application/octet-stream"),N({v:I,ch:"control",type:"http_head",reqId:l,status:D.status,headers:H}),D.body){for await(let E of D.body)if(!N({v:I,ch:"control",type:"http_data",reqId:l,data:Buffer.from(E).toString("base64")}))break}N({v:I,ch:"control",type:"http_end",reqId:l,error:null})}finally{Me.delete(l)}}function mr(a,l,r){let{reqId:i,method:d,path:h,body:w}=a,b=new URL(k);return new Promise(D=>{let H=To.request({host:b.hostname,port:b.port,method:d,path:h,headers:{...l,host:a.host},signal:r.signal},E=>{let{connection:Wt,"keep-alive":_s,"transfer-encoding":bs,upgrade:Ss,...wr}=E.headers;N({v:I,ch:"control",type:"http_head",reqId:i,status:E.statusCode||502,headers:wr}),E.on("data",yr=>{N({v:I,ch:"control",type:"http_data",reqId:i,data:Buffer.from(yr).toString("base64")})||E.destroy()}),E.on("end",()=>{N({v:I,ch:"control",type:"http_end",reqId:i,error:null}),D()}),E.on("error",()=>{N({v:I,ch:"control",type:"http_end",reqId:i,error:"view upstream error"}),D()})});H.on("error",E=>{N({v:I,ch:"control",type:"http_end",reqId:i,error:E?.message||"view request failed"}),D()}),w&&H.write(Buffer.from(w,"base64")),H.end()})}function Kt(){if(ot)return;X=new kt(e,{headers:{authorization:`Bearer ${t}`}}),X.on("open",async()=>{let l=null;try{l=await c?.()||null}catch{l=null}N({v:I,ch:"ctl",type:"hello",nodeId:n,name:o,platform:process.platform,version:G,installKind:g,...typeof x=="function"?{updatePolicy:x()}:x?{updatePolicy:x}:{},providers:Kn(),...l?{agents:l}:{}})}),X.on("message",l=>{let r;try{r=JSON.parse(l)}catch{return}if(r.ch==="ctl"&&r.type==="hello_ok"){q=!0,Oe=Cn,Re=null,y.log(`[plane-link] connected to plane as ${n}`),r.minNodeVersion&&G&&ve(G,r.minNodeVersion)&&y.error(`[plane-link] this node is bostrat-node ${G}; the plane asks for \u2265${r.minNodeVersion} \u2014 update with: ${Fe(g)}`);try{f?.(typeof r.updatePolicy=="string"?r.updatePolicy:null)}catch{}let i=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;if(i&&G&&ve(G,i)&&!It.has(i)){It.add(i),y.log(`[plane-link] bostrat-node ${i} is available (this node runs ${G}) \u2014 ${Fe(g)}`);try{m?.({current:G,latest:i,min:r.minNodeVersion??null,installKind:g,required:!!(r.minNodeVersion&&ve(G,r.minNodeVersion))})}catch(h){y.error(`[plane-link] update notice failed: ${h?.message||h}`)}}let d=r.ingest==="http";O=j==="ws"?"ws":j==="http"||d?"http":"ws",j==="http"&&!d&&y.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),O==="http"&&y.log("[plane-link] spine rides the HTTPS ingest door"),Y=!1,fe=0,U=ie,te&&clearInterval(te),te=setInterval(()=>{N({v:I,ch:"ctl",type:"ping"}),Lt(),dr().catch(()=>{}),ct(),se.length&&!C&&lt()},S),te.unref?.(),fr(),pr().catch(h=>y.error("[plane-link] backfill failed:",h?.message||h));return}if(r.ch==="ctl"&&r.type==="hello_refused"){let i=typeof r.minNodeVersion=="string"?r.minNodeVersion:null,d=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;y.error(`[plane-link] plane REFUSED this node: bostrat-node ${G??"?"} is below its minimum ${i??"?"} \u2014 ${r.fix||Fe(g)}`),Oe=Fn,Re=0;try{_?.({current:G,min:i,latest:d,fix:r.fix||Fe(g),installKind:g})}catch(h){y.error(`[plane-link] refusal handler failed: ${h?.message||h}`)}return}if(r.ch==="ctl"&&r.type==="update_policy"){try{f?.(typeof r.mode=="string"?r.mode:null)}catch{}return}if(r.ch==="ctl"&&r.type==="usage_caps"){Pn(r.caps??{},{source:"plane",updatedAt:r.updatedAt??Date.now()}).then(i=>y.log(`[plane-link] spend caps ${Object.keys(i.caps).length?`updated (${Object.keys(i.caps).join(", ")})`:"cleared"} from plane`)).catch(i=>y.error("[plane-link] spend-caps push rejected:",i?.message||i));return}if(r.ch==="ctl"&&r.type==="transferred"&&Array.isArray(r.tracks)){Promise.resolve().then(()=>u?.(r.tracks)).catch(i=>y.error("[plane-link] transfer notice failed:",i?.message||i));return}if(r.ch==="events"&&r.type==="ack"&&Array.isArray(r.ids)){at(r.ids);return}if(r.ch==="events"&&r.type==="nack"&&Array.isArray(r.ids)){Ct(r.ids,r.reason,r.permanent===!0,r.retryAfterMs??null);return}if(r.ch==="control"&&r.type==="http_open"){hr(r).catch(i=>N({v:I,ch:"control",type:"http_end",reqId:r.reqId,error:i?.message||"tunnel error"}));return}if(r.ch==="control"&&r.type==="http_cancel"){Me.get(r.reqId)?.abort();return}if(r.ch==="attach"&&r.type==="open"){let i=new kt(or+r.path,Array.isArray(r.protocols)?r.protocols:[],r.host?{headers:{host:r.host}}:void 0);le.set(r.streamId,i),ue.set(r.streamId,[]),i.on("open",()=>{let h=ue.get(r.streamId)||[];ue.delete(r.streamId);for(let{buf:w,bin:b}of h)i.send(w,{binary:b})}),i.on("message",(h,w)=>{let b=w?h:Buffer.from(String(h));N({v:I,ch:"attach",type:"data",streamId:r.streamId,data:b.toString("base64"),...w?{bin:!0}:{}})});let d=()=>{ue.delete(r.streamId),le.delete(r.streamId)&&N({v:I,ch:"attach",type:"close",streamId:r.streamId})};i.on("close",d),i.on("error",d);return}if(r.ch==="attach"&&r.type==="data"){let i=le.get(r.streamId);if(!i)return;let d=Buffer.from(r.data,"base64"),h=r.bin===!0,w=ue.get(r.streamId);w?w.push({buf:d,bin:h}):i.send(d,{binary:h});return}if(r.ch==="attach"&&r.type==="close"){let i=le.get(r.streamId);le.delete(r.streamId),ue.delete(r.streamId),i?.close();return}});let a=()=>{q&&y.log("[plane-link] disconnected from plane"),q=!1,te&&(clearInterval(te),te=null),ne&&(clearInterval(ne),ne=null),$.clear(),re={},se=[],C&&(clearTimeout(C),C=null),ye.clear();for(let i of le.values())i.close();le.clear(),ue.clear();for(let i of Me.values())i.abort();if(Me.clear(),ot||ge)return;Re==null&&(Re=Date.now());let l=Date.now()-Re<bo,r=Math.max(l?So+Math.random()*vo:Oe,Ee-Date.now());ge=setTimeout(()=>{ge=null,Kt()},r),ge.unref?.(),l||(Oe=Math.min(Oe*2,Fn))};X.on("close",a),X.on("error",l=>{let r=/Unexpected server response: (\d+)/.exec(l?.message||"")?.[1];(r==="401"||r==="403")&&Date.now()-Ue>=Un&&(Ue=Date.now(),y.error(`[plane-link] plane refused this node's credentials (HTTP ${r}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`)),a()})}return je.on("event",Ht),sr().then(Kt),{stop:()=>{ot=!0,je.off("event",Ht),ge&&clearTimeout(ge),Te&&clearTimeout(Te),te&&clearInterval(te),ne&&clearInterval(ne),C&&clearTimeout(C),N({v:I,ch:"ctl",type:"bye",reason:"shutdown"}),X?.close()},status:()=>({connected:q,nodeId:n,cursor:{...de},inflight:$.size,...Bt()}),_tick:()=>{Lt(),ct()}}}var G,jn,I,Cn,Fn,bo,So,vo,ie,ko,Ao,$o,Wn,xo,Eo,Ln,Oo,Bn,Ro,At,No,Un,$t=v(()=>{Ye();Dn();pt();G=(()=>{try{return _o(import.meta.url)("../package.json").version||null}catch{return null}})(),jn=process.env.BOSTRAT_STATE_DIR||V.join(process.env.HOME||Xe.tmpdir(),".bostrat");I=1,Cn=1e3,Fn=3e4,bo=6e4,So=1500,vo=500,ie=100,ko=2e3,Ao=25e3,$o=6e4,Wn=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},xo=Wn(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Eo=3e4,Ln=10*6e4,Oo=400,Bn=250,Ro=Wn(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),At=4,No=6e4,Un=6e4});import{execFile as Mo}from"node:child_process";import{promisify as Po}from"node:util";function Yn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var nc,rc,oc,qn=v(()=>{yt();nc=Po(Mo),rc=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,oc=Promise.resolve()});var Zn={};ut(Zn,{ACTIONABLE_KINDS:()=>et,SELF_UPDATE_DIR:()=>xt,createAutoUpdater:()=>qo,inFlight:()=>Ot,readStatus:()=>Et,selfUpdatePlan:()=>Jn,settleSelfUpdate:()=>Yo,startSelfUpdate:()=>Xn,underService:()=>Vn,updatePolicy:()=>Uo});import Gn from"node:fs";import ae from"node:fs/promises";import Do from"node:os";import M from"node:path";import{spawn as jo}from"node:child_process";import{createRequire as Co}from"node:module";function Uo({kind:e=ke(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:et.has(e)?e==="git-checkout"||Vn(t)?"auto":"prompt":"off"}function Vn(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Jn({kind:e,to:t,from:n=Ze,statusFile:o=Qe,logFile:s=M.join(xt,"last.log"),port:c=Number(process.env.PORT)||3362,npmPrefix:u=null,serviceName:p=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:T=typeof process.getuid=="function"?process.getuid():0,liveDir:m=process.env.BOSTRAT_LIVE_CHECKOUT||M.resolve(M.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:f=Date.now()}={}){if(!et.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 _=(W,j="")=>`write_status ${F(W)} ${j}`,x=process.platform==="darwin"?`launchctl kickstart -k gui/${T}/${p}`:`systemctl --user restart ${F(p)}`,g=`
80
117
  health() {
81
118
  for i in $(seq 1 45); do
82
119
  sleep 1
83
- if curl -sf -o /dev/null "http://127.0.0.1:${i}/api/health"; then return 0; fi
120
+ if curl -sf -o /dev/null "http://127.0.0.1:${c}/api/health"; then return 0; fi
84
121
  done
85
122
  return 1
86
- }`,_=`#!/usr/bin/env bash
123
+ }`,k=`#!/usr/bin/env bash
87
124
  # bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
88
- # ${n??"?"} \u2192 ${t} (${e}). Status: ${r}
125
+ # ${n??"?"} \u2192 ${t} (${e}). Status: ${o}
89
126
  set -u
90
- FROM=${I(n??"")}
91
- TO=${I(t)}
92
- STATUS_FILE=${I(r)}
93
- STARTED_AT=${Number(l)}
127
+ FROM=${F(n??"")}
128
+ TO=${F(t)}
129
+ STATUS_FILE=${F(o)}
130
+ STARTED_AT=${Number(f)}
94
131
  write_status() { # <status> [error]
95
132
  local err="\${2:-}"
96
133
  err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
97
134
  printf '{"status":"%s","from":"%s","to":"%s","kind":"%s","startedAt":%s,"updatedAt":%s%s}\\n' \\
98
- "$1" "$FROM" "$TO" ${I(e)} "$STARTED_AT" "$(date +%s000)" \\
135
+ "$1" "$FROM" "$TO" ${F(e)} "$STARTED_AT" "$(date +%s000)" \\
99
136
  "\${err:+,\\"error\\":\\"$err\\"}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
100
137
  }
101
- ${y}
102
- `;if(e==="npm-global"){let F=a?R.join(a,"bin","npm"):"npm",M=a?`export PATH=${I(R.join(a,"bin"))}:"$PATH"
103
- `:"",k=a?` --prefix ${I(a)}`:"",A=g=>`${I(F)} install -g "bostrat-node@${g}" --no-audit --no-fund${k}`;return _+M+`
104
- ${b("updating",'"" ')}
105
- if ! ${A("$TO")}; then
106
- ${b("failed",'"npm install failed"')}
138
+ ${g}
139
+ `;if(e==="npm-global"){let W=u?M.join(u,"bin","npm"):"npm",j=u?`export PATH=${F(M.join(u,"bin"))}:"$PATH"
140
+ `:"",B=u?` --prefix ${F(u)}`:"",P=S=>`${F(W)} install -g "bostrat-node@${S}" --no-audit --no-fund${B}`;return k+j+`
141
+ ${_("updating",'"" ')}
142
+ if ! ${P("$TO")}; then
143
+ ${_("failed",'"npm install failed"')}
107
144
  exit 1
108
145
  fi
109
- ${b("restarting")}
110
- if ! ${v}; then
111
- ${b("failed",'"service restart failed"')}
146
+ ${_("restarting")}
147
+ if ! ${x}; then
148
+ ${_("failed",'"service restart failed"')}
112
149
  exit 1
113
150
  fi
114
151
  if health; then
@@ -116,52 +153,52 @@ if health; then
116
153
  exit 0
117
154
  fi
118
155
  # \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
119
- ${b("rolling-back",'"agent did not answer on :'+i+' after the update"')}
120
- if [ -n "$FROM" ] && ${A("$FROM")} && ${v} && health; then
121
- ${b("rolled-back",'"agent did not answer on :'+i+' after the update; rolled back"')}
156
+ ${_("rolling-back",'"agent did not answer on :'+c+' after the update"')}
157
+ if [ -n "$FROM" ] && ${P("$FROM")} && ${x} && health; then
158
+ ${_("rolled-back",'"agent did not answer on :'+c+' after the update; rolled back"')}
122
159
  exit 1
123
160
  fi
124
- ${b("failed",'"agent did not answer after the update AND the rollback"')}
161
+ ${_("failed",'"agent did not answer after the update AND the rollback"')}
125
162
  exit 1
126
- `}let p=F=>`( cd ${I(m)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${F}" )`;return _+`
127
- LIVE=${I(m)}
163
+ `}let A=W=>`( cd ${F(m)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${W}" )`;return k+`
164
+ LIVE=${F(m)}
128
165
  TMP_SCRIPT="$(mktemp)"
129
166
  trap 'rm -f "$TMP_SCRIPT"' EXIT
130
167
  # "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
131
168
  # restart \u2192 health in one call): the agent it restarts settles "done" on boot,
132
169
  # and nothing here may write after that boot or the settle would repeat.
133
- ${b("restarting")}
134
- if ${p("$TO")}; then
170
+ ${_("restarting")}
171
+ if ${A("$TO")}; then
135
172
  exit 0
136
173
  fi
137
- ${b("rolling-back",'"deploy-pi.sh v$TO failed"')}
138
- if [ -n "$FROM" ] && ${p("$FROM")}; then
139
- ${b("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
174
+ ${_("rolling-back",'"deploy-pi.sh v$TO failed"')}
175
+ if [ -n "$FROM" ] && ${A("$FROM")}; then
176
+ ${_("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
140
177
  exit 1
141
178
  fi
142
- ${b("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
179
+ ${_("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
143
180
  exit 1
144
- `}async function Ge(e=xe){try{return JSON.parse(await J.readFile(e,"utf8"))}catch{return null}}async function en({to:e,from:t=Ae,kind:n=ie(),reason:r="manual",statusFile:o=xe,spawnImpl:i=Rr,now:a=Date.now,npmPrefix:d=void 0,log:T=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!ke.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!se(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let m=await Ge(o);if(Je(m))return{ok:!1,reason:`an update to ${m.to} is already in flight`,status:m};if(m&&m.to===e&&(m.status==="failed"||m.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${m.status} (${m.error||"no detail"}) \u2014 retried when a newer release exists`,status:m};await J.mkdir(R.dirname(o),{recursive:!0});let l=d!==void 0?d:n==="npm-global"?Gt(await Cr())||R.resolve(R.dirname(process.execPath),".."):null,b=Qt({kind:n,to:e,from:t,statusFile:o,npmPrefix:l,startedAt:a()}),v=R.join(R.dirname(o),`update-${e}.sh`),y=R.join(R.dirname(o),"last.log");await J.writeFile(v,b,{mode:448}),await J.writeFile(o,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,startedAt:a(),updatedAt:a()}));let _=Xt.existsSync("/run/systemd/system")&&await Fr("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",v]]:["setsid",["-f","bash","-c",`exec bash ${I(v)} >> ${I(y)} 2>&1`]];try{i(_[0],_[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(p){return await J.writeFile(o,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,startedAt:a(),updatedAt:a(),error:`could not spawn updater: ${p?.message||p}`})),{ok:!1,reason:`could not spawn updater: ${p?.message||p}`}}return T.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${o}`),{ok:!0,to:e,from:t,kind:n,scriptFile:v,statusFile:o}}async function Cr(){try{return await J.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Fr(e){for(let t of String(process.env.PATH||"").split(R.delimiter))try{return await J.access(R.join(t,e),Xt.constants.X_OK),!0}catch{}return!1}async function Lr({statusFile:e=xe,current:t=Ae,now:n=Date.now,staleMs:r=Br}={}){let o=await Ge(e);if(!o)return null;let i=a=>J.writeFile(e,JSON.stringify(a)).catch(()=>{});if(Je(o)){if(t&&o.to===t){let a={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await i(a),a}if(n()-Number(o.updatedAt||o.startedAt||0)>r){let a={...o,status:"failed",error:`updater went silent while ${o.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await i(a),a}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let a={...o,announced:!0};return await i(a),a}return null}function Ur({isBusy:e,start:t=en,onStuck:n=null,onStarted:r=null,tickMs:o=Mr,stuckMs:i=Pr,now:a=Date.now,setIntervalImpl:d=setInterval,clearIntervalImpl:T=clearInterval,log:m=console}={}){let l=null,b=()=>{l?.timer&&T(l.timer),l=null},v=async()=>{if(!l)return;let y=!0;try{y=await e()!==!1}catch{y=!0}if(y){if(!l.stuckFired&&a()-l.since>=i){l.stuckFired=!0;try{await n?.({to:l.to,from:l.from,since:l.since})}catch{}}return}let _=l;b();let p=await t({to:_.to,from:_.from,kind:_.kind,reason:"auto"});m.log?.(`[self-update] stasis reached \u2192 ${p.ok?"started":`not started: ${p.reason}`}`);try{await r?.({..._,result:p})}catch{}};return{arm({to:y,from:_=Ae,kind:p=ie()}){return l?.to===y?!1:(b(),l={to:y,from:_,kind:p,since:a(),stuckFired:!1,timer:d(v,o)},l.timer.unref?.(),!0)},tick:v,cancel:b,get armed(){return l?{to:l.to,from:l.from,kind:l.kind,since:l.since}:null}}}var Ae,Ir,Ve,xe,Pr,Mr,ke,I,jr,Je,Br,nn=S(()=>{qe();Jt();Ae=(()=>{try{return Nr(import.meta.url)("../package.json").version||null}catch{return null}})(),Ir=process.env.BOSTRAT_STATE_DIR||R.join(process.env.HOME||Er.tmpdir(),".bostrat"),Ve=R.join(Ir,"self-update"),xe=R.join(Ve,"status.json"),Pr=1440*6e4,Mr=6e4,ke=new Set(["npm-global","git-checkout"]);I=e=>`'${String(e).replace(/'/g,"'\\''")}'`;jr=new Set(["updating","restarting","rolling-back"]),Je=e=>!!(e&&jr.has(e.status));Br=45*6e4});Pe();Be();import H from"node:fs";import x from"node:path";import ce from"node:os";import{createRequire as Xe}from"node:module";import{execFile as Hr,spawn as Kr}from"node:child_process";import{promisify as Wr}from"node:util";import zr from"node:readline/promises";import{randomUUID as Yr}from"node:crypto";import{fileURLToPath as qr}from"node:url";var rn=(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 o=0;o<Math.max(n.length,r.length);o++){let i=(n[o]||0)-(r[o]||0);if(i)return i<0}return!1},X=Wr(Hr),Ze=x.dirname(qr(import.meta.url)),ee=x.resolve(Ze,".."),Vr=x.join(Ze,"index.js"),Gr="wss://plane.bostrat.ai/v1/node",ae=Xe(import.meta.url)("../package.json").version,P=(e,t)=>({name:e,level:"pass",detail:t}),W=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),C=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function Jr(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?P("node runtime",`${process.version} at ${process.execPath}`):C("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Xr(e){let t;try{t=H.statSync(e)}catch{return W("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?W("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):P("node.env",`${e} (0600)`)}async function Zr(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await X(t,["-V"],{timeout:5e3});return P("tmux",`${t} (${n.trim()})`)}catch{return C("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function on(e,{required:t=!1}={}){if(await Ue(e,{loginShell:!0,failOpen:!1}))return P(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",o=Te[e]?`${Te[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?C(e,r,o):W(e,r,o)}async function Qr(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await X(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return P("gh (GitHub CLI)",n)}catch{return W("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",Te.gh)}}async function eo(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>on(t)));return e.some(t=>t.level==="pass")||e.push(C("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 to(){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 Ue(t,{failOpen:!1})?P(t,"resolves on the service PATH"):W(t,`not on the service PATH \u2014 ${n}`,r)))}async function no(){try{let t=Xe(x.join(ee,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let o=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),i=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(i),n()})}),P("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${ee} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Xe(x.join(ee,"package.json")),r=x.join(x.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");H.existsSync(r)&&!(H.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return C("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function ro(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(H.existsSync(t))return P("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"?C:W)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function oo(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?C("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"):P("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function so(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return W("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(),o=fe(e.BOSTRAT_PLANE_URL);return await new Promise(i=>{let a=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),d=m=>{clearTimeout(T);try{a.close()}catch{}i(m)},T=setTimeout(()=>d(C("plane link",`no hello_ok within 5s from ${o}`,"check the URL, the token, and the plane's IP gate")),5e3);a.on("open",()=>a.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${Yr().slice(0,8)}`,ephemeral:!0}))),a.on("message",m=>{try{let l=JSON.parse(m);l.type==="hello_ok"?l.minNodeVersion&&rn(ae,l.minNodeVersion)?d(C("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${l.minNodeVersion} \u2014 this node is ${ae}; the real link is refused until it updates`,`bostrat-node self-update --to ${l.latestNodeVersion||l.minNodeVersion}`)):l.latestNodeVersion&&rn(ae,l.latestNodeVersion)?d(W("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${l.latestNodeVersion} is available (this node: ${ae})`,`bostrat-node self-update --to ${l.latestNodeVersion}`)):d(P("plane link",`hello_ok in ${Date.now()-r}ms (${o})`)):l.type==="error"&&d(C("plane link",`plane said: ${l.code} ${l.message||""}`,"check the token"))}catch{}}),a.on("error",m=>d(C("plane link",`${m?.message||m}`,"check the URL, the token, and the plane's IP gate")))})}function io(){let e;try{e=JSON.parse(H.readFileSync(x.join(Ie,"content-outbox.json"),"utf8"))}catch{return P("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 C("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?W("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"):P("content outbox",t?`${t} op(s) in flight`:"drained")}function ao(e){return e.BOSTRAT_STATE_REMOTE?P("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):W("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")}async function sn(e,t={}){let n=[];return n.push(await Jr()),n.push(Xr(t.envFile||re())),n.push(await Zr(e)),n.push(...await eo()),n.push(await on("git",{required:!0})),n.push(await Qr()),n.push(...await to()),n.push(await no()),n.push(ro(e)),n.push(oo(e)),n.push(await so(e,t)),n.push(io()),n.push(ao(e)),n}function an(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let i of e)t(`${n[i.level]} ${i.name}: ${i.detail}`),i.fix&&i.level!=="pass"&&t(` fix: ${i.fix}`);let r=e.filter(i=>i.level==="fail").length,o=e.filter(i=>i.level==="warn").length;return t(r?`
145
- FAIL \u2014 ${r} blocking, ${o} warnings`:`
146
- OK \u2014 0 blocking, ${o} warnings`),r===0}async function co({envFile:e=re(),input:t=process.stdin,output:n=process.stdout}={}){let r=ye(e),o=zr.createInterface({input:t,output:n}),i=async(A,g)=>(await o.question(g?`${A} [${g}]: `:`${A}: `)).trim()||g||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
181
+ `}async function Et(e=Qe){try{return JSON.parse(await ae.readFile(e,"utf8"))}catch{return null}}async function Xn({to:e,from:t=Ze,kind:n=ke(),reason:o="manual",statusFile:s=Qe,spawnImpl:c=jo,now:u=Date.now,npmPrefix:p=void 0,log:T=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!et.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!ve(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let m=await Et(s);if(Ot(m))return{ok:!1,reason:`an update to ${m.to} is already in flight`,status:m};if(m&&m.to===e&&(m.status==="failed"||m.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${m.status} (${m.error||"no detail"}) \u2014 retried when a newer release exists`,status:m};await ae.mkdir(M.dirname(s),{recursive:!0});let f=p!==void 0?p:n==="npm-global"?Yn(await Ko())||M.resolve(M.dirname(process.execPath),".."):null,_=Jn({kind:n,to:e,from:t,statusFile:s,npmPrefix:f,startedAt:u()}),x=M.join(M.dirname(s),`update-${e}.sh`),g=M.join(M.dirname(s),"last.log");await ae.writeFile(x,_,{mode:448}),await ae.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:o,startedAt:u(),updatedAt:u()}));let k=Gn.existsSync("/run/systemd/system")&&await Wo("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",x]]:["setsid",["-f","bash","-c",`exec bash ${F(x)} >> ${F(g)} 2>&1`]];try{c(k[0],k[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(A){return await ae.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:o,startedAt:u(),updatedAt:u(),error:`could not spawn updater: ${A?.message||A}`})),{ok:!1,reason:`could not spawn updater: ${A?.message||A}`}}return T.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${o}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:x,statusFile:s}}async function Ko(){try{return await ae.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Wo(e){for(let t of String(process.env.PATH||"").split(M.delimiter))try{return await ae.access(M.join(t,e),Gn.constants.X_OK),!0}catch{}return!1}async function Yo({statusFile:e=Qe,current:t=Ze,now:n=Date.now,staleMs:o=zo}={}){let s=await Et(e);if(!s)return null;let c=u=>ae.writeFile(e,JSON.stringify(u)).catch(()=>{});if(Ot(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)>o){let u={...s,status:"failed",error:`updater went silent while ${s.status} (no status change for ${Math.round(o/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 qo({isBusy:e,start:t=Xn,onStuck:n=null,onStarted:o=null,tickMs:s=Bo,stuckMs:c=Lo,now:u=Date.now,setIntervalImpl:p=setInterval,clearIntervalImpl:T=clearInterval,log:m=console}={}){let f=null,_=()=>{f?.timer&&T(f.timer),f=null},x=async()=>{if(!f)return;let g=!0;try{g=await e()!==!1}catch{g=!0}if(g){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;_();let A=await t({to:k.to,from:k.from,kind:k.kind,reason:"auto"});m.log?.(`[self-update] stasis reached \u2192 ${A.ok?"started":`not started: ${A.reason}`}`);try{await o?.({...k,result:A})}catch{}};return{arm({to:g,from:k=Ze,kind:A=ke()}){return f?.to===g?!1:(_(),f={to:g,from:k,kind:A,since:u(),stuckFired:!1,timer:p(x,s)},f.timer.unref?.(),!0)},tick:x,cancel:_,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var Ze,Fo,xt,Qe,Lo,Bo,et,F,Ho,Ot,zo,Qn=v(()=>{$t();qn();Ze=(()=>{try{return Co(import.meta.url)("../package.json").version||null}catch{return null}})(),Fo=process.env.BOSTRAT_STATE_DIR||M.join(process.env.HOME||Do.tmpdir(),".bostrat"),xt=M.join(Fo,"self-update"),Qe=M.join(xt,"status.json"),Lo=1440*6e4,Bo=6e4,et=new Set(["npm-global","git-checkout"]);F=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Ho=new Set(["updating","restarting","rolling-back"]),Ot=e=>!!(e&&Ho.has(e.status));zo=45*6e4});pt();gt();import J from"node:fs";import R from"node:path";import $e from"node:os";import{createRequire as Rt}from"node:module";import{execFile as Go,spawn as Vo}from"node:child_process";import{promisify as Jo}from"node:util";import Xo from"node:readline/promises";import{randomUUID as Zo}from"node:crypto";import{fileURLToPath as Qo}from"node:url";var er=(e,t)=>{let n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);if(n.some(Number.isNaN)||o.some(Number.isNaN))return!1;for(let s=0;s<Math.max(n.length,o.length);s++){let c=(n[s]||0)-(o[s]||0);if(c)return c<0}return!1},ce=Jo(Go),Nt=R.dirname(Qo(import.meta.url)),me=R.resolve(Nt,".."),es=R.join(Nt,"index.js"),ts="wss://plane.bostrat.ai/v1/node",Ae=Rt(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}),K=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function ns(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?L("node runtime",`${process.version} at ${process.execPath}`):K("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function rs(e){let t;try{t=J.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 os(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await ce(t,["-V"],{timeout:5e3});return L("tmux",`${t} (${n.trim()})`)}catch{return K("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function tr(e,{required:t=!1}={}){if(await _t(e,{loginShell:!0,failOpen:!1}))return L(e,"resolves on the login-shell PATH");let o="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",s=Ge[e]?`${Ge[e]}${e==="cursor-agent"?" # installs to ~/.local/bin \u2014 ensure your login shell has it on PATH":""}`:`install ${e} so \`$SHELL -lic 'command -v ${e}'\` finds it`;return t?K(e,o,s):Z(e,o,s)}async function ss(){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",Ge.gh)}}async function is(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>tr(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 as(){let e=[...process.platform==="linux"?[["fuser","stopped views can't free their ports (they leak, and the port can't be reused)","apt install psmisc"]]:[],["pgrep","agent-swap can't detect an idle pane shell \u2014 swaps may misfire","apt install procps"],["npm","codex auto-update and `npm run` views are unavailable","install Node.js with npm on the service PATH"]];return Promise.all(e.map(async([t,n,o])=>await _t(t,{failOpen:!1})?L(t,"resolves on the service PATH"):Z(t,`not on the service PATH \u2014 ${n}`,o)))}async function cs(){try{let t=Rt(R.join(me,"src","node-cli.js"))("node-pty");return await new Promise((n,o)=>{let s=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),c=setTimeout(()=>o(new Error("spawn timeout")),5e3);s.onExit(()=>{clearTimeout(c),n()})}),L("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${me} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Rt(R.join(me,"package.json")),o=R.join(R.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");J.existsSync(o)&&!(J.statSync(o).mode&73)&&(t=`chmod +x ${o} # node-pty ships it non-executable`)}catch{}return K("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function ls(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(J.existsSync(t))return L("chromium (mocks)",t);let n=process.platform==="darwin"?"brew install --cask chromium (or set BOSTRAT_CHROMIUM_BIN to Chrome.app's inner binary)":"apt install chromium fonts-dejavu-core fonts-liberation (or set BOSTRAT_CHROMIUM_BIN)";return(e.BOSTRAT_INSTALL_KIND==="container"?K:Z)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function us(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?K("claude lane","BOSTRAT_CLAUDE_USE_API_KEY=1 but ANTHROPIC_API_KEY is empty","add the key to node.env or set the flag to 0"):L("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function ds(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,o=Date.now(),s=Pe(e.BOSTRAT_PLANE_URL);return await new Promise(c=>{let u=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),p=m=>{clearTimeout(T);try{u.close()}catch{}c(m)},T=setTimeout(()=>p(K("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-${Zo().slice(0,8)}`,ephemeral:!0}))),u.on("message",m=>{try{let f=JSON.parse(m);f.type==="hello_ok"?f.minNodeVersion&&er(Ae,f.minNodeVersion)?p(K("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${f.minNodeVersion} \u2014 this node is ${Ae}; the real link is refused until it updates`,`bostrat-node self-update --to ${f.latestNodeVersion||f.minNodeVersion}`)):f.latestNodeVersion&&er(Ae,f.latestNodeVersion)?p(Z("plane link",`hello_ok in ${Date.now()-o}ms (${s}); bostrat-node ${f.latestNodeVersion} is available (this node: ${Ae})`,`bostrat-node self-update --to ${f.latestNodeVersion}`)):p(L("plane link",`hello_ok in ${Date.now()-o}ms (${s})`)):f.type==="error"&&p(K("plane link",`plane said: ${f.code} ${f.message||""}`,"check the token"))}catch{}}),u.on("error",m=>p(K("plane link",`${m?.message||m}`,"check the URL, the token, and the plane's IP gate")))})}function fs(){let e;try{e=JSON.parse(J.readFileSync(R.join(ft,"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 o=e.parked[0];return K("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${o?.op} ${o?.family}/${o?.id}: ${o?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?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 ps(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")}async function nr(e,t={}){let n=[];return n.push(await ns()),n.push(rs(t.envFile||be())),n.push(await os(e)),n.push(...await is()),n.push(await tr("git",{required:!0})),n.push(await ss()),n.push(...await as()),n.push(await cs()),n.push(ls(e)),n.push(us(e)),n.push(await ds(e,t)),n.push(fs()),n.push(ps(e)),n}function rr(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let c of e)t(`${n[c.level]} ${c.name}: ${c.detail}`),c.fix&&c.level!=="pass"&&t(` fix: ${c.fix}`);let o=e.filter(c=>c.level==="fail").length,s=e.filter(c=>c.level==="warn").length;return t(o?`
182
+ FAIL \u2014 ${o} blocking, ${s} warnings`:`
183
+ OK \u2014 0 blocking, ${s} warnings`),o===0}async function hs({envFile:e=be(),input:t=process.stdin,output:n=process.stdout}={}){let o=Ke(e),s=Xo.createInterface({input:t,output:n}),c=async(P,S)=>(await s.question(S?`${P} [${S}]: `:`${P}: `)).trim()||S||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
147
184
  you type those inside each box, later (box-auth-policy).
148
185
 
149
- `);let a=await i("Plane URL",r.BOSTRAT_PLANE_URL||Gr),d=fe(a);d!==a.trim()&&n.write(` \u2192 using ${d}
150
- `);let T=await i("Node token (minted plane-side; stored 0600)",r.BOSTRAT_PLANE_TOKEN),m=await i("Owner userId (just press Enter \u2014 the plane infers it from your token)",r.BOSTRAT_OWNER||"");m&&!/^user_[A-Za-z0-9]+$/.test(m)&&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.
151
- `);let l=await i("Node name",r.BOSTRAT_NODE_NAME||ce.hostname().split(".")[0]),b=await i("Repos root",r.BOSTRAT_REPOS_ROOT||x.join(ce.homedir(),"Documents")),v=await i("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),y=(await i("Route NEW claude boxes through a BYO API key? (y/N)",r.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");y&&n.write(`
186
+ `);let u=await c("Plane URL",o.BOSTRAT_PLANE_URL||ts),p=Pe(u);p!==u.trim()&&n.write(` \u2192 using ${p}
187
+ `);let T=await c("Node token (minted plane-side; stored 0600)",o.BOSTRAT_PLANE_TOKEN),m=await c("Owner userId (just press Enter \u2014 the plane infers it from your token)",o.BOSTRAT_OWNER||"");m&&!/^user_[A-Za-z0-9]+$/.test(m)&&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",o.BOSTRAT_NODE_NAME||$e.hostname().split(".")[0]),_=await c("Repos root",o.BOSTRAT_REPOS_ROOT||R.join($e.homedir(),"Documents")),x=await c("State remote (per-node private repo; empty = local-only)",o.BOSTRAT_STATE_REMOTE||""),g=(await c("Route NEW claude boxes through a BYO API key? (y/N)",o.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");g&&n.write(`
152
189
  BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
153
190
  injected per box, stored 0600 in node.env, never sent to the plane.
154
191
  \u2022 create/copy a key: https://console.anthropic.com/settings/keys
155
192
  \u2022 set a monthly spend limit while you're there \u2014 the key is live.
156
193
 
157
- `);let _=y?await i("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";y&&_&&!/^sk-ant-/.test(_)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
158
- `),o.close();let p={...st(),...r,BOSTRAT_PLANE_URL:d,BOSTRAT_PLANE_TOKEN:T,BOSTRAT_OWNER:m,BOSTRAT_NODE_NAME:l,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||l,BOSTRAT_REPOS_ROOT:b,BOSTRAT_STATE_REMOTE:v,BOSTRAT_CLAUDE_USE_API_KEY:y?"1":"0",ANTHROPIC_API_KEY:y?_:r.ANTHROPIC_API_KEY};ot(e,p,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
194
+ `);let k=g?await c("ANTHROPIC_API_KEY (starts sk-ant-)",o.ANTHROPIC_API_KEY):"";g&&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 A={...qt(),...o,BOSTRAT_PLANE_URL:p,BOSTRAT_PLANE_TOKEN:T,BOSTRAT_OWNER:m,BOSTRAT_NODE_NAME:f,BOSTRAT_NODE_ID:o.BOSTRAT_NODE_ID||f,BOSTRAT_REPOS_ROOT:_,BOSTRAT_STATE_REMOTE:x,BOSTRAT_CLAUDE_USE_API_KEY:g?"1":"0",ANTHROPIC_API_KEY:g?k:o.ANTHROPIC_API_KEY};Yt(e,A,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
159
196
  0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
160
197
  Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
161
198
  wrote ${e}
162
199
 
163
- `);let F={...p,...process.env},M=await sn(F,{envFile:e}),k=an(M,A=>n.write(A+`
164
- `));return k&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:k,results:M}}function lo({envFile:e=re()}={}){rt(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=Kr(t,[Vr],{cwd:ee,stdio:"inherit",env:process.env});for(let r of["SIGINT","SIGTERM"])process.on(r,()=>n.kill(r));return n.on("exit",(r,o)=>process.exit(o?1:r??1)),n}function uo({agentDir:e=ee,nodeBin:t=process.execPath,envFile:n=re(),home:r=ce.homedir()}={}){let o=x.dirname(t),i=x.join(x.basename(Ze),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
200
+ `);let W={...A,...process.env},j=await nr(W,{envFile:e}),B=rr(j,P=>n.write(P+`
201
+ `));return B&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:B,results:j}}function ms({envFile:e=be()}={}){zt(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=Vo(t,[es],{cwd:me,stdio:"inherit",env:process.env});for(let o of["SIGINT","SIGTERM"])process.on(o,()=>n.kill(o));return n.on("exit",(o,s)=>process.exit(s?1:o??1)),n}function ws({agentDir:e=me,nodeBin:t=process.execPath,envFile:n=be(),home:o=$e.homedir()}={}){let s=R.dirname(t),c=R.join(R.basename(Nt),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
165
202
  # ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
166
203
  [Unit]
167
204
  Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
@@ -171,17 +208,17 @@ After=default.target
171
208
  Type=simple
172
209
  WorkingDirectory=${e}
173
210
  # Pinned runtime: node-pty is compiled against exactly this node (SEGV trap).
174
- ExecStart=${t} --disable-warning=ExperimentalWarning ${i}
211
+ ExecStart=${t} --disable-warning=ExperimentalWarning ${c}
175
212
  EnvironmentFile=${n}
176
213
  # systemd's user PATH omits ~/.local/bin (cursor-agent, bostrat-view) and the
177
214
  # nvm bin dir \u2014 both are load-bearing for box spawning.
178
- Environment=PATH=${r}/.local/bin:${o}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
215
+ Environment=PATH=${o}/.local/bin:${s}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
179
216
  Restart=on-failure
180
217
  RestartSec=2
181
218
 
182
219
  [Install]
183
220
  WantedBy=default.target
184
- `}function fo({agentDir:e=ee,nodeBin:t=process.execPath,home:n=ce.homedir()}={}){let r=x.dirname(t),o=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
221
+ `}function ys({agentDir:e=me,nodeBin:t=process.execPath,home:n=$e.homedir()}={}){let o=R.dirname(t),s=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
185
222
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
186
223
  <plist version="1.0">
187
224
  <dict>
@@ -195,15 +232,15 @@ WantedBy=default.target
195
232
  <key>WorkingDirectory</key><string>${e}</string>
196
233
  <key>EnvironmentVariables</key>
197
234
  <dict>
198
- <key>PATH</key><string>${n}/.local/bin:${r}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
235
+ <key>PATH</key><string>${n}/.local/bin:${o}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
199
236
  </dict>
200
237
  <key>RunAtLoad</key><true/>
201
238
  <key>KeepAlive</key><true/>
202
- <key>StandardOutPath</key><string>${o}/node.out.log</string>
203
- <key>StandardErrorPath</key><string>${o}/node.err.log</string>
239
+ <key>StandardOutPath</key><string>${s}/node.out.log</string>
240
+ <key>StandardErrorPath</key><string>${s}/node.err.log</string>
204
241
  </dict>
205
242
  </plist>
206
- `}function po(e=process.platform,t=ce.homedir()){return e==="darwin"?{kind:"launchd",file:x.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:x.join(t,".config","systemd","user","bostrat-node.service")}}async function mo({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=ee}={}){let{kind:i,file:a}=po(n);if(!e&&o.split(x.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){i==="systemd"?(await X("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),H.rmSync(a,{force:!0}),await X("systemctl",["--user","daemon-reload"])):(await X("launchctl",["unload","-w",a]).catch(()=>{}),H.rmSync(a,{force:!0})),r(`removed ${a}`);return}H.mkdirSync(x.dirname(a),{recursive:!0}),i==="systemd"?(H.writeFileSync(a,uo()),await X("systemctl",["--user","daemon-reload"]),t&&await X("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${a}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(H.mkdirSync(x.join(ce.homedir(),"Library","Logs","bostrat"),{recursive:!0}),H.writeFileSync(a,fo()),t&&await X("launchctl",["load","-w",a]),r(`installed ${a}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function fa(e=process.argv.slice(2)){let t=e[0],n=re();if(t==="--version"||t==="-v"||t==="version")return console.log(ae),0;if(t==="init")return(await co({envFile:n})).ok?0:1;if(t==="doctor"){let r={...ye(n),...process.env};return an(await sn(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return lo({envFile:n}),null;if(t==="install-service")return await mo({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(Et(),$t));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:i}=await Promise.resolve().then(()=>(nn(),tn)),{detectInstallKind:a}=await Promise.resolve().then(()=>(qe(),Vt)),d=a(),T=e.indexOf("--to"),m=T>=0?String(e[T+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:ae,installKind:d,policy:i({kind:d}),status:await o()},null,2)),0;if(!m)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 l=await r({to:m,kind:d,reason:"cli"});return l.ok?(console.log(`\u2713 self-update ${l.from??"?"} \u2192 ${l.to} started (${l.kind}) \u2014 status: ${l.statusFile}; the service restarts when the install completes`),0):(console.error(`\u2717 not started: ${l.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
243
+ `}function gs(e=process.platform,t=$e.homedir()){return e==="darwin"?{kind:"launchd",file:R.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:R.join(t,".config","systemd","user","bostrat-node.service")}}async function Ts({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:o=console.log,agentDir:s=me}={}){let{kind:c,file:u}=gs(n);if(!e&&s.split(R.sep).includes("_npx"))return o("\u2717 running from the npx cache \u2014 a service must point at a durable install."),o(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){c==="systemd"?(await ce("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),J.rmSync(u,{force:!0}),await ce("systemctl",["--user","daemon-reload"])):(await ce("launchctl",["unload","-w",u]).catch(()=>{}),J.rmSync(u,{force:!0})),o(`removed ${u}`);return}J.mkdirSync(R.dirname(u),{recursive:!0}),c==="systemd"?(J.writeFileSync(u,ws()),await ce("systemctl",["--user","daemon-reload"]),t&&await ce("systemctl",["--user","enable","--now","bostrat-node.service"]),o(`installed ${u}${t?" (enabled + started)":""}`),o("logs: journalctl --user -u bostrat-node.service -f")):(J.mkdirSync(R.join($e.homedir(),"Library","Logs","bostrat"),{recursive:!0}),J.writeFileSync(u,ys()),t&&await ce("launchctl",["load","-w",u]),o(`installed ${u}${t?" (loaded)":""}`),o("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function Ac(e=process.argv.slice(2)){let t=e[0],n=be();if(t==="--version"||t==="-v"||t==="version")return console.log(Ae),0;if(t==="init")return(await hs({envFile:n})).ok?0:1;if(t==="doctor"){let o={...Ke(n),...process.env};return rr(await nr(o,{envFile:n}))?0:1}if(t==="run"||t==="start")return ms({envFile:n}),null;if(t==="install-service")return await Ts({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:o}=await Promise.resolve().then(()=>(bn(),_n));return await o({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:o,readStatus:s,updatePolicy:c}=await Promise.resolve().then(()=>(Qn(),Zn)),{detectInstallKind:u}=await Promise.resolve().then(()=>($t(),zn)),p=u(),T=e.indexOf("--to"),m=T>=0?String(e[T+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Ae,installKind:p,policy:c({kind:p}),status:await s()},null,2)),0;if(!m)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let f=await o({to:m,kind:p,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)
207
244
 
208
245
  usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
209
246
 
@@ -212,4 +249,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
212
249
  run start the node in the foreground (sources node.env)
213
250
  install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
214
251
  fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
215
- self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{co as init,mo as installService,fo as launchdPlist,fa as main,an as printDoctor,lo as runAgent,sn as runDoctor,po as servicePaths,uo as systemdUnit};
252
+ self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{hs as init,Ts as installService,ys as launchdPlist,Ac as main,rr as printDoctor,ms as runAgent,nr as runDoctor,gs as servicePaths,ws as systemdUnit};