bostrat-node 1.17.2 → 1.17.4

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
@@ -2,10 +2,10 @@ var ua=Object.defineProperty;var R=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(
2
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 no(e,t=process.env){let n=Ht(e);for(let[r,o]of Object.entries(n))r in t||(t[r]=o);return n}function ro(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
3
3
  `).map(o=>o?`# ${o}`:"#"));for(let[o,s]of Object.entries(t))s==null||s===""||r.push(`${o}=${s}`);Ft.mkdirSync(Rn.dirname(e),{recursive:!0}),Ft.writeFileSync(e,r.join(`
4
4
  `)+`
5
- `,{mode:384}),Ft.chmodSync(e,384)}function oo(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 Ut,Ue,Nn=R(()=>{Ut=process.env.BOSTRAT_STATE_DIR||Rn.join(process.env.HOME||da.tmpdir(),".bostrat"),Ue=()=>Rn.join(Ut,"node.env")});var bd,Wt=R(()=>{bd=16*1024});var le,ht,Kt=R(()=>{le="BOSTRAT_HOOK_TOKEN",ht="x-bostrat-hook"});var pa,Td,so=R(()=>{pa=(e,t)=>{if(e==null||e==="")return t;let n=Number(e);return Number.isFinite(n)&&n>=0?n:t},Td=pa(process.env.BOSTRAT_HOOK_FOLD_MS,250)});function ya(e,t=ha){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 Gt(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function mo(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 po(e){let t=Gt(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 yo(e){let{cmd:t,at:n}=mo(e);if(t==="sudo"){for(n++;n<e.length&&e[n].startsWith("-");)n++;t=e[n]??null}return{cmd:t,at:n}}function bo(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=Gt(e),{cmd:a}=yo(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 Ma(e){let t=Gt(e),{cmd:n,at:r}=yo(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&&xa.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=bo(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 fa,ha,io,ao,co,lo,uo,Ad,ma,wa,Mn,ga,ue,Pn,ba,Sa,_a,Ta,wo,go,xa,$a,va,ka,Aa,fo,ho,Ea,Oa,Ra,Na,q,mt,In,So,Ed,Od,_o=R(()=>{so();fa="BP-AU-R4",ha=160,io=200,ao=5,co=8,lo=5,uo=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"]),ma=5e3,wa=new Set(["tool.called","tool.failed"]),Mn=new Set(["Write","Edit","NotebookEdit"]),ga=e=>String(e??"").replace(/\s+/g," ").trim(),ue=(e,t=120)=>ga(e).slice(0,t);Pn=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,ba=new RegExp(`${Pn}/\\.ssh(?:/|\\b)`),Sa=new RegExp(`${Pn}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),_a=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,Ta=/^\.env\.(?:example|sample|template|dist)$/,wo=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,go=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${Pn}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),xa=/^(?: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)$/,$a=/^\/tmp\/|\/\.bostrat\/tmp\//,va=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,ka=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,Aa=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,fo=e=>ba.test(e)||Sa.test(e),ho=e=>[...String(e??"").matchAll(_a)].some(t=>!Ta.test(t[1])),Ea=e=>wo.test(e),Oa=e=>go.test(e),Ra=e=>(e.startsWith("/")||e.startsWith("~"))&&!$a.test(e);Na=e=>bo(e,wo);q=(e,t,n,r)=>Object.freeze({severity:e,requirement:fa,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 ya(o.head,e.headCap)){let a=t(s,o);a&&(n++,r??=ue(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??=ue(s))}return n?{count:n,sample:r}:null},So=Object.freeze({"force-push":q("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=po(n);return r&&r.force&&!r.lease?n:null})),"protected-config-write":q("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)Mn.has(s.tool)&&s.path&&Ea(s.path)&&(n++,r??=ue(`${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}),"persistence-install":q("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)Mn.has(s.tool)&&s.path&&Oa(s.path)&&(n++,r??=ue(`${s.tool} ${s.path}`));let o=mt(t,s=>{let a=Ma(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"push-outside-track":q("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=po(n);return r&&(r.remote&&!/^(?:origin|upstream)$/.test(r.remote)&&!r.remote.startsWith("$")&&!r.remote.startsWith("-")||r.dsts.some(o=>va.test(o)||!ka.test(o)))?n:null})),"credential-read":q("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&&fo(n.head)?n.head:n.path&&fo(n.path)?`${n.tool} ${n.path}`:null)),"dotenv-read":q("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&&ho(n.head)?n.head:n.path&&ho(n.path)?`${n.tool} ${n.path}`:null)),"privileged-command":q("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}=mo(Gt(n));return r==="sudo"||r==="docker"?n:null})),"write-outside-workspace":q("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=>Mn.has(n.tool)&&n.path&&Ra(n.path)?`${n.tool} ${n.path}`:null)),"egress-new-host":q("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>ma&&t.state.hosts.delete(t.state.hosts.values().next().value),n++,r??=ue(`${s} \xB7 ${o.head}`));return n?{count:n,sample:r}:null}),"spend-spike":q("low",`a cost.recorded turn over ${co}\xD7 the Track's running median (its last ${io} cost events, at least ${ao} of them) and over $${lo} \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>=ao&&r>=lo){let s=[...n].sort((l,h)=>l-h),a=s[Math.floor(s.length/2)];r>co*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>io&&n.shift(),o}),"peer-injected-call":q("medium",`a tool call within ${uo/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>uo||t.ts<n)return null;let r=t.calls[0];return{count:t.count,sample:ue(`${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":q("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:ue(`session ${String(e.payload.sessionId||"?").slice(0,8)} \xB7 ${n.tool}${n.head?`: ${n.head}`:n.path?` ${n.path}`:""}`)}}),"orphan-process":q("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:ue(`${o.comm||"process"}${o.cmd?`: ${o.cmd}`:""}${o.via?` [${o.via}]`:""}${s}${r>1?` (+${r-1} more)`:""}`)}}),"unknown-harness-shape":q("medium","a harness-made user turn of a shape chat-notes.js does not list (harness.shape.seen with known: false, harness-shapes.js): Claude Code wrote a new kind of its own turn into a transcript \u2014 hidden from chat by the generic catch, counted once per shape per node here; the node pages the operator once on first sight, this row is the fleet's record","2026-10-28 fleet replay \xB7 0 harness.shape.seen events in 311,055 (1,132 logs; the type is new, so the replay cannot bound this rule's rate) \xB7 transcript scan the same day: 2,863 claude user turns in 1,539 transcripts over 90 d, 144 of them harness-made (isMeta), 9 distinct shapes, 4 of which had rendered in chat as operator messages (<system-reminder><tools-used-before-summary> on 2 Tracks under 2.1.312, a usage-limit-reset notice, a safety-classifier notice) \u2192 medium (rail finding + security row), never a page from the plane: the once-per-shape page is the node's, so a release that adds one shape pages once, not per Track per hour",e=>{if(e.type!=="harness.shape.seen"||e.source!=="transcript")return null;let t=e.payload||{};if(t.known!==!1||!t.key)return null;let n=`${t.provider||"cli"}${t.cliVersion?` ${t.cliVersion}`:""}`;return{count:1,sample:ue(`${t.key} \xB7 ${n}${t.head?` \xB7 ${t.head}`:""}`)}})}),Ed=Object.freeze(Object.keys(So)),Od=new Set([...wa,"cost.recorded","peer.message","turn.user","audit.procs","harness.shape.seen"])});function ja(e){let t=String(e??"").trim().toLowerCase();if(Pa.has(t))return{enabled:!1,rules:[],unknown:[]};if(Da.has(t))return{enabled:!0,rules:[...Dn],unknown:[]};let n=[],r=[];for(let o of t.split(",")){let s=o.trim();s&&(Dn.includes(s)?n.includes(s)||n.push(s):r.push(s))}return{enabled:n.length>0,rules:n,unknown:r}}function To(e){return e?.enabled?`on \xB7 denies ${e.rules.length===Dn.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 Dn,Pa,Da,jn,Cn=R(()=>{_o();Dn=Object.freeze(["force-push","protected-config-write","credential-read","persistence-install"]),Pa=new Set(["","off","0","false","no","none"]),Da=new Set(["on","1","true","yes","all"]);jn=(e=process.env)=>ja(e.BOSTRAT_AUDIT_GUARD)});import He from"node:fs";import $o from"node:fs/promises";import Vt from"node:os";import Y from"node:path";import{execFile as vo}from"node:child_process";import{promisify as Ca}from"node:util";function Eo(e){try{return He.readFileSync(e,"utf8").split(`
6
- `).filter(t=>t&&!t.startsWith("#")).map(t=>t.split(":"))}catch{return[]}}function Oo(e,t=process.env){let r=Eo(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 Ro(e,t=process.env){let n=Eo(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 wt(e=process.env){let t=String(e[Un]||"").trim();if(Fa.has(t.toLowerCase()))return null;let n=`${t}|${e.BOSTRAT_PASSWD_FILE||""}|${e.BOSTRAT_GROUP_FILE||""}|${e.BOSTRAT_BOX_HOME_VIEW||""}`;if(Bn?.key===n)return Bn.value;let r;if(!La.test(t))r={name:t,error:`${Un}="${t}" is not a valid user name`};else{let o=Oo(t,e),s=zt();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=Ro(o,e),l=a.filter(h=>ko.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 Bn={key:n,value:r},r}function We(e=process.env){let t=wt(e);return t&&!t.error?t.home:Vt.homedir()}function xo(e=process.env){let t=wt(e);return!t||t.error||t.rootNode?We(e):e.BOSTRAT_BOX_HOME_VIEW||Y.join(Ao(e),"box-home")}function Ua(e,t=process.env){let n=wt(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 Ln(e,{env:t=process.env,input:n=null,timeout:r=15e3}={}){let[o,...s]=Ua(e,t);return n==null?Hn(o,s,{timeout:r}):new Promise((a,l)=>{vo(o,s,{timeout:r},(m,d,w)=>m?l(m):a({stdout:d,stderr:w})).stdin.end(n)})}function Ha(e){return e.BOSTRAT_SETFACL_BIN?e.BOSTRAT_SETFACL_BIN:(Fn===void 0&&(Fn=["/usr/bin/setfacl","/bin/setfacl"].find(t=>He.existsSync(t))||null),Fn)}function Wa(e=process.env){let t=Vt.homedir(),n=Ao(e);return[Y.join(t,".ssh"),Y.join(t,".claude.json"),Y.join(t,".claude",".credentials.json"),Y.join(t,".codex","auth.json"),Y.join(t,".config","gh","hosts.yml"),Y.join(t,".cursor","cli-config.json"),Y.join(n,"node.env"),Y.join(n,"api-token"),Y.join(n,"plane-link"),Y.join(n,"secure-inputs")]}async function No({env:e=process.env,probe:t=!0}={}){let n=wt(e),r=await za(e);if(!n){let s=Oo(zt(),e)||{name:Vt.userInfo().username,uid:zt(),gid:-1},a=s.uid===0?["root"]:Ro(s,e).filter(m=>ko.includes(m)),l=s.uid!==0&&t?await Ga():!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 Ln(["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: ${Ka(h)})`)}if(!o.length){await Ln(["sudo","-n","true"],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&o.push(`${n.name} can sudo`);let h=[];for(let m of Wa(e))He.existsSync(m)&&await Ln(["test","-r",m],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&h.push(m);h.length&&o.push(`${n.name} can read ${h.join(", ")}`)}Ha(e)||o.push("setfacl is missing (apt install acl)");let s=xo(e);s!==n.home&&!He.existsSync(Y.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=Y.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:xo(e),problems:o,auditd:r}}async function Ga(){try{return await Hn("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 $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=zt()===0?["auditctl",["-l"]]:["sudo",["-n","auditctl","-l"]];try{let{stdout:h}=await Hn(l[0],l[1],{timeout:5e3});a=h.includes(`key=${Ba}`)}catch{a=null}}else s||(a=!1);return{log:n,readable:r,configured:s,rule:a,rulesFile:o}}function Mo(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"?`${Un} 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 Hn,Un,Ba,ko,La,Fa,Ao,zt,Bn,gt,Fn,Ka,Ae=R(()=>{Hn=Ca(vo),Un="BOSTRAT_BOX_USER",Ba="bostrat-box",ko=Object.freeze(["root","sudo","wheel","admin","docker","lxd","libvirt","disk"]),La=/^[a-z_][a-z0-9_-]{0,31}$/,Fa=new Set(["","off","0","false","no","none"]),Ao=e=>e.BOSTRAT_STATE_DIR||Y.join(e.HOME||Vt.homedir(),".bostrat");zt=()=>typeof process.getuid=="function"?process.getuid():0,Bn=null;gt=(e=process.env)=>{let t=wt(e);return!!(t&&!t.error)};Ka=e=>String(e?.stderr||e?.message||e).trim().split(`
7
- `)[0].slice(0,160)});var yt=R(()=>{});import Ya from"node:os";import Wn from"node:path";function Po(){return gt()?Wn.join(We(),".claude.json"):process.env.CLAUDE_CONFIG_DIR?Wn.join(process.env.CLAUDE_CONFIG_DIR,".claude.json"):Wn.join(Ya.homedir(),".claude.json")}var Gn=R(()=>{Kt();Cn();Ae();yt()});import Xa from"node:os";import zn from"node:path";function Do(){if(gt())return zn.join(We(),".codex","config.toml");let e=process.env.CODEX_HOME||zn.join(Xa.homedir(),".codex");return zn.join(e,"config.toml")}var Ja,tp,Vn=R(()=>{Ae();Ja="check_for_update_on_startup",tp=`${Ja} = false`});import Qa from"node:os";import jo from"node:path";var ec,ap,cp,qn=R(()=>{Yn();Wt();ec=process.env.BOSTRAT_DEBUG_DIR||jo.join(Qa.homedir(),".bostrat","debug"),ap=jo.join(ec,"handoff.jsonl"),cp=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as nc}from"node:child_process";import{promisify as rc}from"node:util";function Xn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var hp,mp,wp,gp,yp,Jn=R(()=>{qn();hp=rc(nc),mp=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,wp=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,gp=Number(process.env.BOSTRAT_CLI_PROBE_TIMEOUT_MS)||8e3,yp=Promise.resolve()});var Co=R(()=>{Ae()});import Zn from"node:path";import{execFile as oc}from"node:child_process";import{promisify as sc}from"node:util";var vp,Bo,ic,kp,Ap,Lo=R(()=>{vp=sc(oc),Bo=process.env.HOME||"/home/globo",ic=Zn.join(process.env.BOSTRAT_STATE_DIR||Zn.join(Bo,".bostrat"),"repos"),kp=[...(process.env.BOSTRAT_REPOS_ROOT||Zn.join(Bo,"Documents")).split(","),ic].map(e=>e.trim()).filter(Boolean),Ap=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function Xt(e=Date.now()){if(Oe)return{tripped:!1,holdMs:1/0};if(Ee>e)return{tripped:!1,holdMs:Ee-e};if((!St||e-St>=qt.windowMs)&&(St=e,bt=0),bt++,bt<qt.trip)return{tripped:!1,holdMs:0};Yt++;let t=Math.min(qt.minMs*2**(Yt-1),qt.maxMs);return Ee=e+t,bt=0,St=0,{tripped:!0,holdMs:t}}function Fo(){bt=0,St=0,Yt=0,Ee=0}function _t(e=Date.now()){return Oe?1/0:Ee>e?Ee-e:0}function Jt(e=Date.now()){return _t(e)>0}function Qn(e={}){Oe={at:Date.now(),...e},Ee=1/0}function er(){return Oe}function Uo(e=Date.now()){return{held:Jt(e),holdMs:Oe?null:_t(e),holds:Yt,removed:Oe?{...Oe}:null}}var ac,qt,bt,St,Yt,Ee,Oe,tr=R(()=>{ac={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},qt={...ac},bt=0,St=0,Yt=0,Ee=0,Oe=null});import Ho from"node:path";import cc from"node:os";import{execFile as lc}from"node:child_process";import{promisify as uc}from"node:util";var Cp,dc,Bp,Lp,Fp,nr=R(()=>{Lo();tr();Cp=uc(lc),dc=process.env.BOSTRAT_STATE_DIR||Ho.join(process.env.HOME||cc.tmpdir(),".bostrat"),Bp=Ho.join(dc,"repos"),Lp=5*6e4,Fp=10*6e4});var Wo=R(()=>{nr()});var Ko=R(()=>{});import fc from"node:fs/promises";import Tt from"node:path";import hc from"node:os";import{EventEmitter as mc}from"node:events";function wc(e){return e?.cwd?Tt.join(e.cwd,".bostrat","events"):Tt.join(Go,"events")}async function Zt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?Tt.join(Go,"events"):wc(e));let o;try{o=await fc.readFile(gc(n,r),"utf8")}catch{return[]}return _c(o)}function _c(e){let t=[];for(let n of e.split(`
8
- `))if(n.trim())try{t.push(JSON.parse(bc(n)?Sc(n):n))}catch{}return t}var xt,Go,gc,yc,bc,Sc,Qt=R(()=>{Ko();Wt();xt=new mc;xt.setMaxListeners(0);Go=process.env.BOSTRAT_STATE_DIR||Tt.join(process.env.HOME||hc.tmpdir(),".bostrat");gc=(e,t)=>Tt.join(e,`${t}.ndjson`),yc=/(?<!\\)((?:\\\\)*)\\u0000/g,bc=e=>e.includes("\\u0000"),Sc=e=>e.replace(yc,"$1\\ufffd")});import xc from"node:os";import $c from"node:path";import{execFile as vc}from"node:child_process";import{promisify as kc}from"node:util";var df,pf,ff,hf,mf,wf,zo=R(()=>{Wo();Qt();df=kc(vc),pf=process.env.BOSTRAT_STATE_DIR||$c.join(process.env.HOME||xc.tmpdir(),".bostrat"),ff=25*1024,hf=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,mf=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,wf=Promise.resolve()});var Sf,Vo=R(()=>{nr();yt();Sf=60*6e4});var qo=R(()=>{Vo()});import Yo from"node:path";import Ac from"node:os";var Ke,Ec,Pf,rr,Df,jf,Cf,Xo=R(()=>{Kt();Ae();Ke="BOSTRAT_NODE_URL",Ec=process.env.BOSTRAT_STATE_DIR||Yo.join(process.env.HOME||Ac.tmpdir(),".bostrat"),Pf=Yo.join(Ec,"git-hooks"),rr=`#!/bin/sh
5
+ `,{mode:384}),Ft.chmodSync(e,384)}function oo(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 Ut,Ue,Nn=R(()=>{Ut=process.env.BOSTRAT_STATE_DIR||Rn.join(process.env.HOME||da.tmpdir(),".bostrat"),Ue=()=>Rn.join(Ut,"node.env")});var bd,Wt=R(()=>{bd=16*1024});var le,ht,Kt=R(()=>{le="BOSTRAT_HOOK_TOKEN",ht="x-bostrat-hook"});var pa,Td,so=R(()=>{pa=(e,t)=>{if(e==null||e==="")return t;let n=Number(e);return Number.isFinite(n)&&n>=0?n:t},Td=pa(process.env.BOSTRAT_HOOK_FOLD_MS,250)});function ya(e,t=ha){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 Gt(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function mo(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 po(e){let t=Gt(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 yo(e){let{cmd:t,at:n}=mo(e);if(t==="sudo"){for(n++;n<e.length&&e[n].startsWith("-");)n++;t=e[n]??null}return{cmd:t,at:n}}function bo(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=Gt(e),{cmd:a}=yo(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 Ma(e){let t=Gt(e),{cmd:n,at:r}=yo(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&&xa.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=bo(e,wo);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 fa,ha,io,ao,co,lo,uo,Ad,ma,ga,Mn,wa,ue,Pn,ba,Sa,_a,Ta,go,wo,xa,$a,va,ka,Aa,fo,ho,Ea,Oa,Ra,Na,q,mt,In,So,Ed,Od,_o=R(()=>{so();fa="BP-AU-R4",ha=160,io=200,ao=5,co=8,lo=5,uo=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"]),ma=5e3,ga=new Set(["tool.called","tool.failed"]),Mn=new Set(["Write","Edit","NotebookEdit"]),wa=e=>String(e??"").replace(/\s+/g," ").trim(),ue=(e,t=120)=>wa(e).slice(0,t);Pn=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,ba=new RegExp(`${Pn}/\\.ssh(?:/|\\b)`),Sa=new RegExp(`${Pn}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),_a=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,Ta=/^\.env\.(?:example|sample|template|dist)$/,go=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,wo=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${Pn}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),xa=/^(?: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)$/,$a=/^\/tmp\/|\/\.bostrat\/tmp\//,va=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,ka=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,Aa=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,fo=e=>ba.test(e)||Sa.test(e),ho=e=>[...String(e??"").matchAll(_a)].some(t=>!Ta.test(t[1])),Ea=e=>go.test(e),Oa=e=>wo.test(e),Ra=e=>(e.startsWith("/")||e.startsWith("~"))&&!$a.test(e);Na=e=>bo(e,go);q=(e,t,n,r)=>Object.freeze({severity:e,requirement:fa,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 ya(o.head,e.headCap)){let a=t(s,o);a&&(n++,r??=ue(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??=ue(s))}return n?{count:n,sample:r}:null},So=Object.freeze({"force-push":q("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=po(n);return r&&r.force&&!r.lease?n:null})),"protected-config-write":q("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)Mn.has(s.tool)&&s.path&&Ea(s.path)&&(n++,r??=ue(`${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}),"persistence-install":q("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)Mn.has(s.tool)&&s.path&&Oa(s.path)&&(n++,r??=ue(`${s.tool} ${s.path}`));let o=mt(t,s=>{let a=Ma(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"push-outside-track":q("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=po(n);return r&&(r.remote&&!/^(?:origin|upstream)$/.test(r.remote)&&!r.remote.startsWith("$")&&!r.remote.startsWith("-")||r.dsts.some(o=>va.test(o)||!ka.test(o)))?n:null})),"credential-read":q("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&&fo(n.head)?n.head:n.path&&fo(n.path)?`${n.tool} ${n.path}`:null)),"dotenv-read":q("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&&ho(n.head)?n.head:n.path&&ho(n.path)?`${n.tool} ${n.path}`:null)),"privileged-command":q("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}=mo(Gt(n));return r==="sudo"||r==="docker"?n:null})),"write-outside-workspace":q("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=>Mn.has(n.tool)&&n.path&&Ra(n.path)?`${n.tool} ${n.path}`:null)),"egress-new-host":q("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>ma&&t.state.hosts.delete(t.state.hosts.values().next().value),n++,r??=ue(`${s} \xB7 ${o.head}`));return n?{count:n,sample:r}:null}),"spend-spike":q("low",`a cost.recorded turn over ${co}\xD7 the Track's running median (its last ${io} cost events, at least ${ao} of them) and over $${lo} \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>=ao&&r>=lo){let s=[...n].sort((l,h)=>l-h),a=s[Math.floor(s.length/2)];r>co*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>io&&n.shift(),o}),"peer-injected-call":q("medium",`a tool call within ${uo/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>uo||t.ts<n)return null;let r=t.calls[0];return{count:t.count,sample:ue(`${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":q("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:ue(`session ${String(e.payload.sessionId||"?").slice(0,8)} \xB7 ${n.tool}${n.head?`: ${n.head}`:n.path?` ${n.path}`:""}`)}}),"orphan-process":q("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:ue(`${o.comm||"process"}${o.cmd?`: ${o.cmd}`:""}${o.via?` [${o.via}]`:""}${s}${r>1?` (+${r-1} more)`:""}`)}}),"unknown-harness-shape":q("medium","a harness-made user turn of a shape chat-notes.js does not list (harness.shape.seen with known: false, harness-shapes.js): Claude Code wrote a new kind of its own turn into a transcript \u2014 hidden from chat by the generic catch, counted once per shape per node here; the node pages the operator once on first sight, this row is the fleet's record","2026-10-28 fleet replay \xB7 0 harness.shape.seen events in 311,055 (1,132 logs; the type is new, so the replay cannot bound this rule's rate) \xB7 transcript scan the same day: 2,863 claude user turns in 1,539 transcripts over 90 d, 144 of them harness-made (isMeta), 9 distinct shapes, 4 of which had rendered in chat as operator messages (<system-reminder><tools-used-before-summary> on 2 Tracks under 2.1.312, a usage-limit-reset notice, a safety-classifier notice) \u2192 medium (rail finding + security row), never a page from the plane: the once-per-shape page is the node's, so a release that adds one shape pages once, not per Track per hour",e=>{if(e.type!=="harness.shape.seen"||e.source!=="transcript")return null;let t=e.payload||{};if(t.known!==!1||!t.key)return null;let n=`${t.provider||"cli"}${t.cliVersion?` ${t.cliVersion}`:""}`;return{count:1,sample:ue(`${t.key} \xB7 ${n}${t.head?` \xB7 ${t.head}`:""}`)}})}),Ed=Object.freeze(Object.keys(So)),Od=new Set([...ga,"cost.recorded","peer.message","turn.user","audit.procs","harness.shape.seen"])});function ja(e){let t=String(e??"").trim().toLowerCase();if(Pa.has(t))return{enabled:!1,rules:[],unknown:[]};if(Da.has(t))return{enabled:!0,rules:[...Dn],unknown:[]};let n=[],r=[];for(let o of t.split(",")){let s=o.trim();s&&(Dn.includes(s)?n.includes(s)||n.push(s):r.push(s))}return{enabled:n.length>0,rules:n,unknown:r}}function To(e){return e?.enabled?`on \xB7 denies ${e.rules.length===Dn.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 Dn,Pa,Da,jn,Cn=R(()=>{_o();Dn=Object.freeze(["force-push","protected-config-write","credential-read","persistence-install"]),Pa=new Set(["","off","0","false","no","none"]),Da=new Set(["on","1","true","yes","all"]);jn=(e=process.env)=>ja(e.BOSTRAT_AUDIT_GUARD)});import He from"node:fs";import $o from"node:fs/promises";import Vt from"node:os";import Y from"node:path";import{execFile as vo}from"node:child_process";import{promisify as Ca}from"node:util";function Eo(e){try{return He.readFileSync(e,"utf8").split(`
6
+ `).filter(t=>t&&!t.startsWith("#")).map(t=>t.split(":"))}catch{return[]}}function Oo(e,t=process.env){let r=Eo(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 Ro(e,t=process.env){let n=Eo(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[Un]||"").trim();if(Fa.has(t.toLowerCase()))return null;let n=`${t}|${e.BOSTRAT_PASSWD_FILE||""}|${e.BOSTRAT_GROUP_FILE||""}|${e.BOSTRAT_BOX_HOME_VIEW||""}`;if(Bn?.key===n)return Bn.value;let r;if(!La.test(t))r={name:t,error:`${Un}="${t}" is not a valid user name`};else{let o=Oo(t,e),s=zt();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=Ro(o,e),l=a.filter(h=>ko.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 Bn={key:n,value:r},r}function We(e=process.env){let t=gt(e);return t&&!t.error?t.home:Vt.homedir()}function xo(e=process.env){let t=gt(e);return!t||t.error||t.rootNode?We(e):e.BOSTRAT_BOX_HOME_VIEW||Y.join(Ao(e),"box-home")}function Ua(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 Ln(e,{env:t=process.env,input:n=null,timeout:r=15e3}={}){let[o,...s]=Ua(e,t);return n==null?Hn(o,s,{timeout:r}):new Promise((a,l)=>{vo(o,s,{timeout:r},(m,d,g)=>m?l(m):a({stdout:d,stderr:g})).stdin.end(n)})}function Ha(e){return e.BOSTRAT_SETFACL_BIN?e.BOSTRAT_SETFACL_BIN:(Fn===void 0&&(Fn=["/usr/bin/setfacl","/bin/setfacl"].find(t=>He.existsSync(t))||null),Fn)}function Wa(e=process.env){let t=Vt.homedir(),n=Ao(e);return[Y.join(t,".ssh"),Y.join(t,".claude.json"),Y.join(t,".claude",".credentials.json"),Y.join(t,".codex","auth.json"),Y.join(t,".config","gh","hosts.yml"),Y.join(t,".cursor","cli-config.json"),Y.join(n,"node.env"),Y.join(n,"api-token"),Y.join(n,"plane-link"),Y.join(n,"secure-inputs")]}async function No({env:e=process.env,probe:t=!0}={}){let n=gt(e),r=await za(e);if(!n){let s=Oo(zt(),e)||{name:Vt.userInfo().username,uid:zt(),gid:-1},a=s.uid===0?["root"]:Ro(s,e).filter(m=>ko.includes(m)),l=s.uid!==0&&t?await Ga():!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 Ln(["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: ${Ka(h)})`)}if(!o.length){await Ln(["sudo","-n","true"],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&o.push(`${n.name} can sudo`);let h=[];for(let m of Wa(e))He.existsSync(m)&&await Ln(["test","-r",m],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&h.push(m);h.length&&o.push(`${n.name} can read ${h.join(", ")}`)}Ha(e)||o.push("setfacl is missing (apt install acl)");let s=xo(e);s!==n.home&&!He.existsSync(Y.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=Y.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:xo(e),problems:o,auditd:r}}async function Ga(){try{return await Hn("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 $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=zt()===0?["auditctl",["-l"]]:["sudo",["-n","auditctl","-l"]];try{let{stdout:h}=await Hn(l[0],l[1],{timeout:5e3});a=h.includes(`key=${Ba}`)}catch{a=null}}else s||(a=!1);return{log:n,readable:r,configured:s,rule:a,rulesFile:o}}function Mo(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"?`${Un} 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 Hn,Un,Ba,ko,La,Fa,Ao,zt,Bn,wt,Fn,Ka,Ae=R(()=>{Hn=Ca(vo),Un="BOSTRAT_BOX_USER",Ba="bostrat-box",ko=Object.freeze(["root","sudo","wheel","admin","docker","lxd","libvirt","disk"]),La=/^[a-z_][a-z0-9_-]{0,31}$/,Fa=new Set(["","off","0","false","no","none"]),Ao=e=>e.BOSTRAT_STATE_DIR||Y.join(e.HOME||Vt.homedir(),".bostrat");zt=()=>typeof process.getuid=="function"?process.getuid():0,Bn=null;wt=(e=process.env)=>{let t=gt(e);return!!(t&&!t.error)};Ka=e=>String(e?.stderr||e?.message||e).trim().split(`
7
+ `)[0].slice(0,160)});var yt=R(()=>{});import Ya from"node:os";import Wn from"node:path";function Po(){return wt()?Wn.join(We(),".claude.json"):process.env.CLAUDE_CONFIG_DIR?Wn.join(process.env.CLAUDE_CONFIG_DIR,".claude.json"):Wn.join(Ya.homedir(),".claude.json")}var Gn=R(()=>{Kt();Cn();Ae();yt()});import Xa from"node:os";import zn from"node:path";function Do(){if(wt())return zn.join(We(),".codex","config.toml");let e=process.env.CODEX_HOME||zn.join(Xa.homedir(),".codex");return zn.join(e,"config.toml")}var Ja,tp,Vn=R(()=>{Ae();Ja="check_for_update_on_startup",tp=`${Ja} = false`});import Qa from"node:os";import jo from"node:path";var ec,ap,cp,qn=R(()=>{Yn();Wt();ec=process.env.BOSTRAT_DEBUG_DIR||jo.join(Qa.homedir(),".bostrat","debug"),ap=jo.join(ec,"handoff.jsonl"),cp=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as nc}from"node:child_process";import{promisify as rc}from"node:util";function Xn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var hp,mp,gp,wp,yp,Jn=R(()=>{qn();hp=rc(nc),mp=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,gp=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,wp=Number(process.env.BOSTRAT_CLI_PROBE_TIMEOUT_MS)||8e3,yp=Promise.resolve()});var Co=R(()=>{Ae()});import Zn from"node:path";import{execFile as oc}from"node:child_process";import{promisify as sc}from"node:util";var vp,Bo,ic,kp,Ap,Lo=R(()=>{vp=sc(oc),Bo=process.env.HOME||"/home/globo",ic=Zn.join(process.env.BOSTRAT_STATE_DIR||Zn.join(Bo,".bostrat"),"repos"),kp=[...(process.env.BOSTRAT_REPOS_ROOT||Zn.join(Bo,"Documents")).split(","),ic].map(e=>e.trim()).filter(Boolean),Ap=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function Xt(e=Date.now()){if(Oe)return{tripped:!1,holdMs:1/0};if(Ee>e)return{tripped:!1,holdMs:Ee-e};if((!St||e-St>=qt.windowMs)&&(St=e,bt=0),bt++,bt<qt.trip)return{tripped:!1,holdMs:0};Yt++;let t=Math.min(qt.minMs*2**(Yt-1),qt.maxMs);return Ee=e+t,bt=0,St=0,{tripped:!0,holdMs:t}}function Fo(){bt=0,St=0,Yt=0,Ee=0}function _t(e=Date.now()){return Oe?1/0:Ee>e?Ee-e:0}function Jt(e=Date.now()){return _t(e)>0}function Qn(e={}){Oe={at:Date.now(),...e},Ee=1/0}function er(){return Oe}function Uo(e=Date.now()){return{held:Jt(e),holdMs:Oe?null:_t(e),holds:Yt,removed:Oe?{...Oe}:null}}var ac,qt,bt,St,Yt,Ee,Oe,tr=R(()=>{ac={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},qt={...ac},bt=0,St=0,Yt=0,Ee=0,Oe=null});import Ho from"node:path";import cc from"node:os";import{execFile as lc}from"node:child_process";import{promisify as uc}from"node:util";var Cp,dc,Bp,Lp,Fp,nr=R(()=>{Lo();tr();Cp=uc(lc),dc=process.env.BOSTRAT_STATE_DIR||Ho.join(process.env.HOME||cc.tmpdir(),".bostrat"),Bp=Ho.join(dc,"repos"),Lp=5*6e4,Fp=10*6e4});var Wo=R(()=>{nr()});var Ko=R(()=>{});import fc from"node:fs/promises";import Tt from"node:path";import hc from"node:os";import{EventEmitter as mc}from"node:events";function gc(e){return e?.cwd?Tt.join(e.cwd,".bostrat","events"):Tt.join(Go,"events")}async function Zt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?Tt.join(Go,"events"):gc(e));let o;try{o=await fc.readFile(wc(n,r),"utf8")}catch{return[]}return _c(o)}function _c(e){let t=[];for(let n of e.split(`
8
+ `))if(n.trim())try{t.push(JSON.parse(bc(n)?Sc(n):n))}catch{}return t}var xt,Go,wc,yc,bc,Sc,Qt=R(()=>{Ko();Wt();xt=new mc;xt.setMaxListeners(0);Go=process.env.BOSTRAT_STATE_DIR||Tt.join(process.env.HOME||hc.tmpdir(),".bostrat");wc=(e,t)=>Tt.join(e,`${t}.ndjson`),yc=/(?<!\\)((?:\\\\)*)\\u0000/g,bc=e=>e.includes("\\u0000"),Sc=e=>e.replace(yc,"$1\\ufffd")});import xc from"node:os";import $c from"node:path";import{execFile as vc}from"node:child_process";import{promisify as kc}from"node:util";var df,pf,ff,hf,mf,gf,zo=R(()=>{Wo();Qt();df=kc(vc),pf=process.env.BOSTRAT_STATE_DIR||$c.join(process.env.HOME||xc.tmpdir(),".bostrat"),ff=25*1024,hf=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,mf=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,gf=Promise.resolve()});var Sf,Vo=R(()=>{nr();yt();Sf=60*6e4});var qo=R(()=>{Vo()});import Yo from"node:path";import Ac from"node:os";var Ke,Ec,Pf,rr,Df,jf,Cf,Xo=R(()=>{Kt();Ae();Ke="BOSTRAT_NODE_URL",Ec=process.env.BOSTRAT_STATE_DIR||Yo.join(process.env.HOME||Ac.tmpdir(),".bostrat"),Pf=Yo.join(Ec,"git-hooks"),rr=`#!/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")
@@ -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 $t from"node:fs/promises";import en from"node:os";import Ge from"node:path";import{execFile as Oc}from"node:child_process";import{promisify as Rc}from"node:util";function es(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function ts(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 jc(e=process.env){let t=ts(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function ns(e=en.totalmem()){return Math.max(e-Mc*vt,Math.floor(e/2))}function Cc(e=en.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(Pc*vt,ns(e))}function Bc(e=process.env){return Ge.join(es(e),Ic)}async function Lc(e){return(await $t.readFile(e,"utf8")).trim()}async function rs({env:e=process.env,totalBytes:t=en.totalmem(),force:n=!1,platform:r=process.platform}={}){if(!n&&!jc(e))return ze=ts(e)==="off"?{available:!1,reason:"disabled (BOSTRAT_BOX_CGROUPS=0)"}:await Fc({env:e,totalBytes:t,platform:r}),ze;let o=es(e),s=Bc(e);try{let a;try{a=(await Lc(Ge.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[Ge.join(o,"cgroup.subtree_control"),Ge.join(s,"cgroup.subtree_control")])try{await $t.writeFile(d,h)}catch(w){throw new Error(`cannot enable ${h} in ${d} (${w?.code||w?.message||w})`)}let m=ns(t);l.includes("cpu")&&await $t.writeFile(Ge.join(s,"cpu.weight"),String(Jo)),l.includes("memory")&&await $t.writeFile(Ge.join(s,"memory.max"),String(m)),ze={available:!0,backend:"cgroupfs",path:s,controllers:l,cpuWeight:l.includes("cpu")?Jo:null,memoryMaxMb:l.includes("memory")?Math.round(m/vt):null}}catch(a){ze={available:!1,reason:a?.message||String(a)}}return ze}async function Fc({env:e=process.env,totalBytes:t=en.totalmem(),platform:n=process.platform}={}){if(n!=="linux")return{available:!1,reason:`not a Fly/container node, and no systemd on ${n}`};try{await Nc(Zo(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=Cc(t,e);return{available:!0,backend:"systemd",path:null,controllers:["memory"],cpuWeight:null,memoryMaxMb:Math.round(r/vt),swapMaxMb:Dc,systemctl:Zo(e),procRoot:e.BOSTRAT_PROC_ROOT||"/proc"}}function os(e=ze){let t=`nice ${Qo} 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 Nc,Qo,Jo,Mc,Ic,Pc,Dc,vt,ze,Zo,or=R(()=>{Nc=Rc(Oc),Qo=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),Jo=50,Mc=768,Ic="bostrat-boxes",Pc=4096,Dc=512,vt=1024*1024;ze=null;Zo=(e=process.env)=>e.BOSTRAT_SYSTEMCTL_BIN||"systemctl"});import{execFile as Uc}from"node:child_process";import{promisify as Hc}from"node:util";import as from"node:fs";import Wc from"node:os";function cs(e){return`/tmp/tmux-${e}/default`}function Gc({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=cs(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function ir(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Vc(e,{loginShell:t});return r===ls?!0:r===sr?!1:n}async function Vc(e,{loginShell:t=!1,timeoutMs:n=zc}={}){if(!e)return sr;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await Kc(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),ls}catch(s){return s?.killed||s?.signal?is:s?.code===1||s?.code===127?sr:is}}var Kc,Oh,ss,Rh,Nh,Mh,Ih,Ph,ls,sr,is,zc,tn,Dh,jh,Ch,Bh,Lh,Fh,Yn=R(()=>{Wt();Gn();Vn();Jn();Co();zo();qo();qn();Kt();Xo();or();Ae();Kc=Hc(Uc),Oh=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";ss=typeof process.getuid=="function"?process.getuid():0,Rh=Gc({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return as.existsSync(cs(ss))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:ss}),Nh=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Mh=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Ih=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),Ph=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);ls="present",sr="absent",is="unknown",zc=5e3;tn={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"},Dh=(()=>{try{let e=Wc.homedir();if(e&&as.existsSync(e))return e}catch{}return"/"})(),jh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Ch=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Bh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Lh=Number(process.env.BOSTRAT_BOX_COLS)||120,Fh=Number(process.env.BOSTRAT_BOX_ROWS)||40});var Ps={};On(Ps,{NODE_IMAGE:()=>ur,commandPlan:()=>Ns,flyToml:()=>Rs,flyWizard:()=>gl,parseFlyFlags:()=>Ms,stageConfig:()=>Is});import lr from"node:fs";import Re from"node:path";import ul from"node:os";import dl from"node:readline/promises";import{execFile as pl}from"node:child_process";import{createRequire as fl}from"node:module";import{randomUUID as hl}from"node:crypto";function Rs({app:e,region:t,nodeName:n=e,planeUrl:r=Os,image:o=ur}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
52
+ `});import $t from"node:fs/promises";import en from"node:os";import Ge from"node:path";import{execFile as Oc}from"node:child_process";import{promisify as Rc}from"node:util";function es(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function ts(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 jc(e=process.env){let t=ts(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function ns(e=en.totalmem()){return Math.max(e-Mc*vt,Math.floor(e/2))}function Cc(e=en.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(Pc*vt,ns(e))}function Bc(e=process.env){return Ge.join(es(e),Ic)}async function Lc(e){return(await $t.readFile(e,"utf8")).trim()}async function rs({env:e=process.env,totalBytes:t=en.totalmem(),force:n=!1,platform:r=process.platform}={}){if(!n&&!jc(e))return ze=ts(e)==="off"?{available:!1,reason:"disabled (BOSTRAT_BOX_CGROUPS=0)"}:await Fc({env:e,totalBytes:t,platform:r}),ze;let o=es(e),s=Bc(e);try{let a;try{a=(await Lc(Ge.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[Ge.join(o,"cgroup.subtree_control"),Ge.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=ns(t);l.includes("cpu")&&await $t.writeFile(Ge.join(s,"cpu.weight"),String(Jo)),l.includes("memory")&&await $t.writeFile(Ge.join(s,"memory.max"),String(m)),ze={available:!0,backend:"cgroupfs",path:s,controllers:l,cpuWeight:l.includes("cpu")?Jo:null,memoryMaxMb:l.includes("memory")?Math.round(m/vt):null}}catch(a){ze={available:!1,reason:a?.message||String(a)}}return ze}async function Fc({env:e=process.env,totalBytes:t=en.totalmem(),platform:n=process.platform}={}){if(n!=="linux")return{available:!1,reason:`not a Fly/container node, and no systemd on ${n}`};try{await Nc(Zo(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=Cc(t,e);return{available:!0,backend:"systemd",path:null,controllers:["memory"],cpuWeight:null,memoryMaxMb:Math.round(r/vt),swapMaxMb:Dc,systemctl:Zo(e),procRoot:e.BOSTRAT_PROC_ROOT||"/proc"}}function os(e=ze){let t=`nice ${Qo} 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 Nc,Qo,Jo,Mc,Ic,Pc,Dc,vt,ze,Zo,or=R(()=>{Nc=Rc(Oc),Qo=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),Jo=50,Mc=768,Ic="bostrat-boxes",Pc=4096,Dc=512,vt=1024*1024;ze=null;Zo=(e=process.env)=>e.BOSTRAT_SYSTEMCTL_BIN||"systemctl"});import{execFile as Uc}from"node:child_process";import{promisify as Hc}from"node:util";import as from"node:fs";import Wc from"node:os";function cs(e){return`/tmp/tmux-${e}/default`}function Gc({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=cs(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function ir(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Vc(e,{loginShell:t});return r===ls?!0:r===sr?!1:n}async function Vc(e,{loginShell:t=!1,timeoutMs:n=zc}={}){if(!e)return sr;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await Kc(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),ls}catch(s){return s?.killed||s?.signal?is:s?.code===1||s?.code===127?sr:is}}var Kc,Oh,ss,Rh,Nh,Mh,Ih,Ph,ls,sr,is,zc,tn,Dh,jh,Ch,Bh,Lh,Fh,Yn=R(()=>{Wt();Gn();Vn();Jn();Co();zo();qo();qn();Kt();Xo();or();Ae();Kc=Hc(Uc),Oh=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";ss=typeof process.getuid=="function"?process.getuid():0,Rh=Gc({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return as.existsSync(cs(ss))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:ss}),Nh=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Mh=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Ih=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),Ph=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);ls="present",sr="absent",is="unknown",zc=5e3;tn={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"},Dh=(()=>{try{let e=Wc.homedir();if(e&&as.existsSync(e))return e}catch{}return"/"})(),jh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Ch=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Bh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Lh=Number(process.env.BOSTRAT_BOX_COLS)||120,Fh=Number(process.env.BOSTRAT_BOX_ROWS)||40});var Ps={};On(Ps,{NODE_IMAGE:()=>ur,commandPlan:()=>Ns,flyToml:()=>Rs,flyWizard:()=>wl,parseFlyFlags:()=>Ms,stageConfig:()=>Is});import lr from"node:fs";import Re from"node:path";import ul from"node:os";import dl from"node:readline/promises";import{execFile as pl}from"node:child_process";import{createRequire as fl}from"node:module";import{randomUUID as hl}from"node:crypto";function Rs({app:e,region:t,nodeName:n=e,planeUrl:r=Os,image:o=ur}){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.
@@ -92,18 +92,18 @@ swap_size_mb = 1024
92
92
  memory = "2gb"
93
93
  `}function Ns({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 Ms(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(ul.homedir(),".bostrat","fly",e);lr.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])lr.rmSync(Re.join(r,o),{recursive:!0,force:!0});return lr.writeFileSync(Re.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function wl({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await rn(["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=Ms(e),a=dl.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 Ms(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(ul.homedir(),".bostrat","fly",e);lr.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])lr.rmSync(Re.join(r,o),{recursive:!0,force:!0});return lr.writeFileSync(Re.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function gl({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await rn(["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 wl({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:o}={}){let s=Ms(e),a=dl.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
99
  `);try{await rn(["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 rn(["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 wl({ask:l,output:n,exec:r,flag:s.org}),d=s.app||await l("App name",`bostrat-node-${hl().slice(0,4)}`),w=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||Os,M=s.token||await l("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!M)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||ur,{dir:N}=Is({app:d,dest:o,toml:Rs({app:d,region:w,nodeName:y,planeUrl:b,image:S})});n.write(`
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 gl({ask:l,output:n,exec:r,flag:s.org}),d=s.app||await l("App name",`bostrat-node-${hl().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||Os,M=s.token||await l("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!M)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||ur,{dir:N}=Is({app:d,dest:o,toml:Rs({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=Ns({app:d,org:m,region:w,sizeGb:v,token:M,dir:N});for(let _ of k)n.write(` $ ${_.display}
106
+ `);let k=Ns({app:d,org:m,region:g,sizeGb:v,token:M,dir:N});for(let _ of k)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
109
  `),h(1);for(let _ of k){n.write(`
@@ -133,8 +133,8 @@ boxes, and they land on this machine's volume, never on bostrat (box-auth-policy
133
133
  `),s&&!s.endsWith(`
134
134
 
135
135
  `)&&(s+=`
136
- `),s+=l);return s}async function Bl(e){try{return await ye.readFile(e,"utf8")}catch(t){if(t?.code==="ENOENT")return null;throw t}}async function mr(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 Ll(e,t,n,r){let o={},s=e==="claude"?Po():e==="codex"?Do():Ml(),a=S=>{for(let N of t.keys())o[N]=S};if(e!=="claude"&&!Ol.existsSync(Xe.dirname(s)))return a("cli-absent"),{managed:[],states:o};let l;try{l=await Bl(s)}catch{return a("error"),{managed:n,states:o}}let h=new Set(n);if(e==="codex"){let S=si(l??""),N=new Map;for(let[x,I]of t)S.has(x)&&!h.has(x)?o[x]="conflict":N.set(x,jl(I,r));let k=new Set([...h].filter(x=>!t.has(x))),_=Cl(l??"",N,k);try{_!==(l??"")&&await mr(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=si(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}:{},w=[];for(let[S,N]of t){if(Object.hasOwn(d,S)&&!h.has(S)){o[S]="conflict";continue}d[S]=Dl(N,r,e),w.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 mr(s,JSON.stringify(v,null,2))}catch{for(let S of w)o[S]="error";return{managed:n,states:o}}for(let S of w)o[S]="applied";let b=m.mcpServers&&typeof m.mcpServers=="object"?m.mcpServers:{},M=new Set(w.filter(S=>JSON.stringify(b[S]??null)!==JSON.stringify(d[S])));return{managed:w.sort(),states:o,wrote:M}}async function Fl(){let e=Nl(),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={...Qs(),...t},o={};for(let s of Object.keys(r))o[s]=s in t?"file":"broker";return{values:r,sources:o}}function Ul(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 Hl(e,t,n,r,o){let s={},a=Ul(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 fi(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 ii(){let{values:e,sources:t}=await Fl(),n=ei(),r=ti(),o=fi(de.entries),s={};for(let d of o){let w=Hl(d,e,t,n,r),v=Object.entries(w).filter(([,y])=>y.state!=="set").map(([y])=>y);s[d.name]={rev:Number(d.updatedAt)||0,clis:{},since:{},missingEnv:v,env:w,...d.auth==="oauth"?{auth:"oauth"}:{}}}let a={...de.managed},l={...de.since||{}},h=Date.now();for(let d of pr){let w=new Map(o.filter(b=>(b.clis||pr).includes(d)&&!s[b.name].missingEnv.length).map(b=>[b.name,b])),v=await Ll(d,w,de.managed?.[d]??[],e);a[d]=v.managed;let y={...l[d]||{}};for(let[b,M]of Object.entries(v.states)){s[b].clis[d]=M;let S=s[b].rev;M==="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))w.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||pr)s[d.name].clis[y]=v}de={...de,managed:a,since:l},await Wl();let m=JSON.stringify(s)!==JSON.stringify(fr);if(fr=s,m)for(let d of hr)try{d(sn())}catch{}return sn()}async function Wl(){let e=JSON.stringify(de,null,2);if(e!==ai)try{await mr(Rl(),e),ai=e}catch(t){console.error("[mcp-config] cache write failed:",t?.message||t)}}function Kl(){let e=ri.then(ii,ii);return ri=e.catch(()=>{}),e}function hi(e,{updatedAt:t=Date.now()}={}){return de={...de,entries:fi(e),updatedAt:t},Kl()}var li,Rl,Nl,Ml,pr,Il,Pl,de,fr,ri,hr,Ye,Et,oi,ai,mi=R(()=>{Gn();Vn();ni();li=()=>process.env.BOSTRAT_STATE_DIR||Xe.join(process.env.HOME||ci.tmpdir(),".bostrat"),Rl=()=>Xe.join(li(),"mcp-config.json"),Nl=()=>Xe.join(li(),"mcp-env.json"),Ml=()=>Xe.join(ci.homedir(),".cursor","mcp.json"),pr=["claude","codex","cursor"],Il=/^[a-z0-9][a-z0-9_-]{0,47}$/,Pl=/\$\{([A-Za-z_][A-Za-z0-9_]{0,63})\}/g,de={entries:[],updatedAt:null,managed:{claude:[],codex:[],cursor:[]},since:{}},fr={},ri=Promise.resolve(),hr=new Set;Ye=(e,t)=>String(e).replace(Pl,(n,r)=>t[r]??"");Et=e=>JSON.stringify(String(e)),oi=e=>`{ ${Object.entries(e).map(([t,n])=>`${Et(t)} = ${Et(n)}`).join(", ")} }`;ai=null});import wi from"node:fs/promises";import bi from"node:path";import Gl from"node:os";function Vl(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 wr))throw new Error(`unknown refresh-flow field "${n}" \u2014 fields: ${_i.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(!yi.test(s))throw new Error(`bad provider key "${s}" in fallback`);if(!Array.isArray(a)||a.some(h=>typeof h!="string"||!yi.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 ql(e){let t={...wr};for(let n of _i){let r=e?.[n];r!=null&&(t[n]=r)}return t}function Xl(){return ql(Je?.flow)}function Ti(){return{flow:Xl(),configured:!!Je,source:Je?.source??null,updatedAt:Je?.updatedAt??null}}async function Jl(){try{await wi.mkdir(Si,{recursive:!0}),await wi.writeFile(zl(),JSON.stringify(Je,null,2))}catch{}}function xi(e=null){for(let t of Yl)try{t(Ti(),e)}catch{}}function $i(e){xi({rejected:String(e||"rejected by the plane")})}async function vi(e,{source:t="plane",updatedAt:n=Date.now()}={}){return Je={flow:Vl(e||{}),updatedAt:n,source:t},await Jl(),xi(),Ti()}var Si,zl,gi,wr,_i,yi,Je,Yl,ki=R(()=>{Si=process.env.BOSTRAT_STATE_DIR||bi.join(process.env.HOME||Gl.tmpdir(),".bostrat"),zl=()=>bi.join(Si,"refresh-flow.json"),gi=["prompt","auto","off"],wr=Object.freeze({contextFull:"prompt",contextFullPct:75,contextFullTokens:null,limitHit:"prompt",fallback:null}),_i=Object.keys(wr),yi=/^[a-z][a-z0-9-]{0,31}$/;Je=null,Yl=new Set});var Pi={};On(Pi,{REMOVED_MARKER:()=>Tr,detectInstallKind:()=>et,detectProviderAuth:()=>Ii,maskToken:()=>_r,readRemovedMarker:()=>Mi,startPlaneLink:()=>mu,updateCommandFor:()=>Rt,versionLt:()=>Qe});import Ze from"node:fs";import Ot from"node:fs/promises";import Zl from"node:http";import K from"node:path";import cn from"node:os";import{createRequire as Ql}from"node:module";import gr from"ws";function _r(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function Mi(e=Tr){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 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||cn.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 mu({url:e,token:t,nodeId:n=cn.hostname(),name:r=cn.hostname(),listTracks:o,detectAgents:s=null,onTracksTransferred:a=null,onTracksMoves:l=null,sampleMetrics:h=null,deliverySample:m=null,onHashKey:d=null,onViewBase:w=null,metricsMs:v=hu,onUpdateAvailable:y=null,onUpdatePolicy:b=null,onConflictProbe:M=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:I=Tr,onRemoved:Me=null,onDegraded:rt=null,onRecovered:Ie=null,onRefused:mn=null,onConnected:Mt=null,ingestMode:Pe=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:De=au,unackedRetryMs:je=iu,pingMs:ot=ou,deadLinkMs:P=Math.round(ot*su),maxInflightEvents:pe=du,httpTimeoutMs:fe=pu,fanoutActive:he=null,fanoutBatchCap:st=fu,stallBackoffMinMs:Pr=uu,fetchImpl:Dr=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 qi=O.replace(/^http/,"ws"),jr=new Set,Cr=c=>{let p=typeof c.latestNodeVersion=="string"?c.latestNodeVersion:null;if(!(!(p&&re&&Qe(re,p))||jr.has(p))){jr.add(p),T.log(`[plane-link] bostrat-node ${p} is available (this node runs ${re}) \u2014 ${Rt(E)}`);try{y?.({current:re,latest:p,min:c.minNodeVersion??null,installKind:E,required:!!(c.minNodeVersion&&Qe(re,c.minNodeVersion))})}catch(f){T.error(`[plane-link] update notice failed: ${f?.message||f}`)}}},_e=new Map,Te=new Map,wn=K.join(Sr,"plane-link","cursor.json"),gn=K.join(Sr,"plane-link","dead-letter.ndjson"),Br=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),se={},ee={},j=new Map,It=null,me=null,ie=0,it=0,Lr=0,Pt={},Fr=new Set,Ur=Promise.resolve(),H="ws",Ce=0,te=!1,xe=0,yn=!1,we=an,at=new Set,ne=[],W=null,J=null,Z=!1,Dt=!1,bn=!1,ct=Ai,lt=null,Sn=S&&typeof S=="object"?S:null,Be=null,Le=null,ae=null,$e=0,Hr=0,ce=null,_n=!1,jt=0,ut=!1,ge=Mi(I);if(ge)if(ge.tokenPreview===_r(t))ut=!0,Qn({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 ${I} to force a dial.`);else try{Ze.unlinkSync(I),T.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function Tn({reason:c="removed",at:p=Date.now(),via:f="ctl"}={}){if(!ut){ut=!0,Qn({reason:c,at:p,nodeId:n,via:f});try{Ze.mkdirSync(K.dirname(I),{recursive:!0}),Ze.writeFileSync(I,JSON.stringify({at:p,reason:c,via:f,nodeId:n,tokenPreview:_r(t)},null,2))}catch(i){T.error(`[plane-link] could not write ${I}: ${i?.message||i}`)}T.error(`[plane-link] the plane REMOVED this node (${c}, via ${f}) \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{Me?.({reason:c,at:p,via:f})}catch{}eo({bye:!1})}}async function Yi(){try{se=JSON.parse(await Ot.readFile(wn,"utf8"))}catch{se={}}}function Wr(){_n=!0,!Le&&(Le=setTimeout(async()=>{if(Le=null,!!_n){_n=!1;try{await Ot.mkdir(K.dirname(wn),{recursive:!0}),await Ot.writeFile(wn,JSON.stringify(se))}catch(c){T.error("[plane-link] cursor flush failed:",c?.message||c)}}},ru),Le.unref?.())}function xn(){try{return!!he?.()}catch{return!1}}function $n(){let c=H==="http"?we:an;return xn()?Math.min(c,st):c}function C(c){return!J||J.readyState!==gr.OPEN?!1:(J.send(JSON.stringify(c)),!0)}let Xi=ui(c=>C({v:B,ch:"ctl",type:"mcp_status",mcp:c}));function Fe(c){let p=Date.now();for(let{trackId:i,event:u}of c){let g=j.get(u.id);j.set(u.id,{trackId:i,seq:u.seq,event:u,sentAt:p,firstSentAt:g?.firstSentAt??p,retryAt:p+je,tries:(g?.tries??0)+1,nacks:g?.nacks??0})}let f=c.map(({trackId:i,event:u})=>({trackId:i,event:lu(u)}));return H==="http"?(na(f),!0):C({v:B,ch:"events",type:"append",events:f})}function Kr(c,p=Date.now()){if(at.has(c))return!0;for(let f of j.values())if(f.trackId===c&&p-f.firstSentAt<De)return!0;return!1}function Ji(c){let p=null;for(let f of j.values())f.trackId===c&&(p==null||f.seq<p)&&(p=f.seq);return p}function Ct(c){if(Dt)return;let p=ee[c];if(p==null)return;let f=Ji(c),i=f==null?p:Math.min(p,f-1);i>(se[c]??0)&&(se[c]=i,Wr())}function dt(){if(It=Date.now(),me!=null){let c=Date.now()-me;T.log(`[plane-link] spine sync recovered after ${Math.round(c/1e3)}s degraded (${ie} stall redial(s))`);let p=me;me=null,ie=0,it=0,te=!1,xe=0;try{Ie?.({since:p,downMs:c})}catch(f){T.error(`[plane-link] onRecovered failed: ${f?.message||f}`)}}}function vn(c){if(!Array.isArray(c)||!c.length)return;let p=new Set;for(let f of c){let i=j.get(f);i&&(j.delete(f),(ee[i.trackId]??0)<i.seq&&(ee[i.trackId]=i.seq),p.add(i.trackId))}for(let f of p)Ct(f);dt()}function Gr(c,p){Lr++;let f={at:Date.now(),trackId:c.trackId,seq:c.seq,id:c.event?.id??null,type:c.event?.type??null,reason:p,event:c.event??null};T.error(`[plane-link] DEAD-LETTER ${c.trackId} seq ${c.seq} (${f.type??"?"}): plane rejected it permanently (${p}) \u2014 kept in ${gn}`),Ur=Ur.then(async()=>{await Ot.mkdir(K.dirname(gn),{recursive:!0}),await Ot.appendFile(gn,JSON.stringify(f)+`
137
- `)}).catch(i=>T.error(`[plane-link] dead-letter write failed: ${i?.message||i}`))}function Zi(c,p){if(Pt[c]=(Pt[c]??0)+1,Fr.has(c))return;Fr.add(c);let f=cu[c]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";T.error(`[plane-link] REFUSED by the plane (${c}) on track ${p}: events are being dropped, not stored \u2014 ${f}`);try{mn?.({reason:c,trackId:p,count:Pt[c],hint:f})}catch(i){T.error(`[plane-link] onRefused failed: ${i?.message||i}`)}}function kn(c,p,f,i=null){if(!Array.isArray(c)||!c.length)return;let u=new Set,g=Date.now();for(let $ of c){let A=j.get($);A&&(f?(j.delete($),Gr(A,p),String(p).startsWith(yr)&&Zi(String(p).slice(yr.length),A.trackId),(ee[A.trackId]??0)<A.seq&&(ee[A.trackId]=A.seq),u.add(A.trackId)):(A.nacks++,A.retryAt=g+Math.max(1e3,Number(i)||je)))}for(let $ of u)Ct($);dt()}function zr(c=Date.now()){let p=1/0;for(let f of j.values())f.firstSentAt<p&&(p=f.firstSentAt);return p===1/0?0:c-p}function Qi(c){if(!P||!c||c!==J||!$e)return!1;let p=Date.now()-$e;if(p<=P)return!1;Hr++,T.error(`[plane-link] no frame from the plane for ${Math.round(p/1e3)}s \u2014 link is half-open; terminating and redialing`);try{c.terminate()}catch{}return!0}function Vr(){if(!Z||!j.size)return;let c=Date.now(),p=zr(c);if(p<De||It!=null&&c-It<De||H==="http"&&te||it>c)return;ie++;let f=Math.min(Pr*2**(ie-1),Oi);if(me==null){me=c-p,T.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(p/1e3)}s with ${j.size} event(s) in flight (${H} door) \u2014 the plane is not answering appends`);try{rt?.({since:me,unacked:j.size,oldestAgeMs:p,mode:H})}catch(i){T.error(`[plane-link] onDegraded failed: ${i?.message||i}`)}}if(H==="http"){te=!0,xe=c+f,T.error(`[plane-link] ingest circuit OPEN (stall #${ie}); probing /v1/ingest/health in ${Math.round(f/1e3)}s`);return}it=c+f,T.error(`[plane-link] closing the link and redialing in ${Math.round(f/1e3)}s (stall redial #${ie})`);try{J?.terminate()}catch{}}function An(){if(!Z)return;let c=Date.now();if(H==="http"&&te)return;let p=[...j.values()].filter(i=>i.event&&i.retryAt<=c&&!(H==="http"&&at.has(i.trackId)));if(!p.length)return;p.sort((i,u)=>i.trackId===u.trackId?i.seq-u.seq:i.trackId<u.trackId?-1:1),T.log(`[plane-link] re-sending ${p.length} unacked event(s) the plane never confirmed`);let f=$n();if(H==="http"){let i=new Map;for(let u of p)(i.get(u.trackId)??i.set(u.trackId,[]).get(u.trackId)).push(u);for(let[,u]of i){if(Ce>=br)return;Fe(u.slice(0,f).map(g=>({trackId:g.trackId,event:g.event})))}return}for(let i=0;i<p.length;i+=f){let u=p.slice(i,i+f).map(g=>({trackId:g.trackId,event:g.event}));if(!Fe(u))return}}async function ea(c=null){for(;;){if(!Z)return!1;let p=j.size<pe,f=H!=="http"||Ce<br&&!te&&(!c||!Kr(c));if(p&&f)return!0;await new Promise(i=>setTimeout(i,100))}}function Bt(){if(W=null,!Z||!ne.length)return;let c=ne;ne=[];let p=$n();if(H!=="http"){for(let u=0;u<c.length;u+=p)Fe(c.slice(u,u+p));return}let f=xn(),i=new Map;for(let u of c)(i.get(u.trackId)??i.set(u.trackId,[]).get(u.trackId)).push(u);for(let[u,g]of i){if(Kr(u)||Ce>=br||te){ne.push(...g);continue}if(f){Fe(g.slice(0,p)),ne.push(...g.slice(p));continue}for(let $=0;$<g.length;$+=p)Fe(g.slice($,$+p))}ne.length&&!W&&(W=setTimeout(Bt,Ri),W.unref?.())}let ta=c=>{let p=new Map;for(let{trackId:f,event:i}of c)(p.get(f)??p.set(f,[]).get(f)).push(i);return[...p].map(([f,i])=>({trackId:f,events:i}))},ve=(c,p,f,{progress:i})=>{let u=Date.now();for(let{event:g}of c){let $=j.get(g.id);$&&($.nacks++,$.retryAt=u+Math.max(1e3,f||je))}i&&dt()};async function na(c){let p=new Set(c.map(f=>f.trackId));for(let f of p)at.add(f);Ce++;try{let f=await Dr(`${Br}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:ta(c)}),signal:AbortSignal.timeout(fe)}),i=(Number(f.headers.get("retry-after"))||0)*1e3;if(f.status===200){let u=await f.json();we=an;for(let A of u.results??[]){vn(A.acked??[]);let F=(oe,V)=>{let Lt=new Map;for(let ke of oe??[])(Lt.get(ke.reason)??Lt.set(ke.reason,[]).get(ke.reason)).push(ke.id);for(let[ke,to]of Lt)kn(to,ke,V,u.retryAfterMs??null)};F(A.rejected,!0),F(A.deferred,!1)}let g=new Set,$=new Map;for(let A of Array.isArray(u.refused)?u.refused:[])!A||typeof A.id!="string"||(g.add(A.id),($.get(A.reason)??$.set(A.reason,[]).get(A.reason)).push(A.id));for(let[A,F]of $)kn(F,`${yr}${A}`,!0);vn((u.discarded??[]).filter(A=>!g.has(A))),dt();return}if(f.status===429){ve(c,"overloaded",i||5e3,{progress:!0});return}if(f.status===413&&c.length>1){we=Math.max(1,Math.floor(c.length/2)),T.error(`[plane-link] ingest request too large (${c.length} events) \u2014 halving batches to ${we}`),ve(c,"too_large",1e3,{progress:!0});return}if(f.status===413){let u=j.get(c[0].event.id);u&&(j.delete(u.event.id),Gr(u,"too_large"),(ee[u.trackId]??0)<u.seq&&(ee[u.trackId]=u.seq),Ct(u.trackId)),dt();return}if(f.status===410){Tn({reason:"removed",via:"410"}),ve(c,"http_410",6e4,{progress:!1});return}if(f.status===401||f.status===403){let{tripped:u,holdMs:g}=Xt();if(u&&T.error(`[plane-link] holding every plane call for ${Math.round(g/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-jt>=Ni){jt=Date.now();let $="";try{$=(await f.json())?.error??""}catch{}T.error(`[plane-link] plane refused ingest (HTTP ${f.status}${$?`: ${$}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}ve(c,`http_${f.status}`,Math.max(6e4,_t()),{progress:!1});return}if(f.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_${f.status}`,i||5e3,{progress:!1})}catch(f){let i=f?.name==="TimeoutError"||f?.name==="AbortError";i&&c.length>1&&(we=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 ${we}`)),ve(c,i?"timeout":"network",5e3,{progress:!1})}finally{Ce--;for(let f of p)at.delete(f);ne.length&&!W&&(W=setTimeout(Bt,0),W.unref?.())}}async function ra(){if(H!=="http"||!te||!Z||yn)return;let c=Date.now();if(!(xe>c||Jt(c))){yn=!0;try{let p=await Dr(`${Br}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(fe)});if(!p.ok)throw new Error(`HTTP ${p.status}`);T.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),te=!1,xe=0,it=Date.now()+fe+je+1e3;for(let f of j.values())f.retryAt=Math.min(f.retryAt,Date.now());An()}catch(p){ie++;let f=Math.min(Pr*2**(ie-1),Oi);xe=Date.now()+f,T.error(`[plane-link] ingest door still not answering (${p?.message||p}); next probe in ${Math.round(f/1e3)}s`)}finally{yn=!1}}}function qr(){let c=Date.now();return{mode:H,unacked:j.size,oldestUnackedAgeMs:zr(c),lastProgressAt:It,degradedSince:me,stallRedials:ie,deadLettered:Lr,fanoutCap:xn()?st:null,http:H==="http"?{inFlight:Ce,circuitOpen:te,nextProbeInMs:te?Math.max(0,xe-c):0,batchCap:we,heldLive:ne.length}:null}}async function Yr(){if(!h)return;let c;try{c=await h()}catch(f){T.error("[plane-link] metrics sample failed:",f?.message||f);return}let p=null;try{p=m?.()??null}catch{}c&&C({v:B,ch:"ctl",type:"metrics",metrics:{...c,planeLink:qr(),...p?{delivery:p}:{}}})}function oa(){h&&(ce&&clearInterval(ce),Yr(),ce=setInterval(Yr,v),ce.unref?.())}async function sa(){let c;try{c=await o()}catch(p){T.error("[plane-link] backfill listTracks failed:",p?.message||p);return}C({v:B,ch:"ctl",type:"tracks",ids:c.filter(p=>!p.transferredTo).map(p=>p.id).filter(p=>typeof p=="string")});for(let p of c)if(!Z||!await Xr(p))return;Dt=!1;for(let p of Object.keys(ee))Ct(p)}async function Xr(c){let p;try{p=await Zt(c)}catch{return!0}let f=se[c.id]??0,i=p.filter(u=>u.seq>f&&typeof u.id=="string");for(let u=0;u<i.length;){if(!await ea(c.id))return!1;let g=i.slice(u,u+$n()).map($=>({trackId:c.id,event:$}));if(!Fe(g))return!1;u+=g.length}return!0}let En=new Map;async function Jr(c,p){if(En.get(c)===p)return!1;En.set(c,p);let f=null;try{f=(await o()).find($=>$?.id===c)??null}catch{return!1}if(!f)return!1;let i;try{i=await Zt(f)}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 g=u.seq-1;return(se[c]??0)>g&&(se[c]=g,Wr()),(ee[c]??0)>g&&(ee[c]=g),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?Xr(f):!1}function Zr(c){!Z||!c?.trackId||typeof c.id!="string"||(ne.push({trackId:c.trackId,event:c}),W||(W=setTimeout(Bt,Ri),W.unref?.()))}let pt=new Map;async function ia(c){let{reqId:p,method:f,path:i,headers:u={},body:g}=c,$=Object.fromEntries(Object.entries(u).filter(([,F])=>F!=null)),A=new AbortController;pt.set(p,A);try{if(c.host){await aa(c,$,A);return}x&&($["x-bostrat-token"]=x);let F=await fetch(O+i,{method:f,headers:$,body:g?Buffer.from(g,"base64"):void 0,signal:A.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:p,status:F.status,headers:oe}),F.body){for await(let V of F.body)if(!C({v:B,ch:"control",type:"http_data",reqId:p,data:Buffer.from(V).toString("base64")}))break}C({v:B,ch:"control",type:"http_end",reqId:p,error:null})}finally{pt.delete(p)}}function aa(c,p,f){let{reqId:i,method:u,path:g,body:$}=c,A=new URL(O);return new Promise(F=>{let oe=Zl.request({host:A.hostname,port:A.port,method:u,path:g,headers:{...p,host:c.host},signal:f.signal},V=>{let{connection:Lt,"keep-alive":ke,"transfer-encoding":to,upgrade:fd,...ca}=V.headers;C({v:B,ch:"control",type:"http_head",reqId:i,status:V.statusCode||502,headers:ca}),V.on("data",la=>{C({v:B,ch:"control",type:"http_data",reqId:i,data:Buffer.from(la).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 Qr(){if(bn||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 f=null;try{f=await s?.()||null}catch{f=null}C({v:B,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:re,installKind:E,...typeof _=="function"?{updatePolicy:_()}:_?{updatePolicy:_}:{},providers:Ii(),...f?{agents:f}:{},mcp:sn(),...Sn?{restart:Sn}:{}})}),J.on("message",f=>{$e=Date.now();let i;try{i=JSON.parse(f)}catch{return}if(i.ch==="ctl"&&i.type==="hello_ok"){En.clear(),Z=!0,ct=Ai,lt=null,Sn=null,Fo(),T.log(`[plane-link] connected to plane as ${n}`);try{Mt?.()}catch{}if(typeof i.hashKey=="string"&&i.hashKey)try{d?.(i.hashKey)}catch{}try{w?.(typeof i.viewBase=="string"&&i.viewBase?i.viewBase:null)}catch{}i.minNodeVersion&&re&&Qe(re,i.minNodeVersion)&&T.error(`[plane-link] this node is bostrat-node ${re}; the plane asks for \u2265${i.minNodeVersion} \u2014 update with: ${Rt(E)}`);try{b?.(typeof i.updatePolicy=="string"?i.updatePolicy:null)}catch{}Cr(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"),te=!1,xe=0,we=an,ae&&clearInterval(ae),$e=Date.now(),ae=setInterval(()=>{Qi(c)||(C({v:B,ch:"ctl",type:"ping"}),Vr(),ra().catch(()=>{}),An(),ne.length&&!W&&Bt())},ot),ae.unref?.(),oa(),Dt=!0,sa().catch(g=>T.error("[plane-link] backfill failed:",g?.message||g));return}if(i.ch==="ctl"&&i.type==="hello_refused"){let u=typeof i.minNodeVersion=="string"?i.minNodeVersion:null,g=typeof i.latestNodeVersion=="string"?i.latestNodeVersion:null;T.error(`[plane-link] plane REFUSED this node: bostrat-node ${re??"?"} is below its minimum ${u??"?"} \u2014 ${i.fix||Rt(E)}`),ct=Ei,lt=0;try{k?.({current:re,min:u,latest:g,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}),Tn({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"){Cr(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{M?.(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"){qs(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"){hi(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"){vi(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"){$i(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 g of Array.isArray(u)?u:[])g?.stale&&g.id&&await Jr(g.id,g.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 g of Array.isArray(u)?u:[])g?.stale&&g.id&&await Jr(g.id,g.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)){vn(i.ids);return}if(i.ch==="events"&&i.type==="nack"&&Array.isArray(i.ids)){kn(i.ids,i.reason,i.permanent===!0,i.retryAfterMs??null);return}if(i.ch==="control"&&i.type==="http_open"){ia(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(qi+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: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 g=()=>{Te.delete(i.streamId),_e.delete(i.streamId)&&C({v:B,ch:"attach",type:"close",streamId:i.streamId})};u.on("close",g),u.on("error",g);return}if(i.ch==="attach"&&i.type==="data"){let u=_e.get(i.streamId);if(!u)return;let g=Buffer.from(i.data,"base64"),$=i.bin===!0,A=Te.get(i.streamId);A?A.push({buf:g,bin:$}):u.send(g,{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 p=()=>{Z&&T.log("[plane-link] disconnected from plane"),Z=!1,ae&&(clearInterval(ae),ae=null),ce&&(clearInterval(ce),ce=null),j.clear(),ee={},ne=[],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(),bn||Be)return;lt==null&&(lt=Date.now());let f=Date.now()-lt<eu,i=Math.max(f?tu+Math.random()*nu:ct,it-Date.now(),_t());Be=setTimeout(()=>{Be=null,Qr()},i),Be.unref?.(),f||(ct=Math.min(ct*2,Ei))};J.on("close",p),J.on("error",f=>{let i=/Unexpected server response: (\d+)/.exec(f?.message||"")?.[1];if(i==="410"){Tn({reason:"removed",via:"410"});return}if(i==="401"||i==="403"){let{tripped:u,holdMs:g}=Xt();u?T.error(`[plane-link] holding every plane call for ${Math.round(g/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(g/6e4)} min.`):Date.now()-jt>=Ni&&(jt=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)`))}p()})}xt.on("event",Zr),Yi().then(Qr);function eo({bye:c=!0}={}){bn=!0,xt.off("event",Zr),Xi(),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:()=>eo(),setRefreshFlow:c=>C({v:B,ch:"ctl",type:"refresh_flow_set",patch:c}),status:()=>({connected:Z,nodeId:n,cursor:{...se},backfillHeld:Dt,inflight:j.size,...qr(),auth:Uo(),dormant:ut,removed:er(),deadLinkMs:P,deadLinkRedials:Hr,refused:{...Pt}}),_tick:()=>{Vr(),An()}}}var re,Sr,Tr,B,Ai,Ei,eu,tu,nu,an,ru,ou,su,iu,xr,au,yr,cu,lu,uu,Oi,du,Ri,pu,br,fu,hu,Ni,$r=R(()=>{Qt();Ys();mi();ki();Nn();tr();re=(()=>{try{return Ql(import.meta.url)("../package.json").version||null}catch{return null}})(),Sr=process.env.BOSTRAT_STATE_DIR||K.join(process.env.HOME||cn.tmpdir(),".bostrat"),Tr=K.join(Sr,"plane-link","removed.json");B=1,Ai=1e3,Ei=3e4,eu=6e4,tu=1500,nu=500,an=100,ru=2e3,ou=25e3,su=2.5,iu=6e4,xr=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},au=xr(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),yr="refused:",cu={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"},lu=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},uu=3e4,Oi=10*6e4,du=400,Ri=250,pu=xr(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),br=4,fu=Math.max(1,Math.round(xr(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),hu=6e4,Ni=6e4});var Di=R(()=>{Jn()});var Hi={};On(Hi,{ACTIONABLE_KINDS:()=>fn,INSTALL_ATTEMPTS:()=>ln,INSTALL_RETRY_STEP_S:()=>ji,REGISTRY_RETRY_ATTEMPTS:()=>Ar,REGISTRY_WAIT_POLLS:()=>vr,REGISTRY_WAIT_STEP_S:()=>kr,RESTART_SIGNAL:()=>Bi,SELF_UPDATE_DIR:()=>dn,SUPERVISOR_PID_FILE:()=>Ci,createAutoUpdater:()=>Ru,inFlight:()=>Nr,readStatus:()=>Rr,restartCommand:()=>Li,restartStrategy:()=>Or,selfUpdatePlan:()=>Fi,settleSelfUpdate:()=>Ou,startSelfUpdate:()=>Ui,underService:()=>Er,updatePolicy:()=>xu});import Nt from"node:fs";import be from"node:fs/promises";import wu from"node:os";import U from"node:path";import{spawn as gu,execFileSync as yu}from"node:child_process";import{createRequire as bu}from"node:module";function xu({kind:e=et(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:fn.has(e)?e==="git-checkout"||Er(t)?"auto":"prompt":"off"}function Er(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Or({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=Ci,readFile:s=l=>Nt.readFileSync(l,"utf8"),alive:a=$u}={}){let l=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(Er(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 $u(e){try{process.kill(e,0)}catch{return!1}try{let t=yu("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 Li(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 -${Bi.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function Fi({kind:e,to:t,from:n=un,statusFile:r=pn,logFile:o=U.join(dn,"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=Or({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:w=Date.now(),attempts:v=1}={}){if(!fn.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=Li(m),M=`
136
+ `),s+=l);return s}async function Bl(e){try{return await ye.readFile(e,"utf8")}catch(t){if(t?.code==="ENOENT")return null;throw t}}async function mr(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 Ll(e,t,n,r){let o={},s=e==="claude"?Po():e==="codex"?Do():Ml(),a=S=>{for(let N of t.keys())o[N]=S};if(e!=="claude"&&!Ol.existsSync(Xe.dirname(s)))return a("cli-absent"),{managed:[],states:o};let l;try{l=await Bl(s)}catch{return a("error"),{managed:n,states:o}}let h=new Set(n);if(e==="codex"){let S=si(l??""),N=new Map;for(let[x,I]of t)S.has(x)&&!h.has(x)?o[x]="conflict":N.set(x,jl(I,r));let k=new Set([...h].filter(x=>!t.has(x))),_=Cl(l??"",N,k);try{_!==(l??"")&&await mr(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=si(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]=Dl(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 mr(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:{},M=new Set(g.filter(S=>JSON.stringify(b[S]??null)!==JSON.stringify(d[S])));return{managed:g.sort(),states:o,wrote:M}}async function Fl(){let e=Nl(),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={...Qs(),...t},o={};for(let s of Object.keys(r))o[s]=s in t?"file":"broker";return{values:r,sources:o}}function Ul(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 Hl(e,t,n,r,o){let s={},a=Ul(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 fi(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 ii(){let{values:e,sources:t}=await Fl(),n=ei(),r=ti(),o=fi(de.entries),s={};for(let d of o){let g=Hl(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={...de.managed},l={...de.since||{}},h=Date.now();for(let d of pr){let g=new Map(o.filter(b=>(b.clis||pr).includes(d)&&!s[b.name].missingEnv.length).map(b=>[b.name,b])),v=await Ll(d,g,de.managed?.[d]??[],e);a[d]=v.managed;let y={...l[d]||{}};for(let[b,M]of Object.entries(v.states)){s[b].clis[d]=M;let S=s[b].rev;M==="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||pr)s[d.name].clis[y]=v}de={...de,managed:a,since:l},await Wl();let m=JSON.stringify(s)!==JSON.stringify(fr);if(fr=s,m)for(let d of hr)try{d(sn())}catch{}return sn()}async function Wl(){let e=JSON.stringify(de,null,2);if(e!==ai)try{await mr(Rl(),e),ai=e}catch(t){console.error("[mcp-config] cache write failed:",t?.message||t)}}function Kl(){let e=ri.then(ii,ii);return ri=e.catch(()=>{}),e}function hi(e,{updatedAt:t=Date.now()}={}){return de={...de,entries:fi(e),updatedAt:t},Kl()}var li,Rl,Nl,Ml,pr,Il,Pl,de,fr,ri,hr,Ye,Et,oi,ai,mi=R(()=>{Gn();Vn();ni();li=()=>process.env.BOSTRAT_STATE_DIR||Xe.join(process.env.HOME||ci.tmpdir(),".bostrat"),Rl=()=>Xe.join(li(),"mcp-config.json"),Nl=()=>Xe.join(li(),"mcp-env.json"),Ml=()=>Xe.join(ci.homedir(),".cursor","mcp.json"),pr=["claude","codex","cursor"],Il=/^[a-z0-9][a-z0-9_-]{0,47}$/,Pl=/\$\{([A-Za-z_][A-Za-z0-9_]{0,63})\}/g,de={entries:[],updatedAt:null,managed:{claude:[],codex:[],cursor:[]},since:{}},fr={},ri=Promise.resolve(),hr=new Set;Ye=(e,t)=>String(e).replace(Pl,(n,r)=>t[r]??"");Et=e=>JSON.stringify(String(e)),oi=e=>`{ ${Object.entries(e).map(([t,n])=>`${Et(t)} = ${Et(n)}`).join(", ")} }`;ai=null});import gi from"node:fs/promises";import bi from"node:path";import Gl from"node:os";function Vl(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 gr))throw new Error(`unknown refresh-flow field "${n}" \u2014 fields: ${_i.join(", ")}`);if(r===null||r===""||r===void 0){t[n]=null;continue}switch(n){case"contextFull":case"limitHit":if(typeof r!="string"||!wi.includes(r))throw new Error(`${n} must be one of ${wi.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(!yi.test(s))throw new Error(`bad provider key "${s}" in fallback`);if(!Array.isArray(a)||a.some(h=>typeof h!="string"||!yi.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 ql(e){let t={...gr};for(let n of _i){let r=e?.[n];r!=null&&(t[n]=r)}return t}function Xl(){return ql(Je?.flow)}function Ti(){return{flow:Xl(),configured:!!Je,source:Je?.source??null,updatedAt:Je?.updatedAt??null}}async function Jl(){try{await gi.mkdir(Si,{recursive:!0}),await gi.writeFile(zl(),JSON.stringify(Je,null,2))}catch{}}function xi(e=null){for(let t of Yl)try{t(Ti(),e)}catch{}}function $i(e){xi({rejected:String(e||"rejected by the plane")})}async function vi(e,{source:t="plane",updatedAt:n=Date.now()}={}){return Je={flow:Vl(e||{}),updatedAt:n,source:t},await Jl(),xi(),Ti()}var Si,zl,wi,gr,_i,yi,Je,Yl,ki=R(()=>{Si=process.env.BOSTRAT_STATE_DIR||bi.join(process.env.HOME||Gl.tmpdir(),".bostrat"),zl=()=>bi.join(Si,"refresh-flow.json"),wi=["prompt","auto","off"],gr=Object.freeze({contextFull:"prompt",contextFullPct:75,contextFullTokens:null,limitHit:"prompt",fallback:null}),_i=Object.keys(gr),yi=/^[a-z][a-z0-9-]{0,31}$/;Je=null,Yl=new Set});var Pi={};On(Pi,{REMOVED_MARKER:()=>Tr,detectInstallKind:()=>et,detectProviderAuth:()=>Ii,maskToken:()=>_r,readRemovedMarker:()=>Mi,startPlaneLink:()=>mu,updateCommandFor:()=>Rt,versionLt:()=>Qe});import Ze from"node:fs";import Ot from"node:fs/promises";import Zl from"node:http";import K from"node:path";import cn from"node:os";import{createRequire as Ql}from"node:module";import wr from"ws";function _r(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function Mi(e=Tr){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 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||cn.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 mu({url:e,token:t,nodeId:n=cn.hostname(),name:r=cn.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=hu,onUpdateAvailable:y=null,onUpdatePolicy:b=null,onConflictProbe:M=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:I=Tr,onRemoved:Me=null,onDegraded:rt=null,onRecovered:Ie=null,onRefused:mn=null,onConnected:Mt=null,ingestMode:Pe=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:De=au,unackedRetryMs:je=iu,pingMs:ot=ou,deadLinkMs:P=Math.round(ot*su),maxInflightEvents:pe=du,httpTimeoutMs:fe=pu,fanoutActive:he=null,fanoutBatchCap:st=fu,stallBackoffMinMs:Pr=uu,fetchImpl:Dr=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 qi=O.replace(/^http/,"ws"),jr=new Set,Cr=c=>{let p=typeof c.latestNodeVersion=="string"?c.latestNodeVersion:null;if(!(!(p&&re&&Qe(re,p))||jr.has(p))){jr.add(p),T.log(`[plane-link] bostrat-node ${p} is available (this node runs ${re}) \u2014 ${Rt(E)}`);try{y?.({current:re,latest:p,min:c.minNodeVersion??null,installKind:E,required:!!(c.minNodeVersion&&Qe(re,c.minNodeVersion))})}catch(f){T.error(`[plane-link] update notice failed: ${f?.message||f}`)}}},_e=new Map,Te=new Map,gn=K.join(Sr,"plane-link","cursor.json"),wn=K.join(Sr,"plane-link","dead-letter.ndjson"),Br=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),se={},ee={},j=new Map,It=null,me=null,ie=0,it=0,Lr=0,Pt={},Fr=new Set,Ur=Promise.resolve(),H="ws",Ce=0,te=!1,xe=0,yn=!1,ge=an,at=new Set,ne=[],W=null,J=null,Z=!1,Dt=!1,bn=!1,ct=Ai,lt=null,Sn=S&&typeof S=="object"?S:null,Be=null,Le=null,ae=null,$e=0,Hr=0,ce=null,_n=!1,jt=0,ut=!1,we=Mi(I);if(we)if(we.tokenPreview===_r(t))ut=!0,Qn({reason:we.reason??"removed",at:we.at??null,nodeId:we.nodeId??n}),T.error(`[plane-link] this node was REMOVED from the plane (${we.reason??"removed"}${we.at?` at ${new Date(we.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${I} to force a dial.`);else try{Ze.unlinkSync(I),T.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function Tn({reason:c="removed",at:p=Date.now(),via:f="ctl"}={}){if(!ut){ut=!0,Qn({reason:c,at:p,nodeId:n,via:f});try{Ze.mkdirSync(K.dirname(I),{recursive:!0}),Ze.writeFileSync(I,JSON.stringify({at:p,reason:c,via:f,nodeId:n,tokenPreview:_r(t)},null,2))}catch(i){T.error(`[plane-link] could not write ${I}: ${i?.message||i}`)}T.error(`[plane-link] the plane REMOVED this node (${c}, via ${f}) \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{Me?.({reason:c,at:p,via:f})}catch{}eo({bye:!1})}}async function Yi(){try{se=JSON.parse(await Ot.readFile(gn,"utf8"))}catch{se={}}}function Wr(){_n=!0,!Le&&(Le=setTimeout(async()=>{if(Le=null,!!_n){_n=!1;try{await Ot.mkdir(K.dirname(gn),{recursive:!0}),await Ot.writeFile(gn,JSON.stringify(se))}catch(c){T.error("[plane-link] cursor flush failed:",c?.message||c)}}},ru),Le.unref?.())}function xn(){try{return!!he?.()}catch{return!1}}function $n(){let c=H==="http"?ge:an;return xn()?Math.min(c,st):c}function C(c){return!J||J.readyState!==wr.OPEN?!1:(J.send(JSON.stringify(c)),!0)}let Xi=ui(c=>C({v:B,ch:"ctl",type:"mcp_status",mcp:c}));function Fe(c){let p=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:p,firstSentAt:w?.firstSentAt??p,retryAt:p+je,tries:(w?.tries??0)+1,nacks:w?.nacks??0})}let f=c.map(({trackId:i,event:u})=>({trackId:i,event:lu(u)}));return H==="http"?(na(f),!0):C({v:B,ch:"events",type:"append",events:f})}function Kr(c,p=Date.now()){if(at.has(c))return!0;for(let f of j.values())if(f.trackId===c&&p-f.firstSentAt<De)return!0;return!1}function Ji(c){let p=null;for(let f of j.values())f.trackId===c&&(p==null||f.seq<p)&&(p=f.seq);return p}function Ct(c){if(Dt)return;let p=ee[c];if(p==null)return;let f=Ji(c),i=f==null?p:Math.min(p,f-1);i>(se[c]??0)&&(se[c]=i,Wr())}function dt(){if(It=Date.now(),me!=null){let c=Date.now()-me;T.log(`[plane-link] spine sync recovered after ${Math.round(c/1e3)}s degraded (${ie} stall redial(s))`);let p=me;me=null,ie=0,it=0,te=!1,xe=0;try{Ie?.({since:p,downMs:c})}catch(f){T.error(`[plane-link] onRecovered failed: ${f?.message||f}`)}}}function vn(c){if(!Array.isArray(c)||!c.length)return;let p=new Set;for(let f of c){let i=j.get(f);i&&(j.delete(f),(ee[i.trackId]??0)<i.seq&&(ee[i.trackId]=i.seq),p.add(i.trackId))}for(let f of p)Ct(f);dt()}function Gr(c,p){Lr++;let f={at:Date.now(),trackId:c.trackId,seq:c.seq,id:c.event?.id??null,type:c.event?.type??null,reason:p,event:c.event??null};T.error(`[plane-link] DEAD-LETTER ${c.trackId} seq ${c.seq} (${f.type??"?"}): plane rejected it permanently (${p}) \u2014 kept in ${wn}`),Ur=Ur.then(async()=>{await Ot.mkdir(K.dirname(wn),{recursive:!0}),await Ot.appendFile(wn,JSON.stringify(f)+`
137
+ `)}).catch(i=>T.error(`[plane-link] dead-letter write failed: ${i?.message||i}`))}function Zi(c,p){if(Pt[c]=(Pt[c]??0)+1,Fr.has(c))return;Fr.add(c);let f=cu[c]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";T.error(`[plane-link] REFUSED by the plane (${c}) on track ${p}: events are being dropped, not stored \u2014 ${f}`);try{mn?.({reason:c,trackId:p,count:Pt[c],hint:f})}catch(i){T.error(`[plane-link] onRefused failed: ${i?.message||i}`)}}function kn(c,p,f,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&&(f?(j.delete($),Gr(A,p),String(p).startsWith(yr)&&Zi(String(p).slice(yr.length),A.trackId),(ee[A.trackId]??0)<A.seq&&(ee[A.trackId]=A.seq),u.add(A.trackId)):(A.nacks++,A.retryAt=w+Math.max(1e3,Number(i)||je)))}for(let $ of u)Ct($);dt()}function zr(c=Date.now()){let p=1/0;for(let f of j.values())f.firstSentAt<p&&(p=f.firstSentAt);return p===1/0?0:c-p}function Qi(c){if(!P||!c||c!==J||!$e)return!1;let p=Date.now()-$e;if(p<=P)return!1;Hr++,T.error(`[plane-link] no frame from the plane for ${Math.round(p/1e3)}s \u2014 link is half-open; terminating and redialing`);try{c.terminate()}catch{}return!0}function Vr(){if(!Z||!j.size)return;let c=Date.now(),p=zr(c);if(p<De||It!=null&&c-It<De||H==="http"&&te||it>c)return;ie++;let f=Math.min(Pr*2**(ie-1),Oi);if(me==null){me=c-p,T.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(p/1e3)}s with ${j.size} event(s) in flight (${H} door) \u2014 the plane is not answering appends`);try{rt?.({since:me,unacked:j.size,oldestAgeMs:p,mode:H})}catch(i){T.error(`[plane-link] onDegraded failed: ${i?.message||i}`)}}if(H==="http"){te=!0,xe=c+f,T.error(`[plane-link] ingest circuit OPEN (stall #${ie}); probing /v1/ingest/health in ${Math.round(f/1e3)}s`);return}it=c+f,T.error(`[plane-link] closing the link and redialing in ${Math.round(f/1e3)}s (stall redial #${ie})`);try{J?.terminate()}catch{}}function An(){if(!Z)return;let c=Date.now();if(H==="http"&&te)return;let p=[...j.values()].filter(i=>i.event&&i.retryAt<=c&&!(H==="http"&&at.has(i.trackId)));if(!p.length)return;p.sort((i,u)=>i.trackId===u.trackId?i.seq-u.seq:i.trackId<u.trackId?-1:1),T.log(`[plane-link] re-sending ${p.length} unacked event(s) the plane never confirmed`);let f=$n();if(H==="http"){let i=new Map;for(let u of p)(i.get(u.trackId)??i.set(u.trackId,[]).get(u.trackId)).push(u);for(let[,u]of i){if(Ce>=br)return;Fe(u.slice(0,f).map(w=>({trackId:w.trackId,event:w.event})))}return}for(let i=0;i<p.length;i+=f){let u=p.slice(i,i+f).map(w=>({trackId:w.trackId,event:w.event}));if(!Fe(u))return}}async function ea(c=null){for(;;){if(!Z)return!1;let p=j.size<pe,f=H!=="http"||Ce<br&&!te&&(!c||!Kr(c));if(p&&f)return!0;await new Promise(i=>setTimeout(i,100))}}function Bt(){if(W=null,!Z||!ne.length)return;let c=ne;ne=[];let p=$n();if(H!=="http"){for(let u=0;u<c.length;u+=p)Fe(c.slice(u,u+p));return}let f=xn(),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(Kr(u)||Ce>=br||te){ne.push(...w);continue}if(f){Fe(w.slice(0,p)),ne.push(...w.slice(p));continue}for(let $=0;$<w.length;$+=p)Fe(w.slice($,$+p))}ne.length&&!W&&(W=setTimeout(Bt,Ri),W.unref?.())}let ta=c=>{let p=new Map;for(let{trackId:f,event:i}of c)(p.get(f)??p.set(f,[]).get(f)).push(i);return[...p].map(([f,i])=>({trackId:f,events:i}))},ve=(c,p,f,{progress:i})=>{let u=Date.now();for(let{event:w}of c){let $=j.get(w.id);$&&($.nacks++,$.retryAt=u+Math.max(1e3,f||je))}i&&dt()};async function na(c){let p=new Set(c.map(f=>f.trackId));for(let f of p)at.add(f);Ce++;try{let f=await Dr(`${Br}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:ta(c)}),signal:AbortSignal.timeout(fe)}),i=(Number(f.headers.get("retry-after"))||0)*1e3;if(f.status===200){let u=await f.json();ge=an;for(let A of u.results??[]){vn(A.acked??[]);let F=(oe,V)=>{let Lt=new Map;for(let ke of oe??[])(Lt.get(ke.reason)??Lt.set(ke.reason,[]).get(ke.reason)).push(ke.id);for(let[ke,to]of Lt)kn(to,ke,V,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 $)kn(F,`${yr}${A}`,!0);vn((u.discarded??[]).filter(A=>!w.has(A))),dt();return}if(f.status===429){ve(c,"overloaded",i||5e3,{progress:!0});return}if(f.status===413&&c.length>1){ge=Math.max(1,Math.floor(c.length/2)),T.error(`[plane-link] ingest request too large (${c.length} events) \u2014 halving batches to ${ge}`),ve(c,"too_large",1e3,{progress:!0});return}if(f.status===413){let u=j.get(c[0].event.id);u&&(j.delete(u.event.id),Gr(u,"too_large"),(ee[u.trackId]??0)<u.seq&&(ee[u.trackId]=u.seq),Ct(u.trackId)),dt();return}if(f.status===410){Tn({reason:"removed",via:"410"}),ve(c,"http_410",6e4,{progress:!1});return}if(f.status===401||f.status===403){let{tripped:u,holdMs:w}=Xt();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()-jt>=Ni){jt=Date.now();let $="";try{$=(await f.json())?.error??""}catch{}T.error(`[plane-link] plane refused ingest (HTTP ${f.status}${$?`: ${$}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}ve(c,`http_${f.status}`,Math.max(6e4,_t()),{progress:!1});return}if(f.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_${f.status}`,i||5e3,{progress:!1})}catch(f){let i=f?.name==="TimeoutError"||f?.name==="AbortError";i&&c.length>1&&(ge=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 ${ge}`)),ve(c,i?"timeout":"network",5e3,{progress:!1})}finally{Ce--;for(let f of p)at.delete(f);ne.length&&!W&&(W=setTimeout(Bt,0),W.unref?.())}}async function ra(){if(H!=="http"||!te||!Z||yn)return;let c=Date.now();if(!(xe>c||Jt(c))){yn=!0;try{let p=await Dr(`${Br}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(fe)});if(!p.ok)throw new Error(`HTTP ${p.status}`);T.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),te=!1,xe=0,it=Date.now()+fe+je+1e3;for(let f of j.values())f.retryAt=Math.min(f.retryAt,Date.now());An()}catch(p){ie++;let f=Math.min(Pr*2**(ie-1),Oi);xe=Date.now()+f,T.error(`[plane-link] ingest door still not answering (${p?.message||p}); next probe in ${Math.round(f/1e3)}s`)}finally{yn=!1}}}function qr(){let c=Date.now();return{mode:H,unacked:j.size,oldestUnackedAgeMs:zr(c),lastProgressAt:It,degradedSince:me,stallRedials:ie,deadLettered:Lr,fanoutCap:xn()?st:null,http:H==="http"?{inFlight:Ce,circuitOpen:te,nextProbeInMs:te?Math.max(0,xe-c):0,batchCap:ge,heldLive:ne.length}:null}}async function Yr(){if(!h)return;let c;try{c=await h()}catch(f){T.error("[plane-link] metrics sample failed:",f?.message||f);return}let p=null;try{p=m?.()??null}catch{}c&&C({v:B,ch:"ctl",type:"metrics",metrics:{...c,planeLink:qr(),...p?{delivery:p}:{}}})}function oa(){h&&(ce&&clearInterval(ce),Yr(),ce=setInterval(Yr,v),ce.unref?.())}async function sa(){let c;try{c=await o()}catch(p){T.error("[plane-link] backfill listTracks failed:",p?.message||p);return}C({v:B,ch:"ctl",type:"tracks",ids:c.filter(p=>!p.transferredTo).map(p=>p.id).filter(p=>typeof p=="string")});for(let p of c)if(!Z||!await Xr(p))return;Dt=!1;for(let p of Object.keys(ee))Ct(p)}async function Xr(c){let p;try{p=await Zt(c)}catch{return!0}let f=se[c.id]??0,i=p.filter(u=>u.seq>f&&typeof u.id=="string");for(let u=0;u<i.length;){if(!await ea(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 En=new Map;async function Jr(c,p){if(En.get(c)===p)return!1;En.set(c,p);let f=null;try{f=(await o()).find($=>$?.id===c)??null}catch{return!1}if(!f)return!1;let i;try{i=await Zt(f)}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,Wr()),(ee[c]??0)>w&&(ee[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?Xr(f):!1}function Zr(c){!Z||!c?.trackId||typeof c.id!="string"||(ne.push({trackId:c.trackId,event:c}),W||(W=setTimeout(Bt,Ri),W.unref?.()))}let pt=new Map;async function ia(c){let{reqId:p,method:f,path:i,headers:u={},body:w}=c,$=Object.fromEntries(Object.entries(u).filter(([,F])=>F!=null)),A=new AbortController;pt.set(p,A);try{if(c.host){await aa(c,$,A);return}x&&($["x-bostrat-token"]=x);let F=await fetch(O+i,{method:f,headers:$,body:w?Buffer.from(w,"base64"):void 0,signal:A.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:p,status:F.status,headers:oe}),F.body){for await(let V of F.body)if(!C({v:B,ch:"control",type:"http_data",reqId:p,data:Buffer.from(V).toString("base64")}))break}C({v:B,ch:"control",type:"http_end",reqId:p,error:null})}finally{pt.delete(p)}}function aa(c,p,f){let{reqId:i,method:u,path:w,body:$}=c,A=new URL(O);return new Promise(F=>{let oe=Zl.request({host:A.hostname,port:A.port,method:u,path:w,headers:{...p,host:c.host},signal:f.signal},V=>{let{connection:Lt,"keep-alive":ke,"transfer-encoding":to,upgrade:fd,...ca}=V.headers;C({v:B,ch:"control",type:"http_head",reqId:i,status:V.statusCode||502,headers:ca}),V.on("data",la=>{C({v:B,ch:"control",type:"http_data",reqId:i,data:Buffer.from(la).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 Qr(){if(bn||ut)return;J=new wr(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 f=null;try{f=await s?.()||null}catch{f=null}C({v:B,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:re,installKind:E,...typeof _=="function"?{updatePolicy:_()}:_?{updatePolicy:_}:{},providers:Ii(),...f?{agents:f}:{},mcp:sn(),...Sn?{restart:Sn}:{}})}),J.on("message",f=>{$e=Date.now();let i;try{i=JSON.parse(f)}catch{return}if(i.ch==="ctl"&&i.type==="hello_ok"){En.clear(),Z=!0,ct=Ai,lt=null,Sn=null,Fo(),T.log(`[plane-link] connected to plane as ${n}`);try{Mt?.()}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&&re&&Qe(re,i.minNodeVersion)&&T.error(`[plane-link] this node is bostrat-node ${re}; the plane asks for \u2265${i.minNodeVersion} \u2014 update with: ${Rt(E)}`);try{b?.(typeof i.updatePolicy=="string"?i.updatePolicy:null)}catch{}Cr(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"),te=!1,xe=0,ge=an,ae&&clearInterval(ae),$e=Date.now(),ae=setInterval(()=>{Qi(c)||(C({v:B,ch:"ctl",type:"ping"}),Vr(),ra().catch(()=>{}),An(),ne.length&&!W&&Bt())},ot),ae.unref?.(),oa(),Dt=!0,sa().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 ${re??"?"} is below its minimum ${u??"?"} \u2014 ${i.fix||Rt(E)}`),ct=Ei,lt=0;try{k?.({current:re,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}),Tn({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"){Cr(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{M?.(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"){qs(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"){hi(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"){vi(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"){$i(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 Jr(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 Jr(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)){vn(i.ids);return}if(i.ch==="events"&&i.type==="nack"&&Array.isArray(i.ids)){kn(i.ids,i.reason,i.permanent===!0,i.retryAfterMs??null);return}if(i.ch==="control"&&i.type==="http_open"){ia(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 wr(qi+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: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=()=>{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,A=Te.get(i.streamId);A?A.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 p=()=>{Z&&T.log("[plane-link] disconnected from plane"),Z=!1,ae&&(clearInterval(ae),ae=null),ce&&(clearInterval(ce),ce=null),j.clear(),ee={},ne=[],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(),bn||Be)return;lt==null&&(lt=Date.now());let f=Date.now()-lt<eu,i=Math.max(f?tu+Math.random()*nu:ct,it-Date.now(),_t());Be=setTimeout(()=>{Be=null,Qr()},i),Be.unref?.(),f||(ct=Math.min(ct*2,Ei))};J.on("close",p),J.on("error",f=>{let i=/Unexpected server response: (\d+)/.exec(f?.message||"")?.[1];if(i==="410"){Tn({reason:"removed",via:"410"});return}if(i==="401"||i==="403"){let{tripped:u,holdMs:w}=Xt();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()-jt>=Ni&&(jt=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)`))}p()})}xt.on("event",Zr),Yi().then(Qr);function eo({bye:c=!0}={}){bn=!0,xt.off("event",Zr),Xi(),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:()=>eo(),setRefreshFlow:c=>C({v:B,ch:"ctl",type:"refresh_flow_set",patch:c}),status:()=>({connected:Z,nodeId:n,cursor:{...se},backfillHeld:Dt,inflight:j.size,...qr(),auth:Uo(),dormant:ut,removed:er(),deadLinkMs:P,deadLinkRedials:Hr,refused:{...Pt}}),_tick:()=>{Vr(),An()}}}var re,Sr,Tr,B,Ai,Ei,eu,tu,nu,an,ru,ou,su,iu,xr,au,yr,cu,lu,uu,Oi,du,Ri,pu,br,fu,hu,Ni,$r=R(()=>{Qt();Ys();mi();ki();Nn();tr();re=(()=>{try{return Ql(import.meta.url)("../package.json").version||null}catch{return null}})(),Sr=process.env.BOSTRAT_STATE_DIR||K.join(process.env.HOME||cn.tmpdir(),".bostrat"),Tr=K.join(Sr,"plane-link","removed.json");B=1,Ai=1e3,Ei=3e4,eu=6e4,tu=1500,nu=500,an=100,ru=2e3,ou=25e3,su=2.5,iu=6e4,xr=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},au=xr(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),yr="refused:",cu={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"},lu=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},uu=3e4,Oi=10*6e4,du=400,Ri=250,pu=xr(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),br=4,fu=Math.max(1,Math.round(xr(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),hu=6e4,Ni=6e4});var Di=R(()=>{Jn()});var Hi={};On(Hi,{ACTIONABLE_KINDS:()=>fn,INSTALL_ATTEMPTS:()=>ln,INSTALL_RETRY_STEP_S:()=>ji,REGISTRY_RETRY_ATTEMPTS:()=>Ar,REGISTRY_WAIT_POLLS:()=>vr,REGISTRY_WAIT_STEP_S:()=>kr,RESTART_SIGNAL:()=>Bi,SELF_UPDATE_DIR:()=>dn,SUPERVISOR_PID_FILE:()=>Ci,createAutoUpdater:()=>Ru,inFlight:()=>Nr,readStatus:()=>Rr,restartCommand:()=>Li,restartStrategy:()=>Or,selfUpdatePlan:()=>Fi,settleSelfUpdate:()=>Ou,startSelfUpdate:()=>Ui,underService:()=>Er,updatePolicy:()=>xu});import Nt from"node:fs";import be from"node:fs/promises";import gu from"node:os";import U from"node:path";import{spawn as wu,execFileSync as yu}from"node:child_process";import{createRequire as bu}from"node:module";function xu({kind:e=et(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:fn.has(e)?e==="git-checkout"||Er(t)?"auto":"prompt":"off"}function Er(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Or({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=Ci,readFile:s=l=>Nt.readFileSync(l,"utf8"),alive:a=$u}={}){let l=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(Er(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 $u(e){try{process.kill(e,0)}catch{return!1}try{let t=yu("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 Li(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 -${Bi.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function Fi({kind:e,to:t,from:n=un,statusFile:r=pn,logFile:o=U.join(dn,"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=Or({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(!fn.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=Li(m),M=`
138
138
  health() {
139
139
  for i in $(seq 1 45); do
140
140
  sleep 1
@@ -148,7 +148,7 @@ set -u
148
148
  FROM=${Q(n??"")}
149
149
  TO=${Q(t)}
150
150
  STATUS_FILE=${Q(r)}
151
- STARTED_AT=${Number(w)}
151
+ STARTED_AT=${Number(g)}
152
152
  ATTEMPTS=${Number(v)||1}
153
153
  write_status() { # <status> [error] [retryable]
154
154
  local err="\${2:-}"
@@ -218,28 +218,28 @@ 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 Rr(e=pn){try{return JSON.parse(await be.readFile(e,"utf8"))}catch{return null}}async function Ui({to:e,from:t=un,kind:n=et(),reason:r="manual",force:o=!1,statusFile:s=pn,spawnImpl:a=gu,now:l=Date.now,npmPrefix:h=void 0,log:m=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!fn.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 Rr(s);if(Nr(d))return{ok:!1,reason:`an update to ${d.to} is already in flight`,status:d};let w=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&&w<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")?w+1:1;await be.mkdir(U.dirname(s),{recursive:!0});let y=h!==void 0?h:n==="npm-global"?Xn(await ku())||U.resolve(U.dirname(process.execPath),".."):null,b=Or(),M=Fi({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,M,{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 k=Nt.existsSync("/run/systemd/system")&&await Au("systemd-run"),_=k?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",S]]:["bash",[S]],E=async x=>{let I=`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:I})).catch(()=>{}),m.error?.(`[self-update] ${I}`),I},O=null;try{k||(O=Nt.openSync(N,"a"));let x=a(_[0],_[1],{detached:!0,stdio:k?"ignore":["ignore",O,O]});x.on?.("error",I=>{E(I)}),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 ku(){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 Ou({statusFile:e=pn,current:t=un,now:n=Date.now,staleMs:r=Eu}={}){let o=await Rr(e);if(!o)return null;let s=a=>be.writeFile(e,JSON.stringify(a)).catch(()=>{});if(Nr(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 Ru({isBusy:e,start:t=Ui,onStuck:n=null,onStarted:r=null,tickMs:o=Tu,stuckMs:s=_u,now:a=Date.now,setIntervalImpl:l=setInterval,clearIntervalImpl:h=clearInterval,log:m=console}={}){let d=null,w=()=>{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;w();let M=await t({to:b.to,from:b.from,kind:b.kind,reason:"auto"});m.log?.(`[self-update] stasis reached \u2192 ${M.ok?"started":`not started: ${M.reason}`}`);try{await r?.({...b,result:M})}catch{}};return{arm({to:y,from:b=un,kind:M=et()}){return d?.to===y?!1:(w(),d={to:y,from:b,kind:M,since:a(),stuckFired:!1,timer:l(v,o)},d.timer.unref?.(),!0)},tick:v,cancel:w,get armed(){return d?{to:d.to,from:d.from,kind:d.kind,since:d.since}:null}}}var un,Su,dn,pn,_u,Tu,vr,kr,Ar,ln,ji,Ci,Bi,fn,Q,vu,Nr,Eu,Wi=R(()=>{$r();Di();un=(()=>{try{return bu(import.meta.url)("../package.json").version||null}catch{return null}})(),Su=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||wu.tmpdir(),".bostrat"),dn=U.join(Su,"self-update"),pn=U.join(dn,"status.json"),_u=1440*6e4,Tu=6e4,vr=60,kr=15,Ar=3,ln=6,ji=20,Ci=U.join(dn,"supervisor.pid"),Bi="SIGUSR2",fn=new Set(["npm-global","git-checkout"]);Q=e=>`'${String(e).replace(/'/g,"'\\''")}'`;vu=new Set(["updating","restarting","rolling-back"]),Nr=e=>!!(e&&vu.has(e.status));Eu=45*6e4});Nn();Yn();or();import G from"node:fs";import L from"node:path";import nt from"node:os";import{createRequire as Mr}from"node:module";import{execFile as Nu,spawn as Mu}from"node:child_process";import{promisify as Iu}from"node:util";import Pu from"node:readline/promises";import{randomUUID as Du}from"node:crypto";import{fileURLToPath as ju}from"node:url";import nn from"node:fs";import Ve from"node:fs/promises";import qc from"node:os";import kt from"node:path";import Yc from"node:readline";import{spawn as Xc}from"node:child_process";var Jc="^(ugrep|rg|2\\.1\\.[0-9]+|cursor-agent|codex|npm|node|MainThread)",Zc="^(bostrat-|tmux|earlyoom|systemd|sshd)",Qc=()=>["-m","10","-s","70","-r","600","--prefer",Jc,"--avoid",Zc],us="BOSTRAT_OOM_GUARD_OWNER",el=6e4,tl=5e3;function ds(e=process.env){return!["0","off","false","no"].includes(String(e.BOSTRAT_OOM_GUARD??"").trim().toLowerCase())}function ps(e=process.env){let t=e.BOSTRAT_STATE_DIR||kt.join(e.HOME||qc.tmpdir(),".bostrat");return kt.join(t,"oom-guard.pid")}function fs(e=process.env){if(e.BOSTRAT_EARLYOOM_BIN)return nn.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=kt.join(n,"earlyoom");if(nn.existsSync(r))return r}return null}async function hs({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(kt.join(e,r,"comm"),"utf8").catch(()=>"")).trim()==="earlyoom"&&n.push({pid:Number(r)})}return n}async function ms(e){let t=Number((await Ve.readFile(e,"utf8").catch(()=>"")).trim());return Number.isInteger(t)&&t>0?t:null}async function ws({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc"}={}){if(!ds(e))return{state:"off"};if(t!=="linux")return{state:"unsupported",platform:t};let r=await hs({procRoot:n}),o=await ms(ps(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=fs(e);return a?{state:"stopped",bin:a}:{state:"absent"}}function ar(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=Xc,checkMs:s=el,relaunchMs:a=tl}={}){let l=null,h={state:null},m=null,d=!1,w="",v=ps(e),y=k=>{h=k;let _=`[oom-guard] ${ar(k)}`;return _!==w&&r(_),w=_,k},b=k=>{d||(clearTimeout(m),m=setTimeout(()=>M().catch(()=>{}),k),m.unref?.())},M=async()=>{if(d||l)return h;if(!ds(e))return y({state:"off"});if(t!=="linux")return y({state:"unsupported",platform:t});let k=await ms(v),_=await hs({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=fs(e);if(!E)return b(s),y({state:"absent"});let O;try{O=o(E,Qc(),{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&&Yc.createInterface({input:x}).on("line",I=>r(`[earlyoom] ${I}`));return O.on("error",x=>{r(`[oom-guard] ${E}: ${x?.message||x}`),!(l!==O||O.pid)&&(l=null,b(s))}),O.on("exit",(x,I)=>{l===O&&(l=null,Ve.rm(v,{force:!0}).catch(()=>{}),!d&&(r(`[oom-guard] earlyoom exited (${I||`code ${x}`}) \u2014 relaunching in ${Math.round(a/1e3)} s`),h={state:"stopped",bin:E},w="",b(a)))}),O.pid&&(await Ve.mkdir(kt.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"),nn.rmSync(v,{force:!0}))};return process.on("exit",S),{ready:M().catch(()=>h),status:()=>h,stop(){d=!0,clearTimeout(m),process.off("exit",S);let k=l;l=null,k&&(k.kill("SIGTERM"),nn.rmSync(v,{force:!0}))}}}Cn();import nl from"node:fs";import ys from"node:path";import rl from"node:os";var ol=()=>process.env.BOSTRAT_STATE_DIR||ys.join(process.env.HOME||rl.tmpdir(),".bostrat"),sl=()=>ys.join(ol(),"plane-link","public-host.json");var At=null;function il(){if(At)return At;try{let e=JSON.parse(nl.readFileSync(sl(),"utf8"));At={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{At={viewBase:null}}return At}function al(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 bs(){return il().viewBase}function Ss(e=process.env.BOSTRAT_PUBLIC_HOST){return al(e,"https")}function _s(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 cl from"node:fs";import ll from"node:os";import Ts from"node:path";var xs=3*6e4;function cr(e=process.env){let t=e.BOSTRAT_STATE_DIR||Ts.join(e.HOME||ll.tmpdir(),".bostrat");return Ts.join(t,"heartbeat.json")}function $s(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return xs;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):xs}function vs(e=cr()){try{let t=JSON.parse(cl.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",sm=2*6e4;var ks=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Es({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:ks(e),staleS:ks(t)!=null?Math.round(t/1e3):null})}Ae();var Ki=(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(Nu),Ir=L.dirname(ju(import.meta.url)),Ne=L.resolve(Ir,".."),Cu=L.join(Ir,"index.js"),Bu="wss://plane.bostrat.ai/v1/node",tt=Mr(import.meta.url)("../package.json").version,D=(e,t)=>({name:e,level:"pass",detail:t}),z=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),X=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function Lu(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?D("node runtime",`${process.version} at ${process.execPath}`):X("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Fu(e){return e.BOSTRAT_OWNER?z("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 Uu(e){let t;try{t=G.statSync(e)}catch{return z("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?z("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):D("node.env",`${e} (0600)`)}async function Hu(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 X("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Gi(e,{required:t=!1}={}){if(await ir(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=tn[e]?`${tn[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?X(e,r,o):z(e,r,o)}async function Wu(){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 z("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",tn.gh)}}async function Ku(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Gi(t)));return e.some(t=>t.level==="pass")||e.push(X("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 Gu(){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 ir(t,{failOpen:!1})?D(t,"resolves on the service PATH"):z(t,`not on the service PATH \u2014 ${n}`,r)))}async function zu(){try{let t=Mr(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=Mr(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 X("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function Vu(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"?X:z)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function qu(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?X("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 Yu(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return z("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),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(X("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-${Du().slice(0,8)}`,ephemeral:!0}))),a.on("message",d=>{try{let w=JSON.parse(d);w.type==="hello_ok"?(typeof w.viewBase=="string"&&w.viewBase&&(l=w.viewBase),w.minNodeVersion&&Ki(tt,w.minNodeVersion)?h(X("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${w.minNodeVersion} \u2014 this node is ${tt}; the real link is refused until it updates`,`bostrat-node self-update --to ${w.latestNodeVersion||w.minNodeVersion}`)):w.latestNodeVersion&&Ki(tt,w.latestNodeVersion)?h(z("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${w.latestNodeVersion} is available (this node: ${tt})`,`bostrat-node self-update --to ${w.latestNodeVersion}`)):h(D("plane link",`hello_ok in ${Date.now()-r}ms (${o})`))):w.type==="error"&&h(X("plane link",`plane said: ${w.code} ${w.message||""}`,"check the token"))}catch{}}),a.on("error",d=>h(X("plane link",`${d?.message||d}`,"check the URL, the token, and the plane's IP gate")))})}function Xu(){let e;try{e=JSON.parse(G.readFileSync(L.join(Ut,"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 X("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?z("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):D("content outbox",t?`${t} op(s) in flight`:"drained")}async function Ju(e){let t=await rs({env:e}),n=os(t);return t.available?D("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?z("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 Zu(e){let t=await ws({env:e}),n=ar(t);return t.state==="absent"?z("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 Qu(e){let t=await No({env:e}),n=Mo(t);return t.level==="misconfigured"?X("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"?z("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)?z("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 ed(e){let t=jn(e),n=To(t);return t.unknown?.length?z("audit guard",n,`BOSTRAT_AUDIT_GUARD names unknown rule(s): ${t.unknown.join(", ")}`):D("audit guard",n)}function td(e){if(e.BOSTRAT_STATE_REMOTE)return D("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`);let t=/^(on|1|true)$/i.test(String(e.BOSTRAT_STATE_SYNC||""));return D("state remote",t?"unset \u2014 local git mirror on (BOSTRAT_STATE_SYNC=on), nothing pushes":"unset \u2014 git export off; the plane holds node state (set BOSTRAT_STATE_REMOTE for an off-box copy)")}function nd(e,t){let n=t?.viewBase??null,r=bs(),o=Ss(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=_s(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}`):X("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 Lu()),n.push(Uu(t.envFile||Ue())),n.push(await Hu(e)),n.push(await Ju(e)),n.push(await Zu(e)),n.push(ed(e)),n.push(await Qu(e)),n.push(...await Ku()),n.push(await Gi("git",{required:!0})),n.push(await Wu()),n.push(...await Gu()),n.push(await zu()),n.push(Vu(e)),n.push(qu(e)),n.push(Fu(e));let r=await Yu(e,t);return n.push(r),n.push(nd(e,r)),n.push(Xu()),n.push(td(e)),n}function Vi(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 Rr(e=pn){try{return JSON.parse(await be.readFile(e,"utf8"))}catch{return null}}async function Ui({to:e,from:t=un,kind:n=et(),reason:r="manual",force:o=!1,statusFile:s=pn,spawnImpl:a=wu,now:l=Date.now,npmPrefix:h=void 0,log:m=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!fn.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 Rr(s);if(Nr(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"?Xn(await ku())||U.resolve(U.dirname(process.execPath),".."):null,b=Or(),M=Fi({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,M,{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 k=Nt.existsSync("/run/systemd/system")&&await Au("systemd-run"),_=k?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",S]]:["bash",[S]],E=async x=>{let I=`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:I})).catch(()=>{}),m.error?.(`[self-update] ${I}`),I},O=null;try{k||(O=Nt.openSync(N,"a"));let x=a(_[0],_[1],{detached:!0,stdio:k?"ignore":["ignore",O,O]});x.on?.("error",I=>{E(I)}),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 ku(){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 Ou({statusFile:e=pn,current:t=un,now:n=Date.now,staleMs:r=Eu}={}){let o=await Rr(e);if(!o)return null;let s=a=>be.writeFile(e,JSON.stringify(a)).catch(()=>{});if(Nr(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 Ru({isBusy:e,start:t=Ui,onStuck:n=null,onStarted:r=null,tickMs:o=Tu,stuckMs:s=_u,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 M=await t({to:b.to,from:b.from,kind:b.kind,reason:"auto"});m.log?.(`[self-update] stasis reached \u2192 ${M.ok?"started":`not started: ${M.reason}`}`);try{await r?.({...b,result:M})}catch{}};return{arm({to:y,from:b=un,kind:M=et()}){return d?.to===y?!1:(g(),d={to:y,from:b,kind:M,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 un,Su,dn,pn,_u,Tu,vr,kr,Ar,ln,ji,Ci,Bi,fn,Q,vu,Nr,Eu,Wi=R(()=>{$r();Di();un=(()=>{try{return bu(import.meta.url)("../package.json").version||null}catch{return null}})(),Su=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||gu.tmpdir(),".bostrat"),dn=U.join(Su,"self-update"),pn=U.join(dn,"status.json"),_u=1440*6e4,Tu=6e4,vr=60,kr=15,Ar=3,ln=6,ji=20,Ci=U.join(dn,"supervisor.pid"),Bi="SIGUSR2",fn=new Set(["npm-global","git-checkout"]);Q=e=>`'${String(e).replace(/'/g,"'\\''")}'`;vu=new Set(["updating","restarting","rolling-back"]),Nr=e=>!!(e&&vu.has(e.status));Eu=45*6e4});Nn();Yn();or();import G from"node:fs";import L from"node:path";import nt from"node:os";import{createRequire as Mr}from"node:module";import{execFile as Nu,spawn as Mu}from"node:child_process";import{promisify as Iu}from"node:util";import Pu from"node:readline/promises";import{randomUUID as Du}from"node:crypto";import{fileURLToPath as ju}from"node:url";import nn from"node:fs";import Ve from"node:fs/promises";import qc from"node:os";import kt from"node:path";import Yc from"node:readline";import{spawn as Xc}from"node:child_process";var Jc="^(ugrep|rg|2\\.1\\.[0-9]+|cursor-agent|codex|npm|node|MainThread)",Zc="^(bostrat-|tmux|earlyoom|systemd|sshd)",Qc=()=>["-m","10","-s","70","-r","600","--prefer",Jc,"--avoid",Zc],us="BOSTRAT_OOM_GUARD_OWNER",el=6e4,tl=5e3;function ds(e=process.env){return!["0","off","false","no"].includes(String(e.BOSTRAT_OOM_GUARD??"").trim().toLowerCase())}function ps(e=process.env){let t=e.BOSTRAT_STATE_DIR||kt.join(e.HOME||qc.tmpdir(),".bostrat");return kt.join(t,"oom-guard.pid")}function fs(e=process.env){if(e.BOSTRAT_EARLYOOM_BIN)return nn.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=kt.join(n,"earlyoom");if(nn.existsSync(r))return r}return null}async function hs({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(kt.join(e,r,"comm"),"utf8").catch(()=>"")).trim()==="earlyoom"&&n.push({pid:Number(r)})}return n}async function ms(e){let t=Number((await Ve.readFile(e,"utf8").catch(()=>"")).trim());return Number.isInteger(t)&&t>0?t:null}async function gs({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc"}={}){if(!ds(e))return{state:"off"};if(t!=="linux")return{state:"unsupported",platform:t};let r=await hs({procRoot:n}),o=await ms(ps(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=fs(e);return a?{state:"stopped",bin:a}:{state:"absent"}}function ar(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 ws({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc",log:r=console.log,spawnImpl:o=Xc,checkMs:s=el,relaunchMs:a=tl}={}){let l=null,h={state:null},m=null,d=!1,g="",v=ps(e),y=k=>{h=k;let _=`[oom-guard] ${ar(k)}`;return _!==g&&r(_),g=_,k},b=k=>{d||(clearTimeout(m),m=setTimeout(()=>M().catch(()=>{}),k),m.unref?.())},M=async()=>{if(d||l)return h;if(!ds(e))return y({state:"off"});if(t!=="linux")return y({state:"unsupported",platform:t});let k=await ms(v),_=await hs({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=fs(e);if(!E)return b(s),y({state:"absent"});let O;try{O=o(E,Qc(),{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&&Yc.createInterface({input:x}).on("line",I=>r(`[earlyoom] ${I}`));return O.on("error",x=>{r(`[oom-guard] ${E}: ${x?.message||x}`),!(l!==O||O.pid)&&(l=null,b(s))}),O.on("exit",(x,I)=>{l===O&&(l=null,Ve.rm(v,{force:!0}).catch(()=>{}),!d&&(r(`[oom-guard] earlyoom exited (${I||`code ${x}`}) \u2014 relaunching in ${Math.round(a/1e3)} s`),h={state:"stopped",bin:E},g="",b(a)))}),O.pid&&(await Ve.mkdir(kt.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"),nn.rmSync(v,{force:!0}))};return process.on("exit",S),{ready:M().catch(()=>h),status:()=>h,stop(){d=!0,clearTimeout(m),process.off("exit",S);let k=l;l=null,k&&(k.kill("SIGTERM"),nn.rmSync(v,{force:!0}))}}}Cn();import nl from"node:fs";import ys from"node:path";import rl from"node:os";var ol=()=>process.env.BOSTRAT_STATE_DIR||ys.join(process.env.HOME||rl.tmpdir(),".bostrat"),sl=()=>ys.join(ol(),"plane-link","public-host.json");var At=null;function il(){if(At)return At;try{let e=JSON.parse(nl.readFileSync(sl(),"utf8"));At={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{At={viewBase:null}}return At}function al(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 bs(){return il().viewBase}function Ss(e=process.env.BOSTRAT_PUBLIC_HOST){return al(e,"https")}function _s(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 cl from"node:fs";import ll from"node:os";import Ts from"node:path";var xs=3*6e4;function cr(e=process.env){let t=e.BOSTRAT_STATE_DIR||Ts.join(e.HOME||ll.tmpdir(),".bostrat");return Ts.join(t,"heartbeat.json")}function $s(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return xs;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):xs}function vs(e=cr()){try{let t=JSON.parse(cl.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",sm=2*6e4;var ks=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Es({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:ks(e),staleS:ks(t)!=null?Math.round(t/1e3):null})}Ae();var Ki=(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(Nu),Ir=L.dirname(ju(import.meta.url)),Ne=L.resolve(Ir,".."),Cu=L.join(Ir,"index.js"),Bu="wss://plane.bostrat.ai/v1/node",tt=Mr(import.meta.url)("../package.json").version,D=(e,t)=>({name:e,level:"pass",detail:t}),z=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),X=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function Lu(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?D("node runtime",`${process.version} at ${process.execPath}`):X("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Fu(e){return e.BOSTRAT_OWNER?z("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 Uu(e){let t;try{t=G.statSync(e)}catch{return z("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?z("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):D("node.env",`${e} (0600)`)}async function Hu(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 X("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Gi(e,{required:t=!1}={}){if(await ir(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=tn[e]?`${tn[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?X(e,r,o):z(e,r,o)}async function Wu(){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 z("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",tn.gh)}}async function Ku(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Gi(t)));return e.some(t=>t.level==="pass")||e.push(X("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 Gu(){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 ir(t,{failOpen:!1})?D(t,"resolves on the service PATH"):z(t,`not on the service PATH \u2014 ${n}`,r)))}async function zu(){try{let t=Mr(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=Mr(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 X("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function Vu(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"?X:z)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function qu(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?X("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 Yu(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return z("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),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(X("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-${Du().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&&Ki(tt,g.minNodeVersion)?h(X("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&&Ki(tt,g.latestNodeVersion)?h(z("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(X("plane link",`plane said: ${g.code} ${g.message||""}`,"check the token"))}catch{}}),a.on("error",d=>h(X("plane link",`${d?.message||d}`,"check the URL, the token, and the plane's IP gate")))})}function Xu(){let e;try{e=JSON.parse(G.readFileSync(L.join(Ut,"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 X("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?z("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):D("content outbox",t?`${t} op(s) in flight`:"drained")}async function Ju(e){let t=await rs({env:e}),n=os(t);return t.available?D("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?z("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 Zu(e){let t=await gs({env:e}),n=ar(t);return t.state==="absent"?z("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 Qu(e){let t=await No({env:e}),n=Mo(t);return t.level==="misconfigured"?X("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"?z("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)?z("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 ed(e){let t=jn(e),n=To(t);return t.unknown?.length?z("audit guard",n,`BOSTRAT_AUDIT_GUARD names unknown rule(s): ${t.unknown.join(", ")}`):D("audit guard",n)}function td(e){if(e.BOSTRAT_STATE_REMOTE)return D("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`);let t=/^(on|1|true)$/i.test(String(e.BOSTRAT_STATE_SYNC||""));return D("state remote",t?"unset \u2014 local git mirror on (BOSTRAT_STATE_SYNC=on), nothing pushes":"unset \u2014 git export off; the plane holds node state (set BOSTRAT_STATE_REMOTE for an off-box copy)")}function nd(e,t){let n=t?.viewBase??null,r=bs(),o=Ss(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=_s(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}`):X("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 Lu()),n.push(Uu(t.envFile||Ue())),n.push(await Hu(e)),n.push(await Ju(e)),n.push(await Zu(e)),n.push(ed(e)),n.push(await Qu(e)),n.push(...await Ku()),n.push(await Gi("git",{required:!0})),n.push(await Wu()),n.push(...await Gu()),n.push(await zu()),n.push(Vu(e)),n.push(qu(e)),n.push(Fu(e));let r=await Yu(e,t);return n.push(r),n.push(nd(e,r)),n.push(Xu()),n.push(td(e)),n}function Vi(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
224
  OK \u2014 0 blocking, ${o} warnings`),r===0}async function rd({envFile:e=Ue(),input:t=process.stdin,output:n=process.stdout}={}){let r=Ht(e),o=Pu.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:
225
225
  you type those inside each box, later (box-auth-policy).
226
226
 
227
227
  `);let a=await s("Plane URL",r.BOSTRAT_PLANE_URL||Bu),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
- `);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")),w=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(`
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,
231
231
  injected per box, stored 0600 in node.env, never sent to the plane.
232
232
  \u2022 create/copy a key: https://console.anthropic.com/settings/keys
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={...oo(),...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:w,BOSTRAT_CLAUDE_USE_API_KEY:v?"1":"0",ANTHROPIC_API_KEY:v?y:r.ANTHROPIC_API_KEY};delete b.BOSTRAT_OWNER,ro(e,b,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
236
+ `),o.close();let b={...oo(),...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,ro(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
241
  `);let M={...b,...process.env},S=await zi(M,{envFile:e}),N=Vi(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 od="SIGUSR2",sd=5*6e4,id=1e4,hn=L.join(Ut,"self-update","supervisor.pid");function ad({spawnChild:e,exit:t=m=>process.exit(m),now:n=Date.now,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:o=clearTimeout,killGraceMs:s=15e3,rollbackGraceMs:a=sd,stall:l=null,log:h=console}={}){let m=null,d=0,w=!1,v="update",y=0,b=null,M=null,S=null,N=0,k=0,_=0,E=!1,O=l&&l.staleMs>0?l.staleMs:0,x=l?.checkMs>0?l.checkMs:id,I=()=>{b&&o(b),b=null},Me=()=>{m.kill("SIGTERM"),M=r(()=>m?.kill("SIGKILL"),s),M.unref?.()},rt=null,Ie=0,mn=()=>{let P=null;try{P=l.readHeartbeat()}catch{}return P&&P.pid===m.pid&&Number.isFinite(P.ts)&&P.ts!==rt&&(rt=P.ts,Ie=Math.max(Ie,Math.min(P.ts,n()))),n()-Ie},Mt=()=>{if(!m||E||w||!O)return!1;let P=mn();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",w=!0,Me(),!0)},Pe=()=>{O&&(S&&o(S),S=r(()=>{S=null,Mt(),Pe()},x),S.unref?.())},De=(P=null)=>{let pe=e(P);return m=pe,d=n(),rt=null,Ie=d,pe.on("exit",(fe,he)=>je(pe,fe,he)),S||Pe(),pe},je=(P,pe,fe)=>{if(P!==m)return;if(m=null,M&&o(M),M=null,w){w=!1,ot(v);return}let he=fe?1:pe??1;if(!E&&he!==0&&n()<y){let st=y-n();h.error?.(`[bostrat-node] the agent exited (code ${he}) right after a self-update restart \u2014 holding ${Math.ceil(st/1e3)} s for the updater's rollback signal`),b=r(()=>t(he),st);return}t(he)},ot=(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",De(P==="stall"?{at:n(),staleMs:_}:null)};return{start:()=>De(),restart(){if(E=!1,I(),v="update",!m){ot("update");return}w||(w=!0,Me())},checkStall:Mt,forward(P){E=!0,m?m.kill(P):(I(),t(1))},get child(){return m},get state(){return{alive:!!m,restartPending:w,restartReason:v,holding:!!b,restarts:N,stallRelaunches:k,stopping:E}}}}function cd({envFile:e=Ue()}={}){no(e),process.title="bostrat-node";let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n={...process.env,BOSTRAT_RUN_SUPERVISOR_PID:String(process.pid),[us]:"supervisor"};gs();try{G.mkdirSync(L.dirname(hn),{recursive:!0}),G.writeFileSync(hn,`${process.pid}
242
+ `));return N&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:N,results:S}}var od="SIGUSR2",sd=5*6e4,id=1e4,hn=L.join(Ut,"self-update","supervisor.pid");function ad({spawnChild:e,exit:t=m=>process.exit(m),now:n=Date.now,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:o=clearTimeout,killGraceMs:s=15e3,rollbackGraceMs:a=sd,stall:l=null,log:h=console}={}){let m=null,d=0,g=!1,v="update",y=0,b=null,M=null,S=null,N=0,k=0,_=0,E=!1,O=l&&l.staleMs>0?l.staleMs:0,x=l?.checkMs>0?l.checkMs:id,I=()=>{b&&o(b),b=null},Me=()=>{m.kill("SIGTERM"),M=r(()=>m?.kill("SIGKILL"),s),M.unref?.()},rt=null,Ie=0,mn=()=>{let P=null;try{P=l.readHeartbeat()}catch{}return P&&P.pid===m.pid&&Number.isFinite(P.ts)&&P.ts!==rt&&(rt=P.ts,Ie=Math.max(Ie,Math.min(P.ts,n()))),n()-Ie},Mt=()=>{if(!m||E||g||!O)return!1;let P=mn();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,Me(),!0)},Pe=()=>{O&&(S&&o(S),S=r(()=>{S=null,Mt(),Pe()},x),S.unref?.())},De=(P=null)=>{let pe=e(P);return m=pe,d=n(),rt=null,Ie=d,pe.on("exit",(fe,he)=>je(pe,fe,he)),S||Pe(),pe},je=(P,pe,fe)=>{if(P!==m)return;if(m=null,M&&o(M),M=null,g){g=!1,ot(v);return}let he=fe?1:pe??1;if(!E&&he!==0&&n()<y){let st=y-n();h.error?.(`[bostrat-node] the agent exited (code ${he}) right after a self-update restart \u2014 holding ${Math.ceil(st/1e3)} s for the updater's rollback signal`),b=r(()=>t(he),st);return}t(he)},ot=(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",De(P==="stall"?{at:n(),staleMs:_}:null)};return{start:()=>De(),restart(){if(E=!1,I(),v="update",!m){ot("update");return}g||(g=!0,Me())},checkStall:Mt,forward(P){E=!0,m?m.kill(P):(I(),t(1))},get child(){return m},get state(){return{alive:!!m,restartPending:g,restartReason:v,holding:!!b,restarts:N,stallRelaunches:k,stopping:E}}}}function cd({envFile:e=Ue()}={}){no(e),process.title="bostrat-node";let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n={...process.env,BOSTRAT_RUN_SUPERVISOR_PID:String(process.pid),[us]:"supervisor"};ws();try{G.mkdirSync(L.dirname(hn),{recursive:!0}),G.writeFileSync(hn,`${process.pid}
243
243
  `)}catch{}let r=$s(process.env),o=cr(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=ad({spawnChild:a=>Mu(t,[Cu],{cwd:Ne,stdio:"inherit",env:a?{...n,[As]:Es(a)}:n}),stall:r?{readHeartbeat:()=>vs(o),staleMs:r}:null});for(let a of["SIGINT","SIGTERM"])process.on(a,()=>s.forward(a));return process.on(od,()=>s.restart()),process.on("exit",()=>{try{G.readFileSync(hn,"utf8").trim()===String(process.pid)&&G.rmSync(hn,{force:!0})}catch{}}),s.start()}function ld({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]
@@ -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 dd(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 pd({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=Ne}={}){let{kind:s,file:a}=dd(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,ld()),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,ud()),t&&await Se("launchctl",["load","-w",a]),r(`installed ${a}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function jw(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 rd({envFile:n})).ok?0:1;if(t==="doctor"){let r={...Ht(n),...process.env};return Vi(await zi(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return cd({envFile:n}),null;if(t==="install-service")return await pd({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(Ds(),Ps));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:s}=await Promise.resolve().then(()=>(Wi(),Hi)),{detectInstallKind:a}=await Promise.resolve().then(()=>($r(),Pi)),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 dd(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 pd({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=Ne}={}){let{kind:s,file:a}=dd(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,ld()),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,ud()),t&&await Se("launchctl",["load","-w",a]),r(`installed ${a}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function jg(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 rd({envFile:n})).ok?0:1;if(t==="doctor"){let r={...Ht(n),...process.env};return Vi(await zi(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return cd({envFile:n}),null;if(t==="install-service")return await pd({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(Ds(),Ps));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:s}=await Promise.resolve().then(()=>(Wi(),Hi)),{detectInstallKind:a}=await Promise.resolve().then(()=>($r(),Pi)),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{od as RESTART_SIGNAL,sd as ROLLBACK_GRACE_MS,id as STALL_CHECK_MS,hn as SUPERVISOR_PID_FILE,ad as createRunSupervisor,rd as init,pd as installService,ud as launchdPlist,jw as main,Vi as printDoctor,cd as runAgent,zi as runDoctor,dd as servicePaths,ld as systemdUnit};
298
+ self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{od as RESTART_SIGNAL,sd as ROLLBACK_GRACE_MS,id as STALL_CHECK_MS,hn as SUPERVISOR_PID_FILE,ad as createRunSupervisor,rd as init,pd as installService,ud as launchdPlist,jg as main,Vi as printDoctor,cd as runAgent,zi as runDoctor,dd as servicePaths,ld as systemdUnit};