bostrat-node 1.16.8 → 1.17.0

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.
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
- var ca=Object.defineProperty;var R=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var En=(e,t)=>{for(var n in t)ca(e,n,{get:t[n],enumerable:!0})};import jt from"node:fs";import On from"node:path";import la from"node:os";function pt(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 Bt(e){let t;try{t=jt.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
2
- `)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!s)continue;let a=s[2].trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n[s[1]]=a}return n}function Qr(e,t=process.env){let n=Bt(e);for(let[r,o]of Object.entries(n))r in t||(t[r]=o);return n}function eo(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
3
- `).map(o=>o?`# ${o}`:"#"));for(let[o,s]of Object.entries(t))s==null||s===""||r.push(`${o}=${s}`);jt.mkdirSync(On.dirname(e),{recursive:!0}),jt.writeFileSync(e,r.join(`
1
+ var la=Object.defineProperty;var R=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var En=(e,t)=>{for(var n in t)la(e,n,{get:t[n],enumerable:!0})};import Bt from"node:fs";import On from"node:path";import ua from"node:os";function ft(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 Ft(e){let t;try{t=Bt.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
2
+ `)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!s)continue;let a=s[2].trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n[s[1]]=a}return n}function to(e,t=process.env){let n=Ft(e);for(let[r,o]of Object.entries(n))r in t||(t[r]=o);return n}function no(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
3
+ `).map(o=>o?`# ${o}`:"#"));for(let[o,s]of Object.entries(t))s==null||s===""||r.push(`${o}=${s}`);Bt.mkdirSync(On.dirname(e),{recursive:!0}),Bt.writeFileSync(e,r.join(`
4
4
  `)+`
5
- `,{mode:384}),jt.chmodSync(e,384)}function to(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 Ct,Ue,Rn=R(()=>{Ct=process.env.BOSTRAT_STATE_DIR||On.join(process.env.HOME||la.tmpdir(),".bostrat"),Ue=()=>On.join(Ct,"node.env")});var wd,Lt=R(()=>{wd=16*1024});var le,ht,Ft=R(()=>{le="BOSTRAT_HOOK_TOKEN",ht="x-bostrat-hook"});var ua,Sd,no=R(()=>{ua=(e,t)=>{if(e==null||e==="")return t;let n=Number(e);return Number.isFinite(n)&&n>=0?n:t},Sd=ua(process.env.BOSTRAT_HOOK_FOLD_MS,250)});function ga(e,t=fa){let n=String(e??""),r=n.split(/\s*(?:;|&&|\|\||\||\n)\s*/).map(o=>o.trim()).filter(Boolean);return Number.isFinite(t)&&n.length>=t&&r.length&&r.pop(),r}function Ut(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function fo(e){let t=0;for(;t<e.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]);)t++;return{cmd:e[t]??null,rest:e.slice(t+1),at:t}}function co(e){let t=Ut(e),n=t.findIndex(m=>m==="git"||m.endsWith("/git"));if(n<0)return null;for(n++;n<t.length&&t[n].startsWith("-");)(t[n]==="-C"||t[n]==="-c")&&n++,n++;if(t[n]!=="push")return null;let r=[],o=[];for(let m=n+1;m<t.length;m++){let d=t[m];d.startsWith("-")?(r.push(d),(d==="-o"||d==="--push-option"||d==="--repo"||d==="--receive-pack"||d==="--exec")&&m++):o.push(d)}let s=r.some(m=>m==="--force"||/^-[a-zA-Z]+$/.test(m)&&m.includes("f"))||o.some(m=>m.startsWith("+")),a=r.some(m=>m.startsWith("--force-with-lease")||m.startsWith("--force-if-includes")),l=o[0]??null,h=o.slice(1).map(m=>m.replace(/^["']|["']$/g,"").replace(/^\+/,"")).map(m=>m.includes(":")?m.slice(m.indexOf(":")+1):m).filter(m=>m&&!m.startsWith("$"));return{force:s,lease:a,remote:l,dsts:h}}function mo(e){let{cmd:t,at:n}=fo(e);if(t==="sudo"){for(n++;n<e.length&&e[n].startsWith("-");)n++;t=e[n]??null}return{cmd:t,at:n}}function go(e,t){let n=String(e??"").match(t);if(!n)return null;let r=n[1],o=r.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");if(new RegExp(`>{1,2}\\s*["']?[^\\s"']*${o}`).test(e))return"redirect";let s=Ut(e),{cmd:a}=mo(s);return!a||!s.some(l=>l.includes(r))?null:/^(?:rm|mv|truncate|chmod|chown|tee|install|shred|unlink|ln|mkdir|touch)$/.test(a)?a:a==="sed"&&s.some(l=>/^-[a-zA-Z]*i/.test(l))?"sed -i":a==="cp"&&s[s.length-1].includes(r)?"cp":/^(?:python3?|perl|node|ruby)$/.test(a)&&/open\([^)]*['"][wa]|writeFile|write_text|appendFile|fs\.write/.test(e)?`${a} write`:null}function Ra(e){let t=Ut(e),{cmd:n,at:r}=mo(t);if(!n)return null;let o=t.slice(r+1);if(n==="crontab"||n.endsWith("/crontab")){let a=!1,l=!1;for(let h=0;h<o.length;h++){if(o[h]==="-u"){h++;continue}o[h]==="-l"||/^-(?:h|V|T|-help|-version)$/.test(o[h])?a=!0:l=!0}return l||!a?"crontab":null}if(n==="systemctl"||n.endsWith("/systemctl")){let a=o.find(l=>!l.startsWith("-"));return a&&_a.test(a)?`systemctl ${a}`:null}if((n==="loginctl"||n.endsWith("/loginctl"))&&o.includes("enable-linger"))return"loginctl enable-linger";if(n==="at"&&o.length&&/^(?:now|midnight|noon|teatime|today|tomorrow|next|\d|-[fqmvt])/.test(o[0]))return"at";let s=go(e,ho);return s?`${s} unit/cron path`:null}function Na(e){let t=new Set;for(let n of String(e??"").matchAll(va))t.add(n[1].toLowerCase());return[...t]}var da,fa,ro,oo,so,io,ao,vd,pa,ha,Nn,ma,ke,Mn,wa,ya,ba,Sa,po,ho,_a,Ta,xa,$a,va,lo,uo,ka,Aa,Ea,Oa,Z,mt,In,wo,kd,Ad,yo=R(()=>{no();da="BP-AU-R4",fa=160,ro=200,oo=5,so=8,io=5,ao=10*6e4,vd=Object.freeze(["localhost","127.0.0.1","0.0.0.0","github.com","api.github.com","raw.githubusercontent.com","objects.githubusercontent.com","registry.npmjs.org","pypi.org","files.pythonhosted.org"]),pa=5e3,ha=new Set(["tool.called","tool.failed"]),Nn=new Set(["Write","Edit","NotebookEdit"]),ma=e=>String(e??"").replace(/\s+/g," ").trim(),ke=(e,t=120)=>ma(e).slice(0,t);Mn=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,wa=new RegExp(`${Mn}/\\.ssh(?:/|\\b)`),ya=new RegExp(`${Mn}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),ba=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,Sa=/^\.env\.(?:example|sample|template|dist)$/,po=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,ho=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${Mn}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),_a=/^(?:enable|disable|start|stop|restart|try-restart|reload|reload-or-restart|daemon-reload|daemon-reexec|link|mask|unmask|edit|preset|preset-all|set-property|revert|isolate|kill|reset-failed|import-environment|set-environment|add-wants|add-requires)$/,Ta=/^\/tmp\/|\/\.bostrat\/tmp\//,xa=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,$a=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,va=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,lo=e=>wa.test(e)||ya.test(e),uo=e=>[...String(e??"").matchAll(ba)].some(t=>!Sa.test(t[1])),ka=e=>po.test(e),Aa=e=>ho.test(e),Ea=e=>(e.startsWith("/")||e.startsWith("~"))&&!Ta.test(e);Oa=e=>go(e,po);Z=(e,t,n,r)=>Object.freeze({severity:e,requirement:da,note:t,measured:n,detect:r}),mt=(e,t)=>{let n=0,r=null;for(let o of e.calls)if(o.head)for(let s of ga(o.head,e.headCap)){let a=t(s,o);a&&(n++,r??=ke(a))}return n?{count:n,sample:r}:null},In=(e,t)=>{let n=0,r=null;for(let o of e.calls){let s=t(o);s&&(n++,r??=ke(s))}return n?{count:n,sample:r}:null},wo=Object.freeze({"force-push":Z("high","git push --force / -f / +refspec in a command head (--force-with-lease, the Track's own rebase flow, is not one)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 1,080 logs 2026-08\u219210 \xB7 58 --force-with-lease pushes excluded by design \u2192 high",(e,t)=>mt(t,n=>{let r=co(n);return r&&r.force&&!r.lease?n:null})),"protected-config-write":Z("high","a write to the box's own harness: .claude/settings*.json, a .claude/hooks/ script or the Track's .bostrat/events/ log \u2014 by a file tool, a redirect, rm/mv/tee/sed -i, or a scripted open-for-write (reads are not hits)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 165 reads of those paths (cat, grep, python json.loads) excluded by design \u2192 high",(e,t)=>{let n=0,r=null;for(let s of t.calls)Nn.has(s.tool)&&s.path&&ka(s.path)&&(n++,r??=ke(`${s.tool} ${s.path}`));let o=mt(t,s=>{let a=Oa(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"persistence-install":Z("medium","a shell segment that installs something the OS runs on its own \u2014 crontab (install / edit / remove; -l is a read), a mutating systemctl verb (enable / start / restart / daemon-reload \u2026; status / show / cat / list / is-* are reads), loginctl enable-linger, at / batch \u2014 or a write (file tool, redirect, cp / mv / tee / ln / sed -i) into a systemd unit or cron directory: how a process outlives its turn by the OS's hand (BP-AU-D6's other half)","2026-10-21 fleet replay \xB7 11 hits / 99,122 hook calls \xB7 10 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-asked service work on the operator's own Pi (systemctl --user restart/stop/start of bostrat-node, tmp-sweep, a samba disable, one `crontab -` install for a backfill) \xB7 the bare `at` word a quoted `|` regex leaves in a segment (4 hits) excluded by design \u2192 medium (rail), the guard's deny when opted in",(e,t)=>{let n=0,r=null;for(let s of t.calls)Nn.has(s.tool)&&s.path&&Aa(s.path)&&(n++,r??=ke(`${s.tool} ${s.path}`));let o=mt(t,s=>{let a=Ra(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"push-outside-track":Z("medium","git push to a protected branch (main/master/develop/release\u2026), to a branch that is not a Track branch, or to a remote other than origin/upstream \u2014 a Track's own code leaves on its track/ branch or the WIP shadow ref","2026-10-21 fleet replay \xB7 7 hits / 98,690 hook calls \xB7 4 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-instructed work on another repo (two dep/ branches, a fork's multiplayer branch, one HEAD:main) \u2192 medium, not a page",(e,t)=>mt(t,n=>{let r=co(n);return r&&(r.remote&&!/^(?:origin|upstream)$/.test(r.remote)&&!r.remote.startsWith("$")&&!r.remote.startsWith("-")||r.dsts.some(o=>xa.test(o)||!$a.test(o)))?n:null})),"credential-read":Z("medium","a command head or file path naming SSH material (~/.ssh) or a vendor auth file (~/.claude.json, ~/.claude/.credentials.json, ~/.codex/auth.json, ~/.cursor) \u2014 the box-auth policy's denylist shapes; ~/.claude/projects (transcripts) is not one","2026-10-21 fleet replay \xB7 12 hits / 98,690 hook calls \xB7 8 Tracks \xB7 3 in the last 14 d \xB7 every hit an operator-asked inspection on the operator's own node (ssh config for a host alias, stat/keys of ~/.claude.json) \u2192 medium until a 14-day window reads 0",(e,t)=>In(t,n=>n.head&&lo(n.head)?n.head:n.path&&lo(n.path)?`${n.tool} ${n.path}`:null)),"dotenv-read":Z("low","a command head or file path naming a .env file (.env, .env.local, .env.production \u2026; the committed .env.example / .sample / .template are not ones)","2026-10-21 fleet replay \xB7 309 hits / 98,690 hook calls \xB7 44 Tracks \xB7 0 in the last 14 d \xB7 all of them an instructed `source \u2026/almanac/.env` on the operator's other repos \u2192 low (report only)",(e,t)=>In(t,n=>n.head&&uo(n.head)?n.head:n.path&&uo(n.path)?`${n.tool} ${n.path}`:null)),"privileged-command":Z("medium","a shell segment whose command is sudo or docker (after any VAR=value prefix) \u2014 host-level reach from inside a box","2026-10-21 fleet replay \xB7 220 hits (183 events) / 98,690 hook calls \xB7 57 Tracks \xB7 3 in the last 14 d \xB7 sudo = the operator's own journalctl/systemctl asks on the Pi, docker = instructed compose/psql work on the operator's other services \u2192 medium (a hosted node's first hit is the number to watch)",(e,t)=>mt(t,n=>{let{cmd:r}=fo(Ut(n));return r==="sudo"||r==="docker"?n:null})),"write-outside-workspace":Z("low","a file tool (Write / Edit / NotebookEdit) on an absolute path \u2014 the hook strips the box's workspace prefix, so an absolute path is outside it \u2014 that is not the box's scratch dir (/tmp/\u2026, \u2026/.bostrat/tmp/\u2026)","2026-10-21 fleet replay \xB7 106 hits / 98,690 hook calls \xB7 10 Tracks \xB7 44 in the last 14 d \xB7 the operator's other repos and Agent-tool worktrees under .bostrat/repos on the operator's own node \u2192 low (report only)",(e,t)=>In(t,n=>Nn.has(n.tool)&&n.path&&Ea(n.path)?`${n.tool} ${n.path}`:null)),"egress-new-host":Z("low","a command head reaching, by URL, a host no box in the fleet has reached before (this projection's lifetime, seeded from the warm tails; KNOWN_HOSTS + PLANE_AUDIT_KNOWN_HOSTS never count) \u2014 a baseline-growth signal, so each host is reported once","2026-10-21 fleet replay \xB7 140 first sightings / 98,690 hook calls \xB7 69 Tracks \xB7 8 in the last 14 d \xB7 198 if the baseline were per Track \xB7 every host a vendor API, a docs site or the operator's own services \u2192 low (report only)",(e,t)=>{let n=0,r=null;for(let o of t.calls)if(o.head)for(let s of Na(o.head))t.state.known.has(s)||t.state.hosts.has(s)||(t.state.hosts.add(s),t.state.hosts.size>pa&&t.state.hosts.delete(t.state.hosts.values().next().value),n++,r??=ke(`${s} \xB7 ${o.head}`));return n?{count:n,sample:r}:null}),"spend-spike":Z("low",`a cost.recorded turn over ${so}\xD7 the Track's running median (its last ${ro} cost events, at least ${oo} of them) and over $${io} \u2014 a turn that cost far more than this Track's turns do`,"2026-10-21 fleet replay \xB7 114 hits / 8,421 cost events \xB7 64 Tracks \xB7 2 in the last 14 d \xB7 every hit a long build turn after short prompts (a $25\u201378 turn on a $0.37 median) \u2014 real spend, no one's attack \u2192 low (report only)",(e,t)=>{if(e.type!=="cost.recorded")return null;let n=t.track.costs,r=Number(e.payload?.usd);if(!Number.isFinite(r)||r<0)return null;let o=null;if(n.length>=oo&&r>=io){let s=[...n].sort((l,h)=>l-h),a=s[Math.floor(s.length/2)];r>so*a&&(o={count:1,sample:`$${r.toFixed(2)} vs median $${a.toFixed(2)} over ${n.length} turns${e.payload?.model?` \xB7 ${e.payload.model}`:""}`})}return n.push(r),n.length>ro&&n.shift(),o}),"peer-injected-call":Z("medium",`a tool call within ${ao/6e4} min of a peer.message on the same box with no operator or node-typed turn in between \u2014 the cross-session injection vector (peer-message.js); a peer is never a root (BP-AU-D1)`,"2026-10-21 fleet replay \xB7 0 peer.message events in 288,395 \xB7 the replay cannot bound this rule's rate, so it stays medium (rail) until a window with peer traffic has been measured; the shape itself is BP-AU-D1's stated R4 case",(e,t)=>{if(!t.calls.length)return null;let n=t.track.peer.get(t.boxKey);if(n==null||t.ts-n>ao||t.ts<n)return null;let r=t.calls[0];return{count:t.count,sample:ke(`${Math.round((t.ts-n)/1e3)}s after a peer message \xB7 ${r.tool}${r.head?`: ${r.head}`:r.path?` ${r.path}`:""}`)}}),"foreign-session-call":Z("medium","a hook-recorded tool call from a claude session that is not the box's own (payload.foreignSession, BP-AU-I12): a nested or stray CLI driving the box's hooks \u2014 R3 never roots it, this names it","2026-10-21 fleet replay \xB7 14 hits / 98,744 hook calls \xB7 3 Tracks \xB7 4 in the last 14 d \xB7 all the xscout loop's nested claude prompts, I12's own acceptance case \u2192 medium (rail), not a page",(e,t)=>{if(!t.calls.length||!e.payload?.foreignSession)return null;let n=t.calls[0];return{count:t.count,sample:ke(`session ${String(e.payload.sessionId||"?").slice(0,8)} \xB7 ${n.tool}${n.head?`: ${n.head}`:n.path?` ${n.path}`:""}`)}})}),kd=Object.freeze(Object.keys(wo)),Ad=new Set([...ha,"cost.recorded","peer.message","turn.user"])});function Pa(e){let t=String(e??"").trim().toLowerCase();if(Ia.has(t))return{enabled:!1,rules:[],unknown:[]};if(Ma.has(t))return{enabled:!0,rules:[...Pn],unknown:[]};let n=[],r=[];for(let o of t.split(",")){let s=o.trim();s&&(Pn.includes(s)?n.includes(s)||n.push(s):r.push(s))}return{enabled:n.length>0,rules:n,unknown:r}}function bo(e){return e?.enabled?`on \xB7 denies ${e.rules.length===Pn.length?"the high set: ":""}${e.rules.join(", ")}${e.unknown.length?` \xB7 ignoring unknown ${e.unknown.join(", ")}`:""} \xB7 fail-open (an unanswered hook allows)`:"off (BOSTRAT_AUDIT_GUARD unset \u2014 PreToolUse records, never denies)"}var Pn,Ia,Ma,Dn,jn=R(()=>{yo();Pn=Object.freeze(["force-push","protected-config-write","credential-read","persistence-install"]),Ia=new Set(["","off","0","false","no","none"]),Ma=new Set(["on","1","true","yes","all"]);Dn=(e=process.env)=>Pa(e.BOSTRAT_AUDIT_GUARD)});import He from"node:fs";import _o from"node:fs/promises";import Wt from"node:os";import V from"node:path";import{execFile as To}from"node:child_process";import{promisify as Da}from"node:util";function vo(e){try{return He.readFileSync(e,"utf8").split(`
6
- `).filter(t=>t&&!t.startsWith("#")).map(t=>t.split(":"))}catch{return[]}}function ko(e,t=process.env){let r=vo(t.BOSTRAT_PASSWD_FILE||"/etc/passwd").find(o=>o[0]===String(e)||o[2]===String(e));return r?{name:r[0],uid:Number(r[2]),gid:Number(r[3]),home:r[5]||null,shell:r[6]||null}:null}function Ao(e,t=process.env){let n=vo(t.BOSTRAT_GROUP_FILE||"/etc/group"),r=new Set;for(let o of n)Number(o[2])===e.gid&&r.add(o[0]),(o[3]||"").split(",").includes(e.name)&&r.add(o[0]);return[...r].sort()}function gt(e=process.env){let t=String(e[Fn]||"").trim();if(Ba.has(t.toLowerCase()))return null;let n=`${t}|${e.BOSTRAT_PASSWD_FILE||""}|${e.BOSTRAT_GROUP_FILE||""}|${e.BOSTRAT_BOX_HOME_VIEW||""}`;if(Cn?.key===n)return Cn.value;let r;if(!Ca.test(t))r={name:t,error:`${Fn}="${t}" is not a valid user name`};else{let o=ko(t,e),s=Ht();if(!o)r={name:t,error:`user "${t}" does not exist \u2014 run scripts/pi/box-user-setup.sh (or the image's useradd)`};else if(o.uid===0)r={name:t,error:`user "${t}" is root`};else if(o.uid===s)r={name:t,error:`user "${t}" is the node's own uid`};else if(!o.home||o.home==="/"||o.home==="/nonexistent")r={name:t,error:`user "${t}" has no home directory`};else{let a=Ao(o,e),l=a.filter(h=>xo.includes(h));r=l.length?{name:t,error:`user "${t}" is in ${l.join(", ")} \u2014 a box user must hold no route to root`}:{...o,groups:a,nodeUid:s,rootNode:s===0}}}return Cn={key:n,value:r},r}function We(e=process.env){let t=gt(e);return t&&!t.error?t.home:Wt.homedir()}function So(e=process.env){let t=gt(e);return!t||t.error||t.rootNode?We(e):e.BOSTRAT_BOX_HOME_VIEW||V.join($o(e),"box-home")}function La(e,t=process.env){let n=gt(t);return!n||n.error?e:n.rootNode?["setpriv",`--reuid=${n.uid}`,`--regid=${n.gid}`,"--init-groups","--","env",`HOME=${n.home}`,`USER=${n.name}`,`LOGNAME=${n.name}`,...e]:["sudo","-n","-H","-u",n.name,"--",...e]}async function Bn(e,{env:t=process.env,input:n=null,timeout:r=15e3}={}){let[o,...s]=La(e,t);return n==null?Un(o,s,{timeout:r}):new Promise((a,l)=>{To(o,s,{timeout:r},(m,d,g)=>m?l(m):a({stdout:d,stderr:g})).stdin.end(n)})}function Fa(e){return e.BOSTRAT_SETFACL_BIN?e.BOSTRAT_SETFACL_BIN:(Ln===void 0&&(Ln=["/usr/bin/setfacl","/bin/setfacl"].find(t=>He.existsSync(t))||null),Ln)}function Ua(e=process.env){let t=Wt.homedir(),n=$o(e);return[V.join(t,".ssh"),V.join(t,".claude.json"),V.join(t,".claude",".credentials.json"),V.join(t,".codex","auth.json"),V.join(t,".config","gh","hosts.yml"),V.join(t,".cursor","cli-config.json"),V.join(n,"node.env"),V.join(n,"api-token"),V.join(n,"plane-link"),V.join(n,"secure-inputs")]}async function Eo({env:e=process.env,probe:t=!0}={}){let n=gt(e),r=await Ka(e);if(!n){let s=ko(Ht(),e)||{name:Wt.userInfo().username,uid:Ht(),gid:-1},a=s.uid===0?["root"]:Ao(s,e).filter(m=>xo.includes(m)),l=s.uid!==0&&t?await Wa():!1,h=[...a,...l&&!a.includes("sudo")?["sudo (sudoers)"]:[]];return{level:h.length?"root-capable":"node-uid",user:s.name,routes:h,problems:[],auditd:r}}if(n.error)return{level:"misconfigured",user:n.name,error:n.error,problems:[n.error],auditd:r};let o=[];if(t){try{let{stdout:h}=await Bn(["id","-u"],{env:e,timeout:5e3});Number(h.trim())!==n.uid&&o.push(`switching to ${n.name} landed as uid ${h.trim()}`)}catch(h){o.push(`the node cannot switch to ${n.name} (${n.rootNode?"setpriv":"sudo -n -u"} failed: ${Ha(h)})`)}if(!o.length){await Bn(["sudo","-n","true"],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&o.push(`${n.name} can sudo`);let h=[];for(let m of Ua(e))He.existsSync(m)&&await Bn(["test","-r",m],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&h.push(m);h.length&&o.push(`${n.name} can read ${h.join(", ")}`)}Fa(e)||o.push("setfacl is missing (apt install acl)");let s=So(e);s!==n.home&&!He.existsSync(V.join(s,".claude"))&&o.push(`the read-only mirror of ${n.home} is not mounted at ${s} \u2014 the node cannot read box transcripts`);let a=V.join(n.home,".claude","settings.json"),l=await _o.stat(a).catch(()=>null);l&&l.uid===n.uid&&o.push(`${a} is owned by ${n.name} \u2014 the box can rewrite its own hooks`)}return{level:"uid",user:n.name,uid:n.uid,home:n.home,view:So(e),problems:o,auditd:r}}async function Wa(){try{return await Un("sudo",["-n","true"],{timeout:3e3}),!0}catch{return!1}}async function Ka(e=process.env,{ask:t=!0}={}){let n=e.BOSTRAT_AUDIT_LOG||"/var/log/audit/audit.log",r=!1;try{await _o.access(n,He.constants.R_OK),r=!0}catch{}let o=e.BOSTRAT_AUDIT_RULES_FILE||"/etc/audit/rules.d/bostrat-box.rules",s=He.existsSync(o),a=null;if(t&&s){let l=Ht()===0?["auditctl",["-l"]]:["sudo",["-n","auditctl","-l"]];try{let{stdout:h}=await Un(l[0],l[1],{timeout:5e3});a=h.includes(`key=${ja}`)}catch{a=null}}else s||(a=!1);return{log:n,readable:r,configured:s,rule:a,rulesFile:o}}function Oo(e){let t=e.auditd||{},n=t.rule===!0&&t.readable?"auditd execve logging on":t.rule===!0?"auditd rule loaded, but the node cannot read the log":t.configured&&t.rule===null?`auditd rule configured (not verifiable without root)${t.readable?"":", log unreadable"}`:t.configured?"auditd rule configured but NOT loaded":"no auditd";if(e.level==="uid"){let r=e.problems.length?` \u2014 ${e.problems.length} problem(s): ${e.problems.join("; ")}`:"";return`boxes run as ${e.user} (uid ${e.uid}, no route to root), event log + hook settings read-only to them; ${n}${r}`}return e.level==="misconfigured"?`${Fn} is set but unusable \u2014 boxes are REFUSED: ${e.error}`:e.level==="root-capable"?`boxes run as ${e.user} (${e.routes.join(", ")}) \u2014 root-capable: an agent can defeat node-side evidence; ${n}`:`boxes run as the node's uid (${e.user}) \u2014 no route to root, but they can rewrite the node's event log and hooks; ${n}`}var Un,Fn,ja,xo,Ca,Ba,$o,Ht,Cn,wt,Ln,Ha,Ae=R(()=>{Un=Da(To),Fn="BOSTRAT_BOX_USER",ja="bostrat-box",xo=Object.freeze(["root","sudo","wheel","admin","docker","lxd","libvirt","disk"]),Ca=/^[a-z_][a-z0-9_-]{0,31}$/,Ba=new Set(["","off","0","false","no","none"]),$o=e=>e.BOSTRAT_STATE_DIR||V.join(e.HOME||Wt.homedir(),".bostrat");Ht=()=>typeof process.getuid=="function"?process.getuid():0,Cn=null;wt=(e=process.env)=>{let t=gt(e);return!!(t&&!t.error)};Ha=e=>String(e?.stderr||e?.message||e).trim().split(`
7
- `)[0].slice(0,160)});import Va from"node:os";import Hn from"node:path";function No(){return wt()?Hn.join(We(),".claude.json"):process.env.CLAUDE_CONFIG_DIR?Hn.join(process.env.CLAUDE_CONFIG_DIR,".claude.json"):Hn.join(Va.homedir(),".claude.json")}var Wn=R(()=>{Ft();jn();Ae()});import qa from"node:os";import Kn from"node:path";function Io(){if(wt())return Kn.join(We(),".codex","config.toml");let e=process.env.CODEX_HOME||Kn.join(qa.homedir(),".codex");return Kn.join(e,"config.toml")}var Ya,Jd,zn=R(()=>{Ae();Ya="check_for_update_on_startup",Jd=`${Ya} = false`});import Ja from"node:os";import Mo from"node:path";var Za,rf,of,Gn=R(()=>{Vn();Lt();Za=process.env.BOSTRAT_DEBUG_DIR||Mo.join(Ja.homedir(),".bostrat","debug"),rf=Mo.join(Za,"handoff.jsonl"),of=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as ec}from"node:child_process";import{promisify as tc}from"node:util";function qn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var df,ff,pf,hf,Yn=R(()=>{Gn();df=tc(ec),ff=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,pf=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,hf=Promise.resolve()});var Po=R(()=>{Ae()});import Xn from"node:path";import{execFile as nc}from"node:child_process";import{promisify as rc}from"node:util";var _f,Do,oc,Tf,xf,jo=R(()=>{_f=rc(nc),Do=process.env.HOME||"/home/globo",oc=Xn.join(process.env.BOSTRAT_STATE_DIR||Xn.join(Do,".bostrat"),"repos"),Tf=[...(process.env.BOSTRAT_REPOS_ROOT||Xn.join(Do,"Documents")).split(","),oc].map(e=>e.trim()).filter(Boolean),xf=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function Gt(e=Date.now()){if(Oe)return{tripped:!1,holdMs:1/0};if(Ee>e)return{tripped:!1,holdMs:Ee-e};if((!bt||e-bt>=Kt.windowMs)&&(bt=e,yt=0),yt++,yt<Kt.trip)return{tripped:!1,holdMs:0};zt++;let t=Math.min(Kt.minMs*2**(zt-1),Kt.maxMs);return Ee=e+t,yt=0,bt=0,{tripped:!0,holdMs:t}}function Co(){yt=0,bt=0,zt=0,Ee=0}function St(e=Date.now()){return Oe?1/0:Ee>e?Ee-e:0}function Vt(e=Date.now()){return St(e)>0}function Jn(e={}){Oe={at:Date.now(),...e},Ee=1/0}function Zn(){return Oe}function Bo(e=Date.now()){return{held:Vt(e),holdMs:Oe?null:St(e),holds:zt,removed:Oe?{...Oe}:null}}var sc,Kt,yt,bt,zt,Ee,Oe,Qn=R(()=>{sc={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},Kt={...sc},yt=0,bt=0,zt=0,Ee=0,Oe=null});import Lo from"node:path";import ic from"node:os";import{execFile as ac}from"node:child_process";import{promisify as cc}from"node:util";var Mf,lc,Pf,Df,jf,er=R(()=>{jo();Qn();Mf=cc(ac),lc=process.env.BOSTRAT_STATE_DIR||Lo.join(process.env.HOME||ic.tmpdir(),".bostrat"),Pf=Lo.join(lc,"repos"),Df=5*6e4,jf=10*6e4});var Fo=R(()=>{er()});var Uo=R(()=>{});import dc from"node:fs/promises";import _t from"node:path";import fc from"node:os";import{EventEmitter as pc}from"node:events";function hc(e){return e?.cwd?_t.join(e.cwd,".bostrat","events"):_t.join(Ho,"events")}async function qt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?_t.join(Ho,"events"):hc(e));let o;try{o=await dc.readFile(mc(n,r),"utf8")}catch{return[]}return bc(o)}function bc(e){let t=[];for(let n of e.split(`
8
- `))if(n.trim())try{t.push(JSON.parse(wc(n)?yc(n):n))}catch{}return t}var Tt,Ho,mc,gc,wc,yc,Yt=R(()=>{Uo();Lt();Tt=new pc;Tt.setMaxListeners(0);Ho=process.env.BOSTRAT_STATE_DIR||_t.join(process.env.HOME||fc.tmpdir(),".bostrat");mc=(e,t)=>_t.join(e,`${t}.ndjson`),gc=/(?<!\\)((?:\\\\)*)\\u0000/g,wc=e=>e.includes("\\u0000"),yc=e=>e.replace(gc,"$1\\ufffd")});import _c from"node:os";import Tc from"node:path";import{execFile as xc}from"node:child_process";import{promisify as $c}from"node:util";var ip,ap,cp,lp,up,dp,Wo=R(()=>{Fo();Yt();ip=$c(xc),ap=process.env.BOSTRAT_STATE_DIR||Tc.join(process.env.HOME||_c.tmpdir(),".bostrat"),cp=25*1024,lp=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,up=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,dp=Promise.resolve()});var Xt=R(()=>{});var gp,zo=R(()=>{er();Xt();gp=60*6e4});var Go=R(()=>{zo()});import Vo from"node:path";import vc from"node:os";var Ke,kc,Rp,tr,Np,Ip,Mp,qo=R(()=>{Ft();Ae();Ke="BOSTRAT_NODE_URL",kc=process.env.BOSTRAT_STATE_DIR||Vo.join(process.env.HOME||vc.tmpdir(),".bostrat"),Rp=Vo.join(kc,"git-hooks"),tr=`#!/bin/sh
5
+ `,{mode:384}),Bt.chmodSync(e,384)}function ro(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 Lt,Ue,Rn=R(()=>{Lt=process.env.BOSTRAT_STATE_DIR||On.join(process.env.HOME||ua.tmpdir(),".bostrat"),Ue=()=>On.join(Lt,"node.env")});var yd,Ut=R(()=>{yd=16*1024});var le,ht,Ht=R(()=>{le="BOSTRAT_HOOK_TOKEN",ht="x-bostrat-hook"});var da,_d,oo=R(()=>{da=(e,t)=>{if(e==null||e==="")return t;let n=Number(e);return Number.isFinite(n)&&n>=0?n:t},_d=da(process.env.BOSTRAT_HOOK_FOLD_MS,250)});function wa(e,t=fa){let n=String(e??""),r=n.split(/\s*(?:;|&&|\|\||\||\n)\s*/).map(o=>o.trim()).filter(Boolean);return Number.isFinite(t)&&n.length>=t&&r.length&&r.pop(),r}function Wt(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function ho(e){let t=0;for(;t<e.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]);)t++;return{cmd:e[t]??null,rest:e.slice(t+1),at:t}}function uo(e){let t=Wt(e),n=t.findIndex(m=>m==="git"||m.endsWith("/git"));if(n<0)return null;for(n++;n<t.length&&t[n].startsWith("-");)(t[n]==="-C"||t[n]==="-c")&&n++,n++;if(t[n]!=="push")return null;let r=[],o=[];for(let m=n+1;m<t.length;m++){let d=t[m];d.startsWith("-")?(r.push(d),(d==="-o"||d==="--push-option"||d==="--repo"||d==="--receive-pack"||d==="--exec")&&m++):o.push(d)}let s=r.some(m=>m==="--force"||/^-[a-zA-Z]+$/.test(m)&&m.includes("f"))||o.some(m=>m.startsWith("+")),a=r.some(m=>m.startsWith("--force-with-lease")||m.startsWith("--force-if-includes")),l=o[0]??null,h=o.slice(1).map(m=>m.replace(/^["']|["']$/g,"").replace(/^\+/,"")).map(m=>m.includes(":")?m.slice(m.indexOf(":")+1):m).filter(m=>m&&!m.startsWith("$"));return{force:s,lease:a,remote:l,dsts:h}}function wo(e){let{cmd:t,at:n}=ho(e);if(t==="sudo"){for(n++;n<e.length&&e[n].startsWith("-");)n++;t=e[n]??null}return{cmd:t,at:n}}function yo(e,t){let n=String(e??"").match(t);if(!n)return null;let r=n[1],o=r.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");if(new RegExp(`>{1,2}\\s*["']?[^\\s"']*${o}`).test(e))return"redirect";let s=Wt(e),{cmd:a}=wo(s);return!a||!s.some(l=>l.includes(r))?null:/^(?:rm|mv|truncate|chmod|chown|tee|install|shred|unlink|ln|mkdir|touch)$/.test(a)?a:a==="sed"&&s.some(l=>/^-[a-zA-Z]*i/.test(l))?"sed -i":a==="cp"&&s[s.length-1].includes(r)?"cp":/^(?:python3?|perl|node|ruby)$/.test(a)&&/open\([^)]*['"][wa]|writeFile|write_text|appendFile|fs\.write/.test(e)?`${a} write`:null}function Na(e){let t=Wt(e),{cmd:n,at:r}=wo(t);if(!n)return null;let o=t.slice(r+1);if(n==="crontab"||n.endsWith("/crontab")){let a=!1,l=!1;for(let h=0;h<o.length;h++){if(o[h]==="-u"){h++;continue}o[h]==="-l"||/^-(?:h|V|T|-help|-version)$/.test(o[h])?a=!0:l=!0}return l||!a?"crontab":null}if(n==="systemctl"||n.endsWith("/systemctl")){let a=o.find(l=>!l.startsWith("-"));return a&&Ta.test(a)?`systemctl ${a}`:null}if((n==="loginctl"||n.endsWith("/loginctl"))&&o.includes("enable-linger"))return"loginctl enable-linger";if(n==="at"&&o.length&&/^(?:now|midnight|noon|teatime|today|tomorrow|next|\d|-[fqmvt])/.test(o[0]))return"at";let s=yo(e,go);return s?`${s} unit/cron path`:null}function Ia(e){let t=new Set;for(let n of String(e??"").matchAll(Aa))t.add(n[1].toLowerCase());return[...t]}var pa,fa,so,io,ao,co,lo,Ad,ha,ma,Nn,ga,we,Mn,ya,ba,Sa,_a,mo,go,Ta,xa,$a,va,Aa,po,fo,ka,Ea,Oa,Ra,X,mt,In,bo,kd,Ed,So=R(()=>{oo();pa="BP-AU-R4",fa=160,so=200,io=5,ao=8,co=5,lo=10*6e4,Ad=Object.freeze(["localhost","127.0.0.1","0.0.0.0","github.com","api.github.com","raw.githubusercontent.com","objects.githubusercontent.com","registry.npmjs.org","pypi.org","files.pythonhosted.org"]),ha=5e3,ma=new Set(["tool.called","tool.failed"]),Nn=new Set(["Write","Edit","NotebookEdit"]),ga=e=>String(e??"").replace(/\s+/g," ").trim(),we=(e,t=120)=>ga(e).slice(0,t);Mn=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,ya=new RegExp(`${Mn}/\\.ssh(?:/|\\b)`),ba=new RegExp(`${Mn}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),Sa=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,_a=/^\.env\.(?:example|sample|template|dist)$/,mo=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,go=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${Mn}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),Ta=/^(?:enable|disable|start|stop|restart|try-restart|reload|reload-or-restart|daemon-reload|daemon-reexec|link|mask|unmask|edit|preset|preset-all|set-property|revert|isolate|kill|reset-failed|import-environment|set-environment|add-wants|add-requires)$/,xa=/^\/tmp\/|\/\.bostrat\/tmp\//,$a=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,va=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,Aa=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,po=e=>ya.test(e)||ba.test(e),fo=e=>[...String(e??"").matchAll(Sa)].some(t=>!_a.test(t[1])),ka=e=>mo.test(e),Ea=e=>go.test(e),Oa=e=>(e.startsWith("/")||e.startsWith("~"))&&!xa.test(e);Ra=e=>yo(e,mo);X=(e,t,n,r)=>Object.freeze({severity:e,requirement:pa,note:t,measured:n,detect:r}),mt=(e,t)=>{let n=0,r=null;for(let o of e.calls)if(o.head)for(let s of wa(o.head,e.headCap)){let a=t(s,o);a&&(n++,r??=we(a))}return n?{count:n,sample:r}:null},In=(e,t)=>{let n=0,r=null;for(let o of e.calls){let s=t(o);s&&(n++,r??=we(s))}return n?{count:n,sample:r}:null},bo=Object.freeze({"force-push":X("high","git push --force / -f / +refspec in a command head (--force-with-lease, the Track's own rebase flow, is not one)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 1,080 logs 2026-08\u219210 \xB7 58 --force-with-lease pushes excluded by design \u2192 high",(e,t)=>mt(t,n=>{let r=uo(n);return r&&r.force&&!r.lease?n:null})),"protected-config-write":X("high","a write to the box's own harness: .claude/settings*.json, a .claude/hooks/ script or the Track's .bostrat/events/ log \u2014 by a file tool, a redirect, rm/mv/tee/sed -i, or a scripted open-for-write (reads are not hits)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 165 reads of those paths (cat, grep, python json.loads) excluded by design \u2192 high",(e,t)=>{let n=0,r=null;for(let s of t.calls)Nn.has(s.tool)&&s.path&&ka(s.path)&&(n++,r??=we(`${s.tool} ${s.path}`));let o=mt(t,s=>{let a=Ra(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"persistence-install":X("medium","a shell segment that installs something the OS runs on its own \u2014 crontab (install / edit / remove; -l is a read), a mutating systemctl verb (enable / start / restart / daemon-reload \u2026; status / show / cat / list / is-* are reads), loginctl enable-linger, at / batch \u2014 or a write (file tool, redirect, cp / mv / tee / ln / sed -i) into a systemd unit or cron directory: how a process outlives its turn by the OS's hand (BP-AU-D6's other half)","2026-10-21 fleet replay \xB7 11 hits / 99,122 hook calls \xB7 10 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-asked service work on the operator's own Pi (systemctl --user restart/stop/start of bostrat-node, tmp-sweep, a samba disable, one `crontab -` install for a backfill) \xB7 the bare `at` word a quoted `|` regex leaves in a segment (4 hits) excluded by design \u2192 medium (rail), the guard's deny when opted in",(e,t)=>{let n=0,r=null;for(let s of t.calls)Nn.has(s.tool)&&s.path&&Ea(s.path)&&(n++,r??=we(`${s.tool} ${s.path}`));let o=mt(t,s=>{let a=Na(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"push-outside-track":X("medium","git push to a protected branch (main/master/develop/release\u2026), to a branch that is not a Track branch, or to a remote other than origin/upstream \u2014 a Track's own code leaves on its track/ branch or the WIP shadow ref","2026-10-21 fleet replay \xB7 7 hits / 98,690 hook calls \xB7 4 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-instructed work on another repo (two dep/ branches, a fork's multiplayer branch, one HEAD:main) \u2192 medium, not a page",(e,t)=>mt(t,n=>{let r=uo(n);return r&&(r.remote&&!/^(?:origin|upstream)$/.test(r.remote)&&!r.remote.startsWith("$")&&!r.remote.startsWith("-")||r.dsts.some(o=>$a.test(o)||!va.test(o)))?n:null})),"credential-read":X("medium","a command head or file path naming SSH material (~/.ssh) or a vendor auth file (~/.claude.json, ~/.claude/.credentials.json, ~/.codex/auth.json, ~/.cursor) \u2014 the box-auth policy's denylist shapes; ~/.claude/projects (transcripts) is not one","2026-10-21 fleet replay \xB7 12 hits / 98,690 hook calls \xB7 8 Tracks \xB7 3 in the last 14 d \xB7 every hit an operator-asked inspection on the operator's own node (ssh config for a host alias, stat/keys of ~/.claude.json) \u2192 medium until a 14-day window reads 0",(e,t)=>In(t,n=>n.head&&po(n.head)?n.head:n.path&&po(n.path)?`${n.tool} ${n.path}`:null)),"dotenv-read":X("low","a command head or file path naming a .env file (.env, .env.local, .env.production \u2026; the committed .env.example / .sample / .template are not ones)","2026-10-21 fleet replay \xB7 309 hits / 98,690 hook calls \xB7 44 Tracks \xB7 0 in the last 14 d \xB7 all of them an instructed `source \u2026/almanac/.env` on the operator's other repos \u2192 low (report only)",(e,t)=>In(t,n=>n.head&&fo(n.head)?n.head:n.path&&fo(n.path)?`${n.tool} ${n.path}`:null)),"privileged-command":X("medium","a shell segment whose command is sudo or docker (after any VAR=value prefix) \u2014 host-level reach from inside a box","2026-10-21 fleet replay \xB7 220 hits (183 events) / 98,690 hook calls \xB7 57 Tracks \xB7 3 in the last 14 d \xB7 sudo = the operator's own journalctl/systemctl asks on the Pi, docker = instructed compose/psql work on the operator's other services \u2192 medium (a hosted node's first hit is the number to watch)",(e,t)=>mt(t,n=>{let{cmd:r}=ho(Wt(n));return r==="sudo"||r==="docker"?n:null})),"write-outside-workspace":X("low","a file tool (Write / Edit / NotebookEdit) on an absolute path \u2014 the hook strips the box's workspace prefix, so an absolute path is outside it \u2014 that is not the box's scratch dir (/tmp/\u2026, \u2026/.bostrat/tmp/\u2026)","2026-10-21 fleet replay \xB7 106 hits / 98,690 hook calls \xB7 10 Tracks \xB7 44 in the last 14 d \xB7 the operator's other repos and Agent-tool worktrees under .bostrat/repos on the operator's own node \u2192 low (report only)",(e,t)=>In(t,n=>Nn.has(n.tool)&&n.path&&Oa(n.path)?`${n.tool} ${n.path}`:null)),"egress-new-host":X("low","a command head reaching, by URL, a host no box in the fleet has reached before (this projection's lifetime, seeded from the warm tails; KNOWN_HOSTS + PLANE_AUDIT_KNOWN_HOSTS never count) \u2014 a baseline-growth signal, so each host is reported once","2026-10-21 fleet replay \xB7 140 first sightings / 98,690 hook calls \xB7 69 Tracks \xB7 8 in the last 14 d \xB7 198 if the baseline were per Track \xB7 every host a vendor API, a docs site or the operator's own services \u2192 low (report only)",(e,t)=>{let n=0,r=null;for(let o of t.calls)if(o.head)for(let s of Ia(o.head))t.state.known.has(s)||t.state.hosts.has(s)||(t.state.hosts.add(s),t.state.hosts.size>ha&&t.state.hosts.delete(t.state.hosts.values().next().value),n++,r??=we(`${s} \xB7 ${o.head}`));return n?{count:n,sample:r}:null}),"spend-spike":X("low",`a cost.recorded turn over ${ao}\xD7 the Track's running median (its last ${so} cost events, at least ${io} of them) and over $${co} \u2014 a turn that cost far more than this Track's turns do`,"2026-10-21 fleet replay \xB7 114 hits / 8,421 cost events \xB7 64 Tracks \xB7 2 in the last 14 d \xB7 every hit a long build turn after short prompts (a $25\u201378 turn on a $0.37 median) \u2014 real spend, no one's attack \u2192 low (report only)",(e,t)=>{if(e.type!=="cost.recorded")return null;let n=t.track.costs,r=Number(e.payload?.usd);if(!Number.isFinite(r)||r<0)return null;let o=null;if(n.length>=io&&r>=co){let s=[...n].sort((l,h)=>l-h),a=s[Math.floor(s.length/2)];r>ao*a&&(o={count:1,sample:`$${r.toFixed(2)} vs median $${a.toFixed(2)} over ${n.length} turns${e.payload?.model?` \xB7 ${e.payload.model}`:""}`})}return n.push(r),n.length>so&&n.shift(),o}),"peer-injected-call":X("medium",`a tool call within ${lo/6e4} min of a peer.message on the same box with no operator or node-typed turn in between \u2014 the cross-session injection vector (peer-message.js); a peer is never a root (BP-AU-D1)`,"2026-10-21 fleet replay \xB7 0 peer.message events in 288,395 \xB7 the replay cannot bound this rule's rate, so it stays medium (rail) until a window with peer traffic has been measured; the shape itself is BP-AU-D1's stated R4 case",(e,t)=>{if(!t.calls.length)return null;let n=t.track.peer.get(t.boxKey);if(n==null||t.ts-n>lo||t.ts<n)return null;let r=t.calls[0];return{count:t.count,sample:we(`${Math.round((t.ts-n)/1e3)}s after a peer message \xB7 ${r.tool}${r.head?`: ${r.head}`:r.path?` ${r.path}`:""}`)}}),"foreign-session-call":X("medium","a hook-recorded tool call from a claude session that is not the box's own (payload.foreignSession, BP-AU-I12): a nested or stray CLI driving the box's hooks \u2014 R3 never roots it, this names it","2026-10-21 fleet replay \xB7 14 hits / 98,744 hook calls \xB7 3 Tracks \xB7 4 in the last 14 d \xB7 all the xscout loop's nested claude prompts, I12's own acceptance case \u2192 medium (rail), not a page",(e,t)=>{if(!t.calls.length||!e.payload?.foreignSession)return null;let n=t.calls[0];return{count:t.count,sample:we(`session ${String(e.payload.sessionId||"?").slice(0,8)} \xB7 ${n.tool}${n.head?`: ${n.head}`:n.path?` ${n.path}`:""}`)}}),"orphan-process":X("medium","a process the box left running: detached from the pane's tree (its cgroup or pty still lists it), alive at a turn's close and still alive minutes later with no turn open and no background job recorded \u2014 the node's own census (orphan-watch.js, BP-AU-D6), each process once","2026-10-27 fleet replay \xB7 0 audit.procs events in 304,814 (1,121 logs; the type is new, so the replay cannot bound this rule's rate) \xB7 live Pi census the same day: 10 boxes, 2 detached processes, both found by the cgroup census and neither by the pty one (a claude tool call runs on pipes) \u2014 one planted `nohup sleep &`, one real `flyctl agent run` that a lead's flyctl call had left behind 10 h earlier \u2192 medium (rail), never a page, until a window of live samples has been measured",e=>{if(e.type!=="audit.procs"||e.source!=="proc")return null;let t=e.payload||{},n=Array.isArray(t.orphans)?t.orphans:[],r=n.length+(Number(t.dropped)||0);if(!r)return null;let o=n[0]||{},s=Number.isFinite(o.sinceMs)?` \xB7 alive ${Math.max(1,Math.round(o.sinceMs/6e4))} min`:"";return{count:r,sample:we(`${o.comm||"process"}${o.cmd?`: ${o.cmd}`:""}${o.via?` [${o.via}]`:""}${s}${r>1?` (+${r-1} more)`:""}`)}})}),kd=Object.freeze(Object.keys(bo)),Ed=new Set([...ma,"cost.recorded","peer.message","turn.user","audit.procs"])});function Da(e){let t=String(e??"").trim().toLowerCase();if(Ma.has(t))return{enabled:!1,rules:[],unknown:[]};if(Pa.has(t))return{enabled:!0,rules:[...Pn],unknown:[]};let n=[],r=[];for(let o of t.split(",")){let s=o.trim();s&&(Pn.includes(s)?n.includes(s)||n.push(s):r.push(s))}return{enabled:n.length>0,rules:n,unknown:r}}function _o(e){return e?.enabled?`on \xB7 denies ${e.rules.length===Pn.length?"the high set: ":""}${e.rules.join(", ")}${e.unknown.length?` \xB7 ignoring unknown ${e.unknown.join(", ")}`:""} \xB7 fail-open (an unanswered hook allows)`:"off (BOSTRAT_AUDIT_GUARD unset \u2014 PreToolUse records, never denies)"}var Pn,Ma,Pa,Dn,jn=R(()=>{So();Pn=Object.freeze(["force-push","protected-config-write","credential-read","persistence-install"]),Ma=new Set(["","off","0","false","no","none"]),Pa=new Set(["on","1","true","yes","all"]);Dn=(e=process.env)=>Da(e.BOSTRAT_AUDIT_GUARD)});import He from"node:fs";import xo from"node:fs/promises";import zt from"node:os";import q from"node:path";import{execFile as $o}from"node:child_process";import{promisify as ja}from"node:util";function ko(e){try{return He.readFileSync(e,"utf8").split(`
6
+ `).filter(t=>t&&!t.startsWith("#")).map(t=>t.split(":"))}catch{return[]}}function Eo(e,t=process.env){let r=ko(t.BOSTRAT_PASSWD_FILE||"/etc/passwd").find(o=>o[0]===String(e)||o[2]===String(e));return r?{name:r[0],uid:Number(r[2]),gid:Number(r[3]),home:r[5]||null,shell:r[6]||null}:null}function Oo(e,t=process.env){let n=ko(t.BOSTRAT_GROUP_FILE||"/etc/group"),r=new Set;for(let o of n)Number(o[2])===e.gid&&r.add(o[0]),(o[3]||"").split(",").includes(e.name)&&r.add(o[0]);return[...r].sort()}function gt(e=process.env){let t=String(e[Fn]||"").trim();if(La.has(t.toLowerCase()))return null;let n=`${t}|${e.BOSTRAT_PASSWD_FILE||""}|${e.BOSTRAT_GROUP_FILE||""}|${e.BOSTRAT_BOX_HOME_VIEW||""}`;if(Cn?.key===n)return Cn.value;let r;if(!Ba.test(t))r={name:t,error:`${Fn}="${t}" is not a valid user name`};else{let o=Eo(t,e),s=Kt();if(!o)r={name:t,error:`user "${t}" does not exist \u2014 run scripts/pi/box-user-setup.sh (or the image's useradd)`};else if(o.uid===0)r={name:t,error:`user "${t}" is root`};else if(o.uid===s)r={name:t,error:`user "${t}" is the node's own uid`};else if(!o.home||o.home==="/"||o.home==="/nonexistent")r={name:t,error:`user "${t}" has no home directory`};else{let a=Oo(o,e),l=a.filter(h=>vo.includes(h));r=l.length?{name:t,error:`user "${t}" is in ${l.join(", ")} \u2014 a box user must hold no route to root`}:{...o,groups:a,nodeUid:s,rootNode:s===0}}}return Cn={key:n,value:r},r}function We(e=process.env){let t=gt(e);return t&&!t.error?t.home:zt.homedir()}function To(e=process.env){let t=gt(e);return!t||t.error||t.rootNode?We(e):e.BOSTRAT_BOX_HOME_VIEW||q.join(Ao(e),"box-home")}function Fa(e,t=process.env){let n=gt(t);return!n||n.error?e:n.rootNode?["setpriv",`--reuid=${n.uid}`,`--regid=${n.gid}`,"--init-groups","--","env",`HOME=${n.home}`,`USER=${n.name}`,`LOGNAME=${n.name}`,...e]:["sudo","-n","-H","-u",n.name,"--",...e]}async function Bn(e,{env:t=process.env,input:n=null,timeout:r=15e3}={}){let[o,...s]=Fa(e,t);return n==null?Un(o,s,{timeout:r}):new Promise((a,l)=>{$o(o,s,{timeout:r},(m,d,g)=>m?l(m):a({stdout:d,stderr:g})).stdin.end(n)})}function Ua(e){return e.BOSTRAT_SETFACL_BIN?e.BOSTRAT_SETFACL_BIN:(Ln===void 0&&(Ln=["/usr/bin/setfacl","/bin/setfacl"].find(t=>He.existsSync(t))||null),Ln)}function Ha(e=process.env){let t=zt.homedir(),n=Ao(e);return[q.join(t,".ssh"),q.join(t,".claude.json"),q.join(t,".claude",".credentials.json"),q.join(t,".codex","auth.json"),q.join(t,".config","gh","hosts.yml"),q.join(t,".cursor","cli-config.json"),q.join(n,"node.env"),q.join(n,"api-token"),q.join(n,"plane-link"),q.join(n,"secure-inputs")]}async function Ro({env:e=process.env,probe:t=!0}={}){let n=gt(e),r=await za(e);if(!n){let s=Eo(Kt(),e)||{name:zt.userInfo().username,uid:Kt(),gid:-1},a=s.uid===0?["root"]:Oo(s,e).filter(m=>vo.includes(m)),l=s.uid!==0&&t?await Ka():!1,h=[...a,...l&&!a.includes("sudo")?["sudo (sudoers)"]:[]];return{level:h.length?"root-capable":"node-uid",user:s.name,routes:h,problems:[],auditd:r}}if(n.error)return{level:"misconfigured",user:n.name,error:n.error,problems:[n.error],auditd:r};let o=[];if(t){try{let{stdout:h}=await Bn(["id","-u"],{env:e,timeout:5e3});Number(h.trim())!==n.uid&&o.push(`switching to ${n.name} landed as uid ${h.trim()}`)}catch(h){o.push(`the node cannot switch to ${n.name} (${n.rootNode?"setpriv":"sudo -n -u"} failed: ${Wa(h)})`)}if(!o.length){await Bn(["sudo","-n","true"],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&o.push(`${n.name} can sudo`);let h=[];for(let m of Ha(e))He.existsSync(m)&&await Bn(["test","-r",m],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&h.push(m);h.length&&o.push(`${n.name} can read ${h.join(", ")}`)}Ua(e)||o.push("setfacl is missing (apt install acl)");let s=To(e);s!==n.home&&!He.existsSync(q.join(s,".claude"))&&o.push(`the read-only mirror of ${n.home} is not mounted at ${s} \u2014 the node cannot read box transcripts`);let a=q.join(n.home,".claude","settings.json"),l=await xo.stat(a).catch(()=>null);l&&l.uid===n.uid&&o.push(`${a} is owned by ${n.name} \u2014 the box can rewrite its own hooks`)}return{level:"uid",user:n.name,uid:n.uid,home:n.home,view:To(e),problems:o,auditd:r}}async function Ka(){try{return await Un("sudo",["-n","true"],{timeout:3e3}),!0}catch{return!1}}async function za(e=process.env,{ask:t=!0}={}){let n=e.BOSTRAT_AUDIT_LOG||"/var/log/audit/audit.log",r=!1;try{await xo.access(n,He.constants.R_OK),r=!0}catch{}let o=e.BOSTRAT_AUDIT_RULES_FILE||"/etc/audit/rules.d/bostrat-box.rules",s=He.existsSync(o),a=null;if(t&&s){let l=Kt()===0?["auditctl",["-l"]]:["sudo",["-n","auditctl","-l"]];try{let{stdout:h}=await Un(l[0],l[1],{timeout:5e3});a=h.includes(`key=${Ca}`)}catch{a=null}}else s||(a=!1);return{log:n,readable:r,configured:s,rule:a,rulesFile:o}}function No(e){let t=e.auditd||{},n=t.rule===!0&&t.readable?"auditd execve logging on":t.rule===!0?"auditd rule loaded, but the node cannot read the log":t.configured&&t.rule===null?`auditd rule configured (not verifiable without root)${t.readable?"":", log unreadable"}`:t.configured?"auditd rule configured but NOT loaded":"no auditd";if(e.level==="uid"){let r=e.problems.length?` \u2014 ${e.problems.length} problem(s): ${e.problems.join("; ")}`:"";return`boxes run as ${e.user} (uid ${e.uid}, no route to root), event log + hook settings read-only to them; ${n}${r}`}return e.level==="misconfigured"?`${Fn} is set but unusable \u2014 boxes are REFUSED: ${e.error}`:e.level==="root-capable"?`boxes run as ${e.user} (${e.routes.join(", ")}) \u2014 root-capable: an agent can defeat node-side evidence; ${n}`:`boxes run as the node's uid (${e.user}) \u2014 no route to root, but they can rewrite the node's event log and hooks; ${n}`}var Un,Fn,Ca,vo,Ba,La,Ao,Kt,Cn,wt,Ln,Wa,ke=R(()=>{Un=ja($o),Fn="BOSTRAT_BOX_USER",Ca="bostrat-box",vo=Object.freeze(["root","sudo","wheel","admin","docker","lxd","libvirt","disk"]),Ba=/^[a-z_][a-z0-9_-]{0,31}$/,La=new Set(["","off","0","false","no","none"]),Ao=e=>e.BOSTRAT_STATE_DIR||q.join(e.HOME||zt.homedir(),".bostrat");Kt=()=>typeof process.getuid=="function"?process.getuid():0,Cn=null;wt=(e=process.env)=>{let t=gt(e);return!!(t&&!t.error)};Wa=e=>String(e?.stderr||e?.message||e).trim().split(`
7
+ `)[0].slice(0,160)});var yt=R(()=>{});import qa from"node:os";import Hn from"node:path";function Mo(){return wt()?Hn.join(We(),".claude.json"):process.env.CLAUDE_CONFIG_DIR?Hn.join(process.env.CLAUDE_CONFIG_DIR,".claude.json"):Hn.join(qa.homedir(),".claude.json")}var Kn=R(()=>{Ht();jn();ke();yt()});import Ya from"node:os";import zn from"node:path";function Po(){if(wt())return zn.join(We(),".codex","config.toml");let e=process.env.CODEX_HOME||zn.join(Ya.homedir(),".codex");return zn.join(e,"config.toml")}var Xa,ep,Gn=R(()=>{ke();Xa="check_for_update_on_startup",ep=`${Xa} = false`});import Za from"node:os";import Do from"node:path";var Qa,ip,ap,Vn=R(()=>{qn();Ut();Qa=process.env.BOSTRAT_DEBUG_DIR||Do.join(Za.homedir(),".bostrat","debug"),ip=Do.join(Qa,"handoff.jsonl"),ap=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as tc}from"node:child_process";import{promisify as nc}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 fp,hp,mp,gp,Xn=R(()=>{Vn();fp=nc(tc),hp=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,mp=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,gp=Promise.resolve()});var jo=R(()=>{ke()});import Jn from"node:path";import{execFile as rc}from"node:child_process";import{promisify as oc}from"node:util";var xp,Co,sc,$p,vp,Bo=R(()=>{xp=oc(rc),Co=process.env.HOME||"/home/globo",sc=Jn.join(process.env.BOSTRAT_STATE_DIR||Jn.join(Co,".bostrat"),"repos"),$p=[...(process.env.BOSTRAT_REPOS_ROOT||Jn.join(Co,"Documents")).split(","),sc].map(e=>e.trim()).filter(Boolean),vp=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function qt(e=Date.now()){if(Oe)return{tripped:!1,holdMs:1/0};if(Ee>e)return{tripped:!1,holdMs:Ee-e};if((!St||e-St>=Gt.windowMs)&&(St=e,bt=0),bt++,bt<Gt.trip)return{tripped:!1,holdMs:0};Vt++;let t=Math.min(Gt.minMs*2**(Vt-1),Gt.maxMs);return Ee=e+t,bt=0,St=0,{tripped:!0,holdMs:t}}function Lo(){bt=0,St=0,Vt=0,Ee=0}function _t(e=Date.now()){return Oe?1/0:Ee>e?Ee-e:0}function Yt(e=Date.now()){return _t(e)>0}function Zn(e={}){Oe={at:Date.now(),...e},Ee=1/0}function Qn(){return Oe}function Fo(e=Date.now()){return{held:Yt(e),holdMs:Oe?null:_t(e),holds:Vt,removed:Oe?{...Oe}:null}}var ic,Gt,bt,St,Vt,Ee,Oe,er=R(()=>{ic={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},Gt={...ic},bt=0,St=0,Vt=0,Ee=0,Oe=null});import Uo from"node:path";import ac from"node:os";import{execFile as cc}from"node:child_process";import{promisify as lc}from"node:util";var Dp,uc,jp,Cp,Bp,tr=R(()=>{Bo();er();Dp=lc(cc),uc=process.env.BOSTRAT_STATE_DIR||Uo.join(process.env.HOME||ac.tmpdir(),".bostrat"),jp=Uo.join(uc,"repos"),Cp=5*6e4,Bp=10*6e4});var Ho=R(()=>{tr()});var Wo=R(()=>{});import pc from"node:fs/promises";import Tt from"node:path";import fc from"node:os";import{EventEmitter as hc}from"node:events";function mc(e){return e?.cwd?Tt.join(e.cwd,".bostrat","events"):Tt.join(Ko,"events")}async function Xt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?Tt.join(Ko,"events"):mc(e));let o;try{o=await pc.readFile(gc(n,r),"utf8")}catch{return[]}return Sc(o)}function Sc(e){let t=[];for(let n of e.split(`
8
+ `))if(n.trim())try{t.push(JSON.parse(yc(n)?bc(n):n))}catch{}return t}var xt,Ko,gc,wc,yc,bc,Jt=R(()=>{Wo();Ut();xt=new hc;xt.setMaxListeners(0);Ko=process.env.BOSTRAT_STATE_DIR||Tt.join(process.env.HOME||fc.tmpdir(),".bostrat");gc=(e,t)=>Tt.join(e,`${t}.ndjson`),wc=/(?<!\\)((?:\\\\)*)\\u0000/g,yc=e=>e.includes("\\u0000"),bc=e=>e.replace(wc,"$1\\ufffd")});import Tc from"node:os";import xc from"node:path";import{execFile as $c}from"node:child_process";import{promisify as vc}from"node:util";var lf,uf,df,pf,ff,hf,zo=R(()=>{Ho();Jt();lf=vc($c),uf=process.env.BOSTRAT_STATE_DIR||xc.join(process.env.HOME||Tc.tmpdir(),".bostrat"),df=25*1024,pf=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,ff=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,hf=Promise.resolve()});var yf,Go=R(()=>{tr();yt();yf=60*6e4});var Vo=R(()=>{Go()});import qo from"node:path";import Ac from"node:os";var Ke,kc,If,nr,Mf,Pf,Df,Yo=R(()=>{Ht();ke();Ke="BOSTRAT_NODE_URL",kc=process.env.BOSTRAT_STATE_DIR||qo.join(process.env.HOME||Ac.tmpdir(),".bostrat"),If=qo.join(kc,"git-hooks"),nr=`#!/bin/sh
9
9
  # bostrat git hook shim (agent/src/git-hooks.js) \u2014 chains to the repo's own hook,
10
10
  # then stamps/reports for rework attribution when running inside a bostrat box.
11
11
  hook=$(basename "$0")
@@ -20,7 +20,7 @@ esac
20
20
  if [ -x "$orig/$hook" ] && [ "$orig/$hook" != "$0" ]; then
21
21
  "$orig/$hook" "$@" || exit $?
22
22
  fi
23
- `,Np=`${tr}
23
+ `,Mf=`${nr}
24
24
  # \u2500\u2500 bostrat: append provenance trailers (Layer 0). Skipped for merge commits
25
25
  # (nobody "wrote" a merge) and outside a box (no token / no node url).
26
26
  [ -z "$${le}" ] && exit 0
@@ -32,7 +32,7 @@ printf '%s\\n' "$trailers" | while IFS= read -r line; do
32
32
  [ -n "$line" ] && git interpret-trailers --in-place --if-exists addIfDifferent --trailer "$line" "$1" >/dev/null 2>&1 || true
33
33
  done
34
34
  exit 0
35
- `,Ip=`${tr}
35
+ `,Pf=`${nr}
36
36
  # \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
37
37
  [ -z "$${le}" ] && exit 0
38
38
  [ -z "$${Ke}" ] && exit 0
@@ -41,7 +41,7 @@ cwd=$(git rev-parse --show-toplevel 2>/dev/null)
41
41
  printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${Ke}/api/git/committed" \\
42
42
  -H 'content-type: application/json' -H "${ht}: $${le}" --data-binary @- >/dev/null 2>&1 || true
43
43
  exit 0
44
- `,Mp=`${tr}
44
+ `,Df=`${nr}
45
45
  # \u2500\u2500 bostrat: the tree moved \u2014 let the node re-read this workspace's lockfiles.
46
46
  [ -z "$${le}" ] && exit 0
47
47
  [ -z "$${Ke}" ] && exit 0
@@ -49,8 +49,8 @@ exit 0
49
49
  curl -sS -m 3 -X POST "$${Ke}/api/deps/refresh" \\
50
50
  -H 'content-type: application/json' -H "${ht}: $${le}" --data-binary '{}' >/dev/null 2>&1 || true
51
51
  exit 0
52
- `});import xt from"node:fs/promises";import Jt from"node:os";import ze from"node:path";import{execFile as Ac}from"node:child_process";import{promisify as Ec}from"node:util";function Zo(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function Qo(e=process.env){let t=String(e.BOSTRAT_BOX_CGROUPS??"").trim().toLowerCase();return["1","on","true","yes"].includes(t)?"on":["0","off","false","no"].includes(t)?"off":"auto"}function Pc(e=process.env){let t=Qo(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function es(e=Jt.totalmem()){return Math.max(e-Rc*$t,Math.floor(e/2))}function Dc(e=Jt.totalmem(),t=process.env){let n=Number(t.BOSTRAT_BOX_MEMORY_MAX_MB);return Number.isFinite(n)&&n>=256?Math.floor(n)*$t:Math.min(Ic*$t,es(e))}function jc(e=process.env){return ze.join(Zo(e),Nc)}async function Cc(e){return(await xt.readFile(e,"utf8")).trim()}async function ts({env:e=process.env,totalBytes:t=Jt.totalmem(),force:n=!1,platform:r=process.platform}={}){if(!n&&!Pc(e))return Ge=Qo(e)==="off"?{available:!1,reason:"disabled (BOSTRAT_BOX_CGROUPS=0)"}:await Bc({env:e,totalBytes:t,platform:r}),Ge;let o=Zo(e),s=jc(e);try{let a;try{a=(await Cc(ze.join(o,"cgroup.controllers"))).split(/\s+/).filter(Boolean)}catch(d){throw new Error(`no cgroup v2 tree at ${o} (${d?.code||d?.message||d})`)}let l=["cpu","memory"].filter(d=>a.includes(d));if(!l.length)throw new Error(`cgroup v2 at ${o} offers neither cpu nor memory (controllers: ${a.join(" ")||"none"})`);await xt.mkdir(s,{recursive:!0});let h=`+${l.join(" +")}`;for(let d of[ze.join(o,"cgroup.subtree_control"),ze.join(s,"cgroup.subtree_control")])try{await xt.writeFile(d,h)}catch(g){throw new Error(`cannot enable ${h} in ${d} (${g?.code||g?.message||g})`)}let m=es(t);l.includes("cpu")&&await xt.writeFile(ze.join(s,"cpu.weight"),String(Yo)),l.includes("memory")&&await xt.writeFile(ze.join(s,"memory.max"),String(m)),Ge={available:!0,backend:"cgroupfs",path:s,controllers:l,cpuWeight:l.includes("cpu")?Yo:null,memoryMaxMb:l.includes("memory")?Math.round(m/$t):null}}catch(a){Ge={available:!1,reason:a?.message||String(a)}}return Ge}async function Bc({env:e=process.env,totalBytes:t=Jt.totalmem(),platform:n=process.platform}={}){if(n!=="linux")return{available:!1,reason:`not a Fly/container node, and no systemd on ${n}`};try{await Oc(Xo(e),["--user","show","--property=Version","--value"],{timeout:3e3})}catch(o){return{available:!1,reason:`not a Fly/container node, and no systemd user manager to ask (${String(o?.stderr||o?.code||o?.message||o).trim().split(`
53
- `)[0]})`}}let r=Dc(t,e);return{available:!0,backend:"systemd",path:null,controllers:["memory"],cpuWeight:null,memoryMaxMb:Math.round(r/$t),swapMaxMb:Mc,systemctl:Xo(e),procRoot:e.BOSTRAT_PROC_ROOT||"/proc"}}function ns(e=Ge){let t=`nice ${Jo} floor on every box`;if(!e)return`${t}; cgroup ceiling not probed yet`;if(e.available&&e.backend==="systemd")return`${t}; memory ceiling on each box's tmux-spawn scope, set through the systemd user manager (MemoryMax ${e.memoryMaxMb} MB, MemorySwapMax ${e.swapMaxMb} MB)`;if(e.available){let n=[];return e.cpuWeight!=null&&n.push(`cpu.weight ${e.cpuWeight}`),e.memoryMaxMb!=null&&n.push(`memory.max ${e.memoryMaxMb} MB`),`${t}; cgroup ceiling at ${e.path} (${n.join(", ")})`}return`${t}; cgroup ceiling unavailable \u2014 ${e.reason}`}var Oc,Jo,Yo,Rc,Nc,Ic,Mc,$t,Ge,Xo,nr=R(()=>{Oc=Ec(Ac),Jo=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),Yo=50,Rc=768,Nc="bostrat-boxes",Ic=4096,Mc=512,$t=1024*1024;Ge=null;Xo=(e=process.env)=>e.BOSTRAT_SYSTEMCTL_BIN||"systemctl"});import{execFile as Lc}from"node:child_process";import{promisify as Fc}from"node:util";import ss from"node:fs";import Uc from"node:os";function is(e){return`/tmp/tmux-${e}/default`}function Wc({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=is(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function or(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await zc(e,{loginShell:t});return r===as?!0:r===rr?!1:n}async function zc(e,{loginShell:t=!1,timeoutMs:n=Kc}={}){if(!e)return rr;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await Hc(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),as}catch(s){return s?.killed||s?.signal?os:s?.code===1||s?.code===127?rr:os}}var Hc,$h,rs,vh,kh,Ah,Eh,Oh,as,rr,os,Kc,Zt,Rh,Nh,Ih,Mh,Ph,Dh,Vn=R(()=>{Lt();Wn();zn();Yn();Po();Wo();Go();Gn();Ft();qo();nr();Ae();Hc=Fc(Lc),$h=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";rs=typeof process.getuid=="function"?process.getuid():0,vh=Wc({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return ss.existsSync(is(rs))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:rs}),kh=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Ah=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Eh=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),Oh=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);as="present",rr="absent",os="unknown",Kc=5e3;Zt={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"},Rh=(()=>{try{let e=Uc.homedir();if(e&&ss.existsSync(e))return e}catch{}return"/"})(),Nh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Ih=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Mh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Ph=Number(process.env.BOSTRAT_BOX_COLS)||120,Dh=Number(process.env.BOSTRAT_BOX_ROWS)||40});var Is={};En(Is,{NODE_IMAGE:()=>cr,commandPlan:()=>Os,flyToml:()=>Es,flyWizard:()=>ml,parseFlyFlags:()=>Rs,stageConfig:()=>Ns});import ar from"node:fs";import Re from"node:path";import cl from"node:os";import ll from"node:readline/promises";import{execFile as ul}from"node:child_process";import{createRequire as dl}from"node:module";import{randomUUID as fl}from"node:crypto";function Es({app:e,region:t,nodeName:n=e,planeUrl:r=As,image:o=cr}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
52
+ `});import $t from"node:fs/promises";import Zt from"node:os";import ze from"node:path";import{execFile as Ec}from"node:child_process";import{promisify as Oc}from"node:util";function Qo(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function es(e=process.env){let t=String(e.BOSTRAT_BOX_CGROUPS??"").trim().toLowerCase();return["1","on","true","yes"].includes(t)?"on":["0","off","false","no"].includes(t)?"off":"auto"}function Dc(e=process.env){let t=es(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function ts(e=Zt.totalmem()){return Math.max(e-Nc*vt,Math.floor(e/2))}function jc(e=Zt.totalmem(),t=process.env){let n=Number(t.BOSTRAT_BOX_MEMORY_MAX_MB);return Number.isFinite(n)&&n>=256?Math.floor(n)*vt:Math.min(Mc*vt,ts(e))}function Cc(e=process.env){return ze.join(Qo(e),Ic)}async function Bc(e){return(await $t.readFile(e,"utf8")).trim()}async function ns({env:e=process.env,totalBytes:t=Zt.totalmem(),force:n=!1,platform:r=process.platform}={}){if(!n&&!Dc(e))return Ge=es(e)==="off"?{available:!1,reason:"disabled (BOSTRAT_BOX_CGROUPS=0)"}:await Lc({env:e,totalBytes:t,platform:r}),Ge;let o=Qo(e),s=Cc(e);try{let a;try{a=(await Bc(ze.join(o,"cgroup.controllers"))).split(/\s+/).filter(Boolean)}catch(d){throw new Error(`no cgroup v2 tree at ${o} (${d?.code||d?.message||d})`)}let l=["cpu","memory"].filter(d=>a.includes(d));if(!l.length)throw new Error(`cgroup v2 at ${o} offers neither cpu nor memory (controllers: ${a.join(" ")||"none"})`);await $t.mkdir(s,{recursive:!0});let h=`+${l.join(" +")}`;for(let d of[ze.join(o,"cgroup.subtree_control"),ze.join(s,"cgroup.subtree_control")])try{await $t.writeFile(d,h)}catch(g){throw new Error(`cannot enable ${h} in ${d} (${g?.code||g?.message||g})`)}let m=ts(t);l.includes("cpu")&&await $t.writeFile(ze.join(s,"cpu.weight"),String(Xo)),l.includes("memory")&&await $t.writeFile(ze.join(s,"memory.max"),String(m)),Ge={available:!0,backend:"cgroupfs",path:s,controllers:l,cpuWeight:l.includes("cpu")?Xo:null,memoryMaxMb:l.includes("memory")?Math.round(m/vt):null}}catch(a){Ge={available:!1,reason:a?.message||String(a)}}return Ge}async function Lc({env:e=process.env,totalBytes:t=Zt.totalmem(),platform:n=process.platform}={}){if(n!=="linux")return{available:!1,reason:`not a Fly/container node, and no systemd on ${n}`};try{await Rc(Jo(e),["--user","show","--property=Version","--value"],{timeout:3e3})}catch(o){return{available:!1,reason:`not a Fly/container node, and no systemd user manager to ask (${String(o?.stderr||o?.code||o?.message||o).trim().split(`
53
+ `)[0]})`}}let r=jc(t,e);return{available:!0,backend:"systemd",path:null,controllers:["memory"],cpuWeight:null,memoryMaxMb:Math.round(r/vt),swapMaxMb:Pc,systemctl:Jo(e),procRoot:e.BOSTRAT_PROC_ROOT||"/proc"}}function rs(e=Ge){let t=`nice ${Zo} floor on every box`;if(!e)return`${t}; cgroup ceiling not probed yet`;if(e.available&&e.backend==="systemd")return`${t}; memory ceiling on each box's tmux-spawn scope, set through the systemd user manager (MemoryMax ${e.memoryMaxMb} MB, MemorySwapMax ${e.swapMaxMb} MB)`;if(e.available){let n=[];return e.cpuWeight!=null&&n.push(`cpu.weight ${e.cpuWeight}`),e.memoryMaxMb!=null&&n.push(`memory.max ${e.memoryMaxMb} MB`),`${t}; cgroup ceiling at ${e.path} (${n.join(", ")})`}return`${t}; cgroup ceiling unavailable \u2014 ${e.reason}`}var Rc,Zo,Xo,Nc,Ic,Mc,Pc,vt,Ge,Jo,rr=R(()=>{Rc=Oc(Ec),Zo=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),Xo=50,Nc=768,Ic="bostrat-boxes",Mc=4096,Pc=512,vt=1024*1024;Ge=null;Jo=(e=process.env)=>e.BOSTRAT_SYSTEMCTL_BIN||"systemctl"});import{execFile as Fc}from"node:child_process";import{promisify as Uc}from"node:util";import is from"node:fs";import Hc from"node:os";function as(e){return`/tmp/tmux-${e}/default`}function Kc({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=as(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function sr(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Gc(e,{loginShell:t});return r===cs?!0:r===or?!1:n}async function Gc(e,{loginShell:t=!1,timeoutMs:n=zc}={}){if(!e)return or;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await Wc(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),cs}catch(s){return s?.killed||s?.signal?ss:s?.code===1||s?.code===127?or:ss}}var Wc,Ah,os,kh,Eh,Oh,Rh,Nh,cs,or,ss,zc,Qt,Ih,Mh,Ph,Dh,jh,Ch,qn=R(()=>{Ut();Kn();Gn();Xn();jo();zo();Vo();Vn();Ht();Yo();rr();ke();Wc=Uc(Fc),Ah=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";os=typeof process.getuid=="function"?process.getuid():0,kh=Kc({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return is.existsSync(as(os))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:os}),Eh=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Oh=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Rh=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),Nh=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);cs="present",or="absent",ss="unknown",zc=5e3;Qt={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"},Ih=(()=>{try{let e=Hc.homedir();if(e&&is.existsSync(e))return e}catch{}return"/"})(),Mh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Ph=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Dh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,jh=Number(process.env.BOSTRAT_BOX_COLS)||120,Ch=Number(process.env.BOSTRAT_BOX_ROWS)||40});var Ms={};En(Ms,{NODE_IMAGE:()=>lr,commandPlan:()=>Rs,flyToml:()=>Os,flyWizard:()=>gl,parseFlyFlags:()=>Ns,stageConfig:()=>Is});import cr from"node:fs";import Re from"node:path";import ll from"node:os";import ul from"node:readline/promises";import{execFile as dl}from"node:child_process";import{createRequire as pl}from"node:module";import{randomUUID as fl}from"node:crypto";function Os({app:e,region:t,nodeName:n=e,planeUrl:r=Es,image:o=lr}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
54
54
  # Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
55
55
  # No [http_service] and none should be added: the node dials OUT to the plane;
56
56
  # nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
@@ -90,25 +90,25 @@ swap_size_mb = 1024
90
90
  # Scale later with: fly scale memory 4096 -a ${e}
91
91
  size = "shared-cpu-2x"
92
92
  memory = "2gb"
93
- `}function Os({app:e,org:t,region:n,sizeGb:r,token:o,dir:s}){let a=[`BOSTRAT_PLANE_TOKEN=${o}`];return[{argv:["apps","create",e,"-o",t],display:`fly apps create ${e} -o ${t}`,tolerate:/already|taken|exists/i},{argv:["volumes","create","node_data","-a",e,"-r",n,"-s",String(r),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${r} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted> via stdin`,stdin:a.join(`
93
+ `}function Rs({app:e,org:t,region:n,sizeGb:r,token:o,dir:s}){let a=[`BOSTRAT_PLANE_TOKEN=${o}`];return[{argv:["apps","create",e,"-o",t],display:`fly apps create ${e} -o ${t}`,tolerate:/already|taken|exists/i},{argv:["volumes","create","node_data","-a",e,"-r",n,"-s",String(r),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${r} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted> via stdin`,stdin:a.join(`
94
94
  `)+`
95
- `},{argv:["deploy",s,"-c",Re.join(s,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${s} -c ${Re.join(s,"fly.toml")} -a ${e} --ha=false`}]}function Rs(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--image":"image"};for(let r=0;r<e.length;r++){let 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[s,...a]=o.split("=");n[s]?t[n[s]]=a.join("="):s==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function Ns({app:e,dest:t,toml:n}){let r=t||Re.join(cl.homedir(),".bostrat","fly",e);ar.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])ar.rmSync(Re.join(r,o),{recursive:!0,force:!0});return ar.writeFileSync(Re.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function hl({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await en(["orgs","list","--json"],{exec:n}),s=JSON.parse(o),a=Array.isArray(s)?s.map(l=>l.Slug||l.slug).filter(Boolean):Object.keys(s);if(a.length===1)return t.write(`Org: ${a[0]} (your only org)
96
- `),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 ml({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:o}={}){let s=Rs(e),a=ll.createInterface({input:t,output:n}),l=async(_,E)=>(await a.question(E?`${_} [${E}]: `:`${_}: `)).trim()||E||"",h=_=>(a.close(),_);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
95
+ `},{argv:["deploy",s,"-c",Re.join(s,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${s} -c ${Re.join(s,"fly.toml")} -a ${e} --ha=false`}]}function Ns(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--image":"image"};for(let r=0;r<e.length;r++){let 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[s,...a]=o.split("=");n[s]?t[n[s]]=a.join("="):s==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function Is({app:e,dest:t,toml:n}){let r=t||Re.join(ll.homedir(),".bostrat","fly",e);cr.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])cr.rmSync(Re.join(r,o),{recursive:!0,force:!0});return cr.writeFileSync(Re.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function ml({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await tn(["orgs","list","--json"],{exec:n}),s=JSON.parse(o),a=Array.isArray(s)?s.map(l=>l.Slug||l.slug).filter(Boolean):Object.keys(s);if(a.length===1)return t.write(`Org: ${a[0]} (your only org)
96
+ `),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 gl({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:o}={}){let s=Ns(e),a=ul.createInterface({input:t,output:n}),l=async(_,E)=>(await a.question(E?`${_} [${E}]: `:`${_}: `)).trim()||E||"",h=_=>(a.close(),_);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
97
97
  bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
98
98
 
99
- `);try{await en(["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"),h(1)}try{let{stdout:_}=await en(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${_.trim()}
100
- `)}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"),h(1)}let m=await hl({ask:l,output:n,exec:r,flag:s.org}),d=s.app||await l("App name",`bostrat-node-${fl().slice(0,4)}`),g=s.region||await l("Region (see `fly platform regions`)","iad"),v=s.sizeGb||Number(await l("Volume size GB (logins + repos live here)","10"))||10,y=s.name||d,b=s.planeUrl||As,I=s.token||await l("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!I)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.
101
- `),h(1);let S=s.image||cr,{dir:N}=Ns({app:d,dest:o,toml:Es({app:d,region:g,nodeName:y,planeUrl:b,image:S})});n.write(`
99
+ `);try{await tn(["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"),h(1)}try{let{stdout:_}=await tn(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${_.trim()}
100
+ `)}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"),h(1)}let m=await ml({ask:l,output:n,exec:r,flag:s.org}),d=s.app||await l("App name",`bostrat-node-${fl().slice(0,4)}`),g=s.region||await l("Region (see `fly platform regions`)","iad"),v=s.sizeGb||Number(await l("Volume size GB (logins + repos live here)","10"))||10,y=s.name||d,b=s.planeUrl||Es,I=s.token||await l("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!I)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.
101
+ `),h(1);let S=s.image||lr,{dir:N}=Is({app:d,dest:o,toml:Os({app:d,region:g,nodeName:y,planeUrl:b,image:S})});n.write(`
102
102
  wrote ${Re.join(N,"fly.toml")} \u2014 deploys the prebuilt node image ${S}
103
103
  (claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
104
104
 
105
105
  Plan (your flyctl, your org, your bill):
106
- `);let k=Os({app:d,org:m,region:g,sizeGb:v,token:I,dir:N});for(let _ of k)n.write(` $ ${_.display}
106
+ `);let A=Rs({app:d,org:m,region:g,sizeGb:v,token:I,dir:N});for(let _ of A)n.write(` $ ${_.display}
107
107
  `);if(!s.yes&&(await l(`
108
108
  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.
109
- `),h(1);for(let _ of k){n.write(`
109
+ `),h(1);for(let _ of A){n.write(`
110
110
  \u2192 ${_.display}
111
- `);try{let{stdout:E,stderr:O}=await en(_.argv,{stdin:_.stdin,exec:r}),x=`${E||""}${O||""}`.trim();x&&n.write(x.split(`
111
+ `);try{let{stdout:E,stderr:O}=await tn(_.argv,{stdin:_.stdin,exec:r}),x=`${E||""}${O||""}`.trim();x&&n.write(x.split(`
112
112
  `).map(M=>` ${M}`).join(`
113
113
  `)+`
114
114
  `)}catch(E){let O=`${E?.stdout||""}${E?.stderr||""}${E?.message||""}`;if(_.tolerate&&_.tolerate.test(O)){n.write(` (already exists \u2014 continuing)
@@ -123,18 +123,18 @@ Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u201
123
123
  redeploy: fly deploy ${N} -c ${Re.join(N,"fly.toml")} -a ${d} --ha=false
124
124
  Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
125
125
  boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
126
- `),h(0)}var As,pl,cr,en,Ms=R(()=>{As="wss://plane.bostrat.ai/v1/node",pl=dl(import.meta.url)("../package.json").version,cr=`ghcr.io/globocodes/bostrat-node:${pl}`;en=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let s=ul("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(a,l,h)=>a?o(Object.assign(a,{stdout:l,stderr:h})):r({stdout:l,stderr:h}));t!=null&&s.stdin?.end(t)})});function Ps(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!wl.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 yl(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:Ps(o.from,"from",n),toMs:Ps(o.to,"to",n)}))}return t}var gl,wl,lm,um,Ds=R(()=>{gl={"claude-opus-5-5":[{from:null,to:null,input:4,output:20,cacheWrite:8,cacheRead:.2,cacheReadX:.05,fast:{input:8,output:40,cacheWrite:16,cacheRead:.4},verifiedAt:"2026-09-28",note:"verified 2026-09-28 against platform.claude.com/docs/en/about-claude/pricing: $4/$20, 1h cache write $8 (2\xD7), cache hits $0.20 (0.05\xD7 \u2014 footnote 2), fast $8/$40; added before any fleet turn was recorded."}],"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-10-05",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; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"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-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"claude-sonnet-5-5":[{from:null,to:"2026-10-11",input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.20 (0.1\xD7 \u2014 footnote 2 then named Opus 5.5 only). Superseded 2026-10-12 when the page moved Sonnet 5.5 hits to 0.05\xD7 (window below)."},{from:"2026-10-12",to:null,input:2,output:10,cacheWrite:4,cacheRead:.1,cacheReadX:.05,verifiedAt:"2026-10-12",note:"verified 2026-10-12 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.10 (0.05\xD7 \u2014 footnote 2 now names Opus 5.5 AND Sonnet 5.5; the prompt-caching multiplier table agrees)."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",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; re-verified 2026-10-05 (live pricing page, footnote 3 still published)."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-haiku-5-5":[{from:null,to:null,input:.1,output:.5,cacheWrite:.2,cacheRead:.01,long:{over:1e5,input:.5,output:2.5,cacheWrite:1,cacheRead:.05},verifiedAt:"2026-10-19",note:"verified 2026-10-19 against platform.claude.com/docs/en/about-claude/pricing: prompts up to 100,000 tokens $0.10/$0.50, 1h cache write $0.20 (2\xD7), cache hits $0.01 (0.1\xD7); prompts over 100,000 tokens (the `long` variant) $0.50/$2.50, 1h cache write $1 (2\xD7), cache hits $0.05 (0.1\xD7); added before any fleet turn was recorded."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-fable-5-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-09-07",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend then; re-verified 2026-10-05 (live pricing page: $10/$50, 1h write $20, hits $1 at 0.1\xD7)."}],"gpt-5.5-pro":[{from:null,to:null,input:30,output:180,cacheWrite:30,cacheRead:30,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $30 in / $180 out, no cached-input or cache-write price published (both priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5-cyber":[{from:null,to:null,input:12.5,output:75,cacheWrite:12.5,cacheRead:1.25,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing, Cyber models table): $12.50 in / $1.25 cached / $75 out, no cache-write price published (priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-10-05",note:"verified 2026-07-03, re-verified 2026-08-17 and 2026-10-05 (developers.openai.com pricing: $5 / $0.50 cached / $30); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-10-12",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL); re-verified 2026-10-12 (live pricing page: $4 / $0.40 cached / $5 cache writes / $20, promo note unchanged)."}],"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-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (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-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-09-07",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed)."}],"gpt-6.1-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.10 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.20 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-luna":[{from:null,to:null,input:.1,output:.5,cacheWrite:.125,cacheRead:.01,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $0.10 in / $0.01 cached / $0.125 cache writes (1.25\xD7) / $0.50 out; added before any fleet turn was recorded."}]},wl=/^\d{4}-\d{2}-\d{2}$/;lm=yl(gl),um=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var js=R(()=>{Ds()});import Cs from"node:fs/promises";import Fs from"node:path";import bl from"node:os";function Hs(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Ws(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Ks(e){let t=new Date(Hs(e));return t.setDate(t.getDate()+7),t.getTime()}function zs(e){let t=new Date(Ws(e));return t.setMonth(t.getMonth()+1),t.getTime()}function $l(e=Date.now()){for(let[t,n]of Object.entries(Tl)){let r=n.startOf(e);if(r!==tn[t]){tn[t]=r;for(let o of lr.values())o[t]=0;for(let o of Bs)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&Bs.delete(o)}}}function vl(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 s of["weeklyUsd","monthlyUsd"]){let a=r?.[s];if(a==null||a==="")continue;let l=Number(a);if(!Number.isFinite(l)||l<=0)throw new Error(`${n}.${s} must be a positive number or null`);o[s]=l}Object.keys(o).length&&(t[n]=o)}return t}async function Gs(e,{source:t="local",updatedAt:n=Date.now()}={}){qe={caps:vl(e),updatedAt:n,source:t};try{await Cs.mkdir(Us,{recursive:!0}),await Cs.writeFile(Sl(),JSON.stringify(qe,null,2))}catch{}return kl()}function kl(e=Date.now()){$l(e);let t=new Set([...lr.keys(),...Object.keys(qe?.caps||{})]),n={};for(let r of t){let o=lr.get(r);n[r]={weeklyUsd:Ls(o?.weekly||0),monthlyUsd:Ls(o?.monthly||0)}}return{caps:qe?.caps||{},configured:!!qe,seeded:xl,updatedAt:qe?.updatedAt??null,spent:n,windows:{weekly:{start:tn.weekly,resetsAt:Ks(e)},monthly:{start:tn.monthly,resetsAt:zs(e)}},warnPct:_l}}var Us,Sl,_l,Tl,qe,xl,tn,lr,Bs,Ls,Vs=R(()=>{Yt();js();Us=process.env.BOSTRAT_STATE_DIR||Fs.join(process.env.HOME||bl.tmpdir(),".bostrat"),Sl=()=>Fs.join(Us,"usage-caps.json"),_l=.8;Tl={weekly:{startOf:Hs,nextStart:Ks,capKey:"weeklyUsd"},monthly:{startOf:Ws,nextStart:zs,capKey:"monthlyUsd"}},qe=null,xl=!1,tn={weekly:0,monthly:0},lr=new Map,Bs=new Set;Ls=e=>Math.round(e*1e4)/1e4});function Js(){return Object.fromEntries(Object.entries(qs.tokens).filter(([,e])=>Xs(e)).map(([e,t])=>[e,t.access]))}function Zs(){let e={};for(let[t,n]of Object.entries(qs.tokens)){let r=Xs(n)?"set":n.needsLogin?"needs-login":n.refresh?"refreshing":"needs-login";e[t]={state:r,source:"broker",...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.obtainedAt?{obtainedAt:n.obtainedAt}:{},refreshable:!!n.refresh,...n.lastError?{error:String(n.lastError).slice(0,200)}:{}}}for(let[t,n]of Ys)e[t]||(e[t]={state:"login-pending",source:"broker",startedAt:n.startedAt,redirectUri:n.redirectUri});return e}var xm,$m,qs,Ys,Xs,Qs,ei=R(()=>{xm=10*6e4,$m=5*6e4,qs={tokens:{},clients:{}},Ys=new Map,Xs=e=>typeof e?.access=="string"&&e.access&&!e.needsLogin&&(e.expiresAt==null||e.expiresAt>Date.now());Qs=()=>[...Ys.keys()]});import Al from"node:fs";import we from"node:fs/promises";import ii from"node:os";import Xe from"node:path";function ci(e){return fr.add(e),()=>fr.delete(e)}function nn(){return{entries:structuredClone(dr),at:Date.now()}}function Ml(e,t,n){if(e.transport==="http"){let o=Object.fromEntries(Object.entries(e.headers||{}).map(([s,a])=>[s,Ye(a,t)]));return{...n==="claude"?{type:"http"}:{},url:Ye(e.url,t),...Object.keys(o).length?{headers:o}:{}}}let r=Object.fromEntries((e.env||[]).map(o=>[o,t[o]]));return{...n==="claude"?{type:"stdio"}:{},command:e.command,args:(e.args||[]).map(o=>Ye(o,t)),...Object.keys(r).length?{env:r}:{}}}function Pl(e,t){let n=[`[mcp_servers.${e.name}]`];if(e.transport==="http"){n.push(`url = ${At(Ye(e.url,t))}`);let r=Object.fromEntries(Object.entries(e.headers||{}).map(([o,s])=>[o,Ye(s,t)]));Object.keys(r).length&&n.push(`http_headers = ${ni(r)}`)}else{n.push(`command = ${At(e.command)}`),n.push(`args = [${(e.args||[]).map(o=>At(Ye(o,t))).join(", ")}]`);let r=Object.fromEntries((e.env||[]).map(o=>[o,t[o]]));Object.keys(r).length&&n.push(`env = ${ni(r)}`)}return n.join(`
126
+ `),h(0)}var Es,hl,lr,tn,Ps=R(()=>{Es="wss://plane.bostrat.ai/v1/node",hl=pl(import.meta.url)("../package.json").version,lr=`ghcr.io/globocodes/bostrat-node:${hl}`;tn=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let s=dl("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(a,l,h)=>a?o(Object.assign(a,{stdout:l,stderr:h})):r({stdout:l,stderr:h}));t!=null&&s.stdin?.end(t)})});function Ds(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!yl.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 bl(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:Ds(o.from,"from",n),toMs:Ds(o.to,"to",n)}))}return t}var wl,yl,dm,pm,js=R(()=>{wl={"claude-opus-5-5":[{from:null,to:null,input:4,output:20,cacheWrite:8,cacheRead:.2,cacheReadX:.05,fast:{input:8,output:40,cacheWrite:16,cacheRead:.4},verifiedAt:"2026-09-28",note:"verified 2026-09-28 against platform.claude.com/docs/en/about-claude/pricing: $4/$20, 1h cache write $8 (2\xD7), cache hits $0.20 (0.05\xD7 \u2014 footnote 2), fast $8/$40; added before any fleet turn was recorded."}],"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-10-05",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; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"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-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"claude-sonnet-5-5":[{from:null,to:"2026-10-11",input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.20 (0.1\xD7 \u2014 footnote 2 then named Opus 5.5 only). Superseded 2026-10-12 when the page moved Sonnet 5.5 hits to 0.05\xD7 (window below)."},{from:"2026-10-12",to:null,input:2,output:10,cacheWrite:4,cacheRead:.1,cacheReadX:.05,verifiedAt:"2026-10-12",note:"verified 2026-10-12 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.10 (0.05\xD7 \u2014 footnote 2 now names Opus 5.5 AND Sonnet 5.5; the prompt-caching multiplier table agrees)."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",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; re-verified 2026-10-05 (live pricing page, footnote 3 still published)."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-haiku-5-5":[{from:null,to:null,input:.1,output:.5,cacheWrite:.2,cacheRead:.01,long:{over:1e5,input:.5,output:2.5,cacheWrite:1,cacheRead:.05},verifiedAt:"2026-10-19",note:"verified 2026-10-19 against platform.claude.com/docs/en/about-claude/pricing: prompts up to 100,000 tokens $0.10/$0.50, 1h cache write $0.20 (2\xD7), cache hits $0.01 (0.1\xD7); prompts over 100,000 tokens (the `long` variant) $0.50/$2.50, 1h cache write $1 (2\xD7), cache hits $0.05 (0.1\xD7); added before any fleet turn was recorded."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-fable-5-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-10-26",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page); re-verified 2026-10-26 (live pricing page, footnote 1 unchanged)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend then; re-verified 2026-10-05 (live pricing page: $10/$50, 1h write $20, hits $1 at 0.1\xD7)."}],"gpt-5.5-pro":[{from:null,to:null,input:30,output:180,cacheWrite:30,cacheRead:30,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $30 in / $180 out, no cached-input or cache-write price published (both priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5-cyber":[{from:null,to:null,input:12.5,output:75,cacheWrite:12.5,cacheRead:1.25,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing, Cyber models table): $12.50 in / $1.25 cached / $75 out, no cache-write price published (priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-10-05",note:"verified 2026-07-03, re-verified 2026-08-17 and 2026-10-05 (developers.openai.com pricing: $5 / $0.50 cached / $30); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-10-12",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL); re-verified 2026-10-12 (live pricing page: $4 / $0.40 cached / $5 cache writes / $20, promo note unchanged)."}],"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-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (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-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-10-26",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed); re-verified 2026-10-26 (live pricing page: $10 / $1 cached / $12.50 30m cache writes / $50, fast $20/$100 \u2014 the page now also lists a 12h cache-write tier at 2.5\xD7 input, not modelled: codex reports no cache-write class)."}],"gpt-6.1-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.10 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.20 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-luna":[{from:null,to:null,input:.1,output:.5,cacheWrite:.125,cacheRead:.01,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $0.10 in / $0.01 cached / $0.125 cache writes (1.25\xD7) / $0.50 out; added before any fleet turn was recorded."}]},yl=/^\d{4}-\d{2}-\d{2}$/;dm=bl(wl),pm=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var Cs=R(()=>{js()});import Bs from"node:fs/promises";import Us from"node:path";import Sl from"node:os";function Ws(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Ks(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function zs(e){let t=new Date(Ws(e));return t.setDate(t.getDate()+7),t.getTime()}function Gs(e){let t=new Date(Ks(e));return t.setMonth(t.getMonth()+1),t.getTime()}function vl(e=Date.now()){for(let[t,n]of Object.entries(xl)){let r=n.startOf(e);if(r!==nn[t]){nn[t]=r;for(let o of ur.values())o[t]=0;for(let o of Ls)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&Ls.delete(o)}}}function Al(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 s of["weeklyUsd","monthlyUsd"]){let a=r?.[s];if(a==null||a==="")continue;let l=Number(a);if(!Number.isFinite(l)||l<=0)throw new Error(`${n}.${s} must be a positive number or null`);o[s]=l}Object.keys(o).length&&(t[n]=o)}return t}async function Vs(e,{source:t="local",updatedAt:n=Date.now()}={}){qe={caps:Al(e),updatedAt:n,source:t};try{await Bs.mkdir(Hs,{recursive:!0}),await Bs.writeFile(_l(),JSON.stringify(qe,null,2))}catch{}return kl()}function kl(e=Date.now()){vl(e);let t=new Set([...ur.keys(),...Object.keys(qe?.caps||{})]),n={};for(let r of t){let o=ur.get(r);n[r]={weeklyUsd:Fs(o?.weekly||0),monthlyUsd:Fs(o?.monthly||0)}}return{caps:qe?.caps||{},configured:!!qe,seeded:$l,updatedAt:qe?.updatedAt??null,spent:n,windows:{weekly:{start:nn.weekly,resetsAt:zs(e)},monthly:{start:nn.monthly,resetsAt:Gs(e)}},warnPct:Tl}}var Hs,_l,Tl,xl,qe,$l,nn,ur,Ls,Fs,qs=R(()=>{Jt();Cs();Hs=process.env.BOSTRAT_STATE_DIR||Us.join(process.env.HOME||Sl.tmpdir(),".bostrat"),_l=()=>Us.join(Hs,"usage-caps.json"),Tl=.8;xl={weekly:{startOf:Ws,nextStart:zs,capKey:"weeklyUsd"},monthly:{startOf:Ks,nextStart:Gs,capKey:"monthlyUsd"}},qe=null,$l=!1,nn={weekly:0,monthly:0},ur=new Map,Ls=new Set;Fs=e=>Math.round(e*1e4)/1e4});function Zs(){return Object.fromEntries(Object.entries(Ys.tokens).filter(([,e])=>Js(e)).map(([e,t])=>[e,t.access]))}function Qs(){let e={};for(let[t,n]of Object.entries(Ys.tokens)){let r=Js(n)?"set":n.needsLogin?"needs-login":n.refresh?"refreshing":"needs-login";e[t]={state:r,source:"broker",...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.obtainedAt?{obtainedAt:n.obtainedAt}:{},refreshable:!!n.refresh,...n.lastError?{error:String(n.lastError).slice(0,200)}:{}}}for(let[t,n]of Xs)e[t]||(e[t]={state:"login-pending",source:"broker",startedAt:n.startedAt,redirectUri:n.redirectUri});return e}var vm,Am,Ys,Xs,Js,ei,ti=R(()=>{vm=10*6e4,Am=5*6e4,Ys={tokens:{},clients:{}},Xs=new Map,Js=e=>typeof e?.access=="string"&&e.access&&!e.needsLogin&&(e.expiresAt==null||e.expiresAt>Date.now());ei=()=>[...Xs.keys()]});import El from"node:fs";import ye from"node:fs/promises";import ai from"node:os";import Xe from"node:path";function li(e){return fr.add(e),()=>fr.delete(e)}function rn(){return{entries:structuredClone(pr),at:Date.now()}}function Pl(e,t,n){if(e.transport==="http"){let o=Object.fromEntries(Object.entries(e.headers||{}).map(([s,a])=>[s,Ye(a,t)]));return{...n==="claude"?{type:"http"}:{},url:Ye(e.url,t),...Object.keys(o).length?{headers:o}:{}}}let r=Object.fromEntries((e.env||[]).map(o=>[o,t[o]]));return{...n==="claude"?{type:"stdio"}:{},command:e.command,args:(e.args||[]).map(o=>Ye(o,t)),...Object.keys(r).length?{env:r}:{}}}function Dl(e,t){let n=[`[mcp_servers.${e.name}]`];if(e.transport==="http"){n.push(`url = ${Et(Ye(e.url,t))}`);let r=Object.fromEntries(Object.entries(e.headers||{}).map(([o,s])=>[o,Ye(s,t)]));Object.keys(r).length&&n.push(`http_headers = ${ri(r)}`)}else{n.push(`command = ${Et(e.command)}`),n.push(`args = [${(e.args||[]).map(o=>Et(Ye(o,t))).join(", ")}]`);let r=Object.fromEntries((e.env||[]).map(o=>[o,t[o]]));Object.keys(r).length&&n.push(`env = ${ri(r)}`)}return n.join(`
127
127
  `)+`
128
128
 
129
- `}function li(e){let t=[],n=`(?:[A-Za-z0-9_-]+|"[^"
129
+ `}function ui(e){let t=[],n=`(?:[A-Za-z0-9_-]+|"[^"
130
130
  ]*"|'[^'
131
- ]*')`,r=new RegExp(`^[ \\t]*\\[\\[?[ \\t]*${n}(?:[ \\t]*\\.[ \\t]*${n})*[ \\t]*\\]\\]?[ \\t]*(?:#.*)?$`,"gm"),o=0,s;for(;s=r.exec(e);)s.index===0&&o===0||(t.push(e.slice(o,s.index)),o=s.index);return t.push(e.slice(o)),t}function ui(e){let t=/^[ \t]*\[\s*mcp_servers\s*\.\s*(?:"([^"]+)"|([A-Za-z0-9_-]+))\s*[\].]/.exec(e);return t?t[1]??t[2]:null}function ri(e){return new Set(li(String(e||"")).map(ui).filter(Boolean))}function Dl(e,t,n){let r=String(e||""),o=new Set,s="";for(let a of li(r)){let l=ui(a);if(l&&t.has(l)){o.has(l)||(s+=t.get(l),o.add(l));continue}l&&n.has(l)||(s+=a)}for(let[a,l]of t)o.has(a)||(s&&!s.endsWith(`
131
+ ]*')`,r=new RegExp(`^[ \\t]*\\[\\[?[ \\t]*${n}(?:[ \\t]*\\.[ \\t]*${n})*[ \\t]*\\]\\]?[ \\t]*(?:#.*)?$`,"gm"),o=0,s;for(;s=r.exec(e);)s.index===0&&o===0||(t.push(e.slice(o,s.index)),o=s.index);return t.push(e.slice(o)),t}function di(e){let t=/^[ \t]*\[\s*mcp_servers\s*\.\s*(?:"([^"]+)"|([A-Za-z0-9_-]+))\s*[\].]/.exec(e);return t?t[1]??t[2]:null}function oi(e){return new Set(ui(String(e||"")).map(di).filter(Boolean))}function jl(e,t,n){let r=String(e||""),o=new Set,s="";for(let a of ui(r)){let l=di(a);if(l&&t.has(l)){o.has(l)||(s+=t.get(l),o.add(l));continue}l&&n.has(l)||(s+=a)}for(let[a,l]of t)o.has(a)||(s&&!s.endsWith(`
132
132
  `)&&(s+=`
133
133
  `),s&&!s.endsWith(`
134
134
 
135
135
  `)&&(s+=`
136
- `),s+=l);return s}async function jl(e){try{return await we.readFile(e,"utf8")}catch(t){if(t?.code==="ENOENT")return null;throw t}}async function pr(e,t){await we.mkdir(Xe.dirname(e),{recursive:!0});let n=`${e}.bostrat-${process.pid}.tmp`,r=384;try{r=(await we.stat(e)).mode&511}catch{}await we.writeFile(n,t,{mode:r}),await we.rename(n,e)}async function Cl(e,t,n,r){let o={},s=e==="claude"?No():e==="codex"?Io():Rl(),a=S=>{for(let N of t.keys())o[N]=S};if(e!=="claude"&&!Al.existsSync(Xe.dirname(s)))return a("cli-absent"),{managed:[],states:o};let l;try{l=await jl(s)}catch{return a("error"),{managed:n,states:o}}let h=new Set(n);if(e==="codex"){let S=ri(l??""),N=new Map;for(let[x,M]of t)S.has(x)&&!h.has(x)?o[x]="conflict":N.set(x,Pl(M,r));let k=new Set([...h].filter(x=>!t.has(x))),_=Dl(l??"",N,k);try{_!==(l??"")&&await pr(s,_)}catch{for(let x of N.keys())o[x]="error";return{managed:n,states:o}}for(let x of N.keys())o[x]="applied";let E=ri(l??""),O=new Set([...N.keys()].filter(x=>_!==(l??"")&&(!E.has(x)||!(l??"").includes(N.get(x)))));return{managed:[...N.keys()].sort(),states:o,wrote:O}}let m={};if(l!=null&&l.trim()){try{m=JSON.parse(l)}catch{return a("error"),{managed:n,states:o}}if(!m||typeof m!="object"||Array.isArray(m))return a("error"),{managed:n,states:o}}let d=m.mcpServers&&typeof m.mcpServers=="object"?{...m.mcpServers}:{},g=[];for(let[S,N]of t){if(Object.hasOwn(d,S)&&!h.has(S)){o[S]="conflict";continue}d[S]=Ml(N,r,e),g.push(S)}for(let S of h)t.has(S)||delete d[S];let v={...m,mcpServers:d};!Object.keys(d).length&&!m.mcpServers&&delete v.mcpServers;let y=JSON.stringify(m.mcpServers??{})!==JSON.stringify(d);try{y&&await pr(s,JSON.stringify(v,null,2))}catch{for(let S of g)o[S]="error";return{managed:n,states:o}}for(let S of g)o[S]="applied";let b=m.mcpServers&&typeof m.mcpServers=="object"?m.mcpServers:{},I=new Set(g.filter(S=>JSON.stringify(b[S]??null)!==JSON.stringify(d[S])));return{managed:g.sort(),states:o,wrote:I}}async function Bl(){let e=Ol(),t={};try{(await we.stat(e)).mode&63&&await we.chmod(e,384).catch(()=>{});let a=JSON.parse(await we.readFile(e,"utf8"));t=Object.fromEntries(Object.entries(a||{}).filter(([,l])=>typeof l=="string"&&l!==""))}catch{t={}}let r={...Js(),...t},o={};for(let s of Object.keys(r))o[s]=s in t?"file":"broker";return{values:r,sources:o}}function Ll(e){if(e?.transport!=="http")return null;for(let[t,n]of Object.entries(e.headers||{})){if(!/^authorization$/i.test(t))continue;let r=/\$\{([A-Za-z_][A-Za-z0-9_]{0,63})\}/.exec(String(n));if(r)return r[1]}return null}function Fl(e,t,n,r,o){let s={},a=Ll(e);for(let l of e.env||[])if(t[l]!=null){let h=n[l]==="broker"?r[l]:null;s[l]={state:"set",source:n[l],...h?.expiresAt?{expiresAt:h.expiresAt}:{},...h?{refreshable:!!h.refreshable}:{}}}else o.includes(l)?s[l]={state:"login-pending",source:"broker"}:r[l]?s[l]={state:"needs-login",source:"broker",...r[l].error?{error:r[l].error}:{}}:e.auth==="oauth"&&l===a?s[l]={state:"needs-login",source:"broker"}:s[l]={state:"missing"};return s}function di(e){return(Array.isArray(e)?e:[]).filter(t=>t&&Nl.test(t.name)&&(t.transport==="http"?typeof t.url=="string":typeof t.command=="string")).map(t=>t.auth==="oauth"?t:(({auth:n,...r})=>r)(t))}async function oi(){let{values:e,sources:t}=await Bl(),n=Zs(),r=Qs(),o=di(ue.entries),s={};for(let d of o){let g=Fl(d,e,t,n,r),v=Object.entries(g).filter(([,y])=>y.state!=="set").map(([y])=>y);s[d.name]={rev:Number(d.updatedAt)||0,clis:{},since:{},missingEnv:v,env:g,...d.auth==="oauth"?{auth:"oauth"}:{}}}let a={...ue.managed},l={...ue.since||{}},h=Date.now();for(let d of ur){let g=new Map(o.filter(b=>(b.clis||ur).includes(d)&&!s[b.name].missingEnv.length).map(b=>[b.name,b])),v=await Cl(d,g,ue.managed?.[d]??[],e);a[d]=v.managed;let y={...l[d]||{}};for(let[b,I]of Object.entries(v.states)){s[b].clis[d]=I;let S=s[b].rev;I==="applied"?((!y[b]||y[b].rev!==S)&&(y[b]={rev:S,at:v.wrote?.has(b)?h:Math.max(S,y[b]?.at??0)||h}),s[b].since[d]=y[b].at):delete y[b]}for(let b of Object.keys(y))g.has(b)||delete y[b];l[d]=y}for(let d of o){if(!s[d.name].missingEnv.length)continue;let v=Object.values(s[d.name].env).map(y=>y.state).includes("missing")?"missing-secret":"needs-login";for(let y of d.clis||ur)s[d.name].clis[y]=v}ue={...ue,managed:a,since:l},await Ul();let m=JSON.stringify(s)!==JSON.stringify(dr);if(dr=s,m)for(let d of fr)try{d(nn())}catch{}return nn()}async function Ul(){let e=JSON.stringify(ue,null,2);if(e!==si)try{await pr(El(),e),si=e}catch(t){console.error("[mcp-config] cache write failed:",t?.message||t)}}function Hl(){let e=ti.then(oi,oi);return ti=e.catch(()=>{}),e}function fi(e,{updatedAt:t=Date.now()}={}){return ue={...ue,entries:di(e),updatedAt:t},Hl()}var ai,El,Ol,Rl,ur,Nl,Il,ue,dr,ti,fr,Ye,At,ni,si,pi=R(()=>{Wn();zn();ei();ai=()=>process.env.BOSTRAT_STATE_DIR||Xe.join(process.env.HOME||ii.tmpdir(),".bostrat"),El=()=>Xe.join(ai(),"mcp-config.json"),Ol=()=>Xe.join(ai(),"mcp-env.json"),Rl=()=>Xe.join(ii.homedir(),".cursor","mcp.json"),ur=["claude","codex","cursor"],Nl=/^[a-z0-9][a-z0-9_-]{0,47}$/,Il=/\$\{([A-Za-z_][A-Za-z0-9_]{0,63})\}/g,ue={entries:[],updatedAt:null,managed:{claude:[],codex:[],cursor:[]},since:{}},dr={},ti=Promise.resolve(),fr=new Set;Ye=(e,t)=>String(e).replace(Il,(n,r)=>t[r]??"");At=e=>JSON.stringify(String(e)),ni=e=>`{ ${Object.entries(e).map(([t,n])=>`${At(t)} = ${At(n)}`).join(", ")} }`;si=null});import hi from"node:fs/promises";import wi from"node:path";import Wl from"node:os";function zl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("refresh-flow patch must be an object");let t={};for(let[n,r]of Object.entries(e)){if(!(n in hr))throw new Error(`unknown refresh-flow field "${n}" \u2014 fields: ${bi.join(", ")}`);if(r===null||r===""||r===void 0){t[n]=null;continue}switch(n){case"contextFull":case"limitHit":if(typeof r!="string"||!mi.includes(r))throw new Error(`${n} must be one of ${mi.join(", ")}`);t[n]=r;break;case"contextFullPct":{let o=Number(r);if(!Number.isFinite(o)||o<1||o>100)throw new Error("contextFullPct must be a number from 1 to 100");t[n]=Math.round(o);break}case"contextFullTokens":{let o=Number(r);if(!Number.isFinite(o)||o<=0)throw new Error("contextFullTokens must be a positive number of tokens or null");t[n]=Math.round(o);break}case"fallback":{if(typeof r!="object"||Array.isArray(r))throw new Error("fallback must be an object of provider \u2192 [providers]");let o={};for(let[s,a]of Object.entries(r)){if(!gi.test(s))throw new Error(`bad provider key "${s}" in fallback`);if(!Array.isArray(a)||a.some(h=>typeof h!="string"||!gi.test(h)))throw new Error(`fallback.${s} must be a list of provider keys`);let l=[...new Set(a.filter(h=>h!==s))];l.length&&(o[s]=l)}t[n]=Object.keys(o).length?o:null;break}default:throw new Error(`unknown refresh-flow field "${n}"`)}}return t}function Gl(e){let t={...hr};for(let n of bi){let r=e?.[n];r!=null&&(t[n]=r)}return t}function ql(){return Gl(Je?.flow)}function Si(){return{flow:ql(),configured:!!Je,source:Je?.source??null,updatedAt:Je?.updatedAt??null}}async function Yl(){try{await hi.mkdir(yi,{recursive:!0}),await hi.writeFile(Kl(),JSON.stringify(Je,null,2))}catch{}}function _i(e=null){for(let t of Vl)try{t(Si(),e)}catch{}}function Ti(e){_i({rejected:String(e||"rejected by the plane")})}async function xi(e,{source:t="plane",updatedAt:n=Date.now()}={}){return Je={flow:zl(e||{}),updatedAt:n,source:t},await Yl(),_i(),Si()}var yi,Kl,mi,hr,bi,gi,Je,Vl,$i=R(()=>{yi=process.env.BOSTRAT_STATE_DIR||wi.join(process.env.HOME||Wl.tmpdir(),".bostrat"),Kl=()=>wi.join(yi,"refresh-flow.json"),mi=["prompt","auto","off"],hr=Object.freeze({contextFull:"prompt",contextFullPct:75,contextFullTokens:null,limitHit:"prompt",fallback:null}),bi=Object.keys(hr),gi=/^[a-z][a-z0-9-]{0,31}$/;Je=null,Vl=new Set});var Ii={};En(Ii,{REMOVED_MARKER:()=>Sr,detectInstallKind:()=>et,detectProviderAuth:()=>Ni,maskToken:()=>br,readRemovedMarker:()=>Ri,startPlaneLink:()=>pu,updateCommandFor:()=>Ot,versionLt:()=>Qe});import Ze from"node:fs";import Et from"node:fs/promises";import Xl from"node:http";import K from"node:path";import on from"node:os";import{createRequire as Jl}from"node:module";import mr from"ws";function br(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function Ri(e=Sr){try{let t=JSON.parse(Ze.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function et({env:e=process.env,pkgDir:t=K.resolve(K.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ze.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(K.join(t,"..",".git"))?"git-checkout":"dev"}function Qe(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 s=(n[o]||0)-(r[o]||0);if(s)return s<0}return!1}function Ot(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 Ni({home:e=process.env.HOME||on.homedir(),env:t=process.env}={}){let n=r=>{try{return Ze.statSync(r),!0}catch{return!1}};return{claude:n(K.join(e,".claude",".credentials.json")),codex:n(K.join(t.CODEX_HOME||K.join(e,".codex"),"auth.json")),cursor:n(K.join(t.XDG_CONFIG_HOME||K.join(e,".config"),"cursor","auth.json"))}}function pu({url:e,token:t,nodeId:n=on.hostname(),name:r=on.hostname(),listTracks:o,detectAgents:s=null,onTracksTransferred:a=null,onTracksMoves:l=null,sampleMetrics:h=null,deliverySample:m=null,onHashKey:d=null,onViewBase:g=null,metricsMs:v=fu,onUpdateAvailable:y=null,onUpdatePolicy:b=null,onConflictProbe:I=null,restart:S=null,onRestarted:N=null,onHelloRefused:k=null,updatePolicy:_=null,installKind:E=et(),selfUrl:O=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:x=null,removedMarkerFile:M=Sr,onRemoved:Ie=null,onDegraded:rt=null,onRecovered:Me=null,onRefused:fn=null,onConnected:Nt=null,ingestMode:Pe=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:ot=su,unackedRetryMs:De=ou,pingMs:st=nu,deadLinkMs:P=Math.round(st*ru),maxInflightEvents:de=lu,httpTimeoutMs:fe=uu,fanoutActive:pe=null,fanoutBatchCap:it=du,stallBackoffMinMs:Ir=cu,fetchImpl:Mr=globalThis.fetch,log:T=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=pt(e);let Gi=O.replace(/^http/,"ws"),Pr=new Set,Dr=c=>{let f=typeof c.latestNodeVersion=="string"?c.latestNodeVersion:null;if(!(!(f&&te&&Qe(te,f))||Pr.has(f))){Pr.add(f),T.log(`[plane-link] bostrat-node ${f} is available (this node runs ${te}) \u2014 ${Ot(E)}`);try{y?.({current:te,latest:f,min:c.minNodeVersion??null,installKind:E,required:!!(c.minNodeVersion&&Qe(te,c.minNodeVersion))})}catch(p){T.error(`[plane-link] update notice failed: ${p?.message||p}`)}}},Se=new Map,_e=new Map,pn=K.join(yr,"plane-link","cursor.json"),hn=K.join(yr,"plane-link","dead-letter.ndjson"),jr=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),oe={},ne={},j=new Map,It=null,he=null,se=0,at=0,Cr=0,Mt={},Br=new Set,Lr=Promise.resolve(),H="ws",je=0,ee=!1,Te=0,mn=!1,me=rn,Ce=new Set,ie=[],Y=null,X=null,J=!1,gn=!1,ct=vi,lt=null,wn=S&&typeof S=="object"?S:null,Be=null,Le=null,ae=null,xe=0,Fr=0,ce=null,yn=!1,Pt=0,ut=!1,ge=Ri(M);if(ge)if(ge.tokenPreview===br(t))ut=!0,Jn({reason:ge.reason??"removed",at:ge.at??null,nodeId:ge.nodeId??n}),T.error(`[plane-link] this node was REMOVED from the plane (${ge.reason??"removed"}${ge.at?` at ${new Date(ge.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${M} to force a dial.`);else try{Ze.unlinkSync(M),T.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function bn({reason:c="removed",at:f=Date.now(),via:p="ctl"}={}){if(!ut){ut=!0,Jn({reason:c,at:f,nodeId:n,via:p});try{Ze.mkdirSync(K.dirname(M),{recursive:!0}),Ze.writeFileSync(M,JSON.stringify({at:f,reason:c,via:p,nodeId:n,tokenPreview:br(t)},null,2))}catch(i){T.error(`[plane-link] could not write ${M}: ${i?.message||i}`)}T.error(`[plane-link] the plane REMOVED this node (${c}, via ${p}) \u2014 going dormant: no more dials, ingest or broker calls. Re-provision with a new node token to reconnect; the box and its data are untouched.`);try{Ie?.({reason:c,at:f,via:p})}catch{}Jr({bye:!1})}}async function Vi(){try{oe=JSON.parse(await Et.readFile(pn,"utf8"))}catch{oe={}}}function Ur(){yn=!0,!Le&&(Le=setTimeout(async()=>{if(Le=null,!!yn){yn=!1;try{await Et.mkdir(K.dirname(pn),{recursive:!0}),await Et.writeFile(pn,JSON.stringify(oe))}catch(c){T.error("[plane-link] cursor flush failed:",c?.message||c)}}},tu),Le.unref?.())}function Sn(){try{return!!pe?.()}catch{return!1}}function _n(){let c=H==="http"?me:rn;return Sn()?Math.min(c,it):c}function C(c){return!X||X.readyState!==mr.OPEN?!1:(X.send(JSON.stringify(c)),!0)}let qi=ci(c=>C({v:B,ch:"ctl",type:"mcp_status",mcp:c}));function Fe(c){let f=Date.now();for(let{trackId:i,event:u}of c){let w=j.get(u.id);j.set(u.id,{trackId:i,seq:u.seq,event:u,sentAt:f,firstSentAt:w?.firstSentAt??f,retryAt:f+De,tries:(w?.tries??0)+1,nacks:w?.nacks??0})}let p=c.map(({trackId:i,event:u})=>({trackId:i,event:au(u)}));return H==="http"?(ea(p),!0):C({v:B,ch:"events",type:"append",events:p})}function Yi(c){let f=null;for(let p of j.values())p.trackId===c&&(f==null||p.seq<f)&&(f=p.seq);return f}function Tn(c){let f=ne[c];if(f==null)return;let p=Yi(c),i=p==null?f:Math.min(f,p-1);i>(oe[c]??0)&&(oe[c]=i,Ur())}function dt(){if(It=Date.now(),he!=null){let c=Date.now()-he;T.log(`[plane-link] spine sync recovered after ${Math.round(c/1e3)}s degraded (${se} stall redial(s))`);let f=he;he=null,se=0,at=0,ee=!1,Te=0;try{Me?.({since:f,downMs:c})}catch(p){T.error(`[plane-link] onRecovered failed: ${p?.message||p}`)}}}function xn(c){if(!Array.isArray(c)||!c.length)return;let f=new Set;for(let p of c){let i=j.get(p);i&&(j.delete(p),(ne[i.trackId]??0)<i.seq&&(ne[i.trackId]=i.seq),f.add(i.trackId))}for(let p of f)Tn(p);dt()}function Hr(c,f){Cr++;let p={at:Date.now(),trackId:c.trackId,seq:c.seq,id:c.event?.id??null,type:c.event?.type??null,reason:f,event:c.event??null};T.error(`[plane-link] DEAD-LETTER ${c.trackId} seq ${c.seq} (${p.type??"?"}): plane rejected it permanently (${f}) \u2014 kept in ${hn}`),Lr=Lr.then(async()=>{await Et.mkdir(K.dirname(hn),{recursive:!0}),await Et.appendFile(hn,JSON.stringify(p)+`
137
- `)}).catch(i=>T.error(`[plane-link] dead-letter write failed: ${i?.message||i}`))}function Xi(c,f){if(Mt[c]=(Mt[c]??0)+1,Br.has(c))return;Br.add(c);let p=iu[c]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";T.error(`[plane-link] REFUSED by the plane (${c}) on track ${f}: events are being dropped, not stored \u2014 ${p}`);try{fn?.({reason:c,trackId:f,count:Mt[c],hint:p})}catch(i){T.error(`[plane-link] onRefused failed: ${i?.message||i}`)}}function $n(c,f,p,i=null){if(!Array.isArray(c)||!c.length)return;let u=new Set,w=Date.now();for(let $ of c){let A=j.get($);A&&(p?(j.delete($),Hr(A,f),String(f).startsWith(gr)&&Xi(String(f).slice(gr.length),A.trackId),(ne[A.trackId]??0)<A.seq&&(ne[A.trackId]=A.seq),u.add(A.trackId)):(A.nacks++,A.retryAt=w+Math.max(1e3,Number(i)||De)))}for(let $ of u)Tn($);dt()}function Wr(c=Date.now()){let f=1/0;for(let p of j.values())p.firstSentAt<f&&(f=p.firstSentAt);return f===1/0?0:c-f}function Ji(c){if(!P||!c||c!==X||!xe)return!1;let f=Date.now()-xe;if(f<=P)return!1;Fr++,T.error(`[plane-link] no frame from the plane for ${Math.round(f/1e3)}s \u2014 link is half-open; terminating and redialing`);try{c.terminate()}catch{}return!0}function Kr(){if(!J||!j.size)return;let c=Date.now(),f=Wr(c);if(f<ot||It!=null&&c-It<ot||H==="http"&&ee||at>c)return;se++;let p=Math.min(Ir*2**(se-1),Ai);if(he==null){he=c-f,T.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(f/1e3)}s with ${j.size} event(s) in flight (${H} door) \u2014 the plane is not answering appends`);try{rt?.({since:he,unacked:j.size,oldestAgeMs:f,mode:H})}catch(i){T.error(`[plane-link] onDegraded failed: ${i?.message||i}`)}}if(H==="http"){ee=!0,Te=c+p,T.error(`[plane-link] ingest circuit OPEN (stall #${se}); probing /v1/ingest/health in ${Math.round(p/1e3)}s`);return}at=c+p,T.error(`[plane-link] closing the link and redialing in ${Math.round(p/1e3)}s (stall redial #${se})`);try{X?.terminate()}catch{}}function vn(){if(!J)return;let c=Date.now();if(H==="http"&&ee)return;let f=[...j.values()].filter(i=>i.event&&i.retryAt<=c&&!(H==="http"&&Ce.has(i.trackId)));if(!f.length)return;f.sort((i,u)=>i.trackId===u.trackId?i.seq-u.seq:i.trackId<u.trackId?-1:1),T.log(`[plane-link] re-sending ${f.length} unacked event(s) the plane never confirmed`);let p=_n();if(H==="http"){let i=new Map;for(let u of f)(i.get(u.trackId)??i.set(u.trackId,[]).get(u.trackId)).push(u);for(let[,u]of i){if(je>=wr)return;Fe(u.slice(0,p).map(w=>({trackId:w.trackId,event:w.event})))}return}for(let i=0;i<f.length;i+=p){let u=f.slice(i,i+p).map(w=>({trackId:w.trackId,event:w.event}));if(!Fe(u))return}}async function Zi(c=null){for(;;){if(!J)return!1;let f=j.size<de,p=H!=="http"||je<wr&&!ee&&(!c||!Ce.has(c));if(f&&p)return!0;await new Promise(i=>setTimeout(i,100))}}function kn(){if(Y=null,!J||!ie.length)return;let c=ie;ie=[];let f=_n();if(H!=="http"){for(let u=0;u<c.length;u+=f)Fe(c.slice(u,u+f));return}let p=Sn(),i=new Map;for(let u of c)(i.get(u.trackId)??i.set(u.trackId,[]).get(u.trackId)).push(u);for(let[u,w]of i){if(Ce.has(u)||je>=wr||ee){ie.push(...w);continue}if(p){Fe(w.slice(0,f)),ie.push(...w.slice(f));continue}for(let $=0;$<w.length;$+=f)Fe(w.slice($,$+f))}ie.length&&!Y&&(Y=setTimeout(kn,Ei),Y.unref?.())}let Qi=c=>{let f=new Map;for(let{trackId:p,event:i}of c)(f.get(p)??f.set(p,[]).get(p)).push(i);return[...f].map(([p,i])=>({trackId:p,events:i}))},$e=(c,f,p,{progress:i})=>{let u=Date.now();for(let{event:w}of c){let $=j.get(w.id);$&&($.nacks++,$.retryAt=u+Math.max(1e3,p||De))}i&&dt()};async function ea(c){let f=new Set(c.map(p=>p.trackId));for(let p of f)Ce.add(p);je++;try{let p=await Mr(`${jr}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:Qi(c)}),signal:AbortSignal.timeout(fe)}),i=(Number(p.headers.get("retry-after"))||0)*1e3;if(p.status===200){let u=await p.json();me=rn;for(let A of u.results??[]){xn(A.acked??[]);let F=(re,G)=>{let Dt=new Map;for(let ve of re??[])(Dt.get(ve.reason)??Dt.set(ve.reason,[]).get(ve.reason)).push(ve.id);for(let[ve,Zr]of Dt)$n(Zr,ve,G,u.retryAfterMs??null)};F(A.rejected,!0),F(A.deferred,!1)}let w=new Set,$=new Map;for(let A of Array.isArray(u.refused)?u.refused:[])!A||typeof A.id!="string"||(w.add(A.id),($.get(A.reason)??$.set(A.reason,[]).get(A.reason)).push(A.id));for(let[A,F]of $)$n(F,`${gr}${A}`,!0);xn((u.discarded??[]).filter(A=>!w.has(A))),dt();return}if(p.status===429){$e(c,"overloaded",i||5e3,{progress:!0});return}if(p.status===413&&c.length>1){me=Math.max(1,Math.floor(c.length/2)),T.error(`[plane-link] ingest request too large (${c.length} events) \u2014 halving batches to ${me}`),$e(c,"too_large",1e3,{progress:!0});return}if(p.status===413){let u=j.get(c[0].event.id);u&&(j.delete(u.event.id),Hr(u,"too_large"),(ne[u.trackId]??0)<u.seq&&(ne[u.trackId]=u.seq),Tn(u.trackId)),dt();return}if(p.status===410){bn({reason:"removed",via:"410"}),$e(c,"http_410",6e4,{progress:!1});return}if(p.status===401||p.status===403){let{tripped:u,holdMs:w}=Gt();if(u&&T.error(`[plane-link] holding every plane call for ${Math.round(w/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Pt>=Oi){Pt=Date.now();let $="";try{$=(await p.json())?.error??""}catch{}T.error(`[plane-link] plane refused ingest (HTTP ${p.status}${$?`: ${$}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}$e(c,`http_${p.status}`,Math.max(6e4,St()),{progress:!1});return}if(p.status===400){T.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${c.length} event(s) for retry; this is a bug, not data`),$e(c,"http_400",6e4,{progress:!1});return}$e(c,`http_${p.status}`,i||5e3,{progress:!1})}catch(p){let i=p?.name==="TimeoutError"||p?.name==="AbortError";i&&c.length>1&&(me=Math.max(1,Math.floor(c.length/2)),T.error(`[plane-link] ingest request of ${c.length} event(s) outlived its ${fe} ms deadline \u2014 halving batches to ${me}`)),$e(c,i?"timeout":"network",5e3,{progress:!1})}finally{je--;for(let p of f)Ce.delete(p)}}async function ta(){if(H!=="http"||!ee||!J||mn)return;let c=Date.now();if(!(Te>c||Vt(c))){mn=!0;try{let f=await Mr(`${jr}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(fe)});if(!f.ok)throw new Error(`HTTP ${f.status}`);T.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),ee=!1,Te=0,at=Date.now()+fe+De+1e3;for(let p of j.values())p.retryAt=Math.min(p.retryAt,Date.now());vn()}catch(f){se++;let p=Math.min(Ir*2**(se-1),Ai);Te=Date.now()+p,T.error(`[plane-link] ingest door still not answering (${f?.message||f}); next probe in ${Math.round(p/1e3)}s`)}finally{mn=!1}}}function zr(){let c=Date.now();return{mode:H,unacked:j.size,oldestUnackedAgeMs:Wr(c),lastProgressAt:It,degradedSince:he,stallRedials:se,deadLettered:Cr,fanoutCap:Sn()?it:null,http:H==="http"?{inFlight:je,circuitOpen:ee,nextProbeInMs:ee?Math.max(0,Te-c):0,batchCap:me}:null}}async function Gr(){if(!h)return;let c;try{c=await h()}catch(p){T.error("[plane-link] metrics sample failed:",p?.message||p);return}let f=null;try{f=m?.()??null}catch{}c&&C({v:B,ch:"ctl",type:"metrics",metrics:{...c,planeLink:zr(),...f?{delivery:f}:{}}})}function na(){h&&(ce&&clearInterval(ce),Gr(),ce=setInterval(Gr,v),ce.unref?.())}async function ra(){let c;try{c=await o()}catch(f){T.error("[plane-link] backfill listTracks failed:",f?.message||f);return}C({v:B,ch:"ctl",type:"tracks",ids:c.filter(f=>!f.transferredTo).map(f=>f.id).filter(f=>typeof f=="string")});for(let f of c)if(!J||!await Vr(f))return}async function Vr(c){let f;try{f=await qt(c)}catch{return!0}let p=oe[c.id]??0,i=f.filter(u=>u.seq>p&&typeof u.id=="string");for(let u=0;u<i.length;){if(!await Zi(c.id))return!1;let w=i.slice(u,u+_n()).map($=>({trackId:c.id,event:$}));if(!Fe(w))return!1;u+=w.length}return!0}let An=new Map;async function qr(c,f){if(An.get(c)===f)return!1;An.set(c,f);let p=null;try{p=(await o()).find($=>$?.id===c)??null}catch{return!1}if(!p)return!1;let i;try{i=await qt(p)}catch{return!1}let u=[...i].reverse().find($=>($?.type==="track.transferred"||$?.type==="track.recovered")&&$.payload?.toNode===n);if(!u||!Number.isFinite(u.seq))return!1;let w=u.seq-1;return(oe[c]??0)>w&&(oe[c]=w,Ur()),(ne[c]??0)>w&&(ne[c]=w),T.log(`[plane-link] re-sending ${c}'s move-commit (seq ${u.seq}, ${u.type}) \u2014 the plane's move record predates this node's adoption`),J?Vr(p):!1}function Yr(c){!J||!c?.trackId||typeof c.id!="string"||(ie.push({trackId:c.trackId,event:c}),Y||(Y=setTimeout(kn,Ei),Y.unref?.()))}let ft=new Map;async function oa(c){let{reqId:f,method:p,path:i,headers:u={},body:w}=c,$=Object.fromEntries(Object.entries(u).filter(([,F])=>F!=null)),A=new AbortController;ft.set(f,A);try{if(c.host){await sa(c,$,A);return}x&&($["x-bostrat-token"]=x);let F=await fetch(O+i,{method:p,headers:$,body:w?Buffer.from(w,"base64"):void 0,signal:A.signal}),re=Object.fromEntries(F.headers);for(let G of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete re[G];if(re["content-type"]||(re["content-type"]="application/octet-stream"),C({v:B,ch:"control",type:"http_head",reqId:f,status:F.status,headers:re}),F.body){for await(let G of F.body)if(!C({v:B,ch:"control",type:"http_data",reqId:f,data:Buffer.from(G).toString("base64")}))break}C({v:B,ch:"control",type:"http_end",reqId:f,error:null})}finally{ft.delete(f)}}function sa(c,f,p){let{reqId:i,method:u,path:w,body:$}=c,A=new URL(O);return new Promise(F=>{let re=Xl.request({host:A.hostname,port:A.port,method:u,path:w,headers:{...f,host:c.host},signal:p.signal},G=>{let{connection:Dt,"keep-alive":ve,"transfer-encoding":Zr,upgrade:dd,...ia}=G.headers;C({v:B,ch:"control",type:"http_head",reqId:i,status:G.statusCode||502,headers:ia}),G.on("data",aa=>{C({v:B,ch:"control",type:"http_data",reqId:i,data:Buffer.from(aa).toString("base64")})||G.destroy()}),G.on("end",()=>{C({v:B,ch:"control",type:"http_end",reqId:i,error:null}),F()}),G.on("error",()=>{C({v:B,ch:"control",type:"http_end",reqId:i,error:"view upstream error"}),F()})});re.on("error",G=>{C({v:B,ch:"control",type:"http_end",reqId:i,error:G?.message||"view request failed"}),F()}),$&&re.write(Buffer.from($,"base64")),re.end()})}function Xr(){if(gn||ut)return;X=new mr(e,{headers:{authorization:`Bearer ${t}`}});let c=X;xe=0,c.on("ping",()=>{xe=Date.now()}),c.on("pong",()=>{xe=Date.now()}),X.on("open",async()=>{let p=null;try{p=await s?.()||null}catch{p=null}C({v:B,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:te,installKind:E,...typeof _=="function"?{updatePolicy:_()}:_?{updatePolicy:_}:{},providers:Ni(),...p?{agents:p}:{},mcp:nn(),...wn?{restart:wn}:{}})}),X.on("message",p=>{xe=Date.now();let i;try{i=JSON.parse(p)}catch{return}if(i.ch==="ctl"&&i.type==="hello_ok"){An.clear(),J=!0,ct=vi,lt=null,wn=null,Co(),T.log(`[plane-link] connected to plane as ${n}`);try{Nt?.()}catch{}if(typeof i.hashKey=="string"&&i.hashKey)try{d?.(i.hashKey)}catch{}try{g?.(typeof i.viewBase=="string"&&i.viewBase?i.viewBase:null)}catch{}i.minNodeVersion&&te&&Qe(te,i.minNodeVersion)&&T.error(`[plane-link] this node is bostrat-node ${te}; the plane asks for \u2265${i.minNodeVersion} \u2014 update with: ${Ot(E)}`);try{b?.(typeof i.updatePolicy=="string"?i.updatePolicy:null)}catch{}Dr(i);let u=i.ingest==="http";H=Pe==="ws"?"ws":Pe==="http"||u?"http":"ws",Pe==="http"&&!u&&T.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),H==="http"&&T.log("[plane-link] spine rides the HTTPS ingest door"),ee=!1,Te=0,me=rn,ae&&clearInterval(ae),xe=Date.now(),ae=setInterval(()=>{Ji(c)||(C({v:B,ch:"ctl",type:"ping"}),Kr(),ta().catch(()=>{}),vn(),ie.length&&!Y&&kn())},st),ae.unref?.(),na(),ra().catch(w=>T.error("[plane-link] backfill failed:",w?.message||w));return}if(i.ch==="ctl"&&i.type==="hello_refused"){let u=typeof i.minNodeVersion=="string"?i.minNodeVersion:null,w=typeof i.latestNodeVersion=="string"?i.latestNodeVersion:null;T.error(`[plane-link] plane REFUSED this node: bostrat-node ${te??"?"} is below its minimum ${u??"?"} \u2014 ${i.fix||Ot(E)}`),ct=ki,lt=0;try{k?.({current:te,min:u,latest:w,fix:i.fix||Ot(E),installKind:E})}catch($){T.error(`[plane-link] refusal handler failed: ${$?.message||$}`)}return}if(i.ch==="ctl"&&i.type==="removed"){C({v:B,ch:"ctl",type:"removed_ack",nodeId:n}),bn({reason:typeof i.reason=="string"?i.reason:"removed",at:Number(i.at)||Date.now(),via:"ctl"});return}if(i.ch==="ctl"&&i.type==="update_available"){Dr(i);return}if(i.ch==="ctl"&&i.type==="update_policy"){try{b?.(typeof i.mode=="string"?i.mode:null)}catch{}return}if(i.ch==="ctl"&&i.type==="conflict_probe"&&Array.isArray(i.trackIds)){try{I?.(i.trackIds.filter(u=>typeof u=="string"&&u).slice(0,200))}catch{}return}if(i.ch==="ctl"&&i.type==="restarted"){Promise.resolve().then(()=>N?.({kind:i.kind,at:i.at,reason:i.reason})).catch(u=>T.error("[plane-link] restart notice failed:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="usage_caps"){Gs(i.caps??{},{source:"plane",updatedAt:i.updatedAt??Date.now()}).then(u=>T.log(`[plane-link] spend caps ${Object.keys(u.caps).length?`updated (${Object.keys(u.caps).join(", ")})`:"cleared"} from plane`)).catch(u=>T.error("[plane-link] spend-caps push rejected:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="mcp_config"){fi(i.entries??[],{updatedAt:i.updatedAt??Date.now()}).then(u=>T.log(`[plane-link] mcp config applied: ${Object.keys(u.entries).length} entr${Object.keys(u.entries).length===1?"y":"ies"}`)).catch(u=>T.error("[plane-link] mcp config apply failed:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="refresh_flow"){xi(i.flow??{},{source:"plane",updatedAt:i.updatedAt??Date.now()}).then(u=>T.log(`[plane-link] refresh flow from plane: contextFull=${u.flow.contextFull} rung=${u.flow.contextFullTokens?`${u.flow.contextFullTokens} tokens`:`${u.flow.contextFullPct}%`}`)).catch(u=>T.error("[plane-link] refresh-flow push rejected:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="refresh_flow_rejected"){Ti(typeof i.error=="string"?i.error:"rejected by the plane");return}if(i.ch==="ctl"&&i.type==="transferred"&&Array.isArray(i.tracks)){Promise.resolve().then(()=>a?.(i.tracks)).then(async u=>{for(let w of Array.isArray(u)?u:[])w?.stale&&w.id&&await qr(w.id,w.since??null)}).catch(u=>T.error("[plane-link] transfer notice failed:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="moves"&&Array.isArray(i.tracks)){Promise.resolve().then(()=>l?.(i.tracks)).then(async u=>{for(let w of Array.isArray(u)?u:[])w?.stale&&w.id&&await qr(w.id,w.since??null)}).catch(u=>T.error("[plane-link] move-record reconcile failed:",u?.message||u));return}if(i.ch==="events"&&i.type==="ack"&&Array.isArray(i.ids)){xn(i.ids);return}if(i.ch==="events"&&i.type==="nack"&&Array.isArray(i.ids)){$n(i.ids,i.reason,i.permanent===!0,i.retryAfterMs??null);return}if(i.ch==="control"&&i.type==="http_open"){oa(i).catch(u=>C({v:B,ch:"control",type:"http_end",reqId:i.reqId,error:u?.message||"tunnel error"}));return}if(i.ch==="control"&&i.type==="http_cancel"){ft.get(i.reqId)?.abort();return}if(i.ch==="attach"&&i.type==="open"){let u=new mr(Gi+i.path,Array.isArray(i.protocols)?i.protocols:[],i.host?{headers:{host:i.host}}:void 0);Se.set(i.streamId,u),_e.set(i.streamId,[]),u.on("open",()=>{let $=_e.get(i.streamId)||[];_e.delete(i.streamId);for(let{buf:A,bin:F}of $)u.send(A,{binary:F})}),u.on("message",($,A)=>{let F=A?$:Buffer.from(String($));C({v:B,ch:"attach",type:"data",streamId:i.streamId,data:F.toString("base64"),...A?{bin:!0}:{}})});let w=()=>{_e.delete(i.streamId),Se.delete(i.streamId)&&C({v:B,ch:"attach",type:"close",streamId:i.streamId})};u.on("close",w),u.on("error",w);return}if(i.ch==="attach"&&i.type==="data"){let u=Se.get(i.streamId);if(!u)return;let w=Buffer.from(i.data,"base64"),$=i.bin===!0,A=_e.get(i.streamId);A?A.push({buf:w,bin:$}):u.send(w,{binary:$});return}if(i.ch==="attach"&&i.type==="close"){let u=Se.get(i.streamId);Se.delete(i.streamId),_e.delete(i.streamId),u?.close();return}});let f=()=>{J&&T.log("[plane-link] disconnected from plane"),J=!1,ae&&(clearInterval(ae),ae=null),ce&&(clearInterval(ce),ce=null),j.clear(),ne={},ie=[],Y&&(clearTimeout(Y),Y=null),Ce.clear();for(let u of Se.values())u.close();Se.clear(),_e.clear();for(let u of ft.values())u.abort();if(ft.clear(),gn||Be)return;lt==null&&(lt=Date.now());let p=Date.now()-lt<Zl,i=Math.max(p?Ql+Math.random()*eu:ct,at-Date.now(),St());Be=setTimeout(()=>{Be=null,Xr()},i),Be.unref?.(),p||(ct=Math.min(ct*2,ki))};X.on("close",f),X.on("error",p=>{let i=/Unexpected server response: (\d+)/.exec(p?.message||"")?.[1];if(i==="410"){bn({reason:"removed",via:"410"});return}if(i==="401"||i==="403"){let{tripped:u,holdMs:w}=Gt();u?T.error(`[plane-link] holding every plane call for ${Math.round(w/6e4)} min \u2014 three credential refusals in a row (HTTP ${i}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(w/6e4)} min.`):Date.now()-Pt>=Oi&&(Pt=Date.now(),T.error(`[plane-link] plane refused this node's credentials (HTTP ${i}) \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()})}Tt.on("event",Yr),Vi().then(Xr);function Jr({bye:c=!0}={}){gn=!0,Tt.off("event",Yr),qi(),Be&&clearTimeout(Be),Le&&clearTimeout(Le),ae&&clearInterval(ae),ce&&clearInterval(ce),Y&&clearTimeout(Y),c&&C({v:B,ch:"ctl",type:"bye",reason:"shutdown"}),X?.close()}return{stop:()=>Jr(),setRefreshFlow:c=>C({v:B,ch:"ctl",type:"refresh_flow_set",patch:c}),status:()=>({connected:J,nodeId:n,cursor:{...oe},inflight:j.size,...zr(),auth:Bo(),dormant:ut,removed:Zn(),deadLinkMs:P,deadLinkRedials:Fr,refused:{...Mt}}),_tick:()=>{Kr(),vn()}}}var te,yr,Sr,B,vi,ki,Zl,Ql,eu,rn,tu,nu,ru,ou,_r,su,gr,iu,au,cu,Ai,lu,Ei,uu,wr,du,fu,Oi,Tr=R(()=>{Yt();Vs();pi();$i();Rn();Qn();te=(()=>{try{return Jl(import.meta.url)("../package.json").version||null}catch{return null}})(),yr=process.env.BOSTRAT_STATE_DIR||K.join(process.env.HOME||on.tmpdir(),".bostrat"),Sr=K.join(yr,"plane-link","removed.json");B=1,vi=1e3,ki=3e4,Zl=6e4,Ql=1500,eu=500,rn=100,tu=2e3,nu=25e3,ru=2.5,ou=6e4,_r=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},su=_r(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),gr="refused:",iu={forgedUserId:"this node's events carry a userId the plane's token does not own \u2014 remove BOSTRAT_OWNER from node.env and the shell environment, then restart the node (current releases never stamp one)",foreignTrack:"the Track belongs to another user's node \u2014 this node must not append to it",squattedTrack:"the Track id is already claimed by another user \u2014 a local Track collided with theirs",transferredAway:"the Track moved to another node \u2014 this copy is stale; it should be demoted, not resumed",slugHijack:"a View slug belongs to another owner \u2014 pick a different slug"},au=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},cu=3e4,Ai=10*6e4,lu=400,Ei=250,uu=_r(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),wr=4,du=Math.max(1,Math.round(_r(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),fu=6e4,Oi=6e4});var Mi=R(()=>{Yn()});var Fi={};En(Fi,{ACTIONABLE_KINDS:()=>un,INSTALL_ATTEMPTS:()=>sn,INSTALL_RETRY_STEP_S:()=>Pi,REGISTRY_RETRY_ATTEMPTS:()=>vr,REGISTRY_WAIT_POLLS:()=>xr,REGISTRY_WAIT_STEP_S:()=>$r,RESTART_SIGNAL:()=>ji,SELF_UPDATE_DIR:()=>cn,SUPERVISOR_PID_FILE:()=>Di,createAutoUpdater:()=>Eu,inFlight:()=>Or,readStatus:()=>Er,restartCommand:()=>Ci,restartStrategy:()=>Ar,selfUpdatePlan:()=>Bi,settleSelfUpdate:()=>Au,startSelfUpdate:()=>Li,underService:()=>kr,updatePolicy:()=>_u});import Rt from"node:fs";import ye from"node:fs/promises";import hu from"node:os";import U from"node:path";import{spawn as mu,execFileSync as gu}from"node:child_process";import{createRequire as wu}from"node:module";function _u({kind:e=et(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:un.has(e)?e==="git-checkout"||kr(t)?"auto":"prompt":"off"}function kr(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Ar({env:e=process.env,platform:t=process.platform,uid:n=typeof process.getuid=="function"?process.getuid():0,serviceName:r=t==="darwin"?"com.bostrat.node":"bostrat-node.service",pidFile:o=Di,readFile:s=l=>Rt.readFileSync(l,"utf8"),alive:a=Tu}={}){let l=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(kr(e))return l;let h=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(h)&&h>0)){try{h=Number(String(s(o)).trim())}catch{h=NaN}Number.isInteger(h)&&h>0&&a(h)||(h=NaN)}return Number.isInteger(h)&&h>0?{mode:"supervisor",pid:h}:l}function Tu(e){try{process.kill(e,0)}catch{return!1}try{let t=gu("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/bostrat-node|\/cli\.js|node-cli\.js/.test(t)}catch{return!1}}function Ci(e){switch(e?.mode){case"systemd":return`systemctl --user restart ${Q(e.serviceName||"bostrat-node.service")}`;case"launchd":return`launchctl kickstart -k gui/${Number(e.uid)||0}/${e.serviceName||"com.bostrat.node"}`;case"supervisor":return`kill -${ji.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function Bi({kind:e,to:t,from:n=an,statusFile:r=ln,logFile:o=U.join(cn,"last.log"),port:s=Number(process.env.PORT)||3362,npmPrefix:a=null,serviceName:l=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:h=typeof process.getuid=="function"?process.getuid():0,restart:m=Ar({env:{},platform:process.platform,uid:h,serviceName:l,readFile:()=>{throw new Error("no pidfile")}}),liveDir:d=process.env.BOSTRAT_LIVE_CHECKOUT||U.resolve(U.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:g=Date.now(),attempts:v=1}={}){if(!un.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 y=(k,_="")=>`write_status ${Q(k)} ${_}`,b=Ci(m),I=`
136
+ `),s+=l);return s}async function Cl(e){try{return await ye.readFile(e,"utf8")}catch(t){if(t?.code==="ENOENT")return null;throw t}}async function hr(e,t){await ye.mkdir(Xe.dirname(e),{recursive:!0});let n=`${e}.bostrat-${process.pid}.tmp`,r=384;try{r=(await ye.stat(e)).mode&511}catch{}await ye.writeFile(n,t,{mode:r}),await ye.rename(n,e)}async function Bl(e,t,n,r){let o={},s=e==="claude"?Mo():e==="codex"?Po():Nl(),a=S=>{for(let N of t.keys())o[N]=S};if(e!=="claude"&&!El.existsSync(Xe.dirname(s)))return a("cli-absent"),{managed:[],states:o};let l;try{l=await Cl(s)}catch{return a("error"),{managed:n,states:o}}let h=new Set(n);if(e==="codex"){let S=oi(l??""),N=new Map;for(let[x,M]of t)S.has(x)&&!h.has(x)?o[x]="conflict":N.set(x,Dl(M,r));let A=new Set([...h].filter(x=>!t.has(x))),_=jl(l??"",N,A);try{_!==(l??"")&&await hr(s,_)}catch{for(let x of N.keys())o[x]="error";return{managed:n,states:o}}for(let x of N.keys())o[x]="applied";let E=oi(l??""),O=new Set([...N.keys()].filter(x=>_!==(l??"")&&(!E.has(x)||!(l??"").includes(N.get(x)))));return{managed:[...N.keys()].sort(),states:o,wrote:O}}let m={};if(l!=null&&l.trim()){try{m=JSON.parse(l)}catch{return a("error"),{managed:n,states:o}}if(!m||typeof m!="object"||Array.isArray(m))return a("error"),{managed:n,states:o}}let d=m.mcpServers&&typeof m.mcpServers=="object"?{...m.mcpServers}:{},g=[];for(let[S,N]of t){if(Object.hasOwn(d,S)&&!h.has(S)){o[S]="conflict";continue}d[S]=Pl(N,r,e),g.push(S)}for(let S of h)t.has(S)||delete d[S];let v={...m,mcpServers:d};!Object.keys(d).length&&!m.mcpServers&&delete v.mcpServers;let y=JSON.stringify(m.mcpServers??{})!==JSON.stringify(d);try{y&&await hr(s,JSON.stringify(v,null,2))}catch{for(let S of g)o[S]="error";return{managed:n,states:o}}for(let S of g)o[S]="applied";let b=m.mcpServers&&typeof m.mcpServers=="object"?m.mcpServers:{},I=new Set(g.filter(S=>JSON.stringify(b[S]??null)!==JSON.stringify(d[S])));return{managed:g.sort(),states:o,wrote:I}}async function Ll(){let e=Rl(),t={};try{(await ye.stat(e)).mode&63&&await ye.chmod(e,384).catch(()=>{});let a=JSON.parse(await ye.readFile(e,"utf8"));t=Object.fromEntries(Object.entries(a||{}).filter(([,l])=>typeof l=="string"&&l!==""))}catch{t={}}let r={...Zs(),...t},o={};for(let s of Object.keys(r))o[s]=s in t?"file":"broker";return{values:r,sources:o}}function Fl(e){if(e?.transport!=="http")return null;for(let[t,n]of Object.entries(e.headers||{})){if(!/^authorization$/i.test(t))continue;let r=/\$\{([A-Za-z_][A-Za-z0-9_]{0,63})\}/.exec(String(n));if(r)return r[1]}return null}function Ul(e,t,n,r,o){let s={},a=Fl(e);for(let l of e.env||[])if(t[l]!=null){let h=n[l]==="broker"?r[l]:null;s[l]={state:"set",source:n[l],...h?.expiresAt?{expiresAt:h.expiresAt}:{},...h?{refreshable:!!h.refreshable}:{}}}else o.includes(l)?s[l]={state:"login-pending",source:"broker"}:r[l]?s[l]={state:"needs-login",source:"broker",...r[l].error?{error:r[l].error}:{}}:e.auth==="oauth"&&l===a?s[l]={state:"needs-login",source:"broker"}:s[l]={state:"missing"};return s}function pi(e){return(Array.isArray(e)?e:[]).filter(t=>t&&Il.test(t.name)&&(t.transport==="http"?typeof t.url=="string":typeof t.command=="string")).map(t=>t.auth==="oauth"?t:(({auth:n,...r})=>r)(t))}async function si(){let{values:e,sources:t}=await Ll(),n=Qs(),r=ei(),o=pi(ue.entries),s={};for(let d of o){let g=Ul(d,e,t,n,r),v=Object.entries(g).filter(([,y])=>y.state!=="set").map(([y])=>y);s[d.name]={rev:Number(d.updatedAt)||0,clis:{},since:{},missingEnv:v,env:g,...d.auth==="oauth"?{auth:"oauth"}:{}}}let a={...ue.managed},l={...ue.since||{}},h=Date.now();for(let d of dr){let g=new Map(o.filter(b=>(b.clis||dr).includes(d)&&!s[b.name].missingEnv.length).map(b=>[b.name,b])),v=await Bl(d,g,ue.managed?.[d]??[],e);a[d]=v.managed;let y={...l[d]||{}};for(let[b,I]of Object.entries(v.states)){s[b].clis[d]=I;let S=s[b].rev;I==="applied"?((!y[b]||y[b].rev!==S)&&(y[b]={rev:S,at:v.wrote?.has(b)?h:Math.max(S,y[b]?.at??0)||h}),s[b].since[d]=y[b].at):delete y[b]}for(let b of Object.keys(y))g.has(b)||delete y[b];l[d]=y}for(let d of o){if(!s[d.name].missingEnv.length)continue;let v=Object.values(s[d.name].env).map(y=>y.state).includes("missing")?"missing-secret":"needs-login";for(let y of d.clis||dr)s[d.name].clis[y]=v}ue={...ue,managed:a,since:l},await Hl();let m=JSON.stringify(s)!==JSON.stringify(pr);if(pr=s,m)for(let d of fr)try{d(rn())}catch{}return rn()}async function Hl(){let e=JSON.stringify(ue,null,2);if(e!==ii)try{await hr(Ol(),e),ii=e}catch(t){console.error("[mcp-config] cache write failed:",t?.message||t)}}function Wl(){let e=ni.then(si,si);return ni=e.catch(()=>{}),e}function fi(e,{updatedAt:t=Date.now()}={}){return ue={...ue,entries:pi(e),updatedAt:t},Wl()}var ci,Ol,Rl,Nl,dr,Il,Ml,ue,pr,ni,fr,Ye,Et,ri,ii,hi=R(()=>{Kn();Gn();ti();ci=()=>process.env.BOSTRAT_STATE_DIR||Xe.join(process.env.HOME||ai.tmpdir(),".bostrat"),Ol=()=>Xe.join(ci(),"mcp-config.json"),Rl=()=>Xe.join(ci(),"mcp-env.json"),Nl=()=>Xe.join(ai.homedir(),".cursor","mcp.json"),dr=["claude","codex","cursor"],Il=/^[a-z0-9][a-z0-9_-]{0,47}$/,Ml=/\$\{([A-Za-z_][A-Za-z0-9_]{0,63})\}/g,ue={entries:[],updatedAt:null,managed:{claude:[],codex:[],cursor:[]},since:{}},pr={},ni=Promise.resolve(),fr=new Set;Ye=(e,t)=>String(e).replace(Ml,(n,r)=>t[r]??"");Et=e=>JSON.stringify(String(e)),ri=e=>`{ ${Object.entries(e).map(([t,n])=>`${Et(t)} = ${Et(n)}`).join(", ")} }`;ii=null});import mi from"node:fs/promises";import yi from"node:path";import Kl from"node:os";function Gl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("refresh-flow patch must be an object");let t={};for(let[n,r]of Object.entries(e)){if(!(n in mr))throw new Error(`unknown refresh-flow field "${n}" \u2014 fields: ${Si.join(", ")}`);if(r===null||r===""||r===void 0){t[n]=null;continue}switch(n){case"contextFull":case"limitHit":if(typeof r!="string"||!gi.includes(r))throw new Error(`${n} must be one of ${gi.join(", ")}`);t[n]=r;break;case"contextFullPct":{let o=Number(r);if(!Number.isFinite(o)||o<1||o>100)throw new Error("contextFullPct must be a number from 1 to 100");t[n]=Math.round(o);break}case"contextFullTokens":{let o=Number(r);if(!Number.isFinite(o)||o<=0)throw new Error("contextFullTokens must be a positive number of tokens or null");t[n]=Math.round(o);break}case"fallback":{if(typeof r!="object"||Array.isArray(r))throw new Error("fallback must be an object of provider \u2192 [providers]");let o={};for(let[s,a]of Object.entries(r)){if(!wi.test(s))throw new Error(`bad provider key "${s}" in fallback`);if(!Array.isArray(a)||a.some(h=>typeof h!="string"||!wi.test(h)))throw new Error(`fallback.${s} must be a list of provider keys`);let l=[...new Set(a.filter(h=>h!==s))];l.length&&(o[s]=l)}t[n]=Object.keys(o).length?o:null;break}default:throw new Error(`unknown refresh-flow field "${n}"`)}}return t}function Vl(e){let t={...mr};for(let n of Si){let r=e?.[n];r!=null&&(t[n]=r)}return t}function Yl(){return Vl(Je?.flow)}function _i(){return{flow:Yl(),configured:!!Je,source:Je?.source??null,updatedAt:Je?.updatedAt??null}}async function Xl(){try{await mi.mkdir(bi,{recursive:!0}),await mi.writeFile(zl(),JSON.stringify(Je,null,2))}catch{}}function Ti(e=null){for(let t of ql)try{t(_i(),e)}catch{}}function xi(e){Ti({rejected:String(e||"rejected by the plane")})}async function $i(e,{source:t="plane",updatedAt:n=Date.now()}={}){return Je={flow:Gl(e||{}),updatedAt:n,source:t},await Xl(),Ti(),_i()}var bi,zl,gi,mr,Si,wi,Je,ql,vi=R(()=>{bi=process.env.BOSTRAT_STATE_DIR||yi.join(process.env.HOME||Kl.tmpdir(),".bostrat"),zl=()=>yi.join(bi,"refresh-flow.json"),gi=["prompt","auto","off"],mr=Object.freeze({contextFull:"prompt",contextFullPct:75,contextFullTokens:null,limitHit:"prompt",fallback:null}),Si=Object.keys(mr),wi=/^[a-z][a-z0-9-]{0,31}$/;Je=null,ql=new Set});var Mi={};En(Mi,{REMOVED_MARKER:()=>_r,detectInstallKind:()=>et,detectProviderAuth:()=>Ii,maskToken:()=>Sr,readRemovedMarker:()=>Ni,startPlaneLink:()=>hu,updateCommandFor:()=>Rt,versionLt:()=>Qe});import Ze from"node:fs";import Ot from"node:fs/promises";import Jl from"node:http";import z from"node:path";import sn from"node:os";import{createRequire as Zl}from"node:module";import gr from"ws";function Sr(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function Ni(e=_r){try{let t=JSON.parse(Ze.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function et({env:e=process.env,pkgDir:t=z.resolve(z.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ze.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(z.join(t,"..",".git"))?"git-checkout":"dev"}function Qe(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 s=(n[o]||0)-(r[o]||0);if(s)return s<0}return!1}function Rt(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 Ii({home:e=process.env.HOME||sn.homedir(),env:t=process.env}={}){let n=r=>{try{return Ze.statSync(r),!0}catch{return!1}};return{claude:n(z.join(e,".claude",".credentials.json")),codex:n(z.join(t.CODEX_HOME||z.join(e,".codex"),"auth.json")),cursor:n(z.join(t.XDG_CONFIG_HOME||z.join(e,".config"),"cursor","auth.json"))}}function hu({url:e,token:t,nodeId:n=sn.hostname(),name:r=sn.hostname(),listTracks:o,detectAgents:s=null,onTracksTransferred:a=null,onTracksMoves:l=null,sampleMetrics:h=null,deliverySample:m=null,onHashKey:d=null,onViewBase:g=null,metricsMs:v=fu,onUpdateAvailable:y=null,onUpdatePolicy:b=null,onConflictProbe:I=null,restart:S=null,onRestarted:N=null,onHelloRefused:A=null,updatePolicy:_=null,installKind:E=et(),selfUrl:O=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:x=null,removedMarkerFile:M=_r,onRemoved:Ie=null,onDegraded:rt=null,onRecovered:Me=null,onRefused:fn=null,onConnected:It=null,ingestMode:Pe=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:De=iu,unackedRetryMs:je=su,pingMs:ot=ru,deadLinkMs:P=Math.round(ot*ou),maxInflightEvents:de=uu,httpTimeoutMs:pe=du,fanoutActive:fe=null,fanoutBatchCap:st=pu,stallBackoffMinMs:Mr=lu,fetchImpl:Pr=globalThis.fetch,log:T=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=ft(e);let Vi=O.replace(/^http/,"ws"),Dr=new Set,jr=c=>{let f=typeof c.latestNodeVersion=="string"?c.latestNodeVersion:null;if(!(!(f&&ne&&Qe(ne,f))||Dr.has(f))){Dr.add(f),T.log(`[plane-link] bostrat-node ${f} is available (this node runs ${ne}) \u2014 ${Rt(E)}`);try{y?.({current:ne,latest:f,min:c.minNodeVersion??null,installKind:E,required:!!(c.minNodeVersion&&Qe(ne,c.minNodeVersion))})}catch(p){T.error(`[plane-link] update notice failed: ${p?.message||p}`)}}},_e=new Map,Te=new Map,hn=z.join(br,"plane-link","cursor.json"),mn=z.join(br,"plane-link","dead-letter.ndjson"),Cr=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),se={},re={},j=new Map,Mt=null,he=null,ie=0,it=0,Br=0,Pt={},Lr=new Set,Fr=Promise.resolve(),H="ws",Ce=0,ee=!1,xe=0,gn=!1,me=on,at=new Set,te=[],W=null,J=null,Z=!1,wn=!1,ct=Ai,lt=null,yn=S&&typeof S=="object"?S:null,Be=null,Le=null,ae=null,$e=0,Ur=0,ce=null,bn=!1,Dt=0,ut=!1,ge=Ni(M);if(ge)if(ge.tokenPreview===Sr(t))ut=!0,Zn({reason:ge.reason??"removed",at:ge.at??null,nodeId:ge.nodeId??n}),T.error(`[plane-link] this node was REMOVED from the plane (${ge.reason??"removed"}${ge.at?` at ${new Date(ge.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${M} to force a dial.`);else try{Ze.unlinkSync(M),T.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function Sn({reason:c="removed",at:f=Date.now(),via:p="ctl"}={}){if(!ut){ut=!0,Zn({reason:c,at:f,nodeId:n,via:p});try{Ze.mkdirSync(z.dirname(M),{recursive:!0}),Ze.writeFileSync(M,JSON.stringify({at:f,reason:c,via:p,nodeId:n,tokenPreview:Sr(t)},null,2))}catch(i){T.error(`[plane-link] could not write ${M}: ${i?.message||i}`)}T.error(`[plane-link] the plane REMOVED this node (${c}, via ${p}) \u2014 going dormant: no more dials, ingest or broker calls. Re-provision with a new node token to reconnect; the box and its data are untouched.`);try{Ie?.({reason:c,at:f,via:p})}catch{}Qr({bye:!1})}}async function qi(){try{se=JSON.parse(await Ot.readFile(hn,"utf8"))}catch{se={}}}function Hr(){bn=!0,!Le&&(Le=setTimeout(async()=>{if(Le=null,!!bn){bn=!1;try{await Ot.mkdir(z.dirname(hn),{recursive:!0}),await Ot.writeFile(hn,JSON.stringify(se))}catch(c){T.error("[plane-link] cursor flush failed:",c?.message||c)}}},nu),Le.unref?.())}function _n(){try{return!!fe?.()}catch{return!1}}function Tn(){let c=H==="http"?me:on;return _n()?Math.min(c,st):c}function C(c){return!J||J.readyState!==gr.OPEN?!1:(J.send(JSON.stringify(c)),!0)}let Yi=li(c=>C({v:B,ch:"ctl",type:"mcp_status",mcp:c}));function Fe(c){let f=Date.now();for(let{trackId:i,event:u}of c){let w=j.get(u.id);j.set(u.id,{trackId:i,seq:u.seq,event:u,sentAt:f,firstSentAt:w?.firstSentAt??f,retryAt:f+je,tries:(w?.tries??0)+1,nacks:w?.nacks??0})}let p=c.map(({trackId:i,event:u})=>({trackId:i,event:cu(u)}));return H==="http"?(ta(p),!0):C({v:B,ch:"events",type:"append",events:p})}function Wr(c,f=Date.now()){if(at.has(c))return!0;for(let p of j.values())if(p.trackId===c&&f-p.firstSentAt<De)return!0;return!1}function Xi(c){let f=null;for(let p of j.values())p.trackId===c&&(f==null||p.seq<f)&&(f=p.seq);return f}function xn(c){let f=re[c];if(f==null)return;let p=Xi(c),i=p==null?f:Math.min(f,p-1);i>(se[c]??0)&&(se[c]=i,Hr())}function dt(){if(Mt=Date.now(),he!=null){let c=Date.now()-he;T.log(`[plane-link] spine sync recovered after ${Math.round(c/1e3)}s degraded (${ie} stall redial(s))`);let f=he;he=null,ie=0,it=0,ee=!1,xe=0;try{Me?.({since:f,downMs:c})}catch(p){T.error(`[plane-link] onRecovered failed: ${p?.message||p}`)}}}function $n(c){if(!Array.isArray(c)||!c.length)return;let f=new Set;for(let p of c){let i=j.get(p);i&&(j.delete(p),(re[i.trackId]??0)<i.seq&&(re[i.trackId]=i.seq),f.add(i.trackId))}for(let p of f)xn(p);dt()}function Kr(c,f){Br++;let p={at:Date.now(),trackId:c.trackId,seq:c.seq,id:c.event?.id??null,type:c.event?.type??null,reason:f,event:c.event??null};T.error(`[plane-link] DEAD-LETTER ${c.trackId} seq ${c.seq} (${p.type??"?"}): plane rejected it permanently (${f}) \u2014 kept in ${mn}`),Fr=Fr.then(async()=>{await Ot.mkdir(z.dirname(mn),{recursive:!0}),await Ot.appendFile(mn,JSON.stringify(p)+`
137
+ `)}).catch(i=>T.error(`[plane-link] dead-letter write failed: ${i?.message||i}`))}function Ji(c,f){if(Pt[c]=(Pt[c]??0)+1,Lr.has(c))return;Lr.add(c);let p=au[c]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";T.error(`[plane-link] REFUSED by the plane (${c}) on track ${f}: events are being dropped, not stored \u2014 ${p}`);try{fn?.({reason:c,trackId:f,count:Pt[c],hint:p})}catch(i){T.error(`[plane-link] onRefused failed: ${i?.message||i}`)}}function vn(c,f,p,i=null){if(!Array.isArray(c)||!c.length)return;let u=new Set,w=Date.now();for(let $ of c){let k=j.get($);k&&(p?(j.delete($),Kr(k,f),String(f).startsWith(wr)&&Ji(String(f).slice(wr.length),k.trackId),(re[k.trackId]??0)<k.seq&&(re[k.trackId]=k.seq),u.add(k.trackId)):(k.nacks++,k.retryAt=w+Math.max(1e3,Number(i)||je)))}for(let $ of u)xn($);dt()}function zr(c=Date.now()){let f=1/0;for(let p of j.values())p.firstSentAt<f&&(f=p.firstSentAt);return f===1/0?0:c-f}function Zi(c){if(!P||!c||c!==J||!$e)return!1;let f=Date.now()-$e;if(f<=P)return!1;Ur++,T.error(`[plane-link] no frame from the plane for ${Math.round(f/1e3)}s \u2014 link is half-open; terminating and redialing`);try{c.terminate()}catch{}return!0}function Gr(){if(!Z||!j.size)return;let c=Date.now(),f=zr(c);if(f<De||Mt!=null&&c-Mt<De||H==="http"&&ee||it>c)return;ie++;let p=Math.min(Mr*2**(ie-1),Ei);if(he==null){he=c-f,T.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(f/1e3)}s with ${j.size} event(s) in flight (${H} door) \u2014 the plane is not answering appends`);try{rt?.({since:he,unacked:j.size,oldestAgeMs:f,mode:H})}catch(i){T.error(`[plane-link] onDegraded failed: ${i?.message||i}`)}}if(H==="http"){ee=!0,xe=c+p,T.error(`[plane-link] ingest circuit OPEN (stall #${ie}); probing /v1/ingest/health in ${Math.round(p/1e3)}s`);return}it=c+p,T.error(`[plane-link] closing the link and redialing in ${Math.round(p/1e3)}s (stall redial #${ie})`);try{J?.terminate()}catch{}}function An(){if(!Z)return;let c=Date.now();if(H==="http"&&ee)return;let f=[...j.values()].filter(i=>i.event&&i.retryAt<=c&&!(H==="http"&&at.has(i.trackId)));if(!f.length)return;f.sort((i,u)=>i.trackId===u.trackId?i.seq-u.seq:i.trackId<u.trackId?-1:1),T.log(`[plane-link] re-sending ${f.length} unacked event(s) the plane never confirmed`);let p=Tn();if(H==="http"){let i=new Map;for(let u of f)(i.get(u.trackId)??i.set(u.trackId,[]).get(u.trackId)).push(u);for(let[,u]of i){if(Ce>=yr)return;Fe(u.slice(0,p).map(w=>({trackId:w.trackId,event:w.event})))}return}for(let i=0;i<f.length;i+=p){let u=f.slice(i,i+p).map(w=>({trackId:w.trackId,event:w.event}));if(!Fe(u))return}}async function Qi(c=null){for(;;){if(!Z)return!1;let f=j.size<de,p=H!=="http"||Ce<yr&&!ee&&(!c||!Wr(c));if(f&&p)return!0;await new Promise(i=>setTimeout(i,100))}}function jt(){if(W=null,!Z||!te.length)return;let c=te;te=[];let f=Tn();if(H!=="http"){for(let u=0;u<c.length;u+=f)Fe(c.slice(u,u+f));return}let p=_n(),i=new Map;for(let u of c)(i.get(u.trackId)??i.set(u.trackId,[]).get(u.trackId)).push(u);for(let[u,w]of i){if(Wr(u)||Ce>=yr||ee){te.push(...w);continue}if(p){Fe(w.slice(0,f)),te.push(...w.slice(f));continue}for(let $=0;$<w.length;$+=f)Fe(w.slice($,$+f))}te.length&&!W&&(W=setTimeout(jt,Oi),W.unref?.())}let ea=c=>{let f=new Map;for(let{trackId:p,event:i}of c)(f.get(p)??f.set(p,[]).get(p)).push(i);return[...f].map(([p,i])=>({trackId:p,events:i}))},ve=(c,f,p,{progress:i})=>{let u=Date.now();for(let{event:w}of c){let $=j.get(w.id);$&&($.nacks++,$.retryAt=u+Math.max(1e3,p||je))}i&&dt()};async function ta(c){let f=new Set(c.map(p=>p.trackId));for(let p of f)at.add(p);Ce++;try{let p=await Pr(`${Cr}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:ea(c)}),signal:AbortSignal.timeout(pe)}),i=(Number(p.headers.get("retry-after"))||0)*1e3;if(p.status===200){let u=await p.json();me=on;for(let k of u.results??[]){$n(k.acked??[]);let F=(oe,V)=>{let Ct=new Map;for(let Ae of oe??[])(Ct.get(Ae.reason)??Ct.set(Ae.reason,[]).get(Ae.reason)).push(Ae.id);for(let[Ae,eo]of Ct)vn(eo,Ae,V,u.retryAfterMs??null)};F(k.rejected,!0),F(k.deferred,!1)}let w=new Set,$=new Map;for(let k of Array.isArray(u.refused)?u.refused:[])!k||typeof k.id!="string"||(w.add(k.id),($.get(k.reason)??$.set(k.reason,[]).get(k.reason)).push(k.id));for(let[k,F]of $)vn(F,`${wr}${k}`,!0);$n((u.discarded??[]).filter(k=>!w.has(k))),dt();return}if(p.status===429){ve(c,"overloaded",i||5e3,{progress:!0});return}if(p.status===413&&c.length>1){me=Math.max(1,Math.floor(c.length/2)),T.error(`[plane-link] ingest request too large (${c.length} events) \u2014 halving batches to ${me}`),ve(c,"too_large",1e3,{progress:!0});return}if(p.status===413){let u=j.get(c[0].event.id);u&&(j.delete(u.event.id),Kr(u,"too_large"),(re[u.trackId]??0)<u.seq&&(re[u.trackId]=u.seq),xn(u.trackId)),dt();return}if(p.status===410){Sn({reason:"removed",via:"410"}),ve(c,"http_410",6e4,{progress:!1});return}if(p.status===401||p.status===403){let{tripped:u,holdMs:w}=qt();if(u&&T.error(`[plane-link] holding every plane call for ${Math.round(w/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Dt>=Ri){Dt=Date.now();let $="";try{$=(await p.json())?.error??""}catch{}T.error(`[plane-link] plane refused ingest (HTTP ${p.status}${$?`: ${$}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}ve(c,`http_${p.status}`,Math.max(6e4,_t()),{progress:!1});return}if(p.status===400){T.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${c.length} event(s) for retry; this is a bug, not data`),ve(c,"http_400",6e4,{progress:!1});return}ve(c,`http_${p.status}`,i||5e3,{progress:!1})}catch(p){let i=p?.name==="TimeoutError"||p?.name==="AbortError";i&&c.length>1&&(me=Math.max(1,Math.floor(c.length/2)),T.error(`[plane-link] ingest request of ${c.length} event(s) outlived its ${pe} ms deadline \u2014 halving batches to ${me}`)),ve(c,i?"timeout":"network",5e3,{progress:!1})}finally{Ce--;for(let p of f)at.delete(p);te.length&&!W&&(W=setTimeout(jt,0),W.unref?.())}}async function na(){if(H!=="http"||!ee||!Z||gn)return;let c=Date.now();if(!(xe>c||Yt(c))){gn=!0;try{let f=await Pr(`${Cr}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(pe)});if(!f.ok)throw new Error(`HTTP ${f.status}`);T.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),ee=!1,xe=0,it=Date.now()+pe+je+1e3;for(let p of j.values())p.retryAt=Math.min(p.retryAt,Date.now());An()}catch(f){ie++;let p=Math.min(Mr*2**(ie-1),Ei);xe=Date.now()+p,T.error(`[plane-link] ingest door still not answering (${f?.message||f}); next probe in ${Math.round(p/1e3)}s`)}finally{gn=!1}}}function Vr(){let c=Date.now();return{mode:H,unacked:j.size,oldestUnackedAgeMs:zr(c),lastProgressAt:Mt,degradedSince:he,stallRedials:ie,deadLettered:Br,fanoutCap:_n()?st:null,http:H==="http"?{inFlight:Ce,circuitOpen:ee,nextProbeInMs:ee?Math.max(0,xe-c):0,batchCap:me,heldLive:te.length}:null}}async function qr(){if(!h)return;let c;try{c=await h()}catch(p){T.error("[plane-link] metrics sample failed:",p?.message||p);return}let f=null;try{f=m?.()??null}catch{}c&&C({v:B,ch:"ctl",type:"metrics",metrics:{...c,planeLink:Vr(),...f?{delivery:f}:{}}})}function ra(){h&&(ce&&clearInterval(ce),qr(),ce=setInterval(qr,v),ce.unref?.())}async function oa(){let c;try{c=await o()}catch(f){T.error("[plane-link] backfill listTracks failed:",f?.message||f);return}C({v:B,ch:"ctl",type:"tracks",ids:c.filter(f=>!f.transferredTo).map(f=>f.id).filter(f=>typeof f=="string")});for(let f of c)if(!Z||!await Yr(f))return}async function Yr(c){let f;try{f=await Xt(c)}catch{return!0}let p=se[c.id]??0,i=f.filter(u=>u.seq>p&&typeof u.id=="string");for(let u=0;u<i.length;){if(!await Qi(c.id))return!1;let w=i.slice(u,u+Tn()).map($=>({trackId:c.id,event:$}));if(!Fe(w))return!1;u+=w.length}return!0}let kn=new Map;async function Xr(c,f){if(kn.get(c)===f)return!1;kn.set(c,f);let p=null;try{p=(await o()).find($=>$?.id===c)??null}catch{return!1}if(!p)return!1;let i;try{i=await Xt(p)}catch{return!1}let u=[...i].reverse().find($=>($?.type==="track.transferred"||$?.type==="track.recovered")&&$.payload?.toNode===n);if(!u||!Number.isFinite(u.seq))return!1;let w=u.seq-1;return(se[c]??0)>w&&(se[c]=w,Hr()),(re[c]??0)>w&&(re[c]=w),T.log(`[plane-link] re-sending ${c}'s move-commit (seq ${u.seq}, ${u.type}) \u2014 the plane's move record predates this node's adoption`),Z?Yr(p):!1}function Jr(c){!Z||!c?.trackId||typeof c.id!="string"||(te.push({trackId:c.trackId,event:c}),W||(W=setTimeout(jt,Oi),W.unref?.()))}let pt=new Map;async function sa(c){let{reqId:f,method:p,path:i,headers:u={},body:w}=c,$=Object.fromEntries(Object.entries(u).filter(([,F])=>F!=null)),k=new AbortController;pt.set(f,k);try{if(c.host){await ia(c,$,k);return}x&&($["x-bostrat-token"]=x);let F=await fetch(O+i,{method:p,headers:$,body:w?Buffer.from(w,"base64"):void 0,signal:k.signal}),oe=Object.fromEntries(F.headers);for(let V of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete oe[V];if(oe["content-type"]||(oe["content-type"]="application/octet-stream"),C({v:B,ch:"control",type:"http_head",reqId:f,status:F.status,headers:oe}),F.body){for await(let V of F.body)if(!C({v:B,ch:"control",type:"http_data",reqId:f,data:Buffer.from(V).toString("base64")}))break}C({v:B,ch:"control",type:"http_end",reqId:f,error:null})}finally{pt.delete(f)}}function ia(c,f,p){let{reqId:i,method:u,path:w,body:$}=c,k=new URL(O);return new Promise(F=>{let oe=Jl.request({host:k.hostname,port:k.port,method:u,path:w,headers:{...f,host:c.host},signal:p.signal},V=>{let{connection:Ct,"keep-alive":Ae,"transfer-encoding":eo,upgrade:pd,...aa}=V.headers;C({v:B,ch:"control",type:"http_head",reqId:i,status:V.statusCode||502,headers:aa}),V.on("data",ca=>{C({v:B,ch:"control",type:"http_data",reqId:i,data:Buffer.from(ca).toString("base64")})||V.destroy()}),V.on("end",()=>{C({v:B,ch:"control",type:"http_end",reqId:i,error:null}),F()}),V.on("error",()=>{C({v:B,ch:"control",type:"http_end",reqId:i,error:"view upstream error"}),F()})});oe.on("error",V=>{C({v:B,ch:"control",type:"http_end",reqId:i,error:V?.message||"view request failed"}),F()}),$&&oe.write(Buffer.from($,"base64")),oe.end()})}function Zr(){if(wn||ut)return;J=new gr(e,{headers:{authorization:`Bearer ${t}`}});let c=J;$e=0,c.on("ping",()=>{$e=Date.now()}),c.on("pong",()=>{$e=Date.now()}),J.on("open",async()=>{let p=null;try{p=await s?.()||null}catch{p=null}C({v:B,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:ne,installKind:E,...typeof _=="function"?{updatePolicy:_()}:_?{updatePolicy:_}:{},providers:Ii(),...p?{agents:p}:{},mcp:rn(),...yn?{restart:yn}:{}})}),J.on("message",p=>{$e=Date.now();let i;try{i=JSON.parse(p)}catch{return}if(i.ch==="ctl"&&i.type==="hello_ok"){kn.clear(),Z=!0,ct=Ai,lt=null,yn=null,Lo(),T.log(`[plane-link] connected to plane as ${n}`);try{It?.()}catch{}if(typeof i.hashKey=="string"&&i.hashKey)try{d?.(i.hashKey)}catch{}try{g?.(typeof i.viewBase=="string"&&i.viewBase?i.viewBase:null)}catch{}i.minNodeVersion&&ne&&Qe(ne,i.minNodeVersion)&&T.error(`[plane-link] this node is bostrat-node ${ne}; the plane asks for \u2265${i.minNodeVersion} \u2014 update with: ${Rt(E)}`);try{b?.(typeof i.updatePolicy=="string"?i.updatePolicy:null)}catch{}jr(i);let u=i.ingest==="http";H=Pe==="ws"?"ws":Pe==="http"||u?"http":"ws",Pe==="http"&&!u&&T.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),H==="http"&&T.log("[plane-link] spine rides the HTTPS ingest door"),ee=!1,xe=0,me=on,ae&&clearInterval(ae),$e=Date.now(),ae=setInterval(()=>{Zi(c)||(C({v:B,ch:"ctl",type:"ping"}),Gr(),na().catch(()=>{}),An(),te.length&&!W&&jt())},ot),ae.unref?.(),ra(),oa().catch(w=>T.error("[plane-link] backfill failed:",w?.message||w));return}if(i.ch==="ctl"&&i.type==="hello_refused"){let u=typeof i.minNodeVersion=="string"?i.minNodeVersion:null,w=typeof i.latestNodeVersion=="string"?i.latestNodeVersion:null;T.error(`[plane-link] plane REFUSED this node: bostrat-node ${ne??"?"} is below its minimum ${u??"?"} \u2014 ${i.fix||Rt(E)}`),ct=ki,lt=0;try{A?.({current:ne,min:u,latest:w,fix:i.fix||Rt(E),installKind:E})}catch($){T.error(`[plane-link] refusal handler failed: ${$?.message||$}`)}return}if(i.ch==="ctl"&&i.type==="removed"){C({v:B,ch:"ctl",type:"removed_ack",nodeId:n}),Sn({reason:typeof i.reason=="string"?i.reason:"removed",at:Number(i.at)||Date.now(),via:"ctl"});return}if(i.ch==="ctl"&&i.type==="update_available"){jr(i);return}if(i.ch==="ctl"&&i.type==="update_policy"){try{b?.(typeof i.mode=="string"?i.mode:null)}catch{}return}if(i.ch==="ctl"&&i.type==="conflict_probe"&&Array.isArray(i.trackIds)){try{I?.(i.trackIds.filter(u=>typeof u=="string"&&u).slice(0,200))}catch{}return}if(i.ch==="ctl"&&i.type==="restarted"){Promise.resolve().then(()=>N?.({kind:i.kind,at:i.at,reason:i.reason})).catch(u=>T.error("[plane-link] restart notice failed:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="usage_caps"){Vs(i.caps??{},{source:"plane",updatedAt:i.updatedAt??Date.now()}).then(u=>T.log(`[plane-link] spend caps ${Object.keys(u.caps).length?`updated (${Object.keys(u.caps).join(", ")})`:"cleared"} from plane`)).catch(u=>T.error("[plane-link] spend-caps push rejected:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="mcp_config"){fi(i.entries??[],{updatedAt:i.updatedAt??Date.now()}).then(u=>T.log(`[plane-link] mcp config applied: ${Object.keys(u.entries).length} entr${Object.keys(u.entries).length===1?"y":"ies"}`)).catch(u=>T.error("[plane-link] mcp config apply failed:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="refresh_flow"){$i(i.flow??{},{source:"plane",updatedAt:i.updatedAt??Date.now()}).then(u=>T.log(`[plane-link] refresh flow from plane: contextFull=${u.flow.contextFull} rung=${u.flow.contextFullTokens?`${u.flow.contextFullTokens} tokens`:`${u.flow.contextFullPct}%`}`)).catch(u=>T.error("[plane-link] refresh-flow push rejected:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="refresh_flow_rejected"){xi(typeof i.error=="string"?i.error:"rejected by the plane");return}if(i.ch==="ctl"&&i.type==="transferred"&&Array.isArray(i.tracks)){Promise.resolve().then(()=>a?.(i.tracks)).then(async u=>{for(let w of Array.isArray(u)?u:[])w?.stale&&w.id&&await Xr(w.id,w.since??null)}).catch(u=>T.error("[plane-link] transfer notice failed:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="moves"&&Array.isArray(i.tracks)){Promise.resolve().then(()=>l?.(i.tracks)).then(async u=>{for(let w of Array.isArray(u)?u:[])w?.stale&&w.id&&await Xr(w.id,w.since??null)}).catch(u=>T.error("[plane-link] move-record reconcile failed:",u?.message||u));return}if(i.ch==="events"&&i.type==="ack"&&Array.isArray(i.ids)){$n(i.ids);return}if(i.ch==="events"&&i.type==="nack"&&Array.isArray(i.ids)){vn(i.ids,i.reason,i.permanent===!0,i.retryAfterMs??null);return}if(i.ch==="control"&&i.type==="http_open"){sa(i).catch(u=>C({v:B,ch:"control",type:"http_end",reqId:i.reqId,error:u?.message||"tunnel error"}));return}if(i.ch==="control"&&i.type==="http_cancel"){pt.get(i.reqId)?.abort();return}if(i.ch==="attach"&&i.type==="open"){let u=new gr(Vi+i.path,Array.isArray(i.protocols)?i.protocols:[],i.host?{headers:{host:i.host}}:void 0);_e.set(i.streamId,u),Te.set(i.streamId,[]),u.on("open",()=>{let $=Te.get(i.streamId)||[];Te.delete(i.streamId);for(let{buf:k,bin:F}of $)u.send(k,{binary:F})}),u.on("message",($,k)=>{let F=k?$:Buffer.from(String($));C({v:B,ch:"attach",type:"data",streamId:i.streamId,data:F.toString("base64"),...k?{bin:!0}:{}})});let w=()=>{Te.delete(i.streamId),_e.delete(i.streamId)&&C({v:B,ch:"attach",type:"close",streamId:i.streamId})};u.on("close",w),u.on("error",w);return}if(i.ch==="attach"&&i.type==="data"){let u=_e.get(i.streamId);if(!u)return;let w=Buffer.from(i.data,"base64"),$=i.bin===!0,k=Te.get(i.streamId);k?k.push({buf:w,bin:$}):u.send(w,{binary:$});return}if(i.ch==="attach"&&i.type==="close"){let u=_e.get(i.streamId);_e.delete(i.streamId),Te.delete(i.streamId),u?.close();return}});let f=()=>{Z&&T.log("[plane-link] disconnected from plane"),Z=!1,ae&&(clearInterval(ae),ae=null),ce&&(clearInterval(ce),ce=null),j.clear(),re={},te=[],W&&(clearTimeout(W),W=null),at.clear();for(let u of _e.values())u.close();_e.clear(),Te.clear();for(let u of pt.values())u.abort();if(pt.clear(),wn||Be)return;lt==null&&(lt=Date.now());let p=Date.now()-lt<Ql,i=Math.max(p?eu+Math.random()*tu:ct,it-Date.now(),_t());Be=setTimeout(()=>{Be=null,Zr()},i),Be.unref?.(),p||(ct=Math.min(ct*2,ki))};J.on("close",f),J.on("error",p=>{let i=/Unexpected server response: (\d+)/.exec(p?.message||"")?.[1];if(i==="410"){Sn({reason:"removed",via:"410"});return}if(i==="401"||i==="403"){let{tripped:u,holdMs:w}=qt();u?T.error(`[plane-link] holding every plane call for ${Math.round(w/6e4)} min \u2014 three credential refusals in a row (HTTP ${i}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(w/6e4)} min.`):Date.now()-Dt>=Ri&&(Dt=Date.now(),T.error(`[plane-link] plane refused this node's credentials (HTTP ${i}) \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()})}xt.on("event",Jr),qi().then(Zr);function Qr({bye:c=!0}={}){wn=!0,xt.off("event",Jr),Yi(),Be&&clearTimeout(Be),Le&&clearTimeout(Le),ae&&clearInterval(ae),ce&&clearInterval(ce),W&&clearTimeout(W),c&&C({v:B,ch:"ctl",type:"bye",reason:"shutdown"}),J?.close()}return{stop:()=>Qr(),setRefreshFlow:c=>C({v:B,ch:"ctl",type:"refresh_flow_set",patch:c}),status:()=>({connected:Z,nodeId:n,cursor:{...se},inflight:j.size,...Vr(),auth:Fo(),dormant:ut,removed:Qn(),deadLinkMs:P,deadLinkRedials:Ur,refused:{...Pt}}),_tick:()=>{Gr(),An()}}}var ne,br,_r,B,Ai,ki,Ql,eu,tu,on,nu,ru,ou,su,Tr,iu,wr,au,cu,lu,Ei,uu,Oi,du,yr,pu,fu,Ri,xr=R(()=>{Jt();qs();hi();vi();Rn();er();ne=(()=>{try{return Zl(import.meta.url)("../package.json").version||null}catch{return null}})(),br=process.env.BOSTRAT_STATE_DIR||z.join(process.env.HOME||sn.tmpdir(),".bostrat"),_r=z.join(br,"plane-link","removed.json");B=1,Ai=1e3,ki=3e4,Ql=6e4,eu=1500,tu=500,on=100,nu=2e3,ru=25e3,ou=2.5,su=6e4,Tr=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},iu=Tr(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),wr="refused:",au={forgedUserId:"this node's events carry a userId the plane's token does not own \u2014 remove BOSTRAT_OWNER from node.env and the shell environment, then restart the node (current releases never stamp one)",foreignTrack:"the Track belongs to another user's node \u2014 this node must not append to it",squattedTrack:"the Track id is already claimed by another user \u2014 a local Track collided with theirs",transferredAway:"the Track moved to another node \u2014 this copy is stale; it should be demoted, not resumed",slugHijack:"a View slug belongs to another owner \u2014 pick a different slug"},cu=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},lu=3e4,Ei=10*6e4,uu=400,Oi=250,du=Tr(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),yr=4,pu=Math.max(1,Math.round(Tr(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),fu=6e4,Ri=6e4});var Pi=R(()=>{Xn()});var Ui={};En(Ui,{ACTIONABLE_KINDS:()=>dn,INSTALL_ATTEMPTS:()=>an,INSTALL_RETRY_STEP_S:()=>Di,REGISTRY_RETRY_ATTEMPTS:()=>Ar,REGISTRY_WAIT_POLLS:()=>$r,REGISTRY_WAIT_STEP_S:()=>vr,RESTART_SIGNAL:()=>Ci,SELF_UPDATE_DIR:()=>ln,SUPERVISOR_PID_FILE:()=>ji,createAutoUpdater:()=>Ou,inFlight:()=>Rr,readStatus:()=>Or,restartCommand:()=>Bi,restartStrategy:()=>Er,selfUpdatePlan:()=>Li,settleSelfUpdate:()=>Eu,startSelfUpdate:()=>Fi,underService:()=>kr,updatePolicy:()=>Tu});import Nt from"node:fs";import be from"node:fs/promises";import mu from"node:os";import U from"node:path";import{spawn as gu,execFileSync as wu}from"node:child_process";import{createRequire as yu}from"node:module";function Tu({kind:e=et(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:dn.has(e)?e==="git-checkout"||kr(t)?"auto":"prompt":"off"}function kr(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Er({env:e=process.env,platform:t=process.platform,uid:n=typeof process.getuid=="function"?process.getuid():0,serviceName:r=t==="darwin"?"com.bostrat.node":"bostrat-node.service",pidFile:o=ji,readFile:s=l=>Nt.readFileSync(l,"utf8"),alive:a=xu}={}){let l=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(kr(e))return l;let h=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(h)&&h>0)){try{h=Number(String(s(o)).trim())}catch{h=NaN}Number.isInteger(h)&&h>0&&a(h)||(h=NaN)}return Number.isInteger(h)&&h>0?{mode:"supervisor",pid:h}:l}function xu(e){try{process.kill(e,0)}catch{return!1}try{let t=wu("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/bostrat-node|\/cli\.js|node-cli\.js/.test(t)}catch{return!1}}function Bi(e){switch(e?.mode){case"systemd":return`systemctl --user restart ${Q(e.serviceName||"bostrat-node.service")}`;case"launchd":return`launchctl kickstart -k gui/${Number(e.uid)||0}/${e.serviceName||"com.bostrat.node"}`;case"supervisor":return`kill -${Ci.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function Li({kind:e,to:t,from:n=cn,statusFile:r=un,logFile:o=U.join(ln,"last.log"),port:s=Number(process.env.PORT)||3362,npmPrefix:a=null,serviceName:l=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:h=typeof process.getuid=="function"?process.getuid():0,restart:m=Er({env:{},platform:process.platform,uid:h,serviceName:l,readFile:()=>{throw new Error("no pidfile")}}),liveDir:d=process.env.BOSTRAT_LIVE_CHECKOUT||U.resolve(U.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:g=Date.now(),attempts:v=1}={}){if(!dn.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 y=(A,_="")=>`write_status ${Q(A)} ${_}`,b=Bi(m),I=`
138
138
  health() {
139
139
  for i in $(seq 1 45); do
140
140
  sleep 1
@@ -158,29 +158,29 @@ write_status() { # <status> [error] [retryable]
158
158
  "\${err:+,\\"error\\":\\"$err\\"}" "\${3:+,\\"retryable\\":true}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
159
159
  }
160
160
  ${I}
161
- `;if(e==="npm-global"){let k=a?U.join(a,"bin","npm"):"npm",_=a?`export PATH=${Q(U.join(a,"bin"))}:"$PATH"
162
- `:"",E=a?` --prefix ${Q(a)}`:"",O=Ie=>`${Q(k)} install -g "bostrat-node@${Ie}" --no-audit --no-fund${E}`,x=`
161
+ `;if(e==="npm-global"){let A=a?U.join(a,"bin","npm"):"npm",_=a?`export PATH=${Q(U.join(a,"bin"))}:"$PATH"
162
+ `:"",E=a?` --prefix ${Q(a)}`:"",O=Ie=>`${Q(A)} install -g "bostrat-node@${Ie}" --no-audit --no-fund${E}`,x=`
163
163
  install_target() {
164
- for i in $(seq 1 ${sn}); do
164
+ for i in $(seq 1 ${an}); do
165
165
  if ${O("$TO")}; then return 0; fi
166
- [ "$i" -lt ${sn} ] && sleep ${Pi}
166
+ [ "$i" -lt ${an} ] && sleep ${Di}
167
167
  done
168
168
  return 1
169
169
  }`,M=`
170
170
  wait_for_registry() {
171
- for i in $(seq 1 ${xr}); do
172
- if [ "$(${Q(k)} view "bostrat-node@$TO" version --prefer-online 2>/dev/null)" = "$TO" ]; then return 0; fi
173
- sleep ${$r}
171
+ for i in $(seq 1 ${$r}); do
172
+ if [ "$(${Q(A)} view "bostrat-node@$TO" version --prefer-online 2>/dev/null)" = "$TO" ]; then return 0; fi
173
+ sleep ${vr}
174
174
  done
175
175
  return 1
176
176
  }`;return S+_+M+x+`
177
177
  ${y("updating",'"" ')}
178
178
  if ! wait_for_registry; then
179
- ${y("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(xr*$r/60)} min, attempt $ATTEMPTS of ${vr})" retryable`)}
179
+ ${y("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round($r*vr/60)} min, attempt $ATTEMPTS of ${Ar})" retryable`)}
180
180
  exit 1
181
181
  fi
182
182
  if ! install_target; then
183
- ${y("failed",`"npm install failed (${sn} attempts)"`)}
183
+ ${y("failed",`"npm install failed (${an} attempts)"`)}
184
184
  exit 1
185
185
  fi
186
186
  ${y("restarting")}
@@ -200,7 +200,7 @@ if [ -n "$FROM" ] && ${O("$FROM")} && ${b} && health; then
200
200
  fi
201
201
  ${y("failed",'"agent did not answer after the update AND the rollback"')}
202
202
  exit 1
203
- `}let N=k=>`( cd ${Q(d)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${k}" )`;return S+`
203
+ `}let N=A=>`( cd ${Q(d)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${A}" )`;return S+`
204
204
  LIVE=${Q(d)}
205
205
  TMP_SCRIPT="$(mktemp)"
206
206
  trap 'rm -f "$TMP_SCRIPT"' EXIT
@@ -218,13 +218,13 @@ if [ -n "$FROM" ] && ${N("$FROM")}; then
218
218
  fi
219
219
  ${y("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
220
220
  exit 1
221
- `}async function Er(e=ln){try{return JSON.parse(await ye.readFile(e,"utf8"))}catch{return null}}async function Li({to:e,from:t=an,kind:n=et(),reason:r="manual",force:o=!1,statusFile:s=ln,spawnImpl:a=mu,now:l=Date.now,npmPrefix:h=void 0,log:m=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!un.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Qe(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let d=await Er(s);if(Or(d))return{ok:!1,reason:`an update to ${d.to} is already in flight`,status:d};let g=d?.to===e?Number(d.attempts)||1:0;if(!o&&d&&d.to===e&&(d.status==="failed"||d.status==="rolled-back")&&!(d.status==="failed"&&d.retryable===!0&&g<vr))return{ok:!1,reason:`update to ${e} already ${d.status} (${d.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:d};let v=d?.to===e&&(d.status==="failed"||d.status==="rolled-back")?g+1:1;await ye.mkdir(U.dirname(s),{recursive:!0});let y=h!==void 0?h:n==="npm-global"?qn(await $u())||U.resolve(U.dirname(process.execPath),".."):null,b=Ar(),I=Bi({kind:n,to:e,from:t,statusFile:s,npmPrefix:y,startedAt:l(),attempts:v,restart:b}),S=U.join(U.dirname(s),`update-${e}.sh`),N=U.join(U.dirname(s),"last.log");await ye.writeFile(S,I,{mode:448}),await ye.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:v,startedAt:l(),updatedAt:l()}));let k=Rt.existsSync("/run/systemd/system")&&await vu("systemd-run"),_=k?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",S]]:["bash",[S]],E=async x=>{let M=`could not spawn updater: ${x?.message||x}`;return await ye.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,attempts:v,startedAt:l(),updatedAt:l(),error:M})).catch(()=>{}),m.error?.(`[self-update] ${M}`),M},O=null;try{k||(O=Rt.openSync(N,"a"));let x=a(_[0],_[1],{detached:!0,stdio:k?"ignore":["ignore",O,O]});x.on?.("error",M=>{E(M)}),x.unref?.()}catch(x){return{ok:!1,reason:await E(x)}}finally{O!==null&&Rt.closeSync(O)}return m.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}, restart via ${b.mode}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:S,statusFile:s}}async function $u(){try{return await ye.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function vu(e){for(let t of String(process.env.PATH||"").split(U.delimiter))try{return await ye.access(U.join(t,e),Rt.constants.X_OK),!0}catch{}return!1}async function Au({statusFile:e=ln,current:t=an,now:n=Date.now,staleMs:r=ku}={}){let o=await Er(e);if(!o)return null;let s=a=>ye.writeFile(e,JSON.stringify(a)).catch(()=>{});if(Or(o)){if(t&&o.to===t){let a={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await s(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 s(a),a}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let a={...o,announced:!0};return await s(a),a}return null}function Eu({isBusy:e,start:t=Li,onStuck:n=null,onStarted:r=null,tickMs:o=Su,stuckMs:s=bu,now:a=Date.now,setIntervalImpl:l=setInterval,clearIntervalImpl:h=clearInterval,log:m=console}={}){let d=null,g=()=>{d?.timer&&h(d.timer),d=null},v=async()=>{if(!d)return;let y=!0;try{y=await e()!==!1}catch{y=!0}if(y){if(!d.stuckFired&&a()-d.since>=s){d.stuckFired=!0;try{await n?.({to:d.to,from:d.from,since:d.since})}catch{}}return}let b=d;g();let I=await t({to:b.to,from:b.from,kind:b.kind,reason:"auto"});m.log?.(`[self-update] stasis reached \u2192 ${I.ok?"started":`not started: ${I.reason}`}`);try{await r?.({...b,result:I})}catch{}};return{arm({to:y,from:b=an,kind:I=et()}){return d?.to===y?!1:(g(),d={to:y,from:b,kind:I,since:a(),stuckFired:!1,timer:l(v,o)},d.timer.unref?.(),!0)},tick:v,cancel:g,get armed(){return d?{to:d.to,from:d.from,kind:d.kind,since:d.since}:null}}}var an,yu,cn,ln,bu,Su,xr,$r,vr,sn,Pi,Di,ji,un,Q,xu,Or,ku,Ui=R(()=>{Tr();Mi();an=(()=>{try{return wu(import.meta.url)("../package.json").version||null}catch{return null}})(),yu=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||hu.tmpdir(),".bostrat"),cn=U.join(yu,"self-update"),ln=U.join(cn,"status.json"),bu=1440*6e4,Su=6e4,xr=60,$r=15,vr=3,sn=6,Pi=20,Di=U.join(cn,"supervisor.pid"),ji="SIGUSR2",un=new Set(["npm-global","git-checkout"]);Q=e=>`'${String(e).replace(/'/g,"'\\''")}'`;xu=new Set(["updating","restarting","rolling-back"]),Or=e=>!!(e&&xu.has(e.status));ku=45*6e4});Rn();Vn();nr();import z from"node:fs";import L from"node:path";import nt from"node:os";import{createRequire as Rr}from"node:module";import{execFile as Ou,spawn as Ru}from"node:child_process";import{promisify as Nu}from"node:util";import Iu from"node:readline/promises";import{randomUUID as Mu}from"node:crypto";import{fileURLToPath as Pu}from"node:url";import Qt from"node:fs";import Ve from"node:fs/promises";import Gc from"node:os";import vt from"node:path";import Vc from"node:readline";import{spawn as qc}from"node:child_process";var Yc="^(ugrep|rg|2\\.1\\.[0-9]+|cursor-agent|codex|npm|node|MainThread)",Xc="^(bostrat-|tmux|earlyoom|systemd|sshd)",Jc=()=>["-m","10","-s","70","-r","600","--prefer",Yc,"--avoid",Xc],cs="BOSTRAT_OOM_GUARD_OWNER",Zc=6e4,Qc=5e3;function ls(e=process.env){return!["0","off","false","no"].includes(String(e.BOSTRAT_OOM_GUARD??"").trim().toLowerCase())}function us(e=process.env){let t=e.BOSTRAT_STATE_DIR||vt.join(e.HOME||Gc.tmpdir(),".bostrat");return vt.join(t,"oom-guard.pid")}function ds(e=process.env){if(e.BOSTRAT_EARLYOOM_BIN)return Qt.existsSync(e.BOSTRAT_EARLYOOM_BIN)?e.BOSTRAT_EARLYOOM_BIN:null;let t=[...String(e.PATH||"").split(":").filter(Boolean),"/usr/bin","/usr/sbin","/usr/local/bin","/bin"];for(let n of t){let r=vt.join(n,"earlyoom");if(Qt.existsSync(r))return r}return null}async function fs({procRoot:e="/proc"}={}){let t=[];try{t=await Ve.readdir(e)}catch{return[]}let n=[];for(let r of t){if(!/^\d+$/.test(r))continue;(await Ve.readFile(vt.join(e,r,"comm"),"utf8").catch(()=>"")).trim()==="earlyoom"&&n.push({pid:Number(r)})}return n}async function ps(e){let t=Number((await Ve.readFile(e,"utf8").catch(()=>"")).trim());return Number.isInteger(t)&&t>0?t:null}async function hs({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc"}={}){if(!ls(e))return{state:"off"};if(t!=="linux")return{state:"unsupported",platform:t};let r=await fs({procRoot:n}),o=await ps(us(e)),s=r.find(l=>l.pid===o);if(s)return{state:"own",pid:s.pid};if(r.length)return{state:"host",pid:r[0].pid};let a=ds(e);return a?{state:"stopped",bin:a}:{state:"absent"}}function sr(e){switch(e?.state){case"own":return`earlyoom running under the node (pid ${e.pid}; acts at 10% memory available and 70% swap free)`;case"host":return`the host's own earlyoom is running (pid ${e.pid}) \u2014 the node starts none beside it`;case"stopped":return`earlyoom is installed (${e.bin}) and not running \u2014 the node starts it at boot`;case"absent":return"none \u2014 earlyoom is not installed, so memory exhaustion is left to the kernel's OOM killer";case"off":return"disabled (BOSTRAT_OOM_GUARD=0)";case"unsupported":return`not available on ${e.platform}`;default:return"not checked yet"}}function ms({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc",log:r=console.log,spawnImpl:o=qc,checkMs:s=Zc,relaunchMs:a=Qc}={}){let l=null,h={state:null},m=null,d=!1,g="",v=us(e),y=k=>{h=k;let _=`[oom-guard] ${sr(k)}`;return _!==g&&r(_),g=_,k},b=k=>{d||(clearTimeout(m),m=setTimeout(()=>I().catch(()=>{}),k),m.unref?.())},I=async()=>{if(d||l)return h;if(!ls(e))return y({state:"off"});if(t!=="linux")return y({state:"unsupported",platform:t});let k=await ps(v),_=await fs({procRoot:n});if(k&&_.some(x=>x.pid===k)){try{process.kill(k,"SIGTERM")}catch{}_=_.filter(x=>x.pid!==k)}if(_.length)return b(s),y({state:"host",pid:_[0].pid});let E=ds(e);if(!E)return b(s),y({state:"absent"});let O;try{O=o(E,Jc(),{stdio:["ignore","pipe","pipe"]})}catch(x){return r(`[oom-guard] could not start ${E}: ${x?.message||x}`),b(s),h}l=O;for(let x of[O.stdout,O.stderr])x&&Vc.createInterface({input:x}).on("line",M=>r(`[earlyoom] ${M}`));return O.on("error",x=>{r(`[oom-guard] ${E}: ${x?.message||x}`),!(l!==O||O.pid)&&(l=null,b(s))}),O.on("exit",(x,M)=>{l===O&&(l=null,Ve.rm(v,{force:!0}).catch(()=>{}),!d&&(r(`[oom-guard] earlyoom exited (${M||`code ${x}`}) \u2014 relaunching in ${Math.round(a/1e3)} s`),h={state:"stopped",bin:E},g="",b(a)))}),O.pid&&(await Ve.mkdir(vt.dirname(v),{recursive:!0}).catch(()=>{}),await Ve.writeFile(v,`${O.pid}
222
- `).catch(()=>{})),b(s),y({state:"own",pid:O.pid})},S=()=>{l&&(l.kill("SIGTERM"),Qt.rmSync(v,{force:!0}))};return process.on("exit",S),{ready:I().catch(()=>h),status:()=>h,stop(){d=!0,clearTimeout(m),process.off("exit",S);let k=l;l=null,k&&(k.kill("SIGTERM"),Qt.rmSync(v,{force:!0}))}}}jn();import el from"node:fs";import gs from"node:path";import tl from"node:os";var nl=()=>process.env.BOSTRAT_STATE_DIR||gs.join(process.env.HOME||tl.tmpdir(),".bostrat"),rl=()=>gs.join(nl(),"plane-link","public-host.json");var kt=null;function ol(){if(kt)return kt;try{let e=JSON.parse(el.readFileSync(rl(),"utf8"));kt={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{kt={viewBase:null}}return kt}function sl(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),o=r?r[1].toLowerCase():t,s=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return s?{proto:o,host:s}:null}function ws(){return ol().viewBase}function ys(e=process.env.BOSTRAT_PUBLIC_HOST){return sl(e,"https")}function bs(e=process.env.BOSTRAT_PLANE_URL){let t=String(e||"").trim();if(!t)return null;let n=/^(wss?|https?):\/\/([^/?#]+)/i.exec(t);return n?`${/^(wss|https)$/i.test(n[1])?"https":"http"}://${n[2]}`:null}Xt();import il from"node:fs";import al from"node:os";import Ss from"node:path";var _s=3*6e4;function ir(e=process.env){let t=e.BOSTRAT_STATE_DIR||Ss.join(e.HOME||al.tmpdir(),".bostrat");return Ss.join(t,"heartbeat.json")}function Ts(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return _s;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):_s}function xs(e=ir()){try{let t=JSON.parse(il.readFileSync(e,"utf8"));if(!t||typeof t!="object")return null;let n=Number(t.ts),r=Number(t.pid);if(!Number.isFinite(n)||!Number.isFinite(r))return null;let o=Number(t.loopLagMs);return{pid:r,ts:n,loopLagMs:Number.isFinite(o)?o:null}}catch{return null}}Xt();var vs="BOSTRAT_RESTART_NOTICE",em=2*6e4;var $s=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function ks({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:$s(e),staleS:$s(t)!=null?Math.round(t/1e3):null})}Ae();var Hi=(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 s=(n[o]||0)-(r[o]||0);if(s)return s<0}return!1},be=Nu(Ou),Nr=L.dirname(Pu(import.meta.url)),Ne=L.resolve(Nr,".."),Du=L.join(Nr,"index.js"),ju="wss://plane.bostrat.ai/v1/node",tt=Rr(import.meta.url)("../package.json").version,D=(e,t)=>({name:e,level:"pass",detail:t}),W=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),q=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function Cu(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?D("node runtime",`${process.version} at ${process.execPath}`):q("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Bu(e){return e.BOSTRAT_OWNER?W("owner stamp",`BOSTRAT_OWNER=${String(e.BOSTRAT_OWNER).slice(0,12)}\u2026 is set \u2014 ignored by this release; on older releases it got every event refused (forgedUserId)`,"remove BOSTRAT_OWNER from node.env and any shell rc, then restart the node"):D("owner stamp","none (the plane infers the owner from the token)")}function Lu(e){let t;try{t=z.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}`):D("node.env",`${e} (0600)`)}async function Fu(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await be(t,["-V"],{timeout:5e3});return D("tmux",`${t} (${n.trim()})`)}catch{return q("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Wi(e,{required:t=!1}={}){if(await or(e,{loginShell:!0,failOpen:!1}))return D(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=Zt[e]?`${Zt[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?q(e,r,o):W(e,r,o)}async function Uu(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await be(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return D("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",Zt.gh)}}async function Hu(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Wi(t)));return e.some(t=>t.level==="pass")||e.push(q("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 Wu(){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 or(t,{failOpen:!1})?D(t,"resolves on the service PATH"):W(t,`not on the service PATH \u2014 ${n}`,r)))}async function Ku(){try{let t=Rr(L.join(Ne,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let o=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),s=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(s),n()})}),D("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${Ne} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Rr(L.join(Ne,"package.json")),r=L.join(L.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");z.existsSync(r)&&!(z.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return q("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function zu(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(z.existsSync(t))return D("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"?q:W)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function Gu(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?q("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"):D("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function Vu(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=pt(e.BOSTRAT_PLANE_URL);return await new Promise(s=>{let a=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),l=null,h=d=>{clearTimeout(m);try{a.close()}catch{}s(l?{...d,viewBase:l}:d)},m=setTimeout(()=>h(q("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-${Mu().slice(0,8)}`,ephemeral:!0}))),a.on("message",d=>{try{let g=JSON.parse(d);g.type==="hello_ok"?(typeof g.viewBase=="string"&&g.viewBase&&(l=g.viewBase),g.minNodeVersion&&Hi(tt,g.minNodeVersion)?h(q("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${g.minNodeVersion} \u2014 this node is ${tt}; the real link is refused until it updates`,`bostrat-node self-update --to ${g.latestNodeVersion||g.minNodeVersion}`)):g.latestNodeVersion&&Hi(tt,g.latestNodeVersion)?h(W("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${g.latestNodeVersion} is available (this node: ${tt})`,`bostrat-node self-update --to ${g.latestNodeVersion}`)):h(D("plane link",`hello_ok in ${Date.now()-r}ms (${o})`))):g.type==="error"&&h(q("plane link",`plane said: ${g.code} ${g.message||""}`,"check the token"))}catch{}}),a.on("error",d=>h(q("plane link",`${d?.message||d}`,"check the URL, the token, and the plane's IP gate")))})}function qu(){let e;try{e=JSON.parse(z.readFileSync(L.join(Ct,"content-outbox.json"),"utf8"))}catch{return D("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 q("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"):D("content outbox",t?`${t} op(s) in flight`:"drained")}async function Yu(e){let t=await ts({env:e}),n=ns(t);return t.available?D("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?W("box caps",n,"boxes run under nice only on this node; if Fly's init mounts /sys/fs/cgroup read-only this is the expected state (blueprint BP-NG-I4)"):D("box caps",n)}async function Xu(e){let t=await hs({env:e}),n=sr(t);return t.state==="absent"?W("oom guard",n,"install earlyoom (apt install earlyoom) \u2014 the node starts it with its own tuning at the next boot"):D("oom guard",n)}async function Ju(e){let t=await Eo({env:e}),n=Oo(t);return t.level==="misconfigured"?q("box containment",n,"fix the user (scripts/pi/box-user-setup.sh) or unset BOSTRAT_BOX_USER in node.env, then restart"):t.level==="root-capable"?W("box containment",n,"opt in to a dedicated box uid: BP-AU-I10 runbook (scripts/pi/box-user-setup.sh, then BOSTRAT_BOX_USER in node.env)"):t.level==="uid"&&(t.problems.length||t.auditd?.rule!==!0||!t.auditd?.readable)?W("box containment",n,"re-run scripts/pi/box-user-setup.sh (idempotent) \u2014 it installs the auditd rule, the log group and the mirror"):D("box containment",n)}function Zu(e){let t=Dn(e),n=bo(t);return t.unknown?.length?W("audit guard",n,`BOSTRAT_AUDIT_GUARD names unknown rule(s): ${t.unknown.join(", ")}`):D("audit guard",n)}function Qu(e){return e.BOSTRAT_STATE_REMOTE?D("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")}function ed(e,t){let n=t?.viewBase??null,r=ws(),o=ys(e.BOSTRAT_PUBLIC_HOST),s=(()=>{let a=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(a)return`${a.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let l=bs(e.BOSTRAT_PLANE_URL);return l?`${l}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let a=o&&o.host!==n?`; BOSTRAT_PUBLIC_HOST=${o.host} is set but the plane's value wins`:"";return D("public host",`views https://<slug>.${n}/ (plane hello_ok)${a} \xB7 track links ${s}`)}return r?D("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${s}`):o?D("public host",`views ${o.proto}://<slug>.${o.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${s}`):q("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${s}`,"link a plane that sets PLANE_VIEW_BASE (bostrat-node init), or set BOSTRAT_PUBLIC_HOST in node.env for a plane-less node")}async function Ki(e,t={}){let n=[];n.push(await Cu()),n.push(Lu(t.envFile||Ue())),n.push(await Fu(e)),n.push(await Yu(e)),n.push(await Xu(e)),n.push(Zu(e)),n.push(await Ju(e)),n.push(...await Hu()),n.push(await Wi("git",{required:!0})),n.push(await Uu()),n.push(...await Wu()),n.push(await Ku()),n.push(zu(e)),n.push(Gu(e)),n.push(Bu(e));let r=await Vu(e,t);return n.push(r),n.push(ed(e,r)),n.push(qu()),n.push(Qu(e)),n}function zi(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let s of e)t(`${n[s.level]} ${s.name}: ${s.detail}`),s.fix&&s.level!=="pass"&&t(` fix: ${s.fix}`);let r=e.filter(s=>s.level==="fail").length,o=e.filter(s=>s.level==="warn").length;return t(r?`
221
+ `}async function Or(e=un){try{return JSON.parse(await be.readFile(e,"utf8"))}catch{return null}}async function Fi({to:e,from:t=cn,kind:n=et(),reason:r="manual",force:o=!1,statusFile:s=un,spawnImpl:a=gu,now:l=Date.now,npmPrefix:h=void 0,log:m=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!dn.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Qe(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let d=await Or(s);if(Rr(d))return{ok:!1,reason:`an update to ${d.to} is already in flight`,status:d};let g=d?.to===e?Number(d.attempts)||1:0;if(!o&&d&&d.to===e&&(d.status==="failed"||d.status==="rolled-back")&&!(d.status==="failed"&&d.retryable===!0&&g<Ar))return{ok:!1,reason:`update to ${e} already ${d.status} (${d.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:d};let v=d?.to===e&&(d.status==="failed"||d.status==="rolled-back")?g+1:1;await be.mkdir(U.dirname(s),{recursive:!0});let y=h!==void 0?h:n==="npm-global"?Yn(await vu())||U.resolve(U.dirname(process.execPath),".."):null,b=Er(),I=Li({kind:n,to:e,from:t,statusFile:s,npmPrefix:y,startedAt:l(),attempts:v,restart:b}),S=U.join(U.dirname(s),`update-${e}.sh`),N=U.join(U.dirname(s),"last.log");await be.writeFile(S,I,{mode:448}),await be.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:v,startedAt:l(),updatedAt:l()}));let A=Nt.existsSync("/run/systemd/system")&&await Au("systemd-run"),_=A?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",S]]:["bash",[S]],E=async x=>{let M=`could not spawn updater: ${x?.message||x}`;return await be.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,attempts:v,startedAt:l(),updatedAt:l(),error:M})).catch(()=>{}),m.error?.(`[self-update] ${M}`),M},O=null;try{A||(O=Nt.openSync(N,"a"));let x=a(_[0],_[1],{detached:!0,stdio:A?"ignore":["ignore",O,O]});x.on?.("error",M=>{E(M)}),x.unref?.()}catch(x){return{ok:!1,reason:await E(x)}}finally{O!==null&&Nt.closeSync(O)}return m.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}, restart via ${b.mode}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:S,statusFile:s}}async function vu(){try{return await be.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Au(e){for(let t of String(process.env.PATH||"").split(U.delimiter))try{return await be.access(U.join(t,e),Nt.constants.X_OK),!0}catch{}return!1}async function Eu({statusFile:e=un,current:t=cn,now:n=Date.now,staleMs:r=ku}={}){let o=await Or(e);if(!o)return null;let s=a=>be.writeFile(e,JSON.stringify(a)).catch(()=>{});if(Rr(o)){if(t&&o.to===t){let a={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await s(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 s(a),a}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let a={...o,announced:!0};return await s(a),a}return null}function Ou({isBusy:e,start:t=Fi,onStuck:n=null,onStarted:r=null,tickMs:o=_u,stuckMs:s=Su,now:a=Date.now,setIntervalImpl:l=setInterval,clearIntervalImpl:h=clearInterval,log:m=console}={}){let d=null,g=()=>{d?.timer&&h(d.timer),d=null},v=async()=>{if(!d)return;let y=!0;try{y=await e()!==!1}catch{y=!0}if(y){if(!d.stuckFired&&a()-d.since>=s){d.stuckFired=!0;try{await n?.({to:d.to,from:d.from,since:d.since})}catch{}}return}let b=d;g();let I=await t({to:b.to,from:b.from,kind:b.kind,reason:"auto"});m.log?.(`[self-update] stasis reached \u2192 ${I.ok?"started":`not started: ${I.reason}`}`);try{await r?.({...b,result:I})}catch{}};return{arm({to:y,from:b=cn,kind:I=et()}){return d?.to===y?!1:(g(),d={to:y,from:b,kind:I,since:a(),stuckFired:!1,timer:l(v,o)},d.timer.unref?.(),!0)},tick:v,cancel:g,get armed(){return d?{to:d.to,from:d.from,kind:d.kind,since:d.since}:null}}}var cn,bu,ln,un,Su,_u,$r,vr,Ar,an,Di,ji,Ci,dn,Q,$u,Rr,ku,Hi=R(()=>{xr();Pi();cn=(()=>{try{return yu(import.meta.url)("../package.json").version||null}catch{return null}})(),bu=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||mu.tmpdir(),".bostrat"),ln=U.join(bu,"self-update"),un=U.join(ln,"status.json"),Su=1440*6e4,_u=6e4,$r=60,vr=15,Ar=3,an=6,Di=20,ji=U.join(ln,"supervisor.pid"),Ci="SIGUSR2",dn=new Set(["npm-global","git-checkout"]);Q=e=>`'${String(e).replace(/'/g,"'\\''")}'`;$u=new Set(["updating","restarting","rolling-back"]),Rr=e=>!!(e&&$u.has(e.status));ku=45*6e4});Rn();qn();rr();import G from"node:fs";import L from"node:path";import nt from"node:os";import{createRequire as Nr}from"node:module";import{execFile as Ru,spawn as Nu}from"node:child_process";import{promisify as Iu}from"node:util";import Mu from"node:readline/promises";import{randomUUID as Pu}from"node:crypto";import{fileURLToPath as Du}from"node:url";import en from"node:fs";import Ve from"node:fs/promises";import Vc from"node:os";import At from"node:path";import qc from"node:readline";import{spawn as Yc}from"node:child_process";var Xc="^(ugrep|rg|2\\.1\\.[0-9]+|cursor-agent|codex|npm|node|MainThread)",Jc="^(bostrat-|tmux|earlyoom|systemd|sshd)",Zc=()=>["-m","10","-s","70","-r","600","--prefer",Xc,"--avoid",Jc],ls="BOSTRAT_OOM_GUARD_OWNER",Qc=6e4,el=5e3;function us(e=process.env){return!["0","off","false","no"].includes(String(e.BOSTRAT_OOM_GUARD??"").trim().toLowerCase())}function ds(e=process.env){let t=e.BOSTRAT_STATE_DIR||At.join(e.HOME||Vc.tmpdir(),".bostrat");return At.join(t,"oom-guard.pid")}function ps(e=process.env){if(e.BOSTRAT_EARLYOOM_BIN)return en.existsSync(e.BOSTRAT_EARLYOOM_BIN)?e.BOSTRAT_EARLYOOM_BIN:null;let t=[...String(e.PATH||"").split(":").filter(Boolean),"/usr/bin","/usr/sbin","/usr/local/bin","/bin"];for(let n of t){let r=At.join(n,"earlyoom");if(en.existsSync(r))return r}return null}async function fs({procRoot:e="/proc"}={}){let t=[];try{t=await Ve.readdir(e)}catch{return[]}let n=[];for(let r of t){if(!/^\d+$/.test(r))continue;(await Ve.readFile(At.join(e,r,"comm"),"utf8").catch(()=>"")).trim()==="earlyoom"&&n.push({pid:Number(r)})}return n}async function hs(e){let t=Number((await Ve.readFile(e,"utf8").catch(()=>"")).trim());return Number.isInteger(t)&&t>0?t:null}async function ms({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc"}={}){if(!us(e))return{state:"off"};if(t!=="linux")return{state:"unsupported",platform:t};let r=await fs({procRoot:n}),o=await hs(ds(e)),s=r.find(l=>l.pid===o);if(s)return{state:"own",pid:s.pid};if(r.length)return{state:"host",pid:r[0].pid};let a=ps(e);return a?{state:"stopped",bin:a}:{state:"absent"}}function ir(e){switch(e?.state){case"own":return`earlyoom running under the node (pid ${e.pid}; acts at 10% memory available and 70% swap free)`;case"host":return`the host's own earlyoom is running (pid ${e.pid}) \u2014 the node starts none beside it`;case"stopped":return`earlyoom is installed (${e.bin}) and not running \u2014 the node starts it at boot`;case"absent":return"none \u2014 earlyoom is not installed, so memory exhaustion is left to the kernel's OOM killer";case"off":return"disabled (BOSTRAT_OOM_GUARD=0)";case"unsupported":return`not available on ${e.platform}`;default:return"not checked yet"}}function gs({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc",log:r=console.log,spawnImpl:o=Yc,checkMs:s=Qc,relaunchMs:a=el}={}){let l=null,h={state:null},m=null,d=!1,g="",v=ds(e),y=A=>{h=A;let _=`[oom-guard] ${ir(A)}`;return _!==g&&r(_),g=_,A},b=A=>{d||(clearTimeout(m),m=setTimeout(()=>I().catch(()=>{}),A),m.unref?.())},I=async()=>{if(d||l)return h;if(!us(e))return y({state:"off"});if(t!=="linux")return y({state:"unsupported",platform:t});let A=await hs(v),_=await fs({procRoot:n});if(A&&_.some(x=>x.pid===A)){try{process.kill(A,"SIGTERM")}catch{}_=_.filter(x=>x.pid!==A)}if(_.length)return b(s),y({state:"host",pid:_[0].pid});let E=ps(e);if(!E)return b(s),y({state:"absent"});let O;try{O=o(E,Zc(),{stdio:["ignore","pipe","pipe"]})}catch(x){return r(`[oom-guard] could not start ${E}: ${x?.message||x}`),b(s),h}l=O;for(let x of[O.stdout,O.stderr])x&&qc.createInterface({input:x}).on("line",M=>r(`[earlyoom] ${M}`));return O.on("error",x=>{r(`[oom-guard] ${E}: ${x?.message||x}`),!(l!==O||O.pid)&&(l=null,b(s))}),O.on("exit",(x,M)=>{l===O&&(l=null,Ve.rm(v,{force:!0}).catch(()=>{}),!d&&(r(`[oom-guard] earlyoom exited (${M||`code ${x}`}) \u2014 relaunching in ${Math.round(a/1e3)} s`),h={state:"stopped",bin:E},g="",b(a)))}),O.pid&&(await Ve.mkdir(At.dirname(v),{recursive:!0}).catch(()=>{}),await Ve.writeFile(v,`${O.pid}
222
+ `).catch(()=>{})),b(s),y({state:"own",pid:O.pid})},S=()=>{l&&(l.kill("SIGTERM"),en.rmSync(v,{force:!0}))};return process.on("exit",S),{ready:I().catch(()=>h),status:()=>h,stop(){d=!0,clearTimeout(m),process.off("exit",S);let A=l;l=null,A&&(A.kill("SIGTERM"),en.rmSync(v,{force:!0}))}}}jn();import tl from"node:fs";import ws from"node:path";import nl from"node:os";var rl=()=>process.env.BOSTRAT_STATE_DIR||ws.join(process.env.HOME||nl.tmpdir(),".bostrat"),ol=()=>ws.join(rl(),"plane-link","public-host.json");var kt=null;function sl(){if(kt)return kt;try{let e=JSON.parse(tl.readFileSync(ol(),"utf8"));kt={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{kt={viewBase:null}}return kt}function il(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),o=r?r[1].toLowerCase():t,s=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return s?{proto:o,host:s}:null}function ys(){return sl().viewBase}function bs(e=process.env.BOSTRAT_PUBLIC_HOST){return il(e,"https")}function Ss(e=process.env.BOSTRAT_PLANE_URL){let t=String(e||"").trim();if(!t)return null;let n=/^(wss?|https?):\/\/([^/?#]+)/i.exec(t);return n?`${/^(wss|https)$/i.test(n[1])?"https":"http"}://${n[2]}`:null}yt();import al from"node:fs";import cl from"node:os";import _s from"node:path";var Ts=3*6e4;function ar(e=process.env){let t=e.BOSTRAT_STATE_DIR||_s.join(e.HOME||cl.tmpdir(),".bostrat");return _s.join(t,"heartbeat.json")}function xs(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return Ts;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):Ts}function $s(e=ar()){try{let t=JSON.parse(al.readFileSync(e,"utf8"));if(!t||typeof t!="object")return null;let n=Number(t.ts),r=Number(t.pid);if(!Number.isFinite(n)||!Number.isFinite(r))return null;let o=Number(t.loopLagMs);return{pid:r,ts:n,loopLagMs:Number.isFinite(o)?o:null}}catch{return null}}yt();var As="BOSTRAT_RESTART_NOTICE",nm=2*6e4;var vs=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function ks({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:vs(e),staleS:vs(t)!=null?Math.round(t/1e3):null})}ke();var Wi=(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 s=(n[o]||0)-(r[o]||0);if(s)return s<0}return!1},Se=Iu(Ru),Ir=L.dirname(Du(import.meta.url)),Ne=L.resolve(Ir,".."),ju=L.join(Ir,"index.js"),Cu="wss://plane.bostrat.ai/v1/node",tt=Nr(import.meta.url)("../package.json").version,D=(e,t)=>({name:e,level:"pass",detail:t}),K=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),Y=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function Bu(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?D("node runtime",`${process.version} at ${process.execPath}`):Y("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Lu(e){return e.BOSTRAT_OWNER?K("owner stamp",`BOSTRAT_OWNER=${String(e.BOSTRAT_OWNER).slice(0,12)}\u2026 is set \u2014 ignored by this release; on older releases it got every event refused (forgedUserId)`,"remove BOSTRAT_OWNER from node.env and any shell rc, then restart the node"):D("owner stamp","none (the plane infers the owner from the token)")}function Fu(e){let t;try{t=G.statSync(e)}catch{return K("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?K("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):D("node.env",`${e} (0600)`)}async function Uu(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await Se(t,["-V"],{timeout:5e3});return D("tmux",`${t} (${n.trim()})`)}catch{return Y("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Ki(e,{required:t=!1}={}){if(await sr(e,{loginShell:!0,failOpen:!1}))return D(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=Qt[e]?`${Qt[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?Y(e,r,o):K(e,r,o)}async function Hu(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await Se(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return D("gh (GitHub CLI)",n)}catch{return K("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",Qt.gh)}}async function Wu(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Ki(t)));return e.some(t=>t.level==="pass")||e.push(Y("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 Ku(){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 sr(t,{failOpen:!1})?D(t,"resolves on the service PATH"):K(t,`not on the service PATH \u2014 ${n}`,r)))}async function zu(){try{let t=Nr(L.join(Ne,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let o=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),s=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(s),n()})}),D("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${Ne} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Nr(L.join(Ne,"package.json")),r=L.join(L.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");G.existsSync(r)&&!(G.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return Y("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function Gu(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(G.existsSync(t))return D("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"?Y:K)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function Vu(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?Y("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"):D("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function qu(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return K("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=ft(e.BOSTRAT_PLANE_URL);return await new Promise(s=>{let a=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),l=null,h=d=>{clearTimeout(m);try{a.close()}catch{}s(l?{...d,viewBase:l}:d)},m=setTimeout(()=>h(Y("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-${Pu().slice(0,8)}`,ephemeral:!0}))),a.on("message",d=>{try{let g=JSON.parse(d);g.type==="hello_ok"?(typeof g.viewBase=="string"&&g.viewBase&&(l=g.viewBase),g.minNodeVersion&&Wi(tt,g.minNodeVersion)?h(Y("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${g.minNodeVersion} \u2014 this node is ${tt}; the real link is refused until it updates`,`bostrat-node self-update --to ${g.latestNodeVersion||g.minNodeVersion}`)):g.latestNodeVersion&&Wi(tt,g.latestNodeVersion)?h(K("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${g.latestNodeVersion} is available (this node: ${tt})`,`bostrat-node self-update --to ${g.latestNodeVersion}`)):h(D("plane link",`hello_ok in ${Date.now()-r}ms (${o})`))):g.type==="error"&&h(Y("plane link",`plane said: ${g.code} ${g.message||""}`,"check the token"))}catch{}}),a.on("error",d=>h(Y("plane link",`${d?.message||d}`,"check the URL, the token, and the plane's IP gate")))})}function Yu(){let e;try{e=JSON.parse(G.readFileSync(L.join(Lt,"content-outbox.json"),"utf8"))}catch{return D("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 Y("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?K("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"):D("content outbox",t?`${t} op(s) in flight`:"drained")}async function Xu(e){let t=await ns({env:e}),n=rs(t);return t.available?D("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?K("box caps",n,"boxes run under nice only on this node; if Fly's init mounts /sys/fs/cgroup read-only this is the expected state (blueprint BP-NG-I4)"):D("box caps",n)}async function Ju(e){let t=await ms({env:e}),n=ir(t);return t.state==="absent"?K("oom guard",n,"install earlyoom (apt install earlyoom) \u2014 the node starts it with its own tuning at the next boot"):D("oom guard",n)}async function Zu(e){let t=await Ro({env:e}),n=No(t);return t.level==="misconfigured"?Y("box containment",n,"fix the user (scripts/pi/box-user-setup.sh) or unset BOSTRAT_BOX_USER in node.env, then restart"):t.level==="root-capable"?K("box containment",n,"opt in to a dedicated box uid: BP-AU-I10 runbook (scripts/pi/box-user-setup.sh, then BOSTRAT_BOX_USER in node.env)"):t.level==="uid"&&(t.problems.length||t.auditd?.rule!==!0||!t.auditd?.readable)?K("box containment",n,"re-run scripts/pi/box-user-setup.sh (idempotent) \u2014 it installs the auditd rule, the log group and the mirror"):D("box containment",n)}function Qu(e){let t=Dn(e),n=_o(t);return t.unknown?.length?K("audit guard",n,`BOSTRAT_AUDIT_GUARD names unknown rule(s): ${t.unknown.join(", ")}`):D("audit guard",n)}function ed(e){return e.BOSTRAT_STATE_REMOTE?D("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):K("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}function td(e,t){let n=t?.viewBase??null,r=ys(),o=bs(e.BOSTRAT_PUBLIC_HOST),s=(()=>{let a=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(a)return`${a.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let l=Ss(e.BOSTRAT_PLANE_URL);return l?`${l}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let a=o&&o.host!==n?`; BOSTRAT_PUBLIC_HOST=${o.host} is set but the plane's value wins`:"";return D("public host",`views https://<slug>.${n}/ (plane hello_ok)${a} \xB7 track links ${s}`)}return r?D("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${s}`):o?D("public host",`views ${o.proto}://<slug>.${o.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${s}`):Y("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${s}`,"link a plane that sets PLANE_VIEW_BASE (bostrat-node init), or set BOSTRAT_PUBLIC_HOST in node.env for a plane-less node")}async function zi(e,t={}){let n=[];n.push(await Bu()),n.push(Fu(t.envFile||Ue())),n.push(await Uu(e)),n.push(await Xu(e)),n.push(await Ju(e)),n.push(Qu(e)),n.push(await Zu(e)),n.push(...await Wu()),n.push(await Ki("git",{required:!0})),n.push(await Hu()),n.push(...await Ku()),n.push(await zu()),n.push(Gu(e)),n.push(Vu(e)),n.push(Lu(e));let r=await qu(e,t);return n.push(r),n.push(td(e,r)),n.push(Yu()),n.push(ed(e)),n}function Gi(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let s of e)t(`${n[s.level]} ${s.name}: ${s.detail}`),s.fix&&s.level!=="pass"&&t(` fix: ${s.fix}`);let r=e.filter(s=>s.level==="fail").length,o=e.filter(s=>s.level==="warn").length;return t(r?`
223
223
  FAIL \u2014 ${r} blocking, ${o} warnings`:`
224
- OK \u2014 0 blocking, ${o} warnings`),r===0}async function td({envFile:e=Ue(),input:t=process.stdin,output:n=process.stdout}={}){let r=Bt(e),o=Iu.createInterface({input:t,output:n}),s=async(k,_)=>(await o.question(_?`${k} [${_}]: `:`${k}: `)).trim()||_||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
224
+ OK \u2014 0 blocking, ${o} warnings`),r===0}async function nd({envFile:e=Ue(),input:t=process.stdin,output:n=process.stdout}={}){let r=Ft(e),o=Mu.createInterface({input:t,output:n}),s=async(A,_)=>(await o.question(_?`${A} [${_}]: `:`${A}: `)).trim()||_||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
225
225
  you type those inside each box, later (box-auth-policy).
226
226
 
227
- `);let a=await s("Plane URL",r.BOSTRAT_PLANE_URL||ju),l=pt(a);l!==a.trim()&&n.write(` \u2192 using ${l}
227
+ `);let a=await s("Plane URL",r.BOSTRAT_PLANE_URL||Cu),l=ft(a);l!==a.trim()&&n.write(` \u2192 using ${l}
228
228
  `);let h=await s("Node token (minted plane-side; stored 0600)",r.BOSTRAT_PLANE_TOKEN);r.BOSTRAT_OWNER&&n.write(` \u2192 dropping BOSTRAT_OWNER from node.env \u2014 the plane infers the owner from the token; a stale id here got every event refused.
229
229
  `);let m=await s("Node name",r.BOSTRAT_NODE_NAME||nt.hostname().split(".")[0]),d=await s("Repos root",r.BOSTRAT_REPOS_ROOT||L.join(nt.homedir(),"Documents")),g=await s("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),v=(await s("Route NEW claude boxes through a BYO API key? (y/N)",r.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");v&&n.write(`
230
230
  BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
@@ -233,14 +233,14 @@ injected per box, stored 0600 in node.env, never sent to the plane.
233
233
  \u2022 set a monthly spend limit while you're there \u2014 the key is live.
234
234
 
235
235
  `);let y=v?await s("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";v&&y&&!/^sk-ant-/.test(y)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
236
- `),o.close();let b={...to(),...r,BOSTRAT_PLANE_URL:l,BOSTRAT_PLANE_TOKEN:h,BOSTRAT_NODE_NAME:m,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||m,BOSTRAT_REPOS_ROOT:d,BOSTRAT_STATE_REMOTE:g,BOSTRAT_CLAUDE_USE_API_KEY:v?"1":"0",ANTHROPIC_API_KEY:v?y:r.ANTHROPIC_API_KEY};delete b.BOSTRAT_OWNER,eo(e,b,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
236
+ `),o.close();let b={...ro(),...r,BOSTRAT_PLANE_URL:l,BOSTRAT_PLANE_TOKEN:h,BOSTRAT_NODE_NAME:m,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||m,BOSTRAT_REPOS_ROOT:d,BOSTRAT_STATE_REMOTE:g,BOSTRAT_CLAUDE_USE_API_KEY:v?"1":"0",ANTHROPIC_API_KEY:v?y:r.ANTHROPIC_API_KEY};delete b.BOSTRAT_OWNER,no(e,b,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
237
237
  0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
238
238
  Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
239
239
  wrote ${e}
240
240
 
241
- `);let I={...b,...process.env},S=await Ki(I,{envFile:e}),N=zi(S,k=>n.write(k+`
242
- `));return N&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:N,results:S}}var nd="SIGUSR2",rd=5*6e4,od=1e4,dn=L.join(Ct,"self-update","supervisor.pid");function sd({spawnChild:e,exit:t=m=>process.exit(m),now:n=Date.now,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:o=clearTimeout,killGraceMs:s=15e3,rollbackGraceMs:a=rd,stall:l=null,log:h=console}={}){let m=null,d=0,g=!1,v="update",y=0,b=null,I=null,S=null,N=0,k=0,_=0,E=!1,O=l&&l.staleMs>0?l.staleMs:0,x=l?.checkMs>0?l.checkMs:od,M=()=>{b&&o(b),b=null},Ie=()=>{m.kill("SIGTERM"),I=r(()=>m?.kill("SIGKILL"),s),I.unref?.()},rt=null,Me=0,fn=()=>{let P=null;try{P=l.readHeartbeat()}catch{}return P&&P.pid===m.pid&&Number.isFinite(P.ts)&&P.ts!==rt&&(rt=P.ts,Me=Math.max(Me,Math.min(P.ts,n()))),n()-Me},Nt=()=>{if(!m||E||g||!O)return!1;let P=fn();return P<O?!1:(k++,_=P,h.error?.(`[bostrat-node] the agent (pid ${m.pid}) has written no heartbeat for ${Math.round(P/1e3)} s \u2014 stalled; relaunching it in place (boxes keep running on the host tmux server; stall relaunch #${k})`),v="stall",g=!0,Ie(),!0)},Pe=()=>{O&&(S&&o(S),S=r(()=>{S=null,Nt(),Pe()},x),S.unref?.())},ot=(P=null)=>{let de=e(P);return m=de,d=n(),rt=null,Me=d,de.on("exit",(fe,pe)=>De(de,fe,pe)),S||Pe(),de},De=(P,de,fe)=>{if(P!==m)return;if(m=null,I&&o(I),I=null,g){g=!1,st(v);return}let pe=fe?1:de??1;if(!E&&pe!==0&&n()<y){let it=y-n();h.error?.(`[bostrat-node] the agent exited (code ${pe}) right after a self-update restart \u2014 holding ${Math.ceil(it/1e3)} s for the updater's rollback signal`),b=r(()=>t(pe),it);return}t(pe)},st=(P="update")=>{N++,P==="stall"?h.log?.(`[bostrat-node] relaunched the agent after a stall (restart #${N}, stall relaunch #${k})`):(y=n()+a,h.log?.(`[bostrat-node] restarting the agent (self-update, restart #${N})`)),v="update",ot(P==="stall"?{at:n(),staleMs:_}:null)};return{start:()=>ot(),restart(){if(E=!1,M(),v="update",!m){st("update");return}g||(g=!0,Ie())},checkStall:Nt,forward(P){E=!0,m?m.kill(P):(M(),t(1))},get child(){return m},get state(){return{alive:!!m,restartPending:g,restartReason:v,holding:!!b,restarts:N,stallRelaunches:k,stopping:E}}}}function id({envFile:e=Ue()}={}){Qr(e),process.title="bostrat-node";let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n={...process.env,BOSTRAT_RUN_SUPERVISOR_PID:String(process.pid),[cs]:"supervisor"};ms();try{z.mkdirSync(L.dirname(dn),{recursive:!0}),z.writeFileSync(dn,`${process.pid}
243
- `)}catch{}let r=Ts(process.env),o=ir(process.env);console.log(r?`[bostrat-node] stall watchdog: relaunch the agent after ${Math.round(r/1e3)} s without a heartbeat (${o})`:"[bostrat-node] stall watchdog: off (BOSTRAT_HEARTBEAT_STALE_MS)");let s=sd({spawnChild:a=>Ru(t,[Du],{cwd:Ne,stdio:"inherit",env:a?{...n,[vs]:ks(a)}:n}),stall:r?{readHeartbeat:()=>xs(o),staleMs:r}:null});for(let a of["SIGINT","SIGTERM"])process.on(a,()=>s.forward(a));return process.on(nd,()=>s.restart()),process.on("exit",()=>{try{z.readFileSync(dn,"utf8").trim()===String(process.pid)&&z.rmSync(dn,{force:!0})}catch{}}),s.start()}function ad({agentDir:e=Ne,nodeBin:t=process.execPath,envFile:n=Ue(),home:r=nt.homedir()}={}){let o=L.dirname(t),s=L.join(L.basename(Nr),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
241
+ `);let I={...b,...process.env},S=await zi(I,{envFile:e}),N=Gi(S,A=>n.write(A+`
242
+ `));return N&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:N,results:S}}var rd="SIGUSR2",od=5*6e4,sd=1e4,pn=L.join(Lt,"self-update","supervisor.pid");function id({spawnChild:e,exit:t=m=>process.exit(m),now:n=Date.now,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:o=clearTimeout,killGraceMs:s=15e3,rollbackGraceMs:a=od,stall:l=null,log:h=console}={}){let m=null,d=0,g=!1,v="update",y=0,b=null,I=null,S=null,N=0,A=0,_=0,E=!1,O=l&&l.staleMs>0?l.staleMs:0,x=l?.checkMs>0?l.checkMs:sd,M=()=>{b&&o(b),b=null},Ie=()=>{m.kill("SIGTERM"),I=r(()=>m?.kill("SIGKILL"),s),I.unref?.()},rt=null,Me=0,fn=()=>{let P=null;try{P=l.readHeartbeat()}catch{}return P&&P.pid===m.pid&&Number.isFinite(P.ts)&&P.ts!==rt&&(rt=P.ts,Me=Math.max(Me,Math.min(P.ts,n()))),n()-Me},It=()=>{if(!m||E||g||!O)return!1;let P=fn();return P<O?!1:(A++,_=P,h.error?.(`[bostrat-node] the agent (pid ${m.pid}) has written no heartbeat for ${Math.round(P/1e3)} s \u2014 stalled; relaunching it in place (boxes keep running on the host tmux server; stall relaunch #${A})`),v="stall",g=!0,Ie(),!0)},Pe=()=>{O&&(S&&o(S),S=r(()=>{S=null,It(),Pe()},x),S.unref?.())},De=(P=null)=>{let de=e(P);return m=de,d=n(),rt=null,Me=d,de.on("exit",(pe,fe)=>je(de,pe,fe)),S||Pe(),de},je=(P,de,pe)=>{if(P!==m)return;if(m=null,I&&o(I),I=null,g){g=!1,ot(v);return}let fe=pe?1:de??1;if(!E&&fe!==0&&n()<y){let st=y-n();h.error?.(`[bostrat-node] the agent exited (code ${fe}) right after a self-update restart \u2014 holding ${Math.ceil(st/1e3)} s for the updater's rollback signal`),b=r(()=>t(fe),st);return}t(fe)},ot=(P="update")=>{N++,P==="stall"?h.log?.(`[bostrat-node] relaunched the agent after a stall (restart #${N}, stall relaunch #${A})`):(y=n()+a,h.log?.(`[bostrat-node] restarting the agent (self-update, restart #${N})`)),v="update",De(P==="stall"?{at:n(),staleMs:_}:null)};return{start:()=>De(),restart(){if(E=!1,M(),v="update",!m){ot("update");return}g||(g=!0,Ie())},checkStall:It,forward(P){E=!0,m?m.kill(P):(M(),t(1))},get child(){return m},get state(){return{alive:!!m,restartPending:g,restartReason:v,holding:!!b,restarts:N,stallRelaunches:A,stopping:E}}}}function ad({envFile:e=Ue()}={}){to(e),process.title="bostrat-node";let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n={...process.env,BOSTRAT_RUN_SUPERVISOR_PID:String(process.pid),[ls]:"supervisor"};gs();try{G.mkdirSync(L.dirname(pn),{recursive:!0}),G.writeFileSync(pn,`${process.pid}
243
+ `)}catch{}let r=xs(process.env),o=ar(process.env);console.log(r?`[bostrat-node] stall watchdog: relaunch the agent after ${Math.round(r/1e3)} s without a heartbeat (${o})`:"[bostrat-node] stall watchdog: off (BOSTRAT_HEARTBEAT_STALE_MS)");let s=id({spawnChild:a=>Nu(t,[ju],{cwd:Ne,stdio:"inherit",env:a?{...n,[As]:ks(a)}:n}),stall:r?{readHeartbeat:()=>$s(o),staleMs:r}:null});for(let a of["SIGINT","SIGTERM"])process.on(a,()=>s.forward(a));return process.on(rd,()=>s.restart()),process.on("exit",()=>{try{G.readFileSync(pn,"utf8").trim()===String(process.pid)&&G.rmSync(pn,{force:!0})}catch{}}),s.start()}function cd({agentDir:e=Ne,nodeBin:t=process.execPath,envFile:n=Ue(),home:r=nt.homedir()}={}){let o=L.dirname(t),s=L.join(L.basename(Ir),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
244
244
  # ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
245
245
  [Unit]
246
246
  Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
@@ -264,7 +264,7 @@ RestartSec=2
264
264
 
265
265
  [Install]
266
266
  WantedBy=default.target
267
- `}function cd({agentDir:e=Ne,nodeBin:t=process.execPath,home:n=nt.homedir()}={}){let r=L.dirname(t),o=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
267
+ `}function ld({agentDir:e=Ne,nodeBin:t=process.execPath,home:n=nt.homedir()}={}){let r=L.dirname(t),o=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
268
268
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
269
269
  <plist version="1.0">
270
270
  <dict>
@@ -286,7 +286,7 @@ WantedBy=default.target
286
286
  <key>StandardErrorPath</key><string>${o}/node.err.log</string>
287
287
  </dict>
288
288
  </plist>
289
- `}function ld(e=process.platform,t=nt.homedir()){return e==="darwin"?{kind:"launchd",file:L.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:L.join(t,".config","systemd","user","bostrat-node.service")}}async function ud({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=Ne}={}){let{kind:s,file:a}=ld(n);if(!e&&o.split(L.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){s==="systemd"?(await be("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),z.rmSync(a,{force:!0}),await be("systemctl",["--user","daemon-reload"])):(await be("launchctl",["unload","-w",a]).catch(()=>{}),z.rmSync(a,{force:!0})),r(`removed ${a}`);return}z.mkdirSync(L.dirname(a),{recursive:!0}),s==="systemd"?(z.writeFileSync(a,ad()),await be("systemctl",["--user","daemon-reload"]),t&&await be("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${a}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(z.mkdirSync(L.join(nt.homedir(),"Library","Logs","bostrat"),{recursive:!0}),z.writeFileSync(a,cd()),t&&await be("launchctl",["load","-w",a]),r(`installed ${a}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function Ng(e=process.argv.slice(2)){let t=e[0],n=Ue();if(t==="--version"||t==="-v"||t==="version")return console.log(tt),0;if(t==="init")return(await td({envFile:n})).ok?0:1;if(t==="doctor"){let r={...Bt(n),...process.env};return zi(await Ki(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return id({envFile:n}),null;if(t==="install-service")return await ud({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(Ms(),Is));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:s}=await Promise.resolve().then(()=>(Ui(),Fi)),{detectInstallKind:a}=await Promise.resolve().then(()=>(Tr(),Ii)),l=a(),h=e.indexOf("--to"),m=h>=0?String(e[h+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:tt,installKind:l,policy:s({kind:l}),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 d=await r({to:m,kind:l,reason:"cli",force:!0});return d.ok?(console.log(`\u2713 self-update ${d.from??"?"} \u2192 ${d.to} started (${d.kind}) \u2014 status: ${d.statusFile}; the node restarts when the install completes`),0):(console.error(`\u2717 not started: ${d.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
289
+ `}function ud(e=process.platform,t=nt.homedir()){return e==="darwin"?{kind:"launchd",file:L.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:L.join(t,".config","systemd","user","bostrat-node.service")}}async function dd({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=Ne}={}){let{kind:s,file:a}=ud(n);if(!e&&o.split(L.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){s==="systemd"?(await Se("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),G.rmSync(a,{force:!0}),await Se("systemctl",["--user","daemon-reload"])):(await Se("launchctl",["unload","-w",a]).catch(()=>{}),G.rmSync(a,{force:!0})),r(`removed ${a}`);return}G.mkdirSync(L.dirname(a),{recursive:!0}),s==="systemd"?(G.writeFileSync(a,cd()),await Se("systemctl",["--user","daemon-reload"]),t&&await Se("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${a}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(G.mkdirSync(L.join(nt.homedir(),"Library","Logs","bostrat"),{recursive:!0}),G.writeFileSync(a,ld()),t&&await Se("launchctl",["load","-w",a]),r(`installed ${a}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function Mg(e=process.argv.slice(2)){let t=e[0],n=Ue();if(t==="--version"||t==="-v"||t==="version")return console.log(tt),0;if(t==="init")return(await nd({envFile:n})).ok?0:1;if(t==="doctor"){let r={...Ft(n),...process.env};return Gi(await zi(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return ad({envFile:n}),null;if(t==="install-service")return await dd({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(Ps(),Ms));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:s}=await Promise.resolve().then(()=>(Hi(),Ui)),{detectInstallKind:a}=await Promise.resolve().then(()=>(xr(),Mi)),l=a(),h=e.indexOf("--to"),m=h>=0?String(e[h+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:tt,installKind:l,policy:s({kind:l}),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 d=await r({to:m,kind:l,reason:"cli",force:!0});return d.ok?(console.log(`\u2713 self-update ${d.from??"?"} \u2192 ${d.to} started (${d.kind}) \u2014 status: ${d.statusFile}; the node restarts when the install completes`),0):(console.error(`\u2717 not started: ${d.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
290
290
 
291
291
  usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
292
292
 
@@ -295,4 +295,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
295
295
  run start the node in the foreground (sources node.env)
296
296
  install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
297
297
  fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
298
- self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{nd as RESTART_SIGNAL,rd as ROLLBACK_GRACE_MS,od as STALL_CHECK_MS,dn as SUPERVISOR_PID_FILE,sd as createRunSupervisor,td as init,ud as installService,cd as launchdPlist,Ng as main,zi as printDoctor,id as runAgent,Ki as runDoctor,ld as servicePaths,ad as systemdUnit};
298
+ self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{rd as RESTART_SIGNAL,od as ROLLBACK_GRACE_MS,sd as STALL_CHECK_MS,pn as SUPERVISOR_PID_FILE,id as createRunSupervisor,nd as init,dd as installService,ld as launchdPlist,Mg as main,Gi as printDoctor,ad as runAgent,zi as runDoctor,ud as servicePaths,cd as systemdUnit};