bostrat-node 1.16.4 → 1.16.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
- var ms=Object.defineProperty;var R=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var cn=(e,t)=>{for(var n in t)ms(e,n,{get:t[n],enumerable:!0})};import _t from"node:fs";import ln from"node:path";import ws from"node:os";function nt(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,r;try{r=new URL(n)}catch{return t}let s={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return s?(r.protocol=s,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function vt(e){let t;try{t=_t.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
2
- `)){let s=r.trim();if(!s||s.startsWith("#"))continue;let a=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(s);if(!a)continue;let d=a[2].trim();(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))&&(d=d.slice(1,-1)),n[a[1]]=d}return n}function fr(e,t=process.env){let n=vt(e);for(let[r,s]of Object.entries(n))r in t||(t[r]=s);return n}function hr(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
3
- `).map(s=>s?`# ${s}`:"#"));for(let[s,a]of Object.entries(t))a==null||a===""||r.push(`${s}=${a}`);_t.mkdirSync(ln.dirname(e),{recursive:!0}),_t.writeFileSync(e,r.join(`
1
+ var ti=Object.defineProperty;var O=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var fn=(e,t)=>{for(var n in t)ti(e,n,{get:t[n],enumerable:!0})};import kt from"node:fs";import hn from"node:path";import ni from"node:os";function st(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,r;try{r=new URL(n)}catch{return t}let o={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return o?(r.protocol=o,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function At(e){let t;try{t=kt.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
2
+ `)){let o=r.trim();if(!o||o.startsWith("#"))continue;let i=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!i)continue;let c=i[2].trim();(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),n[i[1]]=c}return n}function kr(e,t=process.env){let n=At(e);for(let[r,o]of Object.entries(n))r in t||(t[r]=o);return n}function xr(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
3
+ `).map(o=>o?`# ${o}`:"#"));for(let[o,i]of Object.entries(t))i==null||i===""||r.push(`${o}=${i}`);kt.mkdirSync(hn.dirname(e),{recursive:!0}),kt.writeFileSync(e,r.join(`
4
4
  `)+`
5
- `,{mode:384}),_t.chmodSync(e,384)}function mr(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 bt,Be,un=R(()=>{bt=process.env.BOSTRAT_STATE_DIR||ln.join(process.env.HOME||ws.tmpdir(),".bostrat"),Be=()=>ln.join(bt,"node.env")});var ae,rt,$t=R(()=>{ae="BOSTRAT_HOOK_TOKEN",rt="x-bostrat-hook"});var wr=R(()=>{$t()});var ys,yc,yr=R(()=>{ys="check_for_update_on_startup",yc=`${ys} = false`});import gs from"node:os";import gr from"node:path";var Ts,bc,vc,dn=R(()=>{pn();Ts=process.env.BOSTRAT_DEBUG_DIR||gr.join(gs.homedir(),".bostrat","debug"),bc=gr.join(Ts,"handoff.jsonl"),vc=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as _s}from"node:child_process";import{promisify as bs}from"node:util";function fn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Ec,Rc,Nc,Mc,hn=R(()=>{dn();Ec=bs(_s),Rc=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Nc=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,Mc=Promise.resolve()});var Tr=R(()=>{});import mn from"node:path";import{execFile as vs}from"node:child_process";import{promisify as $s}from"node:util";var Lc,Sr,xs,Fc,jc,_r=R(()=>{Lc=$s(vs),Sr=process.env.HOME||"/home/globo",xs=mn.join(process.env.BOSTRAT_STATE_DIR||mn.join(Sr,".bostrat"),"repos"),Fc=[...(process.env.BOSTRAT_REPOS_ROOT||mn.join(Sr,"Documents")).split(","),xs].map(e=>e.trim()).filter(Boolean),jc=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function kt(e=Date.now()){if(ve)return{tripped:!1,holdMs:1/0};if(be>e)return{tripped:!1,holdMs:be-e};if((!st||e-st>=xt.windowMs)&&(st=e,ot=0),ot++,ot<xt.trip)return{tripped:!1,holdMs:0};At++;let t=Math.min(xt.minMs*2**(At-1),xt.maxMs);return be=e+t,ot=0,st=0,{tripped:!0,holdMs:t}}function br(){ot=0,st=0,At=0,be=0}function it(e=Date.now()){return ve?1/0:be>e?be-e:0}function Ot(e=Date.now()){return it(e)>0}function wn(e={}){ve={at:Date.now(),...e},be=1/0}function yn(){return ve}function vr(e=Date.now()){return{held:Ot(e),holdMs:ve?null:it(e),holds:At,removed:ve?{...ve}:null}}var As,xt,ot,st,At,be,ve,gn=R(()=>{As={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},xt={...As},ot=0,st=0,At=0,be=0,ve=null});import $r from"node:path";import ks from"node:os";import{execFile as Os}from"node:child_process";import{promisify as Es}from"node:util";var Xc,Rs,Jc,Zc,Qc,Tn=R(()=>{_r();gn();Xc=Es(Os),Rs=process.env.BOSTRAT_STATE_DIR||$r.join(process.env.HOME||ks.tmpdir(),".bostrat"),Jc=$r.join(Rs,"repos"),Zc=5*6e4,Qc=10*6e4});var xr=R(()=>{Tn()});var Ar=R(()=>{});import Ms from"node:fs/promises";import at from"node:path";import Is from"node:os";import{EventEmitter as Ps}from"node:events";function Bs(e){return e?.cwd?at.join(e.cwd,".bostrat","events"):at.join(kr,"events")}async function Et(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?at.join(kr,"events"):Bs(e));let s;try{s=await Ms.readFile(Cs(n,r),"utf8")}catch{return[]}return js(s)}function js(e){let t=[];for(let n of e.split(`
6
- `))if(n.trim())try{t.push(JSON.parse(Ls(n)?Fs(n):n))}catch{}return t}var ct,kr,Cs,Ds,Ls,Fs,Rt=R(()=>{Ar();ct=new Ps;ct.setMaxListeners(0);kr=process.env.BOSTRAT_STATE_DIR||at.join(process.env.HOME||Is.tmpdir(),".bostrat");Cs=(e,t)=>at.join(e,`${t}.ndjson`),Ds=/(?<!\\)((?:\\\\)*)\\u0000/g,Ls=e=>e.includes("\\u0000"),Fs=e=>e.replace(Ds,"$1\\ufffd")});import Hs from"node:os";import Ws from"node:path";import{execFile as Ks}from"node:child_process";import{promisify as Gs}from"node:util";var Sl,_l,bl,vl,$l,xl,Or=R(()=>{xr();Rt();Sl=Gs(Ks),_l=process.env.BOSTRAT_STATE_DIR||Ws.join(process.env.HOME||Hs.tmpdir(),".bostrat"),bl=25*1024,vl=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,$l=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,xl=Promise.resolve()});var Nt=R(()=>{});var Rl,Rr=R(()=>{Tn();Nt();Rl=60*6e4});var Nr=R(()=>{Rr()});import Mr from"node:path";import qs from"node:os";var Ce,zs,Hl,Sn,Wl,Kl,Gl,Ir=R(()=>{$t();Ce="BOSTRAT_NODE_URL",zs=process.env.BOSTRAT_STATE_DIR||Mr.join(process.env.HOME||qs.tmpdir(),".bostrat"),Hl=Mr.join(zs,"git-hooks"),Sn=`#!/bin/sh
5
+ `,{mode:384}),kt.chmodSync(e,384)}function Ar(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 xt,Be,mn=O(()=>{xt=process.env.BOSTRAT_STATE_DIR||hn.join(process.env.HOME||ni.tmpdir(),".bostrat"),Be=()=>hn.join(xt,"node.env")});var ce,it,Et=O(()=>{ce="BOSTRAT_HOOK_TOKEN",it="x-bostrat-hook"});var ri,Pl,Er=O(()=>{ri=(e,t)=>{if(e==null||e==="")return t;let n=Number(e);return Number.isFinite(n)&&n>=0?n:t},Pl=ri(process.env.BOSTRAT_HOOK_FOLD_MS,250)});function li(e,t=si){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 Ot(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function Br(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 Pr(e){let t=Ot(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 f=t[m];f.startsWith("-")?(r.push(f),(f==="-o"||f==="--push-option"||f==="--repo"||f==="--receive-pack"||f==="--exec")&&m++):o.push(f)}let i=r.some(m=>m==="--force"||/^-[a-zA-Z]+$/.test(m)&&m.includes("f"))||o.some(m=>m.startsWith("+")),c=r.some(m=>m.startsWith("--force-with-lease")||m.startsWith("--force-if-includes")),p=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:i,lease:c,remote:p,dsts:h}}function jr(e){let{cmd:t,at:n}=Br(e);if(t==="sudo"){for(n++;n<e.length&&e[n].startsWith("-");)n++;t=e[n]??null}return{cmd:t,at:n}}function Ur(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 i=Ot(e),{cmd:c}=jr(i);return!c||!i.some(p=>p.includes(r))?null:/^(?:rm|mv|truncate|chmod|chown|tee|install|shred|unlink|ln|mkdir|touch)$/.test(c)?c:c==="sed"&&i.some(p=>/^-[a-zA-Z]*i/.test(p))?"sed -i":c==="cp"&&i[i.length-1].includes(r)?"cp":/^(?:python3?|perl|node|ruby)$/.test(c)&&/open\([^)]*['"][wa]|writeFile|write_text|appendFile|fs\.write/.test(e)?`${c} write`:null}function vi(e){let t=Ot(e),{cmd:n,at:r}=jr(t);if(!n)return null;let o=t.slice(r+1);if(n==="crontab"||n.endsWith("/crontab")){let c=!1,p=!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])?c=!0:p=!0}return p||!c?"crontab":null}if(n==="systemctl"||n.endsWith("/systemctl")){let c=o.find(p=>!p.startsWith("-"));return c&&hi.test(c)?`systemctl ${c}`: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 i=Ur(e,Fr);return i?`${i} unit/cron path`:null}function $i(e){let t=new Set;for(let n of String(e??"").matchAll(yi))t.add(n[1].toLowerCase());return[...t]}var oi,si,Or,Rr,Nr,Mr,Ir,Fl,ii,ai,wn,ci,ve,yn,ui,di,pi,fi,Lr,Fr,hi,mi,wi,gi,yi,Dr,Cr,bi,Ti,Si,_i,J,at,gn,Hr,jl,Ul,Wr=O(()=>{Er();oi="BP-AU-R4",si=160,Or=200,Rr=5,Nr=8,Mr=5,Ir=10*6e4,Fl=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"]),ii=5e3,ai=new Set(["tool.called","tool.failed"]),wn=new Set(["Write","Edit","NotebookEdit"]),ci=e=>String(e??"").replace(/\s+/g," ").trim(),ve=(e,t=120)=>ci(e).slice(0,t);yn=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,ui=new RegExp(`${yn}/\\.ssh(?:/|\\b)`),di=new RegExp(`${yn}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),pi=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,fi=/^\.env\.(?:example|sample|template|dist)$/,Lr=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,Fr=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${yn}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),hi=/^(?: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)$/,mi=/^\/tmp\/|\/\.bostrat\/tmp\//,wi=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,gi=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,yi=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,Dr=e=>ui.test(e)||di.test(e),Cr=e=>[...String(e??"").matchAll(pi)].some(t=>!fi.test(t[1])),bi=e=>Lr.test(e),Ti=e=>Fr.test(e),Si=e=>(e.startsWith("/")||e.startsWith("~"))&&!mi.test(e);_i=e=>Ur(e,Lr);J=(e,t,n,r)=>Object.freeze({severity:e,requirement:oi,note:t,measured:n,detect:r}),at=(e,t)=>{let n=0,r=null;for(let o of e.calls)if(o.head)for(let i of li(o.head,e.headCap)){let c=t(i,o);c&&(n++,r??=ve(c))}return n?{count:n,sample:r}:null},gn=(e,t)=>{let n=0,r=null;for(let o of e.calls){let i=t(o);i&&(n++,r??=ve(i))}return n?{count:n,sample:r}:null},Hr=Object.freeze({"force-push":J("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)=>at(t,n=>{let r=Pr(n);return r&&r.force&&!r.lease?n:null})),"protected-config-write":J("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 i of t.calls)wn.has(i.tool)&&i.path&&bi(i.path)&&(n++,r??=ve(`${i.tool} ${i.path}`));let o=at(t,i=>{let c=_i(i);return c?`${c}: ${i}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"persistence-install":J("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 i of t.calls)wn.has(i.tool)&&i.path&&Ti(i.path)&&(n++,r??=ve(`${i.tool} ${i.path}`));let o=at(t,i=>{let c=vi(i);return c?`${c}: ${i}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"push-outside-track":J("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)=>at(t,n=>{let r=Pr(n);return r&&(r.remote&&!/^(?:origin|upstream)$/.test(r.remote)&&!r.remote.startsWith("$")&&!r.remote.startsWith("-")||r.dsts.some(o=>wi.test(o)||!gi.test(o)))?n:null})),"credential-read":J("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)=>gn(t,n=>n.head&&Dr(n.head)?n.head:n.path&&Dr(n.path)?`${n.tool} ${n.path}`:null)),"dotenv-read":J("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)=>gn(t,n=>n.head&&Cr(n.head)?n.head:n.path&&Cr(n.path)?`${n.tool} ${n.path}`:null)),"privileged-command":J("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)=>at(t,n=>{let{cmd:r}=Br(Ot(n));return r==="sudo"||r==="docker"?n:null})),"write-outside-workspace":J("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)=>gn(t,n=>wn.has(n.tool)&&n.path&&Si(n.path)?`${n.tool} ${n.path}`:null)),"egress-new-host":J("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 i of $i(o.head))t.state.known.has(i)||t.state.hosts.has(i)||(t.state.hosts.add(i),t.state.hosts.size>ii&&t.state.hosts.delete(t.state.hosts.values().next().value),n++,r??=ve(`${i} \xB7 ${o.head}`));return n?{count:n,sample:r}:null}),"spend-spike":J("low",`a cost.recorded turn over ${Nr}\xD7 the Track's running median (its last ${Or} cost events, at least ${Rr} of them) and over $${Mr} \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>=Rr&&r>=Mr){let i=[...n].sort((p,h)=>p-h),c=i[Math.floor(i.length/2)];r>Nr*c&&(o={count:1,sample:`$${r.toFixed(2)} vs median $${c.toFixed(2)} over ${n.length} turns${e.payload?.model?` \xB7 ${e.payload.model}`:""}`})}return n.push(r),n.length>Or&&n.shift(),o}),"peer-injected-call":J("medium",`a tool call within ${Ir/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>Ir||t.ts<n)return null;let r=t.calls[0];return{count:t.count,sample:ve(`${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":J("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:ve(`session ${String(e.payload.sessionId||"?").slice(0,8)} \xB7 ${n.tool}${n.head?`: ${n.head}`:n.path?` ${n.path}`:""}`)}})}),jl=Object.freeze(Object.keys(Hr)),Ul=new Set([...ai,"cost.recorded","peer.message","turn.user"])});function Ai(e){let t=String(e??"").trim().toLowerCase();if(ki.has(t))return{enabled:!1,rules:[],unknown:[]};if(xi.has(t))return{enabled:!0,rules:[...bn],unknown:[]};let n=[],r=[];for(let o of t.split(",")){let i=o.trim();i&&(bn.includes(i)?n.includes(i)||n.push(i):r.push(i))}return{enabled:n.length>0,rules:n,unknown:r}}function Kr(e){return e?.enabled?`on \xB7 denies ${e.rules.length===bn.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 bn,ki,xi,Tn,Sn=O(()=>{Wr();bn=Object.freeze(["force-push","protected-config-write","credential-read","persistence-install"]),ki=new Set(["","off","0","false","no","none"]),xi=new Set(["on","1","true","yes","all"]);Tn=(e=process.env)=>Ai(e.BOSTRAT_AUDIT_GUARD)});var Gr=O(()=>{Et();Sn()});var Ei,Jl,zr=O(()=>{Ei="check_for_update_on_startup",Jl=`${Ei} = false`});import Oi from"node:os";import qr from"node:path";var Ri,nu,ru,_n=O(()=>{vn();Ri=process.env.BOSTRAT_DEBUG_DIR||qr.join(Oi.homedir(),".bostrat","debug"),nu=qr.join(Ri,"handoff.jsonl"),ru=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as Mi}from"node:child_process";import{promisify as Ii}from"node:util";function $n(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var lu,uu,du,pu,kn=O(()=>{_n();lu=Ii(Mi),uu=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,du=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,pu=Promise.resolve()});var Vr=O(()=>{});import xn from"node:path";import{execFile as Pi}from"node:child_process";import{promisify as Di}from"node:util";var yu,Yr,Ci,bu,Tu,Xr=O(()=>{yu=Di(Pi),Yr=process.env.HOME||"/home/globo",Ci=xn.join(process.env.BOSTRAT_STATE_DIR||xn.join(Yr,".bostrat"),"repos"),bu=[...(process.env.BOSTRAT_REPOS_ROOT||xn.join(Yr,"Documents")).split(","),Ci].map(e=>e.trim()).filter(Boolean),Tu=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function Mt(e=Date.now()){if(ke)return{tripped:!1,holdMs:1/0};if($e>e)return{tripped:!1,holdMs:$e-e};if((!lt||e-lt>=Rt.windowMs)&&(lt=e,ct=0),ct++,ct<Rt.trip)return{tripped:!1,holdMs:0};Nt++;let t=Math.min(Rt.minMs*2**(Nt-1),Rt.maxMs);return $e=e+t,ct=0,lt=0,{tripped:!0,holdMs:t}}function Jr(){ct=0,lt=0,Nt=0,$e=0}function ut(e=Date.now()){return ke?1/0:$e>e?$e-e:0}function It(e=Date.now()){return ut(e)>0}function An(e={}){ke={at:Date.now(),...e},$e=1/0}function En(){return ke}function Zr(e=Date.now()){return{held:It(e),holdMs:ke?null:ut(e),holds:Nt,removed:ke?{...ke}:null}}var Bi,Rt,ct,lt,Nt,$e,ke,On=O(()=>{Bi={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},Rt={...Bi},ct=0,lt=0,Nt=0,$e=0,ke=null});import Qr from"node:path";import Li from"node:os";import{execFile as Fi}from"node:child_process";import{promisify as ji}from"node:util";var Ru,Ui,Nu,Mu,Iu,Rn=O(()=>{Xr();On();Ru=ji(Fi),Ui=process.env.BOSTRAT_STATE_DIR||Qr.join(process.env.HOME||Li.tmpdir(),".bostrat"),Nu=Qr.join(Ui,"repos"),Mu=5*6e4,Iu=10*6e4});var eo=O(()=>{Rn()});var to=O(()=>{});import Wi from"node:fs/promises";import dt from"node:path";import Ki from"node:os";import{EventEmitter as Gi}from"node:events";function zi(e){return e?.cwd?dt.join(e.cwd,".bostrat","events"):dt.join(no,"events")}async function Pt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?dt.join(no,"events"):zi(e));let o;try{o=await Wi.readFile(qi(n,r),"utf8")}catch{return[]}return Ji(o)}function Ji(e){let t=[];for(let n of e.split(`
6
+ `))if(n.trim())try{t.push(JSON.parse(Yi(n)?Xi(n):n))}catch{}return t}var pt,no,qi,Vi,Yi,Xi,Dt=O(()=>{to();pt=new Gi;pt.setMaxListeners(0);no=process.env.BOSTRAT_STATE_DIR||dt.join(process.env.HOME||Ki.tmpdir(),".bostrat");qi=(e,t)=>dt.join(e,`${t}.ndjson`),Vi=/(?<!\\)((?:\\\\)*)\\u0000/g,Yi=e=>e.includes("\\u0000"),Xi=e=>e.replace(Vi,"$1\\ufffd")});import Qi from"node:os";import ea from"node:path";import{execFile as ta}from"node:child_process";import{promisify as na}from"node:util";var ed,td,nd,rd,od,sd,ro=O(()=>{eo();Dt();ed=na(ta),td=process.env.BOSTRAT_STATE_DIR||ea.join(process.env.HOME||Qi.tmpdir(),".bostrat"),nd=25*1024,rd=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,od=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,sd=Promise.resolve()});var Ct=O(()=>{});var ud,so=O(()=>{Rn();Ct();ud=60*6e4});var io=O(()=>{so()});import ao from"node:path";import ra from"node:os";var Le,oa,_d,Nn,vd,$d,kd,co=O(()=>{Et();Le="BOSTRAT_NODE_URL",oa=process.env.BOSTRAT_STATE_DIR||ao.join(process.env.HOME||ra.tmpdir(),".bostrat"),_d=ao.join(oa,"git-hooks"),Nn=`#!/bin/sh
7
7
  # bostrat git hook shim (agent/src/git-hooks.js) \u2014 chains to the repo's own hook,
8
8
  # then stamps/reports for rework attribution when running inside a bostrat box.
9
9
  hook=$(basename "$0")
@@ -18,37 +18,37 @@ esac
18
18
  if [ -x "$orig/$hook" ] && [ "$orig/$hook" != "$0" ]; then
19
19
  "$orig/$hook" "$@" || exit $?
20
20
  fi
21
- `,Wl=`${Sn}
21
+ `,vd=`${Nn}
22
22
  # \u2500\u2500 bostrat: append provenance trailers (Layer 0). Skipped for merge commits
23
23
  # (nobody "wrote" a merge) and outside a box (no token / no node url).
24
- [ -z "$${ae}" ] && exit 0
25
- [ -z "$${Ce}" ] && exit 0
24
+ [ -z "$${ce}" ] && exit 0
25
+ [ -z "$${Le}" ] && exit 0
26
26
  [ "$2" = "merge" ] && exit 0
27
- trailers=$(curl -sS -m 3 -H "${rt}: $${ae}" "$${Ce}/api/git/trailers" 2>/dev/null) || exit 0
27
+ trailers=$(curl -sS -m 3 -H "${it}: $${ce}" "$${Le}/api/git/trailers" 2>/dev/null) || exit 0
28
28
  [ -z "$trailers" ] && exit 0
29
29
  printf '%s\\n' "$trailers" | while IFS= read -r line; do
30
30
  [ -n "$line" ] && git interpret-trailers --in-place --if-exists addIfDifferent --trailer "$line" "$1" >/dev/null 2>&1 || true
31
31
  done
32
32
  exit 0
33
- `,Kl=`${Sn}
33
+ `,$d=`${Nn}
34
34
  # \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
35
- [ -z "$${ae}" ] && exit 0
36
- [ -z "$${Ce}" ] && exit 0
35
+ [ -z "$${ce}" ] && exit 0
36
+ [ -z "$${Le}" ] && exit 0
37
37
  sha=$(git rev-parse HEAD 2>/dev/null) || exit 0
38
38
  cwd=$(git rev-parse --show-toplevel 2>/dev/null)
39
- printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${Ce}/api/git/committed" \\
40
- -H 'content-type: application/json' -H "${rt}: $${ae}" --data-binary @- >/dev/null 2>&1 || true
39
+ printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${Le}/api/git/committed" \\
40
+ -H 'content-type: application/json' -H "${it}: $${ce}" --data-binary @- >/dev/null 2>&1 || true
41
41
  exit 0
42
- `,Gl=`${Sn}
42
+ `,kd=`${Nn}
43
43
  # \u2500\u2500 bostrat: the tree moved \u2014 let the node re-read this workspace's lockfiles.
44
- [ -z "$${ae}" ] && exit 0
45
- [ -z "$${Ce}" ] && exit 0
44
+ [ -z "$${ce}" ] && exit 0
45
+ [ -z "$${Le}" ] && exit 0
46
46
  [ "$hook" = "post-checkout" ] && [ "$3" != "1" ] && exit 0
47
- curl -sS -m 3 -X POST "$${Ce}/api/deps/refresh" \\
48
- -H 'content-type: application/json' -H "${rt}: $${ae}" --data-binary '{}' >/dev/null 2>&1 || true
47
+ curl -sS -m 3 -X POST "$${Le}/api/deps/refresh" \\
48
+ -H 'content-type: application/json' -H "${it}: $${ce}" --data-binary '{}' >/dev/null 2>&1 || true
49
49
  exit 0
50
- `});import lt from"node:fs/promises";import Mt from"node:os";import De from"node:path";import{execFile as Vs}from"node:child_process";import{promisify as Ys}from"node:util";function Cr(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function Dr(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 ni(e=process.env){let t=Dr(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function Lr(e=Mt.totalmem()){return Math.max(e-Zs*ut,Math.floor(e/2))}function ri(e=Mt.totalmem(),t=process.env){let n=Number(t.BOSTRAT_BOX_MEMORY_MAX_MB);return Number.isFinite(n)&&n>=256?Math.floor(n)*ut:Math.min(ei*ut,Lr(e))}function oi(e=process.env){return De.join(Cr(e),Qs)}async function si(e){return(await lt.readFile(e,"utf8")).trim()}async function Fr({env:e=process.env,totalBytes:t=Mt.totalmem(),force:n=!1,platform:r=process.platform}={}){if(!n&&!ni(e))return Le=Dr(e)==="off"?{available:!1,reason:"disabled (BOSTRAT_BOX_CGROUPS=0)"}:await ii({env:e,totalBytes:t,platform:r}),Le;let s=Cr(e),a=oi(e);try{let d;try{d=(await si(De.join(s,"cgroup.controllers"))).split(/\s+/).filter(Boolean)}catch(p){throw new Error(`no cgroup v2 tree at ${s} (${p?.code||p?.message||p})`)}let f=["cpu","memory"].filter(p=>d.includes(p));if(!f.length)throw new Error(`cgroup v2 at ${s} offers neither cpu nor memory (controllers: ${d.join(" ")||"none"})`);await lt.mkdir(a,{recursive:!0});let m=`+${f.join(" +")}`;for(let p of[De.join(s,"cgroup.subtree_control"),De.join(a,"cgroup.subtree_control")])try{await lt.writeFile(p,m)}catch(w){throw new Error(`cannot enable ${m} in ${p} (${w?.code||w?.message||w})`)}let S=Lr(t);f.includes("cpu")&&await lt.writeFile(De.join(a,"cpu.weight"),String(Pr)),f.includes("memory")&&await lt.writeFile(De.join(a,"memory.max"),String(S)),Le={available:!0,backend:"cgroupfs",path:a,controllers:f,cpuWeight:f.includes("cpu")?Pr:null,memoryMaxMb:f.includes("memory")?Math.round(S/ut):null}}catch(d){Le={available:!1,reason:d?.message||String(d)}}return Le}async function ii({env:e=process.env,totalBytes:t=Mt.totalmem(),platform:n=process.platform}={}){if(n!=="linux")return{available:!1,reason:`not a Fly/container node, and no systemd on ${n}`};try{await Xs(Br(e),["--user","show","--property=Version","--value"],{timeout:3e3})}catch(s){return{available:!1,reason:`not a Fly/container node, and no systemd user manager to ask (${String(s?.stderr||s?.code||s?.message||s).trim().split(`
51
- `)[0]})`}}let r=ri(t,e);return{available:!0,backend:"systemd",path:null,controllers:["memory"],cpuWeight:null,memoryMaxMb:Math.round(r/ut),swapMaxMb:ti,systemctl:Br(e),procRoot:e.BOSTRAT_PROC_ROOT||"/proc"}}function jr(e=Le){let t=`nice ${Js} 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 Xs,Js,Pr,Zs,Qs,ei,ti,ut,Le,Br,_n=R(()=>{Xs=Ys(Vs),Js=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),Pr=50,Zs=768,Qs="bostrat-boxes",ei=4096,ti=512,ut=1024*1024;Le=null;Br=(e=process.env)=>e.BOSTRAT_SYSTEMCTL_BIN||"systemctl"});import{execFile as ai}from"node:child_process";import{promisify as ci}from"node:util";import Wr from"node:fs";import li from"node:os";function Kr(e){return`/tmp/tmux-${e}/default`}function di({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let s=Kr(r);return t?s:n?`${n}/bostrat/tmux-default`:s}async function vn(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await fi(e,{loginShell:t});return r===Gr?!0:r===bn?!1:n}async function fi(e,{loginShell:t=!1,timeoutMs:n=pi}={}){if(!e)return bn;let r=t?process.env.SHELL||"/bin/sh":"sh",s=t?"-lic":"-c";try{return await ui(r,[s,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),Gr}catch(a){return a?.killed||a?.signal?Hr:a?.code===1||a?.code===127?bn:Hr}}var ui,Ou,Ur,Eu,Ru,Nu,Mu,Iu,Gr,bn,Hr,pi,It,Pu,Bu,Cu,Du,Lu,Fu,pn=R(()=>{wr();yr();hn();Tr();Or();Nr();dn();$t();Ir();_n();ui=ci(ai),Ou=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";Ur=typeof process.getuid=="function"?process.getuid():0,Eu=di({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Wr.existsSync(Kr(Ur))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:Ur}),Ru=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Nu=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Mu=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),Iu=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);Gr="present",bn="absent",Hr="unknown",pi=5e3;It={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"},Pu=(()=>{try{let e=li.homedir();if(e&&Wr.existsSync(e))return e}catch{}return"/"})(),Bu=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Cu=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Du=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Lu=Number(process.env.BOSTRAT_BOX_COLS)||120,Fu=Number(process.env.BOSTRAT_BOX_ROWS)||40});var yo={};cn(yo,{NODE_IMAGE:()=>kn,commandPlan:()=>ho,flyToml:()=>fo,flyWizard:()=>Di,parseFlyFlags:()=>mo,stageConfig:()=>wo});import An from"node:fs";import $e from"node:path";import Ri from"node:os";import Ni from"node:readline/promises";import{execFile as Mi}from"node:child_process";import{createRequire as Ii}from"node:module";import{randomUUID as Pi}from"node:crypto";function fo({app:e,region:t,nodeName:n=e,planeUrl:r=po,image:s=kn}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
50
+ `});import ft from"node:fs/promises";import Bt from"node:os";import Fe from"node:path";import{execFile as sa}from"node:child_process";import{promisify as ia}from"node:util";function po(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function fo(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 fa(e=process.env){let t=fo(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function ho(e=Bt.totalmem()){return Math.max(e-la*ht,Math.floor(e/2))}function ha(e=Bt.totalmem(),t=process.env){let n=Number(t.BOSTRAT_BOX_MEMORY_MAX_MB);return Number.isFinite(n)&&n>=256?Math.floor(n)*ht:Math.min(da*ht,ho(e))}function ma(e=process.env){return Fe.join(po(e),ua)}async function wa(e){return(await ft.readFile(e,"utf8")).trim()}async function mo({env:e=process.env,totalBytes:t=Bt.totalmem(),force:n=!1,platform:r=process.platform}={}){if(!n&&!fa(e))return je=fo(e)==="off"?{available:!1,reason:"disabled (BOSTRAT_BOX_CGROUPS=0)"}:await ga({env:e,totalBytes:t,platform:r}),je;let o=po(e),i=ma(e);try{let c;try{c=(await wa(Fe.join(o,"cgroup.controllers"))).split(/\s+/).filter(Boolean)}catch(f){throw new Error(`no cgroup v2 tree at ${o} (${f?.code||f?.message||f})`)}let p=["cpu","memory"].filter(f=>c.includes(f));if(!p.length)throw new Error(`cgroup v2 at ${o} offers neither cpu nor memory (controllers: ${c.join(" ")||"none"})`);await ft.mkdir(i,{recursive:!0});let h=`+${p.join(" +")}`;for(let f of[Fe.join(o,"cgroup.subtree_control"),Fe.join(i,"cgroup.subtree_control")])try{await ft.writeFile(f,h)}catch(g){throw new Error(`cannot enable ${h} in ${f} (${g?.code||g?.message||g})`)}let m=ho(t);p.includes("cpu")&&await ft.writeFile(Fe.join(i,"cpu.weight"),String(lo)),p.includes("memory")&&await ft.writeFile(Fe.join(i,"memory.max"),String(m)),je={available:!0,backend:"cgroupfs",path:i,controllers:p,cpuWeight:p.includes("cpu")?lo:null,memoryMaxMb:p.includes("memory")?Math.round(m/ht):null}}catch(c){je={available:!1,reason:c?.message||String(c)}}return je}async function ga({env:e=process.env,totalBytes:t=Bt.totalmem(),platform:n=process.platform}={}){if(n!=="linux")return{available:!1,reason:`not a Fly/container node, and no systemd on ${n}`};try{await aa(uo(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(`
51
+ `)[0]})`}}let r=ha(t,e);return{available:!0,backend:"systemd",path:null,controllers:["memory"],cpuWeight:null,memoryMaxMb:Math.round(r/ht),swapMaxMb:pa,systemctl:uo(e),procRoot:e.BOSTRAT_PROC_ROOT||"/proc"}}function wo(e=je){let t=`nice ${ca} 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 aa,ca,lo,la,ua,da,pa,ht,je,uo,Mn=O(()=>{aa=ia(sa),ca=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),lo=50,la=768,ua="bostrat-boxes",da=4096,pa=512,ht=1024*1024;je=null;uo=(e=process.env)=>e.BOSTRAT_SYSTEMCTL_BIN||"systemctl"});import{execFile as ya}from"node:child_process";import{promisify as ba}from"node:util";import bo from"node:fs";import Ta from"node:os";function To(e){return`/tmp/tmux-${e}/default`}function _a({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=To(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function Pn(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await $a(e,{loginShell:t});return r===So?!0:r===In?!1:n}async function $a(e,{loginShell:t=!1,timeoutMs:n=va}={}){if(!e)return In;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await Sa(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),So}catch(i){return i?.killed||i?.signal?yo:i?.code===1||i?.code===127?In:yo}}var Sa,cp,go,lp,up,dp,pp,fp,So,In,yo,va,Lt,hp,mp,wp,gp,yp,bp,vn=O(()=>{Gr();zr();kn();Vr();ro();io();_n();Et();co();Mn();Sa=ba(ya),cp=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";go=typeof process.getuid=="function"?process.getuid():0,lp=_a({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return bo.existsSync(To(go))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:go}),up=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",dp=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",pp=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),fp=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);So="present",In="absent",yo="unknown",va=5e3;Lt={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"},hp=(()=>{try{let e=Ta.homedir();if(e&&bo.existsSync(e))return e}catch{}return"/"})(),mp=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,wp=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,gp=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,yp=Number(process.env.BOSTRAT_BOX_COLS)||120,bp=Number(process.env.BOSTRAT_BOX_ROWS)||40});var zo={};fn(zo,{NODE_IMAGE:()=>Ln,commandPlan:()=>Wo,flyToml:()=>Ho,flyWizard:()=>Va,parseFlyFlags:()=>Ko,stageConfig:()=>Go});import Bn from"node:fs";import xe from"node:path";import Ua from"node:os";import Ha from"node:readline/promises";import{execFile as Wa}from"node:child_process";import{createRequire as Ka}from"node:module";import{randomUUID as Ga}from"node:crypto";function Ho({app:e,region:t,nodeName:n=e,planeUrl:r=Uo,image:o=Ln}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
52
52
  # Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
53
53
  # No [http_service] and none should be added: the node dials OUT to the plane;
54
54
  # nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
@@ -63,7 +63,7 @@ swap_size_mb = 1024
63
63
  # The published node image (claude + cursor-agent + codex baked in, logged
64
64
  # out), pinned to the bostrat-node version that wrote this file. Update with:
65
65
  # npm i -g bostrat-node && bostrat-node fly (re-run is safe), or bump the tag.
66
- image = "${s}"
66
+ image = "${o}"
67
67
 
68
68
  [env]
69
69
  PORT = "3362"
@@ -88,92 +88,92 @@ swap_size_mb = 1024
88
88
  # Scale later with: fly scale memory 4096 -a ${e}
89
89
  size = "shared-cpu-2x"
90
90
  memory = "2gb"
91
- `}function ho({app:e,org:t,region:n,sizeGb:r,token:s,dir:a}){let d=[`BOSTRAT_PLANE_TOKEN=${s}`];return[{argv:["apps","create",e,"-o",t],display:`fly apps create ${e} -o ${t}`,tolerate:/already|taken|exists/i},{argv:["volumes","create","node_data","-a",e,"-r",n,"-s",String(r),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${r} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted> via stdin`,stdin:d.join(`
91
+ `}function Wo({app:e,org:t,region:n,sizeGb:r,token:o,dir:i}){let c=[`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:c.join(`
92
92
  `)+`
93
- `},{argv:["deploy",a,"-c",$e.join(a,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${a} -c ${$e.join(a,"fly.toml")} -a ${e} --ha=false`}]}function mo(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--image":"image"};for(let r=0;r<e.length;r++){let s=e[r];if(s==="--yes"||s==="-y")t.yes=!0;else if(n[s])t[n[s]]=e[++r]??"";else if(s.startsWith("--")&&s.includes("=")){let[a,...d]=s.split("=");n[a]?t[n[a]]=d.join("="):a==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function wo({app:e,dest:t,toml:n}){let r=t||$e.join(Ri.homedir(),".bostrat","fly",e);An.mkdirSync(r,{recursive:!0});for(let s of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])An.rmSync($e.join(r,s),{recursive:!0,force:!0});return An.writeFileSync($e.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function Ci({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:s}=await Bt(["orgs","list","--json"],{exec:n}),a=JSON.parse(s),d=Array.isArray(a)?a.map(f=>f.Slug||f.slug).filter(Boolean):Object.keys(a);if(d.length===1)return t.write(`Org: ${d[0]} (your only org)
94
- `),d[0];if(d.length>1)return await e(`Fly org (${d.join(" / ")})`,d[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function Di({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:s}={}){let a=mo(e),d=Ni.createInterface({input:t,output:n}),f=async(g,x)=>(await d.question(x?`${g} [${x}]: `:`${g}: `)).trim()||x||"",m=g=>(d.close(),g);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
93
+ `},{argv:["deploy",i,"-c",xe.join(i,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${i} -c ${xe.join(i,"fly.toml")} -a ${e} --ha=false`}]}function Ko(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[i,...c]=o.split("=");n[i]?t[n[i]]=c.join("="):i==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function Go({app:e,dest:t,toml:n}){let r=t||xe.join(Ua.homedir(),".bostrat","fly",e);Bn.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])Bn.rmSync(xe.join(r,o),{recursive:!0,force:!0});return Bn.writeFileSync(xe.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function qa({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await jt(["orgs","list","--json"],{exec:n}),i=JSON.parse(o),c=Array.isArray(i)?i.map(p=>p.Slug||p.slug).filter(Boolean):Object.keys(i);if(c.length===1)return t.write(`Org: ${c[0]} (your only org)
94
+ `),c[0];if(c.length>1)return await e(`Fly org (${c.join(" / ")})`,c[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function Va({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:o}={}){let i=Ko(e),c=Ha.createInterface({input:t,output:n}),p=async(T,k)=>(await c.question(k?`${T} [${k}]: `:`${T}: `)).trim()||k||"",h=T=>(c.close(),T);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
95
95
  bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
96
96
 
97
- `);try{await Bt(["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"),m(1)}try{let{stdout:g}=await Bt(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${g.trim()}
98
- `)}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"),m(1)}let S=await Ci({ask:f,output:n,exec:r,flag:a.org}),p=a.app||await f("App name",`bostrat-node-${Pi().slice(0,4)}`),w=a.region||await f("Region (see `fly platform regions`)","iad"),O=a.sizeGb||Number(await f("Volume size GB (logins + repos live here)","10"))||10,b=a.name||p,$=a.planeUrl||po,N=a.token||await f("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!N)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.
99
- `),m(1);let E=a.image||kn,{dir:P}=wo({app:p,dest:s,toml:fo({app:p,region:w,nodeName:b,planeUrl:$,image:E})});n.write(`
100
- wrote ${$e.join(P,"fly.toml")} \u2014 deploys the prebuilt node image ${E}
97
+ `);try{await jt(["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:T}=await jt(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${T.trim()}
98
+ `)}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 qa({ask:p,output:n,exec:r,flag:i.org}),f=i.app||await p("App name",`bostrat-node-${Ga().slice(0,4)}`),g=i.region||await p("Region (see `fly platform regions`)","iad"),E=i.sizeGb||Number(await p("Volume size GB (logins + repos live here)","10"))||10,_=i.name||f,$=i.planeUrl||Uo,N=i.token||await p("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!N)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.
99
+ `),h(1);let R=i.image||Ln,{dir:D}=Go({app:f,dest:o,toml:Ho({app:f,region:g,nodeName:_,planeUrl:$,image:R})});n.write(`
100
+ wrote ${xe.join(D,"fly.toml")} \u2014 deploys the prebuilt node image ${R}
101
101
  (claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
102
102
 
103
103
  Plan (your flyctl, your org, your bill):
104
- `);let v=ho({app:p,org:S,region:w,sizeGb:O,token:N,dir:P});for(let g of v)n.write(` $ ${g.display}
105
- `);if(!a.yes&&(await f(`
104
+ `);let v=Wo({app:f,org:m,region:g,sizeGb:E,token:N,dir:D});for(let T of v)n.write(` $ ${T.display}
105
+ `);if(!i.yes&&(await p(`
106
106
  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.
107
- `),m(1);for(let g of v){n.write(`
108
- \u2192 ${g.display}
109
- `);try{let{stdout:x,stderr:A}=await Bt(g.argv,{stdin:g.stdin,exec:r}),k=`${x||""}${A||""}`.trim();k&&n.write(k.split(`
107
+ `),h(1);for(let T of v){n.write(`
108
+ \u2192 ${T.display}
109
+ `);try{let{stdout:k,stderr:x}=await jt(T.argv,{stdin:T.stdin,exec:r}),A=`${k||""}${x||""}`.trim();A&&n.write(A.split(`
110
110
  `).map(I=>` ${I}`).join(`
111
111
  `)+`
112
- `)}catch(x){let A=`${x?.stdout||""}${x?.stderr||""}${x?.message||""}`;if(g.tolerate&&g.tolerate.test(A)){n.write(` (already exists \u2014 continuing)
113
- `);continue}return n.write(`\u2717 failed: ${A.trim().split(`
112
+ `)}catch(k){let x=`${k?.stdout||""}${k?.stderr||""}${k?.message||""}`;if(T.tolerate&&T.tolerate.test(x)){n.write(` (already exists \u2014 continuing)
113
+ `);continue}return n.write(`\u2717 failed: ${x.trim().split(`
114
114
  `).slice(-4).join(`
115
115
  `)}
116
116
  fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
117
- `),m(1)}}return n.write(`
117
+ `),h(1)}}return n.write(`
118
118
  \u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
119
119
  chat: the node step advances on its own within a minute.
120
- logs: fly logs -a ${p}
121
- redeploy: fly deploy ${P} -c ${$e.join(P,"fly.toml")} -a ${p} --ha=false
120
+ logs: fly logs -a ${f}
121
+ redeploy: fly deploy ${D} -c ${xe.join(D,"fly.toml")} -a ${f} --ha=false
122
122
  Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
123
123
  boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
124
- `),m(0)}var po,Bi,kn,Bt,go=R(()=>{po="wss://plane.bostrat.ai/v1/node",Bi=Ii(import.meta.url)("../package.json").version,kn=`ghcr.io/globocodes/bostrat-node:${Bi}`;Bt=(e,{stdin:t,exec:n}={})=>new Promise((r,s)=>{if(n)return n(e,{stdin:t}).then(r,s);let a=Mi("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,f,m)=>d?s(Object.assign(d,{stdout:f,stderr:m})):r({stdout:f,stderr:m}));t!=null&&a.stdin?.end(t)})});function To(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!Fi.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let r=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(r))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return r}function ji(e){let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||r.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=r.map(s=>({...s,fromMs:To(s.from,"from",n),toMs:To(s.to,"to",n)}))}return t}var Li,Fi,fd,hd,So=R(()=>{Li={"claude-opus-5-5":[{from:null,to:null,input:4,output:20,cacheWrite:8,cacheRead:.2,cacheReadX:.05,fast:{input:8,output:40,cacheWrite:16,cacheRead:.4},verifiedAt:"2026-09-28",note:"verified 2026-09-28 against platform.claude.com/docs/en/about-claude/pricing: $4/$20, 1h cache write $8 (2\xD7), cache hits $0.20 (0.05\xD7 \u2014 footnote 2), fast $8/$40; added before any fleet turn was recorded."}],"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-10-05",note:"GA rates; verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"claude-sonnet-5-5":[{from:null,to:"2026-10-11",input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.20 (0.1\xD7 \u2014 footnote 2 then named Opus 5.5 only). Superseded 2026-10-12 when the page moved Sonnet 5.5 hits to 0.05\xD7 (window below)."},{from:"2026-10-12",to:null,input:2,output:10,cacheWrite:4,cacheRead:.1,cacheReadX:.05,verifiedAt:"2026-10-12",note:"verified 2026-10-12 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.10 (0.05\xD7 \u2014 footnote 2 now names Opus 5.5 AND Sonnet 5.5; the prompt-caching multiplier table agrees)."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",note:"$2/$10 is the standard price (intro pricing made permanent; the 2026-09-01 $3/$15 increase was cancelled) \u2014 verified 2026-08-17 against platform.claude.com/docs/en/about-claude/pricing; re-verified 2026-10-05 (live pricing page, footnote 3 still published)."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-haiku-5-5":[{from:null,to:null,input:.1,output:.5,cacheWrite:.2,cacheRead:.01,long:{over:1e5,input:.5,output:2.5,cacheWrite:1,cacheRead:.05},verifiedAt:"2026-10-19",note:"verified 2026-10-19 against platform.claude.com/docs/en/about-claude/pricing: prompts up to 100,000 tokens $0.10/$0.50, 1h cache write $0.20 (2\xD7), cache hits $0.01 (0.1\xD7); prompts over 100,000 tokens (the `long` variant) $0.50/$2.50, 1h cache write $1 (2\xD7), cache hits $0.05 (0.1\xD7); added before any fleet turn was recorded."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-fable-5-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-09-07",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend then; re-verified 2026-10-05 (live pricing page: $10/$50, 1h write $20, hits $1 at 0.1\xD7)."}],"gpt-5.5-pro":[{from:null,to:null,input:30,output:180,cacheWrite:30,cacheRead:30,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $30 in / $180 out, no cached-input or cache-write price published (both priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5-cyber":[{from:null,to:null,input:12.5,output:75,cacheWrite:12.5,cacheRead:1.25,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing, Cyber models table): $12.50 in / $1.25 cached / $75 out, no cache-write price published (priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-10-05",note:"verified 2026-07-03, re-verified 2026-08-17 and 2026-10-05 (developers.openai.com pricing: $5 / $0.50 cached / $30); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-10-12",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL); re-verified 2026-10-12 (live pricing page: $4 / $0.40 cached / $5 cache writes / $20, promo note unchanged)."}],"gpt-5.6-terra":[{from:null,to:"2026-08-16",input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:2,output:12,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:"2026-08-16",input:1,output:6,cacheWrite:1.25,cacheRead:.1,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:.2,output:1.2,cacheWrite:.25,cacheRead:.02,verifiedAt:"2026-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-09-07",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed)."}],"gpt-6.1-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.10 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.20 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-luna":[{from:null,to:null,input:.1,output:.5,cacheWrite:.125,cacheRead:.01,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $0.10 in / $0.01 cached / $0.125 cache writes (1.25\xD7) / $0.50 out; added before any fleet turn was recorded."}]},Fi=/^\d{4}-\d{2}-\d{2}$/;fd=ji(Li),hd=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var _o=R(()=>{So()});import bo from"node:fs/promises";import xo from"node:path";import Ui from"node:os";function ko(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Oo(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Eo(e){let t=new Date(ko(e));return t.setDate(t.getDate()+7),t.getTime()}function Ro(e){let t=new Date(Oo(e));return t.setMonth(t.getMonth()+1),t.getTime()}function qi(e=Date.now()){for(let[t,n]of Object.entries(Ki)){let r=n.startOf(e);if(r!==Ct[t]){Ct[t]=r;for(let s of On.values())s[t]=0;for(let s of vo)s.includes(`:${t}:`)&&!s.endsWith(`:${r}`)&&vo.delete(s)}}}function zi(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let s={};for(let a of["weeklyUsd","monthlyUsd"]){let d=r?.[a];if(d==null||d==="")continue;let f=Number(d);if(!Number.isFinite(f)||f<=0)throw new Error(`${n}.${a} must be a positive number or null`);s[a]=f}Object.keys(s).length&&(t[n]=s)}return t}async function No(e,{source:t="local",updatedAt:n=Date.now()}={}){je={caps:zi(e),updatedAt:n,source:t};try{await bo.mkdir(Ao,{recursive:!0}),await bo.writeFile(Hi(),JSON.stringify(je,null,2))}catch{}return Vi()}function Vi(e=Date.now()){qi(e);let t=new Set([...On.keys(),...Object.keys(je?.caps||{})]),n={};for(let r of t){let s=On.get(r);n[r]={weeklyUsd:$o(s?.weekly||0),monthlyUsd:$o(s?.monthly||0)}}return{caps:je?.caps||{},configured:!!je,seeded:Gi,updatedAt:je?.updatedAt??null,spent:n,windows:{weekly:{start:Ct.weekly,resetsAt:Eo(e)},monthly:{start:Ct.monthly,resetsAt:Ro(e)}},warnPct:Wi}}var Ao,Hi,Wi,Ki,je,Gi,Ct,On,vo,$o,Mo=R(()=>{Rt();_o();Ao=process.env.BOSTRAT_STATE_DIR||xo.join(process.env.HOME||Ui.tmpdir(),".bostrat"),Hi=()=>xo.join(Ao,"usage-caps.json"),Wi=.8;Ki={weekly:{startOf:ko,nextStart:Eo,capKey:"weeklyUsd"},monthly:{startOf:Oo,nextStart:Ro,capKey:"monthlyUsd"}},je=null,Gi=!1,Ct={weekly:0,monthly:0},On=new Map,vo=new Set;$o=e=>Math.round(e*1e4)/1e4});var jo={};cn(jo,{REMOVED_MARKER:()=>Pn,detectInstallKind:()=>We,detectProviderAuth:()=>Fo,maskToken:()=>In,readRemovedMarker:()=>Lo,startPlaneLink:()=>pa,updateCommandFor:()=>ht,versionLt:()=>He});import Ue from"node:fs";import ft from"node:fs/promises";import Yi from"node:http";import W from"node:path";import Lt from"node:os";import{createRequire as Xi}from"node:module";import En from"ws";function In(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function Lo(e=Pn){try{let t=JSON.parse(Ue.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function We({env:e=process.env,pkgDir:t=W.resolve(W.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ue.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(W.join(t,"..",".git"))?"git-checkout":"dev"}function He(e,t){let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let s=0;s<Math.max(n.length,r.length);s++){let a=(n[s]||0)-(r[s]||0);if(a)return a<0}return!1}function ht(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 Fo({home:e=process.env.HOME||Lt.homedir(),env:t=process.env}={}){let n=r=>{try{return Ue.statSync(r),!0}catch{return!1}};return{claude:n(W.join(e,".claude",".credentials.json")),codex:n(W.join(t.CODEX_HOME||W.join(e,".codex"),"auth.json")),cursor:n(W.join(t.XDG_CONFIG_HOME||W.join(e,".config"),"cursor","auth.json"))}}function pa({url:e,token:t,nodeId:n=Lt.hostname(),name:r=Lt.hostname(),listTracks:s,detectAgents:a=null,onTracksTransferred:d=null,onTracksMoves:f=null,sampleMetrics:m=null,deliverySample:S=null,onHashKey:p=null,onViewBase:w=null,metricsMs:O=da,onUpdateAvailable:b=null,onUpdatePolicy:$=null,onConflictProbe:N=null,restart:E=null,onRestarted:P=null,onHelloRefused:v=null,updatePolicy:g=null,installKind:x=We(),selfUrl:A=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:k=null,removedMarkerFile:I=Pn,onRemoved:Ae=null,onDegraded:qe=null,onRecovered:ke=null,onRefused:Gt=null,onConnected:wt=null,ingestMode:Oe=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:ze=oa,unackedRetryMs:Ee=ra,pingMs:Ve=ta,deadLinkMs:M=Math.round(Ve*na),maxInflightEvents:ce=ca,httpTimeoutMs:le=la,fanoutActive:ue=null,fanoutBatchCap:Ye=ua,stallBackoffMinMs:qn=aa,fetchImpl:zn=globalThis.fetch,log:T=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof s!="function")throw new Error("plane-link: listTracks is required");e=nt(e);let es=A.replace(/^http/,"ws"),Vn=new Set,Yn=i=>{let l=typeof i.latestNodeVersion=="string"?i.latestNodeVersion:null;if(!(!(l&&Q&&He(Q,l))||Vn.has(l))){Vn.add(l),T.log(`[plane-link] bostrat-node ${l} is available (this node runs ${Q}) \u2014 ${ht(x)}`);try{b?.({current:Q,latest:l,min:i.minNodeVersion??null,installKind:x,required:!!(i.minNodeVersion&&He(Q,i.minNodeVersion))})}catch(u){T.error(`[plane-link] update notice failed: ${u?.message||u}`)}}},we=new Map,ye=new Map,qt=W.join(Mn,"plane-link","cursor.json"),zt=W.join(Mn,"plane-link","dead-letter.ndjson"),Xn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),ne={},ee={},B=new Map,yt=null,de=null,re=0,Xe=0,Jn=0,gt={},Zn=new Set,Qn=Promise.resolve(),H="ws",Re=0,Z=!1,ge=0,Vt=!1,pe=Dt,Ne=new Set,oe=[],q=null,Y=null,X=!1,Yt=!1,Je=Io,Ze=null,Xt=E&&typeof E=="object"?E:null,Me=null,Ie=null,se=null,Te=0,er=0,ie=null,Jt=!1,Tt=0,Qe=!1,fe=Lo(I);if(fe)if(fe.tokenPreview===In(t))Qe=!0,wn({reason:fe.reason??"removed",at:fe.at??null,nodeId:fe.nodeId??n}),T.error(`[plane-link] this node was REMOVED from the plane (${fe.reason??"removed"}${fe.at?` at ${new Date(fe.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${I} to force a dial.`);else try{Ue.unlinkSync(I),T.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function Zt({reason:i="removed",at:l=Date.now(),via:u="ctl"}={}){if(!Qe){Qe=!0,wn({reason:i,at:l,nodeId:n,via:u});try{Ue.mkdirSync(W.dirname(I),{recursive:!0}),Ue.writeFileSync(I,JSON.stringify({at:l,reason:i,via:u,nodeId:n,tokenPreview:In(t)},null,2))}catch(o){T.error(`[plane-link] could not write ${I}: ${o?.message||o}`)}T.error(`[plane-link] the plane REMOVED this node (${i}, via ${u}) \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{Ae?.({reason:i,at:l,via:u})}catch{}dr({bye:!1})}}async function ts(){try{ne=JSON.parse(await ft.readFile(qt,"utf8"))}catch{ne={}}}function tr(){Jt=!0,!Ie&&(Ie=setTimeout(async()=>{if(Ie=null,!!Jt){Jt=!1;try{await ft.mkdir(W.dirname(qt),{recursive:!0}),await ft.writeFile(qt,JSON.stringify(ne))}catch(i){T.error("[plane-link] cursor flush failed:",i?.message||i)}}},ea),Ie.unref?.())}function Qt(){try{return!!ue?.()}catch{return!1}}function en(){let i=H==="http"?pe:Dt;return Qt()?Math.min(i,Ye):i}function F(i){return!Y||Y.readyState!==En.OPEN?!1:(Y.send(JSON.stringify(i)),!0)}function Pe(i){let l=Date.now();for(let{trackId:o,event:c}of i){let h=B.get(c.id);B.set(c.id,{trackId:o,seq:c.seq,event:c,sentAt:l,firstSentAt:h?.firstSentAt??l,retryAt:l+Ee,tries:(h?.tries??0)+1,nacks:h?.nacks??0})}let u=i.map(({trackId:o,event:c})=>({trackId:o,event:ia(c)}));return H==="http"?(as(u),!0):F({v:j,ch:"events",type:"append",events:u})}function ns(i){let l=null;for(let u of B.values())u.trackId===i&&(l==null||u.seq<l)&&(l=u.seq);return l}function tn(i){let l=ee[i];if(l==null)return;let u=ns(i),o=u==null?l:Math.min(l,u-1);o>(ne[i]??0)&&(ne[i]=o,tr())}function et(){if(yt=Date.now(),de!=null){let i=Date.now()-de;T.log(`[plane-link] spine sync recovered after ${Math.round(i/1e3)}s degraded (${re} stall redial(s))`);let l=de;de=null,re=0,Xe=0,Z=!1,ge=0;try{ke?.({since:l,downMs:i})}catch(u){T.error(`[plane-link] onRecovered failed: ${u?.message||u}`)}}}function nn(i){if(!Array.isArray(i)||!i.length)return;let l=new Set;for(let u of i){let o=B.get(u);o&&(B.delete(u),(ee[o.trackId]??0)<o.seq&&(ee[o.trackId]=o.seq),l.add(o.trackId))}for(let u of l)tn(u);et()}function nr(i,l){Jn++;let u={at:Date.now(),trackId:i.trackId,seq:i.seq,id:i.event?.id??null,type:i.event?.type??null,reason:l,event:i.event??null};T.error(`[plane-link] DEAD-LETTER ${i.trackId} seq ${i.seq} (${u.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${zt}`),Qn=Qn.then(async()=>{await ft.mkdir(W.dirname(zt),{recursive:!0}),await ft.appendFile(zt,JSON.stringify(u)+`
125
- `)}).catch(o=>T.error(`[plane-link] dead-letter write failed: ${o?.message||o}`))}function rs(i,l){if(gt[i]=(gt[i]??0)+1,Zn.has(i))return;Zn.add(i);let u=sa[i]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";T.error(`[plane-link] REFUSED by the plane (${i}) on track ${l}: events are being dropped, not stored \u2014 ${u}`);try{Gt?.({reason:i,trackId:l,count:gt[i],hint:u})}catch(o){T.error(`[plane-link] onRefused failed: ${o?.message||o}`)}}function rn(i,l,u,o=null){if(!Array.isArray(i)||!i.length)return;let c=new Set,h=Date.now();for(let y of i){let _=B.get(y);_&&(u?(B.delete(y),nr(_,l),String(l).startsWith(Rn)&&rs(String(l).slice(Rn.length),_.trackId),(ee[_.trackId]??0)<_.seq&&(ee[_.trackId]=_.seq),c.add(_.trackId)):(_.nacks++,_.retryAt=h+Math.max(1e3,Number(o)||Ee)))}for(let y of c)tn(y);et()}function rr(i=Date.now()){let l=1/0;for(let u of B.values())u.firstSentAt<l&&(l=u.firstSentAt);return l===1/0?0:i-l}function os(i){if(!M||!i||i!==Y||!Te)return!1;let l=Date.now()-Te;if(l<=M)return!1;er++,T.error(`[plane-link] no frame from the plane for ${Math.round(l/1e3)}s \u2014 link is half-open; terminating and redialing`);try{i.terminate()}catch{}return!0}function or(){if(!X||!B.size)return;let i=Date.now(),l=rr(i);if(l<ze||yt!=null&&i-yt<ze||H==="http"&&Z||Xe>i)return;re++;let u=Math.min(qn*2**(re-1),Bo);if(de==null){de=i-l,T.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${B.size} event(s) in flight (${H} door) \u2014 the plane is not answering appends`);try{qe?.({since:de,unacked:B.size,oldestAgeMs:l,mode:H})}catch(o){T.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(H==="http"){Z=!0,ge=i+u,T.error(`[plane-link] ingest circuit OPEN (stall #${re}); probing /v1/ingest/health in ${Math.round(u/1e3)}s`);return}Xe=i+u,T.error(`[plane-link] closing the link and redialing in ${Math.round(u/1e3)}s (stall redial #${re})`);try{Y?.terminate()}catch{}}function on(){if(!X)return;let i=Date.now();if(H==="http"&&Z)return;let l=[...B.values()].filter(o=>o.event&&o.retryAt<=i&&!(H==="http"&&Ne.has(o.trackId)));if(!l.length)return;l.sort((o,c)=>o.trackId===c.trackId?o.seq-c.seq:o.trackId<c.trackId?-1:1),T.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let u=en();if(H==="http"){let o=new Map;for(let c of l)(o.get(c.trackId)??o.set(c.trackId,[]).get(c.trackId)).push(c);for(let[,c]of o){if(Re>=Nn)return;Pe(c.slice(0,u).map(h=>({trackId:h.trackId,event:h.event})))}return}for(let o=0;o<l.length;o+=u){let c=l.slice(o,o+u).map(h=>({trackId:h.trackId,event:h.event}));if(!Pe(c))return}}async function ss(i=null){for(;;){if(!X)return!1;let l=B.size<ce,u=H!=="http"||Re<Nn&&!Z&&(!i||!Ne.has(i));if(l&&u)return!0;await new Promise(o=>setTimeout(o,100))}}function sn(){if(q=null,!X||!oe.length)return;let i=oe;oe=[];let l=en();if(H!=="http"){for(let c=0;c<i.length;c+=l)Pe(i.slice(c,c+l));return}let u=Qt(),o=new Map;for(let c of i)(o.get(c.trackId)??o.set(c.trackId,[]).get(c.trackId)).push(c);for(let[c,h]of o){if(Ne.has(c)||Re>=Nn||Z){oe.push(...h);continue}if(u){Pe(h.slice(0,l)),oe.push(...h.slice(l));continue}for(let y=0;y<h.length;y+=l)Pe(h.slice(y,y+l))}oe.length&&!q&&(q=setTimeout(sn,Co),q.unref?.())}let is=i=>{let l=new Map;for(let{trackId:u,event:o}of i)(l.get(u)??l.set(u,[]).get(u)).push(o);return[...l].map(([u,o])=>({trackId:u,events:o}))},Se=(i,l,u,{progress:o})=>{let c=Date.now();for(let{event:h}of i){let y=B.get(h.id);y&&(y.nacks++,y.retryAt=c+Math.max(1e3,u||Ee))}o&&et()};async function as(i){let l=new Set(i.map(u=>u.trackId));for(let u of l)Ne.add(u);Re++;try{let u=await zn(`${Xn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:is(i)}),signal:AbortSignal.timeout(le)}),o=(Number(u.headers.get("retry-after"))||0)*1e3;if(u.status===200){let c=await u.json();pe=Dt;for(let _ of c.results??[]){nn(_.acked??[]);let L=(te,G)=>{let St=new Map;for(let _e of te??[])(St.get(_e.reason)??St.set(_e.reason,[]).get(_e.reason)).push(_e.id);for(let[_e,pr]of St)rn(pr,_e,G,c.retryAfterMs??null)};L(_.rejected,!0),L(_.deferred,!1)}let h=new Set,y=new Map;for(let _ of Array.isArray(c.refused)?c.refused:[])!_||typeof _.id!="string"||(h.add(_.id),(y.get(_.reason)??y.set(_.reason,[]).get(_.reason)).push(_.id));for(let[_,L]of y)rn(L,`${Rn}${_}`,!0);nn((c.discarded??[]).filter(_=>!h.has(_))),et();return}if(u.status===429){Se(i,"overloaded",o||5e3,{progress:!0});return}if(u.status===413&&i.length>1){pe=Math.max(1,Math.floor(i.length/2)),T.error(`[plane-link] ingest request too large (${i.length} events) \u2014 halving batches to ${pe}`),Se(i,"too_large",1e3,{progress:!0});return}if(u.status===413){let c=B.get(i[0].event.id);c&&(B.delete(c.event.id),nr(c,"too_large"),(ee[c.trackId]??0)<c.seq&&(ee[c.trackId]=c.seq),tn(c.trackId)),et();return}if(u.status===410){Zt({reason:"removed",via:"410"}),Se(i,"http_410",6e4,{progress:!1});return}if(u.status===401||u.status===403){let{tripped:c,holdMs:h}=kt();if(c&&T.error(`[plane-link] holding every plane call for ${Math.round(h/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Tt>=Do){Tt=Date.now();let y="";try{y=(await u.json())?.error??""}catch{}T.error(`[plane-link] plane refused ingest (HTTP ${u.status}${y?`: ${y}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}Se(i,`http_${u.status}`,Math.max(6e4,it()),{progress:!1});return}if(u.status===400){T.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${i.length} event(s) for retry; this is a bug, not data`),Se(i,"http_400",6e4,{progress:!1});return}Se(i,`http_${u.status}`,o||5e3,{progress:!1})}catch(u){let o=u?.name==="TimeoutError"||u?.name==="AbortError";o&&i.length>1&&(pe=Math.max(1,Math.floor(i.length/2)),T.error(`[plane-link] ingest request of ${i.length} event(s) outlived its ${le} ms deadline \u2014 halving batches to ${pe}`)),Se(i,o?"timeout":"network",5e3,{progress:!1})}finally{Re--;for(let u of l)Ne.delete(u)}}async function cs(){if(H!=="http"||!Z||!X||Vt)return;let i=Date.now();if(!(ge>i||Ot(i))){Vt=!0;try{let l=await zn(`${Xn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(le)});if(!l.ok)throw new Error(`HTTP ${l.status}`);T.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Z=!1,ge=0,Xe=Date.now()+le+Ee+1e3;for(let u of B.values())u.retryAt=Math.min(u.retryAt,Date.now());on()}catch(l){re++;let u=Math.min(qn*2**(re-1),Bo);ge=Date.now()+u,T.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(u/1e3)}s`)}finally{Vt=!1}}}function sr(){let i=Date.now();return{mode:H,unacked:B.size,oldestUnackedAgeMs:rr(i),lastProgressAt:yt,degradedSince:de,stallRedials:re,deadLettered:Jn,fanoutCap:Qt()?Ye:null,http:H==="http"?{inFlight:Re,circuitOpen:Z,nextProbeInMs:Z?Math.max(0,ge-i):0,batchCap:pe}:null}}async function ir(){if(!m)return;let i;try{i=await m()}catch(u){T.error("[plane-link] metrics sample failed:",u?.message||u);return}let l=null;try{l=S?.()??null}catch{}i&&F({v:j,ch:"ctl",type:"metrics",metrics:{...i,planeLink:sr(),...l?{delivery:l}:{}}})}function ls(){m&&(ie&&clearInterval(ie),ir(),ie=setInterval(ir,O),ie.unref?.())}async function us(){let i;try{i=await s()}catch(l){T.error("[plane-link] backfill listTracks failed:",l?.message||l);return}F({v:j,ch:"ctl",type:"tracks",ids:i.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of i)if(!X||!await ar(l))return}async function ar(i){let l;try{l=await Et(i)}catch{return!0}let u=ne[i.id]??0,o=l.filter(c=>c.seq>u&&typeof c.id=="string");for(let c=0;c<o.length;){if(!await ss(i.id))return!1;let h=o.slice(c,c+en()).map(y=>({trackId:i.id,event:y}));if(!Pe(h))return!1;c+=h.length}return!0}let an=new Map;async function cr(i,l){if(an.get(i)===l)return!1;an.set(i,l);let u=null;try{u=(await s()).find(y=>y?.id===i)??null}catch{return!1}if(!u)return!1;let o;try{o=await Et(u)}catch{return!1}let c=[...o].reverse().find(y=>(y?.type==="track.transferred"||y?.type==="track.recovered")&&y.payload?.toNode===n);if(!c||!Number.isFinite(c.seq))return!1;let h=c.seq-1;return(ne[i]??0)>h&&(ne[i]=h,tr()),(ee[i]??0)>h&&(ee[i]=h),T.log(`[plane-link] re-sending ${i}'s move-commit (seq ${c.seq}, ${c.type}) \u2014 the plane's move record predates this node's adoption`),X?ar(u):!1}function lr(i){!X||!i?.trackId||typeof i.id!="string"||(oe.push({trackId:i.trackId,event:i}),q||(q=setTimeout(sn,Co),q.unref?.()))}let tt=new Map;async function ds(i){let{reqId:l,method:u,path:o,headers:c={},body:h}=i,y=Object.fromEntries(Object.entries(c).filter(([,L])=>L!=null)),_=new AbortController;tt.set(l,_);try{if(i.host){await ps(i,y,_);return}k&&(y["x-bostrat-token"]=k);let L=await fetch(A+o,{method:u,headers:y,body:h?Buffer.from(h,"base64"):void 0,signal:_.signal}),te=Object.fromEntries(L.headers);for(let G of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete te[G];if(te["content-type"]||(te["content-type"]="application/octet-stream"),F({v:j,ch:"control",type:"http_head",reqId:l,status:L.status,headers:te}),L.body){for await(let G of L.body)if(!F({v:j,ch:"control",type:"http_data",reqId:l,data:Buffer.from(G).toString("base64")}))break}F({v:j,ch:"control",type:"http_end",reqId:l,error:null})}finally{tt.delete(l)}}function ps(i,l,u){let{reqId:o,method:c,path:h,body:y}=i,_=new URL(A);return new Promise(L=>{let te=Yi.request({host:_.hostname,port:_.port,method:c,path:h,headers:{...l,host:i.host},signal:u.signal},G=>{let{connection:St,"keep-alive":_e,"transfer-encoding":pr,upgrade:cc,...fs}=G.headers;F({v:j,ch:"control",type:"http_head",reqId:o,status:G.statusCode||502,headers:fs}),G.on("data",hs=>{F({v:j,ch:"control",type:"http_data",reqId:o,data:Buffer.from(hs).toString("base64")})||G.destroy()}),G.on("end",()=>{F({v:j,ch:"control",type:"http_end",reqId:o,error:null}),L()}),G.on("error",()=>{F({v:j,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),L()})});te.on("error",G=>{F({v:j,ch:"control",type:"http_end",reqId:o,error:G?.message||"view request failed"}),L()}),y&&te.write(Buffer.from(y,"base64")),te.end()})}function ur(){if(Yt||Qe)return;Y=new En(e,{headers:{authorization:`Bearer ${t}`}});let i=Y;Te=0,i.on("ping",()=>{Te=Date.now()}),i.on("pong",()=>{Te=Date.now()}),Y.on("open",async()=>{let u=null;try{u=await a?.()||null}catch{u=null}F({v:j,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:Q,installKind:x,...typeof g=="function"?{updatePolicy:g()}:g?{updatePolicy:g}:{},providers:Fo(),...u?{agents:u}:{},...Xt?{restart:Xt}:{}})}),Y.on("message",u=>{Te=Date.now();let o;try{o=JSON.parse(u)}catch{return}if(o.ch==="ctl"&&o.type==="hello_ok"){an.clear(),X=!0,Je=Io,Ze=null,Xt=null,br(),T.log(`[plane-link] connected to plane as ${n}`);try{wt?.()}catch{}if(typeof o.hashKey=="string"&&o.hashKey)try{p?.(o.hashKey)}catch{}try{w?.(typeof o.viewBase=="string"&&o.viewBase?o.viewBase:null)}catch{}o.minNodeVersion&&Q&&He(Q,o.minNodeVersion)&&T.error(`[plane-link] this node is bostrat-node ${Q}; the plane asks for \u2265${o.minNodeVersion} \u2014 update with: ${ht(x)}`);try{$?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}Yn(o);let c=o.ingest==="http";H=Oe==="ws"?"ws":Oe==="http"||c?"http":"ws",Oe==="http"&&!c&&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"),Z=!1,ge=0,pe=Dt,se&&clearInterval(se),Te=Date.now(),se=setInterval(()=>{os(i)||(F({v:j,ch:"ctl",type:"ping"}),or(),cs().catch(()=>{}),on(),oe.length&&!q&&sn())},Ve),se.unref?.(),ls(),us().catch(h=>T.error("[plane-link] backfill failed:",h?.message||h));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let c=typeof o.minNodeVersion=="string"?o.minNodeVersion:null,h=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;T.error(`[plane-link] plane REFUSED this node: bostrat-node ${Q??"?"} is below its minimum ${c??"?"} \u2014 ${o.fix||ht(x)}`),Je=Po,Ze=0;try{v?.({current:Q,min:c,latest:h,fix:o.fix||ht(x),installKind:x})}catch(y){T.error(`[plane-link] refusal handler failed: ${y?.message||y}`)}return}if(o.ch==="ctl"&&o.type==="removed"){F({v:j,ch:"ctl",type:"removed_ack",nodeId:n}),Zt({reason:typeof o.reason=="string"?o.reason:"removed",at:Number(o.at)||Date.now(),via:"ctl"});return}if(o.ch==="ctl"&&o.type==="update_available"){Yn(o);return}if(o.ch==="ctl"&&o.type==="update_policy"){try{$?.(typeof o.mode=="string"?o.mode:null)}catch{}return}if(o.ch==="ctl"&&o.type==="conflict_probe"&&Array.isArray(o.trackIds)){try{N?.(o.trackIds.filter(c=>typeof c=="string"&&c).slice(0,200))}catch{}return}if(o.ch==="ctl"&&o.type==="restarted"){Promise.resolve().then(()=>P?.({kind:o.kind,at:o.at,reason:o.reason})).catch(c=>T.error("[plane-link] restart notice failed:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="usage_caps"){No(o.caps??{},{source:"plane",updatedAt:o.updatedAt??Date.now()}).then(c=>T.log(`[plane-link] spend caps ${Object.keys(c.caps).length?`updated (${Object.keys(c.caps).join(", ")})`:"cleared"} from plane`)).catch(c=>T.error("[plane-link] spend-caps push rejected:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="transferred"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>d?.(o.tracks)).then(async c=>{for(let h of Array.isArray(c)?c:[])h?.stale&&h.id&&await cr(h.id,h.since??null)}).catch(c=>T.error("[plane-link] transfer notice failed:",c?.message||c));return}if(o.ch==="ctl"&&o.type==="moves"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>f?.(o.tracks)).then(async c=>{for(let h of Array.isArray(c)?c:[])h?.stale&&h.id&&await cr(h.id,h.since??null)}).catch(c=>T.error("[plane-link] move-record reconcile failed:",c?.message||c));return}if(o.ch==="events"&&o.type==="ack"&&Array.isArray(o.ids)){nn(o.ids);return}if(o.ch==="events"&&o.type==="nack"&&Array.isArray(o.ids)){rn(o.ids,o.reason,o.permanent===!0,o.retryAfterMs??null);return}if(o.ch==="control"&&o.type==="http_open"){ds(o).catch(c=>F({v:j,ch:"control",type:"http_end",reqId:o.reqId,error:c?.message||"tunnel error"}));return}if(o.ch==="control"&&o.type==="http_cancel"){tt.get(o.reqId)?.abort();return}if(o.ch==="attach"&&o.type==="open"){let c=new En(es+o.path,Array.isArray(o.protocols)?o.protocols:[],o.host?{headers:{host:o.host}}:void 0);we.set(o.streamId,c),ye.set(o.streamId,[]),c.on("open",()=>{let y=ye.get(o.streamId)||[];ye.delete(o.streamId);for(let{buf:_,bin:L}of y)c.send(_,{binary:L})}),c.on("message",(y,_)=>{let L=_?y:Buffer.from(String(y));F({v:j,ch:"attach",type:"data",streamId:o.streamId,data:L.toString("base64"),..._?{bin:!0}:{}})});let h=()=>{ye.delete(o.streamId),we.delete(o.streamId)&&F({v:j,ch:"attach",type:"close",streamId:o.streamId})};c.on("close",h),c.on("error",h);return}if(o.ch==="attach"&&o.type==="data"){let c=we.get(o.streamId);if(!c)return;let h=Buffer.from(o.data,"base64"),y=o.bin===!0,_=ye.get(o.streamId);_?_.push({buf:h,bin:y}):c.send(h,{binary:y});return}if(o.ch==="attach"&&o.type==="close"){let c=we.get(o.streamId);we.delete(o.streamId),ye.delete(o.streamId),c?.close();return}});let l=()=>{X&&T.log("[plane-link] disconnected from plane"),X=!1,se&&(clearInterval(se),se=null),ie&&(clearInterval(ie),ie=null),B.clear(),ee={},oe=[],q&&(clearTimeout(q),q=null),Ne.clear();for(let c of we.values())c.close();we.clear(),ye.clear();for(let c of tt.values())c.abort();if(tt.clear(),Yt||Me)return;Ze==null&&(Ze=Date.now());let u=Date.now()-Ze<Ji,o=Math.max(u?Zi+Math.random()*Qi:Je,Xe-Date.now(),it());Me=setTimeout(()=>{Me=null,ur()},o),Me.unref?.(),u||(Je=Math.min(Je*2,Po))};Y.on("close",l),Y.on("error",u=>{let o=/Unexpected server response: (\d+)/.exec(u?.message||"")?.[1];if(o==="410"){Zt({reason:"removed",via:"410"});return}if(o==="401"||o==="403"){let{tripped:c,holdMs:h}=kt();c?T.error(`[plane-link] holding every plane call for ${Math.round(h/6e4)} min \u2014 three credential refusals in a row (HTTP ${o}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(h/6e4)} min.`):Date.now()-Tt>=Do&&(Tt=Date.now(),T.error(`[plane-link] plane refused this node's credentials (HTTP ${o}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`))}l()})}ct.on("event",lr),ts().then(ur);function dr({bye:i=!0}={}){Yt=!0,ct.off("event",lr),Me&&clearTimeout(Me),Ie&&clearTimeout(Ie),se&&clearInterval(se),ie&&clearInterval(ie),q&&clearTimeout(q),i&&F({v:j,ch:"ctl",type:"bye",reason:"shutdown"}),Y?.close()}return{stop:()=>dr(),status:()=>({connected:X,nodeId:n,cursor:{...ne},inflight:B.size,...sr(),auth:vr(),dormant:Qe,removed:yn(),deadLinkMs:M,deadLinkRedials:er,refused:{...gt}}),_tick:()=>{or(),on()}}}var Q,Mn,Pn,j,Io,Po,Ji,Zi,Qi,Dt,ea,ta,na,ra,Bn,oa,Rn,sa,ia,aa,Bo,ca,Co,la,Nn,ua,da,Do,Cn=R(()=>{Rt();Mo();un();gn();Q=(()=>{try{return Xi(import.meta.url)("../package.json").version||null}catch{return null}})(),Mn=process.env.BOSTRAT_STATE_DIR||W.join(process.env.HOME||Lt.tmpdir(),".bostrat"),Pn=W.join(Mn,"plane-link","removed.json");j=1,Io=1e3,Po=3e4,Ji=6e4,Zi=1500,Qi=500,Dt=100,ea=2e3,ta=25e3,na=2.5,ra=6e4,Bn=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},oa=Bn(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Rn="refused:",sa={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"},ia=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},aa=3e4,Bo=10*6e4,ca=400,Co=250,la=Bn(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Nn=4,ua=Math.max(1,Math.round(Bn(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),da=6e4,Do=6e4});var Uo=R(()=>{hn()});var Vo={};cn(Vo,{ACTIONABLE_KINDS:()=>Wt,INSTALL_ATTEMPTS:()=>Ft,INSTALL_RETRY_STEP_S:()=>Ho,REGISTRY_RETRY_ATTEMPTS:()=>Fn,REGISTRY_WAIT_POLLS:()=>Dn,REGISTRY_WAIT_STEP_S:()=>Ln,RESTART_SIGNAL:()=>Ko,SELF_UPDATE_DIR:()=>Ut,SUPERVISOR_PID_FILE:()=>Wo,createAutoUpdater:()=>ka,inFlight:()=>Wn,readStatus:()=>Hn,restartCommand:()=>Go,restartStrategy:()=>Un,selfUpdatePlan:()=>qo,settleSelfUpdate:()=>Aa,startSelfUpdate:()=>zo,underService:()=>jn,updatePolicy:()=>Sa});import mt from"node:fs";import he from"node:fs/promises";import fa from"node:os";import U from"node:path";import{spawn as ha,execFileSync as ma}from"node:child_process";import{createRequire as wa}from"node:module";function Sa({kind:e=We(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:Wt.has(e)?e==="git-checkout"||jn(t)?"auto":"prompt":"off"}function jn(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Un({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:s=Wo,readFile:a=f=>mt.readFileSync(f,"utf8"),alive:d=_a}={}){let f=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(jn(e))return f;let m=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(m)&&m>0)){try{m=Number(String(a(s)).trim())}catch{m=NaN}Number.isInteger(m)&&m>0&&d(m)||(m=NaN)}return Number.isInteger(m)&&m>0?{mode:"supervisor",pid:m}:f}function _a(e){try{process.kill(e,0)}catch{return!1}try{let t=ma("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 Go(e){switch(e?.mode){case"systemd":return`systemctl --user restart ${J(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 -${Ko.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function qo({kind:e,to:t,from:n=jt,statusFile:r=Ht,logFile:s=U.join(Ut,"last.log"),port:a=Number(process.env.PORT)||3362,npmPrefix:d=null,serviceName:f=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:m=typeof process.getuid=="function"?process.getuid():0,restart:S=Un({env:{},platform:process.platform,uid:m,serviceName:f,readFile:()=>{throw new Error("no pidfile")}}),liveDir:p=process.env.BOSTRAT_LIVE_CHECKOUT||U.resolve(U.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:w=Date.now(),attempts:O=1}={}){if(!Wt.has(e))throw new Error(`self-update: install kind "${e}" is not actionable here`);if(!/^\d+\.\d+\.\d+$/.test(String(t)))throw new Error(`self-update: bad target version "${t}"`);if(n&&!/^\d+\.\d+\.\d+$/.test(String(n)))throw new Error(`self-update: bad current version "${n}"`);let b=(v,g="")=>`write_status ${J(v)} ${g}`,$=Go(S),N=`
124
+ `),h(0)}var Uo,za,Ln,jt,qo=O(()=>{Uo="wss://plane.bostrat.ai/v1/node",za=Ka(import.meta.url)("../package.json").version,Ln=`ghcr.io/globocodes/bostrat-node:${za}`;jt=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let i=Wa("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(c,p,h)=>c?o(Object.assign(c,{stdout:p,stderr:h})):r({stdout:p,stderr:h}));t!=null&&i.stdin?.end(t)})});function Vo(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!Xa.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let r=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(r))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return r}function Ja(e){let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||r.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=r.map(o=>({...o,fromMs:Vo(o.from,"from",n),toMs:Vo(o.to,"to",n)}))}return t}var Ya,Xa,qp,Vp,Yo=O(()=>{Ya={"claude-opus-5-5":[{from:null,to:null,input:4,output:20,cacheWrite:8,cacheRead:.2,cacheReadX:.05,fast:{input:8,output:40,cacheWrite:16,cacheRead:.4},verifiedAt:"2026-09-28",note:"verified 2026-09-28 against platform.claude.com/docs/en/about-claude/pricing: $4/$20, 1h cache write $8 (2\xD7), cache hits $0.20 (0.05\xD7 \u2014 footnote 2), fast $8/$40; added before any fleet turn was recorded."}],"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-10-05",note:"GA rates; verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"claude-sonnet-5-5":[{from:null,to:"2026-10-11",input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.20 (0.1\xD7 \u2014 footnote 2 then named Opus 5.5 only). Superseded 2026-10-12 when the page moved Sonnet 5.5 hits to 0.05\xD7 (window below)."},{from:"2026-10-12",to:null,input:2,output:10,cacheWrite:4,cacheRead:.1,cacheReadX:.05,verifiedAt:"2026-10-12",note:"verified 2026-10-12 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.10 (0.05\xD7 \u2014 footnote 2 now names Opus 5.5 AND Sonnet 5.5; the prompt-caching multiplier table agrees)."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",note:"$2/$10 is the standard price (intro pricing made permanent; the 2026-09-01 $3/$15 increase was cancelled) \u2014 verified 2026-08-17 against platform.claude.com/docs/en/about-claude/pricing; re-verified 2026-10-05 (live pricing page, footnote 3 still published)."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-haiku-5-5":[{from:null,to:null,input:.1,output:.5,cacheWrite:.2,cacheRead:.01,long:{over:1e5,input:.5,output:2.5,cacheWrite:1,cacheRead:.05},verifiedAt:"2026-10-19",note:"verified 2026-10-19 against platform.claude.com/docs/en/about-claude/pricing: prompts up to 100,000 tokens $0.10/$0.50, 1h cache write $0.20 (2\xD7), cache hits $0.01 (0.1\xD7); prompts over 100,000 tokens (the `long` variant) $0.50/$2.50, 1h cache write $1 (2\xD7), cache hits $0.05 (0.1\xD7); added before any fleet turn was recorded."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-fable-5-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-09-07",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend then; re-verified 2026-10-05 (live pricing page: $10/$50, 1h write $20, hits $1 at 0.1\xD7)."}],"gpt-5.5-pro":[{from:null,to:null,input:30,output:180,cacheWrite:30,cacheRead:30,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $30 in / $180 out, no cached-input or cache-write price published (both priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5-cyber":[{from:null,to:null,input:12.5,output:75,cacheWrite:12.5,cacheRead:1.25,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing, Cyber models table): $12.50 in / $1.25 cached / $75 out, no cache-write price published (priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-10-05",note:"verified 2026-07-03, re-verified 2026-08-17 and 2026-10-05 (developers.openai.com pricing: $5 / $0.50 cached / $30); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-10-12",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL); re-verified 2026-10-12 (live pricing page: $4 / $0.40 cached / $5 cache writes / $20, promo note unchanged)."}],"gpt-5.6-terra":[{from:null,to:"2026-08-16",input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:2,output:12,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:"2026-08-16",input:1,output:6,cacheWrite:1.25,cacheRead:.1,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:.2,output:1.2,cacheWrite:.25,cacheRead:.02,verifiedAt:"2026-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-09-07",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed)."}],"gpt-6.1-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.10 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.20 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-luna":[{from:null,to:null,input:.1,output:.5,cacheWrite:.125,cacheRead:.01,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $0.10 in / $0.01 cached / $0.125 cache writes (1.25\xD7) / $0.50 out; added before any fleet turn was recorded."}]},Xa=/^\d{4}-\d{2}-\d{2}$/;qp=Ja(Ya),Vp=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var Xo=O(()=>{Yo()});import Jo from"node:fs/promises";import es from"node:path";import Za from"node:os";function ns(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function rs(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function os(e){let t=new Date(ns(e));return t.setDate(t.getDate()+7),t.getTime()}function ss(e){let t=new Date(rs(e));return t.setMonth(t.getMonth()+1),t.getTime()}function rc(e=Date.now()){for(let[t,n]of Object.entries(tc)){let r=n.startOf(e);if(r!==Ut[t]){Ut[t]=r;for(let o of Fn.values())o[t]=0;for(let o of Zo)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&Zo.delete(o)}}}function oc(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let o={};for(let i of["weeklyUsd","monthlyUsd"]){let c=r?.[i];if(c==null||c==="")continue;let p=Number(c);if(!Number.isFinite(p)||p<=0)throw new Error(`${n}.${i} must be a positive number or null`);o[i]=p}Object.keys(o).length&&(t[n]=o)}return t}async function is(e,{source:t="local",updatedAt:n=Date.now()}={}){He={caps:oc(e),updatedAt:n,source:t};try{await Jo.mkdir(ts,{recursive:!0}),await Jo.writeFile(Qa(),JSON.stringify(He,null,2))}catch{}return sc()}function sc(e=Date.now()){rc(e);let t=new Set([...Fn.keys(),...Object.keys(He?.caps||{})]),n={};for(let r of t){let o=Fn.get(r);n[r]={weeklyUsd:Qo(o?.weekly||0),monthlyUsd:Qo(o?.monthly||0)}}return{caps:He?.caps||{},configured:!!He,seeded:nc,updatedAt:He?.updatedAt??null,spent:n,windows:{weekly:{start:Ut.weekly,resetsAt:os(e)},monthly:{start:Ut.monthly,resetsAt:ss(e)}},warnPct:ec}}var ts,Qa,ec,tc,He,nc,Ut,Fn,Zo,Qo,as=O(()=>{Dt();Xo();ts=process.env.BOSTRAT_STATE_DIR||es.join(process.env.HOME||Za.tmpdir(),".bostrat"),Qa=()=>es.join(ts,"usage-caps.json"),ec=.8;tc={weekly:{startOf:ns,nextStart:os,capKey:"weeklyUsd"},monthly:{startOf:rs,nextStart:ss,capKey:"monthlyUsd"}},He=null,nc=!1,Ut={weekly:0,monthly:0},Fn=new Map,Zo=new Set;Qo=e=>Math.round(e*1e4)/1e4});import cs from"node:fs/promises";import ds from"node:path";import ic from"node:os";function cc(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 jn))throw new Error(`unknown refresh-flow field "${n}" \u2014 fields: ${fs.join(", ")}`);if(r===null||r===""||r===void 0){t[n]=null;continue}switch(n){case"contextFull":case"limitHit":if(typeof r!="string"||!ls.includes(r))throw new Error(`${n} must be one of ${ls.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[i,c]of Object.entries(r)){if(!us.test(i))throw new Error(`bad provider key "${i}" in fallback`);if(!Array.isArray(c)||c.some(h=>typeof h!="string"||!us.test(h)))throw new Error(`fallback.${i} must be a list of provider keys`);let p=[...new Set(c.filter(h=>h!==i))];p.length&&(o[i]=p)}t[n]=Object.keys(o).length?o:null;break}default:throw new Error(`unknown refresh-flow field "${n}"`)}}return t}function lc(e){let t={...jn};for(let n of fs){let r=e?.[n];r!=null&&(t[n]=r)}return t}function dc(){return lc(We?.flow)}function hs(){return{flow:dc(),configured:!!We,source:We?.source??null,updatedAt:We?.updatedAt??null}}async function pc(){try{await cs.mkdir(ps,{recursive:!0}),await cs.writeFile(ac(),JSON.stringify(We,null,2))}catch{}}function ms(e=null){for(let t of uc)try{t(hs(),e)}catch{}}function ws(e){ms({rejected:String(e||"rejected by the plane")})}async function gs(e,{source:t="plane",updatedAt:n=Date.now()}={}){return We={flow:cc(e||{}),updatedAt:n,source:t},await pc(),ms(),hs()}var ps,ac,ls,jn,fs,us,We,uc,ys=O(()=>{ps=process.env.BOSTRAT_STATE_DIR||ds.join(process.env.HOME||ic.tmpdir(),".bostrat"),ac=()=>ds.join(ps,"refresh-flow.json"),ls=["prompt","auto","off"],jn=Object.freeze({contextFull:"prompt",contextFullPct:75,contextFullTokens:null,limitHit:"prompt",fallback:null}),fs=Object.keys(jn),us=/^[a-z][a-z0-9-]{0,31}$/;We=null,uc=new Set});var xs={};fn(xs,{REMOVED_MARKER:()=>zn,detectInstallKind:()=>ze,detectProviderAuth:()=>ks,maskToken:()=>Gn,readRemovedMarker:()=>$s,startPlaneLink:()=>Rc,updateCommandFor:()=>yt,versionLt:()=>Ge});import Ke from"node:fs";import gt from"node:fs/promises";import fc from"node:http";import W from"node:path";import Wt from"node:os";import{createRequire as hc}from"node:module";import Un from"ws";function Gn(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function $s(e=zn){try{let t=JSON.parse(Ke.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function ze({env:e=process.env,pkgDir:t=W.resolve(W.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ke.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(W.join(t,"..",".git"))?"git-checkout":"dev"}function Ge(e,t){let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let o=0;o<Math.max(n.length,r.length);o++){let i=(n[o]||0)-(r[o]||0);if(i)return i<0}return!1}function yt(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 ks({home:e=process.env.HOME||Wt.homedir(),env:t=process.env}={}){let n=r=>{try{return Ke.statSync(r),!0}catch{return!1}};return{claude:n(W.join(e,".claude",".credentials.json")),codex:n(W.join(t.CODEX_HOME||W.join(e,".codex"),"auth.json")),cursor:n(W.join(t.XDG_CONFIG_HOME||W.join(e,".config"),"cursor","auth.json"))}}function Rc({url:e,token:t,nodeId:n=Wt.hostname(),name:r=Wt.hostname(),listTracks:o,detectAgents:i=null,onTracksTransferred:c=null,onTracksMoves:p=null,sampleMetrics:h=null,deliverySample:m=null,onHashKey:f=null,onViewBase:g=null,metricsMs:E=Oc,onUpdateAvailable:_=null,onUpdatePolicy:$=null,onConflictProbe:N=null,restart:R=null,onRestarted:D=null,onHelloRefused:v=null,updatePolicy:T=null,installKind:k=ze(),selfUrl:x=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:A=null,removedMarkerFile:I=zn,onRemoved:Ee=null,onDegraded:Ye=null,onRecovered:Oe=null,onRefused:Xt=null,onConnected:Tt=null,ingestMode:Re=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:Xe=_c,unackedRetryMs:Ne=Sc,pingMs:Je=bc,deadLinkMs:M=Math.round(Je*Tc),maxInflightEvents:le=xc,httpTimeoutMs:ue=Ac,fanoutActive:de=null,fanoutBatchCap:Ze=Ec,stallBackoffMinMs:or=kc,fetchImpl:sr=globalThis.fetch,log:b=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=st(e);let js=x.replace(/^http/,"ws"),ir=new Set,ar=a=>{let u=typeof a.latestNodeVersion=="string"?a.latestNodeVersion:null;if(!(!(u&&ee&&Ge(ee,u))||ir.has(u))){ir.add(u),b.log(`[plane-link] bostrat-node ${u} is available (this node runs ${ee}) \u2014 ${yt(k)}`);try{_?.({current:ee,latest:u,min:a.minNodeVersion??null,installKind:k,required:!!(a.minNodeVersion&&Ge(ee,a.minNodeVersion))})}catch(d){b.error(`[plane-link] update notice failed: ${d?.message||d}`)}}},ge=new Map,ye=new Map,Jt=W.join(Kn,"plane-link","cursor.json"),Zt=W.join(Kn,"plane-link","dead-letter.ndjson"),cr=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),re={},te={},C=new Map,St=null,pe=null,oe=0,Qe=0,lr=0,_t={},ur=new Set,dr=Promise.resolve(),H="ws",Me=0,Q=!1,be=0,Qt=!1,fe=Ht,Ie=new Set,se=[],q=null,Y=null,X=!1,en=!1,et=bs,tt=null,tn=R&&typeof R=="object"?R:null,Pe=null,De=null,ie=null,Te=0,pr=0,ae=null,nn=!1,vt=0,nt=!1,he=$s(I);if(he)if(he.tokenPreview===Gn(t))nt=!0,An({reason:he.reason??"removed",at:he.at??null,nodeId:he.nodeId??n}),b.error(`[plane-link] this node was REMOVED from the plane (${he.reason??"removed"}${he.at?` at ${new Date(he.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${I} to force a dial.`);else try{Ke.unlinkSync(I),b.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function rn({reason:a="removed",at:u=Date.now(),via:d="ctl"}={}){if(!nt){nt=!0,An({reason:a,at:u,nodeId:n,via:d});try{Ke.mkdirSync(W.dirname(I),{recursive:!0}),Ke.writeFileSync(I,JSON.stringify({at:u,reason:a,via:d,nodeId:n,tokenPreview:Gn(t)},null,2))}catch(s){b.error(`[plane-link] could not write ${I}: ${s?.message||s}`)}b.error(`[plane-link] the plane REMOVED this node (${a}, via ${d}) \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{Ee?.({reason:a,at:u,via:d})}catch{}vr({bye:!1})}}async function Us(){try{re=JSON.parse(await gt.readFile(Jt,"utf8"))}catch{re={}}}function fr(){nn=!0,!De&&(De=setTimeout(async()=>{if(De=null,!!nn){nn=!1;try{await gt.mkdir(W.dirname(Jt),{recursive:!0}),await gt.writeFile(Jt,JSON.stringify(re))}catch(a){b.error("[plane-link] cursor flush failed:",a?.message||a)}}},yc),De.unref?.())}function on(){try{return!!de?.()}catch{return!1}}function sn(){let a=H==="http"?fe:Ht;return on()?Math.min(a,Ze):a}function L(a){return!Y||Y.readyState!==Un.OPEN?!1:(Y.send(JSON.stringify(a)),!0)}function Ce(a){let u=Date.now();for(let{trackId:s,event:l}of a){let w=C.get(l.id);C.set(l.id,{trackId:s,seq:l.seq,event:l,sentAt:u,firstSentAt:w?.firstSentAt??u,retryAt:u+Ne,tries:(w?.tries??0)+1,nacks:w?.nacks??0})}let d=a.map(({trackId:s,event:l})=>({trackId:s,event:$c(l)}));return H==="http"?(qs(d),!0):L({v:j,ch:"events",type:"append",events:d})}function Hs(a){let u=null;for(let d of C.values())d.trackId===a&&(u==null||d.seq<u)&&(u=d.seq);return u}function an(a){let u=te[a];if(u==null)return;let d=Hs(a),s=d==null?u:Math.min(u,d-1);s>(re[a]??0)&&(re[a]=s,fr())}function rt(){if(St=Date.now(),pe!=null){let a=Date.now()-pe;b.log(`[plane-link] spine sync recovered after ${Math.round(a/1e3)}s degraded (${oe} stall redial(s))`);let u=pe;pe=null,oe=0,Qe=0,Q=!1,be=0;try{Oe?.({since:u,downMs:a})}catch(d){b.error(`[plane-link] onRecovered failed: ${d?.message||d}`)}}}function cn(a){if(!Array.isArray(a)||!a.length)return;let u=new Set;for(let d of a){let s=C.get(d);s&&(C.delete(d),(te[s.trackId]??0)<s.seq&&(te[s.trackId]=s.seq),u.add(s.trackId))}for(let d of u)an(d);rt()}function hr(a,u){lr++;let d={at:Date.now(),trackId:a.trackId,seq:a.seq,id:a.event?.id??null,type:a.event?.type??null,reason:u,event:a.event??null};b.error(`[plane-link] DEAD-LETTER ${a.trackId} seq ${a.seq} (${d.type??"?"}): plane rejected it permanently (${u}) \u2014 kept in ${Zt}`),dr=dr.then(async()=>{await gt.mkdir(W.dirname(Zt),{recursive:!0}),await gt.appendFile(Zt,JSON.stringify(d)+`
125
+ `)}).catch(s=>b.error(`[plane-link] dead-letter write failed: ${s?.message||s}`))}function Ws(a,u){if(_t[a]=(_t[a]??0)+1,ur.has(a))return;ur.add(a);let d=vc[a]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";b.error(`[plane-link] REFUSED by the plane (${a}) on track ${u}: events are being dropped, not stored \u2014 ${d}`);try{Xt?.({reason:a,trackId:u,count:_t[a],hint:d})}catch(s){b.error(`[plane-link] onRefused failed: ${s?.message||s}`)}}function ln(a,u,d,s=null){if(!Array.isArray(a)||!a.length)return;let l=new Set,w=Date.now();for(let y of a){let S=C.get(y);S&&(d?(C.delete(y),hr(S,u),String(u).startsWith(Hn)&&Ws(String(u).slice(Hn.length),S.trackId),(te[S.trackId]??0)<S.seq&&(te[S.trackId]=S.seq),l.add(S.trackId)):(S.nacks++,S.retryAt=w+Math.max(1e3,Number(s)||Ne)))}for(let y of l)an(y);rt()}function mr(a=Date.now()){let u=1/0;for(let d of C.values())d.firstSentAt<u&&(u=d.firstSentAt);return u===1/0?0:a-u}function Ks(a){if(!M||!a||a!==Y||!Te)return!1;let u=Date.now()-Te;if(u<=M)return!1;pr++,b.error(`[plane-link] no frame from the plane for ${Math.round(u/1e3)}s \u2014 link is half-open; terminating and redialing`);try{a.terminate()}catch{}return!0}function wr(){if(!X||!C.size)return;let a=Date.now(),u=mr(a);if(u<Xe||St!=null&&a-St<Xe||H==="http"&&Q||Qe>a)return;oe++;let d=Math.min(or*2**(oe-1),Ss);if(pe==null){pe=a-u,b.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(u/1e3)}s with ${C.size} event(s) in flight (${H} door) \u2014 the plane is not answering appends`);try{Ye?.({since:pe,unacked:C.size,oldestAgeMs:u,mode:H})}catch(s){b.error(`[plane-link] onDegraded failed: ${s?.message||s}`)}}if(H==="http"){Q=!0,be=a+d,b.error(`[plane-link] ingest circuit OPEN (stall #${oe}); probing /v1/ingest/health in ${Math.round(d/1e3)}s`);return}Qe=a+d,b.error(`[plane-link] closing the link and redialing in ${Math.round(d/1e3)}s (stall redial #${oe})`);try{Y?.terminate()}catch{}}function un(){if(!X)return;let a=Date.now();if(H==="http"&&Q)return;let u=[...C.values()].filter(s=>s.event&&s.retryAt<=a&&!(H==="http"&&Ie.has(s.trackId)));if(!u.length)return;u.sort((s,l)=>s.trackId===l.trackId?s.seq-l.seq:s.trackId<l.trackId?-1:1),b.log(`[plane-link] re-sending ${u.length} unacked event(s) the plane never confirmed`);let d=sn();if(H==="http"){let s=new Map;for(let l of u)(s.get(l.trackId)??s.set(l.trackId,[]).get(l.trackId)).push(l);for(let[,l]of s){if(Me>=Wn)return;Ce(l.slice(0,d).map(w=>({trackId:w.trackId,event:w.event})))}return}for(let s=0;s<u.length;s+=d){let l=u.slice(s,s+d).map(w=>({trackId:w.trackId,event:w.event}));if(!Ce(l))return}}async function Gs(a=null){for(;;){if(!X)return!1;let u=C.size<le,d=H!=="http"||Me<Wn&&!Q&&(!a||!Ie.has(a));if(u&&d)return!0;await new Promise(s=>setTimeout(s,100))}}function dn(){if(q=null,!X||!se.length)return;let a=se;se=[];let u=sn();if(H!=="http"){for(let l=0;l<a.length;l+=u)Ce(a.slice(l,l+u));return}let d=on(),s=new Map;for(let l of a)(s.get(l.trackId)??s.set(l.trackId,[]).get(l.trackId)).push(l);for(let[l,w]of s){if(Ie.has(l)||Me>=Wn||Q){se.push(...w);continue}if(d){Ce(w.slice(0,u)),se.push(...w.slice(u));continue}for(let y=0;y<w.length;y+=u)Ce(w.slice(y,y+u))}se.length&&!q&&(q=setTimeout(dn,_s),q.unref?.())}let zs=a=>{let u=new Map;for(let{trackId:d,event:s}of a)(u.get(d)??u.set(d,[]).get(d)).push(s);return[...u].map(([d,s])=>({trackId:d,events:s}))},Se=(a,u,d,{progress:s})=>{let l=Date.now();for(let{event:w}of a){let y=C.get(w.id);y&&(y.nacks++,y.retryAt=l+Math.max(1e3,d||Ne))}s&&rt()};async function qs(a){let u=new Set(a.map(d=>d.trackId));for(let d of u)Ie.add(d);Me++;try{let d=await sr(`${cr}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:zs(a)}),signal:AbortSignal.timeout(ue)}),s=(Number(d.headers.get("retry-after"))||0)*1e3;if(d.status===200){let l=await d.json();fe=Ht;for(let S of l.results??[]){cn(S.acked??[]);let F=(ne,G)=>{let $t=new Map;for(let _e of ne??[])($t.get(_e.reason)??$t.set(_e.reason,[]).get(_e.reason)).push(_e.id);for(let[_e,$r]of $t)ln($r,_e,G,l.retryAfterMs??null)};F(S.rejected,!0),F(S.deferred,!1)}let w=new Set,y=new Map;for(let S of Array.isArray(l.refused)?l.refused:[])!S||typeof S.id!="string"||(w.add(S.id),(y.get(S.reason)??y.set(S.reason,[]).get(S.reason)).push(S.id));for(let[S,F]of y)ln(F,`${Hn}${S}`,!0);cn((l.discarded??[]).filter(S=>!w.has(S))),rt();return}if(d.status===429){Se(a,"overloaded",s||5e3,{progress:!0});return}if(d.status===413&&a.length>1){fe=Math.max(1,Math.floor(a.length/2)),b.error(`[plane-link] ingest request too large (${a.length} events) \u2014 halving batches to ${fe}`),Se(a,"too_large",1e3,{progress:!0});return}if(d.status===413){let l=C.get(a[0].event.id);l&&(C.delete(l.event.id),hr(l,"too_large"),(te[l.trackId]??0)<l.seq&&(te[l.trackId]=l.seq),an(l.trackId)),rt();return}if(d.status===410){rn({reason:"removed",via:"410"}),Se(a,"http_410",6e4,{progress:!1});return}if(d.status===401||d.status===403){let{tripped:l,holdMs:w}=Mt();if(l&&b.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()-vt>=vs){vt=Date.now();let y="";try{y=(await d.json())?.error??""}catch{}b.error(`[plane-link] plane refused ingest (HTTP ${d.status}${y?`: ${y}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}Se(a,`http_${d.status}`,Math.max(6e4,ut()),{progress:!1});return}if(d.status===400){b.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${a.length} event(s) for retry; this is a bug, not data`),Se(a,"http_400",6e4,{progress:!1});return}Se(a,`http_${d.status}`,s||5e3,{progress:!1})}catch(d){let s=d?.name==="TimeoutError"||d?.name==="AbortError";s&&a.length>1&&(fe=Math.max(1,Math.floor(a.length/2)),b.error(`[plane-link] ingest request of ${a.length} event(s) outlived its ${ue} ms deadline \u2014 halving batches to ${fe}`)),Se(a,s?"timeout":"network",5e3,{progress:!1})}finally{Me--;for(let d of u)Ie.delete(d)}}async function Vs(){if(H!=="http"||!Q||!X||Qt)return;let a=Date.now();if(!(be>a||It(a))){Qt=!0;try{let u=await sr(`${cr}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(ue)});if(!u.ok)throw new Error(`HTTP ${u.status}`);b.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Q=!1,be=0,Qe=Date.now()+ue+Ne+1e3;for(let d of C.values())d.retryAt=Math.min(d.retryAt,Date.now());un()}catch(u){oe++;let d=Math.min(or*2**(oe-1),Ss);be=Date.now()+d,b.error(`[plane-link] ingest door still not answering (${u?.message||u}); next probe in ${Math.round(d/1e3)}s`)}finally{Qt=!1}}}function gr(){let a=Date.now();return{mode:H,unacked:C.size,oldestUnackedAgeMs:mr(a),lastProgressAt:St,degradedSince:pe,stallRedials:oe,deadLettered:lr,fanoutCap:on()?Ze:null,http:H==="http"?{inFlight:Me,circuitOpen:Q,nextProbeInMs:Q?Math.max(0,be-a):0,batchCap:fe}:null}}async function yr(){if(!h)return;let a;try{a=await h()}catch(d){b.error("[plane-link] metrics sample failed:",d?.message||d);return}let u=null;try{u=m?.()??null}catch{}a&&L({v:j,ch:"ctl",type:"metrics",metrics:{...a,planeLink:gr(),...u?{delivery:u}:{}}})}function Ys(){h&&(ae&&clearInterval(ae),yr(),ae=setInterval(yr,E),ae.unref?.())}async function Xs(){let a;try{a=await o()}catch(u){b.error("[plane-link] backfill listTracks failed:",u?.message||u);return}L({v:j,ch:"ctl",type:"tracks",ids:a.filter(u=>!u.transferredTo).map(u=>u.id).filter(u=>typeof u=="string")});for(let u of a)if(!X||!await br(u))return}async function br(a){let u;try{u=await Pt(a)}catch{return!0}let d=re[a.id]??0,s=u.filter(l=>l.seq>d&&typeof l.id=="string");for(let l=0;l<s.length;){if(!await Gs(a.id))return!1;let w=s.slice(l,l+sn()).map(y=>({trackId:a.id,event:y}));if(!Ce(w))return!1;l+=w.length}return!0}let pn=new Map;async function Tr(a,u){if(pn.get(a)===u)return!1;pn.set(a,u);let d=null;try{d=(await o()).find(y=>y?.id===a)??null}catch{return!1}if(!d)return!1;let s;try{s=await Pt(d)}catch{return!1}let l=[...s].reverse().find(y=>(y?.type==="track.transferred"||y?.type==="track.recovered")&&y.payload?.toNode===n);if(!l||!Number.isFinite(l.seq))return!1;let w=l.seq-1;return(re[a]??0)>w&&(re[a]=w,fr()),(te[a]??0)>w&&(te[a]=w),b.log(`[plane-link] re-sending ${a}'s move-commit (seq ${l.seq}, ${l.type}) \u2014 the plane's move record predates this node's adoption`),X?br(d):!1}function Sr(a){!X||!a?.trackId||typeof a.id!="string"||(se.push({trackId:a.trackId,event:a}),q||(q=setTimeout(dn,_s),q.unref?.()))}let ot=new Map;async function Js(a){let{reqId:u,method:d,path:s,headers:l={},body:w}=a,y=Object.fromEntries(Object.entries(l).filter(([,F])=>F!=null)),S=new AbortController;ot.set(u,S);try{if(a.host){await Zs(a,y,S);return}A&&(y["x-bostrat-token"]=A);let F=await fetch(x+s,{method:d,headers:y,body:w?Buffer.from(w,"base64"):void 0,signal:S.signal}),ne=Object.fromEntries(F.headers);for(let G of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete ne[G];if(ne["content-type"]||(ne["content-type"]="application/octet-stream"),L({v:j,ch:"control",type:"http_head",reqId:u,status:F.status,headers:ne}),F.body){for await(let G of F.body)if(!L({v:j,ch:"control",type:"http_data",reqId:u,data:Buffer.from(G).toString("base64")}))break}L({v:j,ch:"control",type:"http_end",reqId:u,error:null})}finally{ot.delete(u)}}function Zs(a,u,d){let{reqId:s,method:l,path:w,body:y}=a,S=new URL(x);return new Promise(F=>{let ne=fc.request({host:S.hostname,port:S.port,method:l,path:w,headers:{...u,host:a.host},signal:d.signal},G=>{let{connection:$t,"keep-alive":_e,"transfer-encoding":$r,upgrade:Al,...Qs}=G.headers;L({v:j,ch:"control",type:"http_head",reqId:s,status:G.statusCode||502,headers:Qs}),G.on("data",ei=>{L({v:j,ch:"control",type:"http_data",reqId:s,data:Buffer.from(ei).toString("base64")})||G.destroy()}),G.on("end",()=>{L({v:j,ch:"control",type:"http_end",reqId:s,error:null}),F()}),G.on("error",()=>{L({v:j,ch:"control",type:"http_end",reqId:s,error:"view upstream error"}),F()})});ne.on("error",G=>{L({v:j,ch:"control",type:"http_end",reqId:s,error:G?.message||"view request failed"}),F()}),y&&ne.write(Buffer.from(y,"base64")),ne.end()})}function _r(){if(en||nt)return;Y=new Un(e,{headers:{authorization:`Bearer ${t}`}});let a=Y;Te=0,a.on("ping",()=>{Te=Date.now()}),a.on("pong",()=>{Te=Date.now()}),Y.on("open",async()=>{let d=null;try{d=await i?.()||null}catch{d=null}L({v:j,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:ee,installKind:k,...typeof T=="function"?{updatePolicy:T()}:T?{updatePolicy:T}:{},providers:ks(),...d?{agents:d}:{},...tn?{restart:tn}:{}})}),Y.on("message",d=>{Te=Date.now();let s;try{s=JSON.parse(d)}catch{return}if(s.ch==="ctl"&&s.type==="hello_ok"){pn.clear(),X=!0,et=bs,tt=null,tn=null,Jr(),b.log(`[plane-link] connected to plane as ${n}`);try{Tt?.()}catch{}if(typeof s.hashKey=="string"&&s.hashKey)try{f?.(s.hashKey)}catch{}try{g?.(typeof s.viewBase=="string"&&s.viewBase?s.viewBase:null)}catch{}s.minNodeVersion&&ee&&Ge(ee,s.minNodeVersion)&&b.error(`[plane-link] this node is bostrat-node ${ee}; the plane asks for \u2265${s.minNodeVersion} \u2014 update with: ${yt(k)}`);try{$?.(typeof s.updatePolicy=="string"?s.updatePolicy:null)}catch{}ar(s);let l=s.ingest==="http";H=Re==="ws"?"ws":Re==="http"||l?"http":"ws",Re==="http"&&!l&&b.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),H==="http"&&b.log("[plane-link] spine rides the HTTPS ingest door"),Q=!1,be=0,fe=Ht,ie&&clearInterval(ie),Te=Date.now(),ie=setInterval(()=>{Ks(a)||(L({v:j,ch:"ctl",type:"ping"}),wr(),Vs().catch(()=>{}),un(),se.length&&!q&&dn())},Je),ie.unref?.(),Ys(),Xs().catch(w=>b.error("[plane-link] backfill failed:",w?.message||w));return}if(s.ch==="ctl"&&s.type==="hello_refused"){let l=typeof s.minNodeVersion=="string"?s.minNodeVersion:null,w=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;b.error(`[plane-link] plane REFUSED this node: bostrat-node ${ee??"?"} is below its minimum ${l??"?"} \u2014 ${s.fix||yt(k)}`),et=Ts,tt=0;try{v?.({current:ee,min:l,latest:w,fix:s.fix||yt(k),installKind:k})}catch(y){b.error(`[plane-link] refusal handler failed: ${y?.message||y}`)}return}if(s.ch==="ctl"&&s.type==="removed"){L({v:j,ch:"ctl",type:"removed_ack",nodeId:n}),rn({reason:typeof s.reason=="string"?s.reason:"removed",at:Number(s.at)||Date.now(),via:"ctl"});return}if(s.ch==="ctl"&&s.type==="update_available"){ar(s);return}if(s.ch==="ctl"&&s.type==="update_policy"){try{$?.(typeof s.mode=="string"?s.mode:null)}catch{}return}if(s.ch==="ctl"&&s.type==="conflict_probe"&&Array.isArray(s.trackIds)){try{N?.(s.trackIds.filter(l=>typeof l=="string"&&l).slice(0,200))}catch{}return}if(s.ch==="ctl"&&s.type==="restarted"){Promise.resolve().then(()=>D?.({kind:s.kind,at:s.at,reason:s.reason})).catch(l=>b.error("[plane-link] restart notice failed:",l?.message||l));return}if(s.ch==="ctl"&&s.type==="usage_caps"){is(s.caps??{},{source:"plane",updatedAt:s.updatedAt??Date.now()}).then(l=>b.log(`[plane-link] spend caps ${Object.keys(l.caps).length?`updated (${Object.keys(l.caps).join(", ")})`:"cleared"} from plane`)).catch(l=>b.error("[plane-link] spend-caps push rejected:",l?.message||l));return}if(s.ch==="ctl"&&s.type==="refresh_flow"){gs(s.flow??{},{source:"plane",updatedAt:s.updatedAt??Date.now()}).then(l=>b.log(`[plane-link] refresh flow from plane: contextFull=${l.flow.contextFull} rung=${l.flow.contextFullTokens?`${l.flow.contextFullTokens} tokens`:`${l.flow.contextFullPct}%`}`)).catch(l=>b.error("[plane-link] refresh-flow push rejected:",l?.message||l));return}if(s.ch==="ctl"&&s.type==="refresh_flow_rejected"){ws(typeof s.error=="string"?s.error:"rejected by the plane");return}if(s.ch==="ctl"&&s.type==="transferred"&&Array.isArray(s.tracks)){Promise.resolve().then(()=>c?.(s.tracks)).then(async l=>{for(let w of Array.isArray(l)?l:[])w?.stale&&w.id&&await Tr(w.id,w.since??null)}).catch(l=>b.error("[plane-link] transfer notice failed:",l?.message||l));return}if(s.ch==="ctl"&&s.type==="moves"&&Array.isArray(s.tracks)){Promise.resolve().then(()=>p?.(s.tracks)).then(async l=>{for(let w of Array.isArray(l)?l:[])w?.stale&&w.id&&await Tr(w.id,w.since??null)}).catch(l=>b.error("[plane-link] move-record reconcile failed:",l?.message||l));return}if(s.ch==="events"&&s.type==="ack"&&Array.isArray(s.ids)){cn(s.ids);return}if(s.ch==="events"&&s.type==="nack"&&Array.isArray(s.ids)){ln(s.ids,s.reason,s.permanent===!0,s.retryAfterMs??null);return}if(s.ch==="control"&&s.type==="http_open"){Js(s).catch(l=>L({v:j,ch:"control",type:"http_end",reqId:s.reqId,error:l?.message||"tunnel error"}));return}if(s.ch==="control"&&s.type==="http_cancel"){ot.get(s.reqId)?.abort();return}if(s.ch==="attach"&&s.type==="open"){let l=new Un(js+s.path,Array.isArray(s.protocols)?s.protocols:[],s.host?{headers:{host:s.host}}:void 0);ge.set(s.streamId,l),ye.set(s.streamId,[]),l.on("open",()=>{let y=ye.get(s.streamId)||[];ye.delete(s.streamId);for(let{buf:S,bin:F}of y)l.send(S,{binary:F})}),l.on("message",(y,S)=>{let F=S?y:Buffer.from(String(y));L({v:j,ch:"attach",type:"data",streamId:s.streamId,data:F.toString("base64"),...S?{bin:!0}:{}})});let w=()=>{ye.delete(s.streamId),ge.delete(s.streamId)&&L({v:j,ch:"attach",type:"close",streamId:s.streamId})};l.on("close",w),l.on("error",w);return}if(s.ch==="attach"&&s.type==="data"){let l=ge.get(s.streamId);if(!l)return;let w=Buffer.from(s.data,"base64"),y=s.bin===!0,S=ye.get(s.streamId);S?S.push({buf:w,bin:y}):l.send(w,{binary:y});return}if(s.ch==="attach"&&s.type==="close"){let l=ge.get(s.streamId);ge.delete(s.streamId),ye.delete(s.streamId),l?.close();return}});let u=()=>{X&&b.log("[plane-link] disconnected from plane"),X=!1,ie&&(clearInterval(ie),ie=null),ae&&(clearInterval(ae),ae=null),C.clear(),te={},se=[],q&&(clearTimeout(q),q=null),Ie.clear();for(let l of ge.values())l.close();ge.clear(),ye.clear();for(let l of ot.values())l.abort();if(ot.clear(),en||Pe)return;tt==null&&(tt=Date.now());let d=Date.now()-tt<mc,s=Math.max(d?wc+Math.random()*gc:et,Qe-Date.now(),ut());Pe=setTimeout(()=>{Pe=null,_r()},s),Pe.unref?.(),d||(et=Math.min(et*2,Ts))};Y.on("close",u),Y.on("error",d=>{let s=/Unexpected server response: (\d+)/.exec(d?.message||"")?.[1];if(s==="410"){rn({reason:"removed",via:"410"});return}if(s==="401"||s==="403"){let{tripped:l,holdMs:w}=Mt();l?b.error(`[plane-link] holding every plane call for ${Math.round(w/6e4)} min \u2014 three credential refusals in a row (HTTP ${s}) 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()-vt>=vs&&(vt=Date.now(),b.error(`[plane-link] plane refused this node's credentials (HTTP ${s}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`))}u()})}pt.on("event",Sr),Us().then(_r);function vr({bye:a=!0}={}){en=!0,pt.off("event",Sr),Pe&&clearTimeout(Pe),De&&clearTimeout(De),ie&&clearInterval(ie),ae&&clearInterval(ae),q&&clearTimeout(q),a&&L({v:j,ch:"ctl",type:"bye",reason:"shutdown"}),Y?.close()}return{stop:()=>vr(),setRefreshFlow:a=>L({v:j,ch:"ctl",type:"refresh_flow_set",patch:a}),status:()=>({connected:X,nodeId:n,cursor:{...re},inflight:C.size,...gr(),auth:Zr(),dormant:nt,removed:En(),deadLinkMs:M,deadLinkRedials:pr,refused:{..._t}}),_tick:()=>{wr(),un()}}}var ee,Kn,zn,j,bs,Ts,mc,wc,gc,Ht,yc,bc,Tc,Sc,qn,_c,Hn,vc,$c,kc,Ss,xc,_s,Ac,Wn,Ec,Oc,vs,Vn=O(()=>{Dt();as();ys();mn();On();ee=(()=>{try{return hc(import.meta.url)("../package.json").version||null}catch{return null}})(),Kn=process.env.BOSTRAT_STATE_DIR||W.join(process.env.HOME||Wt.tmpdir(),".bostrat"),zn=W.join(Kn,"plane-link","removed.json");j=1,bs=1e3,Ts=3e4,mc=6e4,wc=1500,gc=500,Ht=100,yc=2e3,bc=25e3,Tc=2.5,Sc=6e4,qn=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},_c=qn(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Hn="refused:",vc={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"},$c=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},kc=3e4,Ss=10*6e4,xc=400,_s=250,Ac=qn(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Wn=4,Ec=Math.max(1,Math.round(qn(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),Oc=6e4,vs=6e4});var As=O(()=>{kn()});var Ps={};fn(Ps,{ACTIONABLE_KINDS:()=>Vt,INSTALL_ATTEMPTS:()=>Kt,INSTALL_RETRY_STEP_S:()=>Es,REGISTRY_RETRY_ATTEMPTS:()=>Jn,REGISTRY_WAIT_POLLS:()=>Yn,REGISTRY_WAIT_STEP_S:()=>Xn,RESTART_SIGNAL:()=>Rs,SELF_UPDATE_DIR:()=>zt,SUPERVISOR_PID_FILE:()=>Os,createAutoUpdater:()=>Gc,inFlight:()=>tr,readStatus:()=>er,restartCommand:()=>Ns,restartStrategy:()=>Qn,selfUpdatePlan:()=>Ms,settleSelfUpdate:()=>Kc,startSelfUpdate:()=>Is,underService:()=>Zn,updatePolicy:()=>Lc});import bt from"node:fs";import me from"node:fs/promises";import Nc from"node:os";import U from"node:path";import{spawn as Mc,execFileSync as Ic}from"node:child_process";import{createRequire as Pc}from"node:module";function Lc({kind:e=ze(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:Vt.has(e)?e==="git-checkout"||Zn(t)?"auto":"prompt":"off"}function Zn(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Qn({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=Os,readFile:i=p=>bt.readFileSync(p,"utf8"),alive:c=Fc}={}){let p=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(Zn(e))return p;let h=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(h)&&h>0)){try{h=Number(String(i(o)).trim())}catch{h=NaN}Number.isInteger(h)&&h>0&&c(h)||(h=NaN)}return Number.isInteger(h)&&h>0?{mode:"supervisor",pid:h}:p}function Fc(e){try{process.kill(e,0)}catch{return!1}try{let t=Ic("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 Ns(e){switch(e?.mode){case"systemd":return`systemctl --user restart ${Z(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 -${Rs.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function Ms({kind:e,to:t,from:n=Gt,statusFile:r=qt,logFile:o=U.join(zt,"last.log"),port:i=Number(process.env.PORT)||3362,npmPrefix:c=null,serviceName:p=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:h=typeof process.getuid=="function"?process.getuid():0,restart:m=Qn({env:{},platform:process.platform,uid:h,serviceName:p,readFile:()=>{throw new Error("no pidfile")}}),liveDir:f=process.env.BOSTRAT_LIVE_CHECKOUT||U.resolve(U.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:g=Date.now(),attempts:E=1}={}){if(!Vt.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 _=(v,T="")=>`write_status ${Z(v)} ${T}`,$=Ns(m),N=`
126
126
  health() {
127
127
  for i in $(seq 1 45); do
128
128
  sleep 1
129
- if curl -sf -o /dev/null "http://127.0.0.1:${a}/api/health"; then return 0; fi
129
+ if curl -sf -o /dev/null "http://127.0.0.1:${i}/api/health"; then return 0; fi
130
130
  done
131
131
  return 1
132
- }`,E=`#!/usr/bin/env bash
132
+ }`,R=`#!/usr/bin/env bash
133
133
  # bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
134
134
  # ${n??"?"} \u2192 ${t} (${e}). Status: ${r}
135
135
  set -u
136
- FROM=${J(n??"")}
137
- TO=${J(t)}
138
- STATUS_FILE=${J(r)}
139
- STARTED_AT=${Number(w)}
140
- ATTEMPTS=${Number(O)||1}
136
+ FROM=${Z(n??"")}
137
+ TO=${Z(t)}
138
+ STATUS_FILE=${Z(r)}
139
+ STARTED_AT=${Number(g)}
140
+ ATTEMPTS=${Number(E)||1}
141
141
  write_status() { # <status> [error] [retryable]
142
142
  local err="\${2:-}"
143
143
  err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
144
144
  printf '{"status":"%s","from":"%s","to":"%s","kind":"%s","attempts":%s,"startedAt":%s,"updatedAt":%s%s%s}\\n' \\
145
- "$1" "$FROM" "$TO" ${J(e)} "$ATTEMPTS" "$STARTED_AT" "$(date +%s000)" \\
145
+ "$1" "$FROM" "$TO" ${Z(e)} "$ATTEMPTS" "$STARTED_AT" "$(date +%s000)" \\
146
146
  "\${err:+,\\"error\\":\\"$err\\"}" "\${3:+,\\"retryable\\":true}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
147
147
  }
148
148
  ${N}
149
- `;if(e==="npm-global"){let v=d?U.join(d,"bin","npm"):"npm",g=d?`export PATH=${J(U.join(d,"bin"))}:"$PATH"
150
- `:"",x=d?` --prefix ${J(d)}`:"",A=Ae=>`${J(v)} install -g "bostrat-node@${Ae}" --no-audit --no-fund${x}`,k=`
149
+ `;if(e==="npm-global"){let v=c?U.join(c,"bin","npm"):"npm",T=c?`export PATH=${Z(U.join(c,"bin"))}:"$PATH"
150
+ `:"",k=c?` --prefix ${Z(c)}`:"",x=Ee=>`${Z(v)} install -g "bostrat-node@${Ee}" --no-audit --no-fund${k}`,A=`
151
151
  install_target() {
152
- for i in $(seq 1 ${Ft}); do
153
- if ${A("$TO")}; then return 0; fi
154
- [ "$i" -lt ${Ft} ] && sleep ${Ho}
152
+ for i in $(seq 1 ${Kt}); do
153
+ if ${x("$TO")}; then return 0; fi
154
+ [ "$i" -lt ${Kt} ] && sleep ${Es}
155
155
  done
156
156
  return 1
157
157
  }`,I=`
158
158
  wait_for_registry() {
159
- for i in $(seq 1 ${Dn}); do
160
- if [ "$(${J(v)} view "bostrat-node@$TO" version --prefer-online 2>/dev/null)" = "$TO" ]; then return 0; fi
161
- sleep ${Ln}
159
+ for i in $(seq 1 ${Yn}); do
160
+ if [ "$(${Z(v)} view "bostrat-node@$TO" version --prefer-online 2>/dev/null)" = "$TO" ]; then return 0; fi
161
+ sleep ${Xn}
162
162
  done
163
163
  return 1
164
- }`;return E+g+I+k+`
165
- ${b("updating",'"" ')}
164
+ }`;return R+T+I+A+`
165
+ ${_("updating",'"" ')}
166
166
  if ! wait_for_registry; then
167
- ${b("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(Dn*Ln/60)} min, attempt $ATTEMPTS of ${Fn})" retryable`)}
167
+ ${_("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(Yn*Xn/60)} min, attempt $ATTEMPTS of ${Jn})" retryable`)}
168
168
  exit 1
169
169
  fi
170
170
  if ! install_target; then
171
- ${b("failed",`"npm install failed (${Ft} attempts)"`)}
171
+ ${_("failed",`"npm install failed (${Kt} attempts)"`)}
172
172
  exit 1
173
173
  fi
174
- ${b("restarting")}
174
+ ${_("restarting")}
175
175
  if ! ${$}; then
176
- ${b("failed",`"restart failed (${$.replace(/"/g,"")})"`)}
176
+ ${_("failed",`"restart failed (${$.replace(/"/g,"")})"`)}
177
177
  exit 1
178
178
  fi
179
179
  if health; then
@@ -181,54 +181,54 @@ if health; then
181
181
  exit 0
182
182
  fi
183
183
  # \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
184
- ${b("rolling-back",'"agent did not answer on :'+a+' after the update"')}
185
- if [ -n "$FROM" ] && ${A("$FROM")} && ${$} && health; then
186
- ${b("rolled-back",'"agent did not answer on :'+a+' after the update; rolled back"')}
184
+ ${_("rolling-back",'"agent did not answer on :'+i+' after the update"')}
185
+ if [ -n "$FROM" ] && ${x("$FROM")} && ${$} && health; then
186
+ ${_("rolled-back",'"agent did not answer on :'+i+' after the update; rolled back"')}
187
187
  exit 1
188
188
  fi
189
- ${b("failed",'"agent did not answer after the update AND the rollback"')}
189
+ ${_("failed",'"agent did not answer after the update AND the rollback"')}
190
190
  exit 1
191
- `}let P=v=>`( cd ${J(p)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${v}" )`;return E+`
192
- LIVE=${J(p)}
191
+ `}let D=v=>`( cd ${Z(f)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${v}" )`;return R+`
192
+ LIVE=${Z(f)}
193
193
  TMP_SCRIPT="$(mktemp)"
194
194
  trap 'rm -f "$TMP_SCRIPT"' EXIT
195
195
  # "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
196
196
  # restart \u2192 health in one call): the agent it restarts settles "done" on boot,
197
197
  # and nothing here may write after that boot or the settle would repeat.
198
- ${b("restarting")}
199
- if ${P("$TO")}; then
198
+ ${_("restarting")}
199
+ if ${D("$TO")}; then
200
200
  exit 0
201
201
  fi
202
- ${b("rolling-back",'"deploy-pi.sh v$TO failed"')}
203
- if [ -n "$FROM" ] && ${P("$FROM")}; then
204
- ${b("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
202
+ ${_("rolling-back",'"deploy-pi.sh v$TO failed"')}
203
+ if [ -n "$FROM" ] && ${D("$FROM")}; then
204
+ ${_("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
205
205
  exit 1
206
206
  fi
207
- ${b("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
207
+ ${_("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
208
208
  exit 1
209
- `}async function Hn(e=Ht){try{return JSON.parse(await he.readFile(e,"utf8"))}catch{return null}}async function zo({to:e,from:t=jt,kind:n=We(),reason:r="manual",force:s=!1,statusFile:a=Ht,spawnImpl:d=ha,now:f=Date.now,npmPrefix:m=void 0,log:S=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!Wt.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!He(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let p=await Hn(a);if(Wn(p))return{ok:!1,reason:`an update to ${p.to} is already in flight`,status:p};let w=p?.to===e?Number(p.attempts)||1:0;if(!s&&p&&p.to===e&&(p.status==="failed"||p.status==="rolled-back")&&!(p.status==="failed"&&p.retryable===!0&&w<Fn))return{ok:!1,reason:`update to ${e} already ${p.status} (${p.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:p};let O=p?.to===e&&(p.status==="failed"||p.status==="rolled-back")?w+1:1;await he.mkdir(U.dirname(a),{recursive:!0});let b=m!==void 0?m:n==="npm-global"?fn(await va())||U.resolve(U.dirname(process.execPath),".."):null,$=Un(),N=qo({kind:n,to:e,from:t,statusFile:a,npmPrefix:b,startedAt:f(),attempts:O,restart:$}),E=U.join(U.dirname(a),`update-${e}.sh`),P=U.join(U.dirname(a),"last.log");await he.writeFile(E,N,{mode:448}),await he.writeFile(a,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:O,startedAt:f(),updatedAt:f()}));let v=mt.existsSync("/run/systemd/system")&&await $a("systemd-run"),g=v?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",E]]:["bash",[E]],x=async k=>{let I=`could not spawn updater: ${k?.message||k}`;return await he.writeFile(a,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,attempts:O,startedAt:f(),updatedAt:f(),error:I})).catch(()=>{}),S.error?.(`[self-update] ${I}`),I},A=null;try{v||(A=mt.openSync(P,"a"));let k=d(g[0],g[1],{detached:!0,stdio:v?"ignore":["ignore",A,A]});k.on?.("error",I=>{x(I)}),k.unref?.()}catch(k){return{ok:!1,reason:await x(k)}}finally{A!==null&&mt.closeSync(A)}return S.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}, restart via ${$.mode}) started \u2014 status ${a}`),{ok:!0,to:e,from:t,kind:n,scriptFile:E,statusFile:a}}async function va(){try{return await he.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function $a(e){for(let t of String(process.env.PATH||"").split(U.delimiter))try{return await he.access(U.join(t,e),mt.constants.X_OK),!0}catch{}return!1}async function Aa({statusFile:e=Ht,current:t=jt,now:n=Date.now,staleMs:r=xa}={}){let s=await Hn(e);if(!s)return null;let a=d=>he.writeFile(e,JSON.stringify(d)).catch(()=>{});if(Wn(s)){if(t&&s.to===t){let d={...s,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await a(d),d}if(n()-Number(s.updatedAt||s.startedAt||0)>r){let d={...s,status:"failed",error:`updater went silent while ${s.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await a(d),d}return null}if(["failed","rolled-back","done"].includes(s.status)&&!s.announced){let d={...s,announced:!0};return await a(d),d}return null}function ka({isBusy:e,start:t=zo,onStuck:n=null,onStarted:r=null,tickMs:s=Ta,stuckMs:a=ga,now:d=Date.now,setIntervalImpl:f=setInterval,clearIntervalImpl:m=clearInterval,log:S=console}={}){let p=null,w=()=>{p?.timer&&m(p.timer),p=null},O=async()=>{if(!p)return;let b=!0;try{b=await e()!==!1}catch{b=!0}if(b){if(!p.stuckFired&&d()-p.since>=a){p.stuckFired=!0;try{await n?.({to:p.to,from:p.from,since:p.since})}catch{}}return}let $=p;w();let N=await t({to:$.to,from:$.from,kind:$.kind,reason:"auto"});S.log?.(`[self-update] stasis reached \u2192 ${N.ok?"started":`not started: ${N.reason}`}`);try{await r?.({...$,result:N})}catch{}};return{arm({to:b,from:$=jt,kind:N=We()}){return p?.to===b?!1:(w(),p={to:b,from:$,kind:N,since:d(),stuckFired:!1,timer:f(O,s)},p.timer.unref?.(),!0)},tick:O,cancel:w,get armed(){return p?{to:p.to,from:p.from,kind:p.kind,since:p.since}:null}}}var jt,ya,Ut,Ht,ga,Ta,Dn,Ln,Fn,Ft,Ho,Wo,Ko,Wt,J,ba,Wn,xa,Yo=R(()=>{Cn();Uo();jt=(()=>{try{return wa(import.meta.url)("../package.json").version||null}catch{return null}})(),ya=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||fa.tmpdir(),".bostrat"),Ut=U.join(ya,"self-update"),Ht=U.join(Ut,"status.json"),ga=1440*6e4,Ta=6e4,Dn=60,Ln=15,Fn=3,Ft=6,Ho=20,Wo=U.join(Ut,"supervisor.pid"),Ko="SIGUSR2",Wt=new Set(["npm-global","git-checkout"]);J=e=>`'${String(e).replace(/'/g,"'\\''")}'`;ba=new Set(["updating","restarting","rolling-back"]),Wn=e=>!!(e&&ba.has(e.status));xa=45*6e4});un();pn();_n();import K from"node:fs";import C from"node:path";import Ge from"node:os";import{createRequire as Kn}from"node:module";import{execFile as Oa,spawn as Ea}from"node:child_process";import{promisify as Ra}from"node:util";import Na from"node:readline/promises";import{randomUUID as Ma}from"node:crypto";import{fileURLToPath as Ia}from"node:url";import Pt from"node:fs";import Fe from"node:fs/promises";import hi from"node:os";import dt from"node:path";import mi from"node:readline";import{spawn as wi}from"node:child_process";var yi="^(ugrep|rg|2\\.1\\.[0-9]+|cursor-agent|codex|npm|node|MainThread)",gi="^(bostrat-|tmux|earlyoom|systemd|sshd)",Ti=()=>["-m","10","-s","70","-r","600","--prefer",yi,"--avoid",gi],qr="BOSTRAT_OOM_GUARD_OWNER",Si=6e4,_i=5e3;function zr(e=process.env){return!["0","off","false","no"].includes(String(e.BOSTRAT_OOM_GUARD??"").trim().toLowerCase())}function Vr(e=process.env){let t=e.BOSTRAT_STATE_DIR||dt.join(e.HOME||hi.tmpdir(),".bostrat");return dt.join(t,"oom-guard.pid")}function Yr(e=process.env){if(e.BOSTRAT_EARLYOOM_BIN)return Pt.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=dt.join(n,"earlyoom");if(Pt.existsSync(r))return r}return null}async function Xr({procRoot:e="/proc"}={}){let t=[];try{t=await Fe.readdir(e)}catch{return[]}let n=[];for(let r of t){if(!/^\d+$/.test(r))continue;(await Fe.readFile(dt.join(e,r,"comm"),"utf8").catch(()=>"")).trim()==="earlyoom"&&n.push({pid:Number(r)})}return n}async function Jr(e){let t=Number((await Fe.readFile(e,"utf8").catch(()=>"")).trim());return Number.isInteger(t)&&t>0?t:null}async function Zr({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc"}={}){if(!zr(e))return{state:"off"};if(t!=="linux")return{state:"unsupported",platform:t};let r=await Xr({procRoot:n}),s=await Jr(Vr(e)),a=r.find(f=>f.pid===s);if(a)return{state:"own",pid:a.pid};if(r.length)return{state:"host",pid:r[0].pid};let d=Yr(e);return d?{state:"stopped",bin:d}:{state:"absent"}}function $n(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 Qr({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc",log:r=console.log,spawnImpl:s=wi,checkMs:a=Si,relaunchMs:d=_i}={}){let f=null,m={state:null},S=null,p=!1,w="",O=Vr(e),b=v=>{m=v;let g=`[oom-guard] ${$n(v)}`;return g!==w&&r(g),w=g,v},$=v=>{p||(clearTimeout(S),S=setTimeout(()=>N().catch(()=>{}),v),S.unref?.())},N=async()=>{if(p||f)return m;if(!zr(e))return b({state:"off"});if(t!=="linux")return b({state:"unsupported",platform:t});let v=await Jr(O),g=await Xr({procRoot:n});if(v&&g.some(k=>k.pid===v)){try{process.kill(v,"SIGTERM")}catch{}g=g.filter(k=>k.pid!==v)}if(g.length)return $(a),b({state:"host",pid:g[0].pid});let x=Yr(e);if(!x)return $(a),b({state:"absent"});let A;try{A=s(x,Ti(),{stdio:["ignore","pipe","pipe"]})}catch(k){return r(`[oom-guard] could not start ${x}: ${k?.message||k}`),$(a),m}f=A;for(let k of[A.stdout,A.stderr])k&&mi.createInterface({input:k}).on("line",I=>r(`[earlyoom] ${I}`));return A.on("error",k=>{r(`[oom-guard] ${x}: ${k?.message||k}`),!(f!==A||A.pid)&&(f=null,$(a))}),A.on("exit",(k,I)=>{f===A&&(f=null,Fe.rm(O,{force:!0}).catch(()=>{}),!p&&(r(`[oom-guard] earlyoom exited (${I||`code ${k}`}) \u2014 relaunching in ${Math.round(d/1e3)} s`),m={state:"stopped",bin:x},w="",$(d)))}),A.pid&&(await Fe.mkdir(dt.dirname(O),{recursive:!0}).catch(()=>{}),await Fe.writeFile(O,`${A.pid}
210
- `).catch(()=>{})),$(a),b({state:"own",pid:A.pid})},E=()=>{f&&(f.kill("SIGTERM"),Pt.rmSync(O,{force:!0}))};return process.on("exit",E),{ready:N().catch(()=>m),status:()=>m,stop(){p=!0,clearTimeout(S),process.off("exit",E);let v=f;f=null,v&&(v.kill("SIGTERM"),Pt.rmSync(O,{force:!0}))}}}import bi from"node:fs";import eo from"node:path";import vi from"node:os";var $i=()=>process.env.BOSTRAT_STATE_DIR||eo.join(process.env.HOME||vi.tmpdir(),".bostrat"),xi=()=>eo.join($i(),"plane-link","public-host.json");var pt=null;function Ai(){if(pt)return pt;try{let e=JSON.parse(bi.readFileSync(xi(),"utf8"));pt={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{pt={viewBase:null}}return pt}function ki(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),s=r?r[1].toLowerCase():t,a=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return a?{proto:s,host:a}:null}function to(){return Ai().viewBase}function no(e=process.env.BOSTRAT_PUBLIC_HOST){return ki(e,"https")}function ro(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}Nt();import Oi from"node:fs";import Ei from"node:os";import oo from"node:path";var so=3*6e4;function xn(e=process.env){let t=e.BOSTRAT_STATE_DIR||oo.join(e.HOME||Ei.tmpdir(),".bostrat");return oo.join(t,"heartbeat.json")}function io(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return so;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):so}function ao(e=xn()){try{let t=JSON.parse(Oi.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 s=Number(t.loopLagMs);return{pid:r,ts:n,loopLagMs:Number.isFinite(s)?s:null}}catch{return null}}Nt();var lo="BOSTRAT_RESTART_NOTICE",od=2*6e4;var co=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function uo({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:co(e),staleS:co(t)!=null?Math.round(t/1e3):null})}var Xo=(e,t)=>{let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let s=0;s<Math.max(n.length,r.length);s++){let a=(n[s]||0)-(r[s]||0);if(a)return a<0}return!1},me=Ra(Oa),Gn=C.dirname(Ia(import.meta.url)),xe=C.resolve(Gn,".."),Pa=C.join(Gn,"index.js"),Ba="wss://plane.bostrat.ai/v1/node",Ke=Kn(import.meta.url)("../package.json").version,D=(e,t)=>({name:e,level:"pass",detail:t}),V=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),z=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function Ca(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?D("node runtime",`${process.version} at ${process.execPath}`):z("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Da(e){return e.BOSTRAT_OWNER?V("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 La(e){let t;try{t=K.statSync(e)}catch{return V("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?V("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 Fa(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await me(t,["-V"],{timeout:5e3});return D("tmux",`${t} (${n.trim()})`)}catch{return z("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Jo(e,{required:t=!1}={}){if(await vn(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",s=It[e]?`${It[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?z(e,r,s):V(e,r,s)}async function ja(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await me(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 V("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",It.gh)}}async function Ua(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Jo(t)));return e.some(t=>t.level==="pass")||e.push(z("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 Ha(){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 vn(t,{failOpen:!1})?D(t,"resolves on the service PATH"):V(t,`not on the service PATH \u2014 ${n}`,r)))}async function Wa(){try{let t=Kn(C.join(xe,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let s=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),a=setTimeout(()=>r(new Error("spawn timeout")),5e3);s.onExit(()=>{clearTimeout(a),n()})}),D("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${xe} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Kn(C.join(xe,"package.json")),r=C.join(C.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");K.existsSync(r)&&!(K.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return z("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function Ka(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(K.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"?z:V)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function Ga(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?z("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 qa(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return V("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),s=nt(e.BOSTRAT_PLANE_URL);return await new Promise(a=>{let d=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),f=null,m=p=>{clearTimeout(S);try{d.close()}catch{}a(f?{...p,viewBase:f}:p)},S=setTimeout(()=>m(z("plane link",`no hello_ok within 5s from ${s}`,"check the URL, the token, and the plane's IP gate")),5e3);d.on("open",()=>d.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${Ma().slice(0,8)}`,ephemeral:!0}))),d.on("message",p=>{try{let w=JSON.parse(p);w.type==="hello_ok"?(typeof w.viewBase=="string"&&w.viewBase&&(f=w.viewBase),w.minNodeVersion&&Xo(Ke,w.minNodeVersion)?m(z("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${w.minNodeVersion} \u2014 this node is ${Ke}; the real link is refused until it updates`,`bostrat-node self-update --to ${w.latestNodeVersion||w.minNodeVersion}`)):w.latestNodeVersion&&Xo(Ke,w.latestNodeVersion)?m(V("plane link",`hello_ok in ${Date.now()-r}ms (${s}); bostrat-node ${w.latestNodeVersion} is available (this node: ${Ke})`,`bostrat-node self-update --to ${w.latestNodeVersion}`)):m(D("plane link",`hello_ok in ${Date.now()-r}ms (${s})`))):w.type==="error"&&m(z("plane link",`plane said: ${w.code} ${w.message||""}`,"check the token"))}catch{}}),d.on("error",p=>m(z("plane link",`${p?.message||p}`,"check the URL, the token, and the plane's IP gate")))})}function za(){let e;try{e=JSON.parse(K.readFileSync(C.join(bt,"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 z("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?V("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 Va(e){let t=await Fr({env:e}),n=jr(t);return t.available?D("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?V("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 Ya(e){let t=await Zr({env:e}),n=$n(t);return t.state==="absent"?V("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)}function Xa(e){return e.BOSTRAT_STATE_REMOTE?D("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):V("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}function Ja(e,t){let n=t?.viewBase??null,r=to(),s=no(e.BOSTRAT_PUBLIC_HOST),a=(()=>{let d=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(d)return`${d.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let f=ro(e.BOSTRAT_PLANE_URL);return f?`${f}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let d=s&&s.host!==n?`; BOSTRAT_PUBLIC_HOST=${s.host} is set but the plane's value wins`:"";return D("public host",`views https://<slug>.${n}/ (plane hello_ok)${d} \xB7 track links ${a}`)}return r?D("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${a}`):s?D("public host",`views ${s.proto}://<slug>.${s.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${a}`):z("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${a}`,"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 Zo(e,t={}){let n=[];n.push(await Ca()),n.push(La(t.envFile||Be())),n.push(await Fa(e)),n.push(await Va(e)),n.push(await Ya(e)),n.push(...await Ua()),n.push(await Jo("git",{required:!0})),n.push(await ja()),n.push(...await Ha()),n.push(await Wa()),n.push(Ka(e)),n.push(Ga(e)),n.push(Da(e));let r=await qa(e,t);return n.push(r),n.push(Ja(e,r)),n.push(za()),n.push(Xa(e)),n}function Qo(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let a of e)t(`${n[a.level]} ${a.name}: ${a.detail}`),a.fix&&a.level!=="pass"&&t(` fix: ${a.fix}`);let r=e.filter(a=>a.level==="fail").length,s=e.filter(a=>a.level==="warn").length;return t(r?`
211
- FAIL \u2014 ${r} blocking, ${s} warnings`:`
212
- OK \u2014 0 blocking, ${s} warnings`),r===0}async function Za({envFile:e=Be(),input:t=process.stdin,output:n=process.stdout}={}){let r=vt(e),s=Na.createInterface({input:t,output:n}),a=async(v,g)=>(await s.question(g?`${v} [${g}]: `:`${v}: `)).trim()||g||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
209
+ `}async function er(e=qt){try{return JSON.parse(await me.readFile(e,"utf8"))}catch{return null}}async function Is({to:e,from:t=Gt,kind:n=ze(),reason:r="manual",force:o=!1,statusFile:i=qt,spawnImpl:c=Mc,now:p=Date.now,npmPrefix:h=void 0,log:m=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!Vt.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Ge(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let f=await er(i);if(tr(f))return{ok:!1,reason:`an update to ${f.to} is already in flight`,status:f};let g=f?.to===e?Number(f.attempts)||1:0;if(!o&&f&&f.to===e&&(f.status==="failed"||f.status==="rolled-back")&&!(f.status==="failed"&&f.retryable===!0&&g<Jn))return{ok:!1,reason:`update to ${e} already ${f.status} (${f.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:f};let E=f?.to===e&&(f.status==="failed"||f.status==="rolled-back")?g+1:1;await me.mkdir(U.dirname(i),{recursive:!0});let _=h!==void 0?h:n==="npm-global"?$n(await Uc())||U.resolve(U.dirname(process.execPath),".."):null,$=Qn(),N=Ms({kind:n,to:e,from:t,statusFile:i,npmPrefix:_,startedAt:p(),attempts:E,restart:$}),R=U.join(U.dirname(i),`update-${e}.sh`),D=U.join(U.dirname(i),"last.log");await me.writeFile(R,N,{mode:448}),await me.writeFile(i,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:E,startedAt:p(),updatedAt:p()}));let v=bt.existsSync("/run/systemd/system")&&await Hc("systemd-run"),T=v?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",R]]:["bash",[R]],k=async A=>{let I=`could not spawn updater: ${A?.message||A}`;return await me.writeFile(i,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,attempts:E,startedAt:p(),updatedAt:p(),error:I})).catch(()=>{}),m.error?.(`[self-update] ${I}`),I},x=null;try{v||(x=bt.openSync(D,"a"));let A=c(T[0],T[1],{detached:!0,stdio:v?"ignore":["ignore",x,x]});A.on?.("error",I=>{k(I)}),A.unref?.()}catch(A){return{ok:!1,reason:await k(A)}}finally{x!==null&&bt.closeSync(x)}return m.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}, restart via ${$.mode}) started \u2014 status ${i}`),{ok:!0,to:e,from:t,kind:n,scriptFile:R,statusFile:i}}async function Uc(){try{return await me.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Hc(e){for(let t of String(process.env.PATH||"").split(U.delimiter))try{return await me.access(U.join(t,e),bt.constants.X_OK),!0}catch{}return!1}async function Kc({statusFile:e=qt,current:t=Gt,now:n=Date.now,staleMs:r=Wc}={}){let o=await er(e);if(!o)return null;let i=c=>me.writeFile(e,JSON.stringify(c)).catch(()=>{});if(tr(o)){if(t&&o.to===t){let c={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await i(c),c}if(n()-Number(o.updatedAt||o.startedAt||0)>r){let c={...o,status:"failed",error:`updater went silent while ${o.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await i(c),c}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let c={...o,announced:!0};return await i(c),c}return null}function Gc({isBusy:e,start:t=Is,onStuck:n=null,onStarted:r=null,tickMs:o=Bc,stuckMs:i=Cc,now:c=Date.now,setIntervalImpl:p=setInterval,clearIntervalImpl:h=clearInterval,log:m=console}={}){let f=null,g=()=>{f?.timer&&h(f.timer),f=null},E=async()=>{if(!f)return;let _=!0;try{_=await e()!==!1}catch{_=!0}if(_){if(!f.stuckFired&&c()-f.since>=i){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let $=f;g();let N=await t({to:$.to,from:$.from,kind:$.kind,reason:"auto"});m.log?.(`[self-update] stasis reached \u2192 ${N.ok?"started":`not started: ${N.reason}`}`);try{await r?.({...$,result:N})}catch{}};return{arm({to:_,from:$=Gt,kind:N=ze()}){return f?.to===_?!1:(g(),f={to:_,from:$,kind:N,since:c(),stuckFired:!1,timer:p(E,o)},f.timer.unref?.(),!0)},tick:E,cancel:g,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var Gt,Dc,zt,qt,Cc,Bc,Yn,Xn,Jn,Kt,Es,Os,Rs,Vt,Z,jc,tr,Wc,Ds=O(()=>{Vn();As();Gt=(()=>{try{return Pc(import.meta.url)("../package.json").version||null}catch{return null}})(),Dc=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||Nc.tmpdir(),".bostrat"),zt=U.join(Dc,"self-update"),qt=U.join(zt,"status.json"),Cc=1440*6e4,Bc=6e4,Yn=60,Xn=15,Jn=3,Kt=6,Es=20,Os=U.join(zt,"supervisor.pid"),Rs="SIGUSR2",Vt=new Set(["npm-global","git-checkout"]);Z=e=>`'${String(e).replace(/'/g,"'\\''")}'`;jc=new Set(["updating","restarting","rolling-back"]),tr=e=>!!(e&&jc.has(e.status));Wc=45*6e4});mn();vn();Mn();import K from"node:fs";import B from"node:path";import Ve from"node:os";import{createRequire as nr}from"node:module";import{execFile as zc,spawn as qc}from"node:child_process";import{promisify as Vc}from"node:util";import Yc from"node:readline/promises";import{randomUUID as Xc}from"node:crypto";import{fileURLToPath as Jc}from"node:url";import Ft from"node:fs";import Ue from"node:fs/promises";import ka from"node:os";import mt from"node:path";import xa from"node:readline";import{spawn as Aa}from"node:child_process";var Ea="^(ugrep|rg|2\\.1\\.[0-9]+|cursor-agent|codex|npm|node|MainThread)",Oa="^(bostrat-|tmux|earlyoom|systemd|sshd)",Ra=()=>["-m","10","-s","70","-r","600","--prefer",Ea,"--avoid",Oa],_o="BOSTRAT_OOM_GUARD_OWNER",Na=6e4,Ma=5e3;function vo(e=process.env){return!["0","off","false","no"].includes(String(e.BOSTRAT_OOM_GUARD??"").trim().toLowerCase())}function $o(e=process.env){let t=e.BOSTRAT_STATE_DIR||mt.join(e.HOME||ka.tmpdir(),".bostrat");return mt.join(t,"oom-guard.pid")}function ko(e=process.env){if(e.BOSTRAT_EARLYOOM_BIN)return Ft.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=mt.join(n,"earlyoom");if(Ft.existsSync(r))return r}return null}async function xo({procRoot:e="/proc"}={}){let t=[];try{t=await Ue.readdir(e)}catch{return[]}let n=[];for(let r of t){if(!/^\d+$/.test(r))continue;(await Ue.readFile(mt.join(e,r,"comm"),"utf8").catch(()=>"")).trim()==="earlyoom"&&n.push({pid:Number(r)})}return n}async function Ao(e){let t=Number((await Ue.readFile(e,"utf8").catch(()=>"")).trim());return Number.isInteger(t)&&t>0?t:null}async function Eo({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc"}={}){if(!vo(e))return{state:"off"};if(t!=="linux")return{state:"unsupported",platform:t};let r=await xo({procRoot:n}),o=await Ao($o(e)),i=r.find(p=>p.pid===o);if(i)return{state:"own",pid:i.pid};if(r.length)return{state:"host",pid:r[0].pid};let c=ko(e);return c?{state:"stopped",bin:c}:{state:"absent"}}function Dn(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 Oo({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc",log:r=console.log,spawnImpl:o=Aa,checkMs:i=Na,relaunchMs:c=Ma}={}){let p=null,h={state:null},m=null,f=!1,g="",E=$o(e),_=v=>{h=v;let T=`[oom-guard] ${Dn(v)}`;return T!==g&&r(T),g=T,v},$=v=>{f||(clearTimeout(m),m=setTimeout(()=>N().catch(()=>{}),v),m.unref?.())},N=async()=>{if(f||p)return h;if(!vo(e))return _({state:"off"});if(t!=="linux")return _({state:"unsupported",platform:t});let v=await Ao(E),T=await xo({procRoot:n});if(v&&T.some(A=>A.pid===v)){try{process.kill(v,"SIGTERM")}catch{}T=T.filter(A=>A.pid!==v)}if(T.length)return $(i),_({state:"host",pid:T[0].pid});let k=ko(e);if(!k)return $(i),_({state:"absent"});let x;try{x=o(k,Ra(),{stdio:["ignore","pipe","pipe"]})}catch(A){return r(`[oom-guard] could not start ${k}: ${A?.message||A}`),$(i),h}p=x;for(let A of[x.stdout,x.stderr])A&&xa.createInterface({input:A}).on("line",I=>r(`[earlyoom] ${I}`));return x.on("error",A=>{r(`[oom-guard] ${k}: ${A?.message||A}`),!(p!==x||x.pid)&&(p=null,$(i))}),x.on("exit",(A,I)=>{p===x&&(p=null,Ue.rm(E,{force:!0}).catch(()=>{}),!f&&(r(`[oom-guard] earlyoom exited (${I||`code ${A}`}) \u2014 relaunching in ${Math.round(c/1e3)} s`),h={state:"stopped",bin:k},g="",$(c)))}),x.pid&&(await Ue.mkdir(mt.dirname(E),{recursive:!0}).catch(()=>{}),await Ue.writeFile(E,`${x.pid}
210
+ `).catch(()=>{})),$(i),_({state:"own",pid:x.pid})},R=()=>{p&&(p.kill("SIGTERM"),Ft.rmSync(E,{force:!0}))};return process.on("exit",R),{ready:N().catch(()=>h),status:()=>h,stop(){f=!0,clearTimeout(m),process.off("exit",R);let v=p;p=null,v&&(v.kill("SIGTERM"),Ft.rmSync(E,{force:!0}))}}}Sn();import Ia from"node:fs";import Ro from"node:path";import Pa from"node:os";var Da=()=>process.env.BOSTRAT_STATE_DIR||Ro.join(process.env.HOME||Pa.tmpdir(),".bostrat"),Ca=()=>Ro.join(Da(),"plane-link","public-host.json");var wt=null;function Ba(){if(wt)return wt;try{let e=JSON.parse(Ia.readFileSync(Ca(),"utf8"));wt={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{wt={viewBase:null}}return wt}function La(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),o=r?r[1].toLowerCase():t,i=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return i?{proto:o,host:i}:null}function No(){return Ba().viewBase}function Mo(e=process.env.BOSTRAT_PUBLIC_HOST){return La(e,"https")}function Io(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}Ct();import Fa from"node:fs";import ja from"node:os";import Po from"node:path";var Do=3*6e4;function Cn(e=process.env){let t=e.BOSTRAT_STATE_DIR||Po.join(e.HOME||ja.tmpdir(),".bostrat");return Po.join(t,"heartbeat.json")}function Co(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return Do;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):Do}function Bo(e=Cn()){try{let t=JSON.parse(Fa.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}}Ct();var Fo="BOSTRAT_RESTART_NOTICE",Lp=2*6e4;var Lo=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function jo({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:Lo(e),staleS:Lo(t)!=null?Math.round(t/1e3):null})}var Cs=(e,t)=>{let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let o=0;o<Math.max(n.length,r.length);o++){let i=(n[o]||0)-(r[o]||0);if(i)return i<0}return!1},we=Vc(zc),rr=B.dirname(Jc(import.meta.url)),Ae=B.resolve(rr,".."),Zc=B.join(rr,"index.js"),Qc="wss://plane.bostrat.ai/v1/node",qe=nr(import.meta.url)("../package.json").version,P=(e,t)=>({name:e,level:"pass",detail:t}),z=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),V=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function el(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?P("node runtime",`${process.version} at ${process.execPath}`):V("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function tl(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"):P("owner stamp","none (the plane infers the owner from the token)")}function nl(e){let t;try{t=K.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}`):P("node.env",`${e} (0600)`)}async function rl(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await we(t,["-V"],{timeout:5e3});return P("tmux",`${t} (${n.trim()})`)}catch{return V("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Bs(e,{required:t=!1}={}){if(await Pn(e,{loginShell:!0,failOpen:!1}))return P(e,"resolves on the login-shell PATH");let r="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",o=Lt[e]?`${Lt[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?V(e,r,o):z(e,r,o)}async function ol(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await we(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return P("gh (GitHub CLI)",n)}catch{return 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",Lt.gh)}}async function sl(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Bs(t)));return e.some(t=>t.level==="pass")||e.push(V("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 il(){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 Pn(t,{failOpen:!1})?P(t,"resolves on the service PATH"):z(t,`not on the service PATH \u2014 ${n}`,r)))}async function al(){try{let t=nr(B.join(Ae,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let o=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),i=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(i),n()})}),P("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${Ae} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=nr(B.join(Ae,"package.json")),r=B.join(B.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");K.existsSync(r)&&!(K.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return V("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function cl(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(K.existsSync(t))return P("chromium (mocks)",t);let n=process.platform==="darwin"?"brew install --cask chromium (or set BOSTRAT_CHROMIUM_BIN to Chrome.app's inner binary)":"apt install chromium fonts-dejavu-core fonts-liberation (or set BOSTRAT_CHROMIUM_BIN)";return(e.BOSTRAT_INSTALL_KIND==="container"?V:z)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function ll(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?V("claude lane","BOSTRAT_CLAUDE_USE_API_KEY=1 but ANTHROPIC_API_KEY is empty","add the key to node.env or set the flag to 0"):P("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function ul(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=st(e.BOSTRAT_PLANE_URL);return await new Promise(i=>{let c=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),p=null,h=f=>{clearTimeout(m);try{c.close()}catch{}i(p?{...f,viewBase:p}:f)},m=setTimeout(()=>h(V("plane link",`no hello_ok within 5s from ${o}`,"check the URL, the token, and the plane's IP gate")),5e3);c.on("open",()=>c.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${Xc().slice(0,8)}`,ephemeral:!0}))),c.on("message",f=>{try{let g=JSON.parse(f);g.type==="hello_ok"?(typeof g.viewBase=="string"&&g.viewBase&&(p=g.viewBase),g.minNodeVersion&&Cs(qe,g.minNodeVersion)?h(V("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${g.minNodeVersion} \u2014 this node is ${qe}; the real link is refused until it updates`,`bostrat-node self-update --to ${g.latestNodeVersion||g.minNodeVersion}`)):g.latestNodeVersion&&Cs(qe,g.latestNodeVersion)?h(z("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${g.latestNodeVersion} is available (this node: ${qe})`,`bostrat-node self-update --to ${g.latestNodeVersion}`)):h(P("plane link",`hello_ok in ${Date.now()-r}ms (${o})`))):g.type==="error"&&h(V("plane link",`plane said: ${g.code} ${g.message||""}`,"check the token"))}catch{}}),c.on("error",f=>h(V("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function dl(){let e;try{e=JSON.parse(K.readFileSync(B.join(xt,"content-outbox.json"),"utf8"))}catch{return P("content outbox","empty \u2014 every deliverable has reached the plane")}let t=e.ops?.length||0,n=e.parked?.length||0;if(n){let r=e.parked[0];return V("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"):P("content outbox",t?`${t} op(s) in flight`:"drained")}async function pl(e){let t=await mo({env:e}),n=wo(t);return t.available?P("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)"):P("box caps",n)}async function fl(e){let t=await Eo({env:e}),n=Dn(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"):P("oom guard",n)}function hl(e){let t=Tn(e),n=Kr(t);return t.unknown?.length?z("audit guard",n,`BOSTRAT_AUDIT_GUARD names unknown rule(s): ${t.unknown.join(", ")}`):P("audit guard",n)}function ml(e){return e.BOSTRAT_STATE_REMOTE?P("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):z("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}function wl(e,t){let n=t?.viewBase??null,r=No(),o=Mo(e.BOSTRAT_PUBLIC_HOST),i=(()=>{let c=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(c)return`${c.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let p=Io(e.BOSTRAT_PLANE_URL);return p?`${p}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let c=o&&o.host!==n?`; BOSTRAT_PUBLIC_HOST=${o.host} is set but the plane's value wins`:"";return P("public host",`views https://<slug>.${n}/ (plane hello_ok)${c} \xB7 track links ${i}`)}return r?P("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${i}`):o?P("public host",`views ${o.proto}://<slug>.${o.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${i}`):V("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${i}`,"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 Ls(e,t={}){let n=[];n.push(await el()),n.push(nl(t.envFile||Be())),n.push(await rl(e)),n.push(await pl(e)),n.push(await fl(e)),n.push(hl(e)),n.push(...await sl()),n.push(await Bs("git",{required:!0})),n.push(await ol()),n.push(...await il()),n.push(await al()),n.push(cl(e)),n.push(ll(e)),n.push(tl(e));let r=await ul(e,t);return n.push(r),n.push(wl(e,r)),n.push(dl()),n.push(ml(e)),n}function Fs(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let i of e)t(`${n[i.level]} ${i.name}: ${i.detail}`),i.fix&&i.level!=="pass"&&t(` fix: ${i.fix}`);let r=e.filter(i=>i.level==="fail").length,o=e.filter(i=>i.level==="warn").length;return t(r?`
211
+ FAIL \u2014 ${r} blocking, ${o} warnings`:`
212
+ OK \u2014 0 blocking, ${o} warnings`),r===0}async function gl({envFile:e=Be(),input:t=process.stdin,output:n=process.stdout}={}){let r=At(e),o=Yc.createInterface({input:t,output:n}),i=async(v,T)=>(await o.question(T?`${v} [${T}]: `:`${v}: `)).trim()||T||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
213
213
  you type those inside each box, later (box-auth-policy).
214
214
 
215
- `);let d=await a("Plane URL",r.BOSTRAT_PLANE_URL||Ba),f=nt(d);f!==d.trim()&&n.write(` \u2192 using ${f}
216
- `);let m=await a("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.
217
- `);let S=await a("Node name",r.BOSTRAT_NODE_NAME||Ge.hostname().split(".")[0]),p=await a("Repos root",r.BOSTRAT_REPOS_ROOT||C.join(Ge.homedir(),"Documents")),w=await a("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),O=(await a("Route NEW claude boxes through a BYO API key? (y/N)",r.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");O&&n.write(`
215
+ `);let c=await i("Plane URL",r.BOSTRAT_PLANE_URL||Qc),p=st(c);p!==c.trim()&&n.write(` \u2192 using ${p}
216
+ `);let h=await i("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.
217
+ `);let m=await i("Node name",r.BOSTRAT_NODE_NAME||Ve.hostname().split(".")[0]),f=await i("Repos root",r.BOSTRAT_REPOS_ROOT||B.join(Ve.homedir(),"Documents")),g=await i("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),E=(await i("Route NEW claude boxes through a BYO API key? (y/N)",r.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");E&&n.write(`
218
218
  BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
219
219
  injected per box, stored 0600 in node.env, never sent to the plane.
220
220
  \u2022 create/copy a key: https://console.anthropic.com/settings/keys
221
221
  \u2022 set a monthly spend limit while you're there \u2014 the key is live.
222
222
 
223
- `);let b=O?await a("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";O&&b&&!/^sk-ant-/.test(b)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
224
- `),s.close();let $={...mr(),...r,BOSTRAT_PLANE_URL:f,BOSTRAT_PLANE_TOKEN:m,BOSTRAT_NODE_NAME:S,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||S,BOSTRAT_REPOS_ROOT:p,BOSTRAT_STATE_REMOTE:w,BOSTRAT_CLAUDE_USE_API_KEY:O?"1":"0",ANTHROPIC_API_KEY:O?b:r.ANTHROPIC_API_KEY};delete $.BOSTRAT_OWNER,hr(e,$,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
223
+ `);let _=E?await i("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";E&&_&&!/^sk-ant-/.test(_)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
224
+ `),o.close();let $={...Ar(),...r,BOSTRAT_PLANE_URL:p,BOSTRAT_PLANE_TOKEN:h,BOSTRAT_NODE_NAME:m,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||m,BOSTRAT_REPOS_ROOT:f,BOSTRAT_STATE_REMOTE:g,BOSTRAT_CLAUDE_USE_API_KEY:E?"1":"0",ANTHROPIC_API_KEY:E?_:r.ANTHROPIC_API_KEY};delete $.BOSTRAT_OWNER,xr(e,$,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
225
225
  0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
226
226
  Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
227
227
  wrote ${e}
228
228
 
229
- `);let N={...$,...process.env},E=await Zo(N,{envFile:e}),P=Qo(E,v=>n.write(v+`
230
- `));return P&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:P,results:E}}var Qa="SIGUSR2",ec=5*6e4,tc=1e4,Kt=C.join(bt,"self-update","supervisor.pid");function nc({spawnChild:e,exit:t=S=>process.exit(S),now:n=Date.now,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:s=clearTimeout,killGraceMs:a=15e3,rollbackGraceMs:d=ec,stall:f=null,log:m=console}={}){let S=null,p=0,w=!1,O="update",b=0,$=null,N=null,E=null,P=0,v=0,g=0,x=!1,A=f&&f.staleMs>0?f.staleMs:0,k=f?.checkMs>0?f.checkMs:tc,I=()=>{$&&s($),$=null},Ae=()=>{S.kill("SIGTERM"),N=r(()=>S?.kill("SIGKILL"),a),N.unref?.()},qe=null,ke=0,Gt=()=>{let M=null;try{M=f.readHeartbeat()}catch{}return M&&M.pid===S.pid&&Number.isFinite(M.ts)&&M.ts!==qe&&(qe=M.ts,ke=Math.max(ke,Math.min(M.ts,n()))),n()-ke},wt=()=>{if(!S||x||w||!A)return!1;let M=Gt();return M<A?!1:(v++,g=M,m.error?.(`[bostrat-node] the agent (pid ${S.pid}) has written no heartbeat for ${Math.round(M/1e3)} s \u2014 stalled; relaunching it in place (boxes keep running on the host tmux server; stall relaunch #${v})`),O="stall",w=!0,Ae(),!0)},Oe=()=>{A&&(E&&s(E),E=r(()=>{E=null,wt(),Oe()},k),E.unref?.())},ze=(M=null)=>{let ce=e(M);return S=ce,p=n(),qe=null,ke=p,ce.on("exit",(le,ue)=>Ee(ce,le,ue)),E||Oe(),ce},Ee=(M,ce,le)=>{if(M!==S)return;if(S=null,N&&s(N),N=null,w){w=!1,Ve(O);return}let ue=le?1:ce??1;if(!x&&ue!==0&&n()<b){let Ye=b-n();m.error?.(`[bostrat-node] the agent exited (code ${ue}) right after a self-update restart \u2014 holding ${Math.ceil(Ye/1e3)} s for the updater's rollback signal`),$=r(()=>t(ue),Ye);return}t(ue)},Ve=(M="update")=>{P++,M==="stall"?m.log?.(`[bostrat-node] relaunched the agent after a stall (restart #${P}, stall relaunch #${v})`):(b=n()+d,m.log?.(`[bostrat-node] restarting the agent (self-update, restart #${P})`)),O="update",ze(M==="stall"?{at:n(),staleMs:g}:null)};return{start:()=>ze(),restart(){if(x=!1,I(),O="update",!S){Ve("update");return}w||(w=!0,Ae())},checkStall:wt,forward(M){x=!0,S?S.kill(M):(I(),t(1))},get child(){return S},get state(){return{alive:!!S,restartPending:w,restartReason:O,holding:!!$,restarts:P,stallRelaunches:v,stopping:x}}}}function rc({envFile:e=Be()}={}){fr(e),process.title="bostrat-node";let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n={...process.env,BOSTRAT_RUN_SUPERVISOR_PID:String(process.pid),[qr]:"supervisor"};Qr();try{K.mkdirSync(C.dirname(Kt),{recursive:!0}),K.writeFileSync(Kt,`${process.pid}
231
- `)}catch{}let r=io(process.env),s=xn(process.env);console.log(r?`[bostrat-node] stall watchdog: relaunch the agent after ${Math.round(r/1e3)} s without a heartbeat (${s})`:"[bostrat-node] stall watchdog: off (BOSTRAT_HEARTBEAT_STALE_MS)");let a=nc({spawnChild:d=>Ea(t,[Pa],{cwd:xe,stdio:"inherit",env:d?{...n,[lo]:uo(d)}:n}),stall:r?{readHeartbeat:()=>ao(s),staleMs:r}:null});for(let d of["SIGINT","SIGTERM"])process.on(d,()=>a.forward(d));return process.on(Qa,()=>a.restart()),process.on("exit",()=>{try{K.readFileSync(Kt,"utf8").trim()===String(process.pid)&&K.rmSync(Kt,{force:!0})}catch{}}),a.start()}function oc({agentDir:e=xe,nodeBin:t=process.execPath,envFile:n=Be(),home:r=Ge.homedir()}={}){let s=C.dirname(t),a=C.join(C.basename(Gn),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
229
+ `);let N={...$,...process.env},R=await Ls(N,{envFile:e}),D=Fs(R,v=>n.write(v+`
230
+ `));return D&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:D,results:R}}var yl="SIGUSR2",bl=5*6e4,Tl=1e4,Yt=B.join(xt,"self-update","supervisor.pid");function Sl({spawnChild:e,exit:t=m=>process.exit(m),now:n=Date.now,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:o=clearTimeout,killGraceMs:i=15e3,rollbackGraceMs:c=bl,stall:p=null,log:h=console}={}){let m=null,f=0,g=!1,E="update",_=0,$=null,N=null,R=null,D=0,v=0,T=0,k=!1,x=p&&p.staleMs>0?p.staleMs:0,A=p?.checkMs>0?p.checkMs:Tl,I=()=>{$&&o($),$=null},Ee=()=>{m.kill("SIGTERM"),N=r(()=>m?.kill("SIGKILL"),i),N.unref?.()},Ye=null,Oe=0,Xt=()=>{let M=null;try{M=p.readHeartbeat()}catch{}return M&&M.pid===m.pid&&Number.isFinite(M.ts)&&M.ts!==Ye&&(Ye=M.ts,Oe=Math.max(Oe,Math.min(M.ts,n()))),n()-Oe},Tt=()=>{if(!m||k||g||!x)return!1;let M=Xt();return M<x?!1:(v++,T=M,h.error?.(`[bostrat-node] the agent (pid ${m.pid}) has written no heartbeat for ${Math.round(M/1e3)} s \u2014 stalled; relaunching it in place (boxes keep running on the host tmux server; stall relaunch #${v})`),E="stall",g=!0,Ee(),!0)},Re=()=>{x&&(R&&o(R),R=r(()=>{R=null,Tt(),Re()},A),R.unref?.())},Xe=(M=null)=>{let le=e(M);return m=le,f=n(),Ye=null,Oe=f,le.on("exit",(ue,de)=>Ne(le,ue,de)),R||Re(),le},Ne=(M,le,ue)=>{if(M!==m)return;if(m=null,N&&o(N),N=null,g){g=!1,Je(E);return}let de=ue?1:le??1;if(!k&&de!==0&&n()<_){let Ze=_-n();h.error?.(`[bostrat-node] the agent exited (code ${de}) right after a self-update restart \u2014 holding ${Math.ceil(Ze/1e3)} s for the updater's rollback signal`),$=r(()=>t(de),Ze);return}t(de)},Je=(M="update")=>{D++,M==="stall"?h.log?.(`[bostrat-node] relaunched the agent after a stall (restart #${D}, stall relaunch #${v})`):(_=n()+c,h.log?.(`[bostrat-node] restarting the agent (self-update, restart #${D})`)),E="update",Xe(M==="stall"?{at:n(),staleMs:T}:null)};return{start:()=>Xe(),restart(){if(k=!1,I(),E="update",!m){Je("update");return}g||(g=!0,Ee())},checkStall:Tt,forward(M){k=!0,m?m.kill(M):(I(),t(1))},get child(){return m},get state(){return{alive:!!m,restartPending:g,restartReason:E,holding:!!$,restarts:D,stallRelaunches:v,stopping:k}}}}function _l({envFile:e=Be()}={}){kr(e),process.title="bostrat-node";let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n={...process.env,BOSTRAT_RUN_SUPERVISOR_PID:String(process.pid),[_o]:"supervisor"};Oo();try{K.mkdirSync(B.dirname(Yt),{recursive:!0}),K.writeFileSync(Yt,`${process.pid}
231
+ `)}catch{}let r=Co(process.env),o=Cn(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 i=Sl({spawnChild:c=>qc(t,[Zc],{cwd:Ae,stdio:"inherit",env:c?{...n,[Fo]:jo(c)}:n}),stall:r?{readHeartbeat:()=>Bo(o),staleMs:r}:null});for(let c of["SIGINT","SIGTERM"])process.on(c,()=>i.forward(c));return process.on(yl,()=>i.restart()),process.on("exit",()=>{try{K.readFileSync(Yt,"utf8").trim()===String(process.pid)&&K.rmSync(Yt,{force:!0})}catch{}}),i.start()}function vl({agentDir:e=Ae,nodeBin:t=process.execPath,envFile:n=Be(),home:r=Ve.homedir()}={}){let o=B.dirname(t),i=B.join(B.basename(rr),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
232
232
  # ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
233
233
  [Unit]
234
234
  Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
@@ -238,17 +238,21 @@ After=default.target
238
238
  Type=simple
239
239
  WorkingDirectory=${e}
240
240
  # Pinned runtime: node-pty is compiled against exactly this node (SEGV trap).
241
- ExecStart=${t} --disable-warning=ExperimentalWarning ${a}
241
+ ExecStart=${t} --disable-warning=ExperimentalWarning ${i}
242
242
  EnvironmentFile=${n}
243
243
  # systemd's user PATH omits ~/.local/bin (cursor-agent, bostrat-view) and the
244
244
  # nvm bin dir \u2014 both are load-bearing for box spawning.
245
- Environment=PATH=${r}/.local/bin:${s}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
245
+ Environment=PATH=${r}/.local/bin:${o}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
246
+ # glibc keeps freed malloc chunks per thread arena (64 MB each, one per libuv /
247
+ # V8 worker that ever allocated); two arenas bound what the boot burst leaves
248
+ # resident (boot-release.js carries the V8 half).
249
+ Environment=MALLOC_ARENA_MAX=2
246
250
  Restart=on-failure
247
251
  RestartSec=2
248
252
 
249
253
  [Install]
250
254
  WantedBy=default.target
251
- `}function sc({agentDir:e=xe,nodeBin:t=process.execPath,home:n=Ge.homedir()}={}){let r=C.dirname(t),s=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
255
+ `}function $l({agentDir:e=Ae,nodeBin:t=process.execPath,home:n=Ve.homedir()}={}){let r=B.dirname(t),o=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
252
256
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
253
257
  <plist version="1.0">
254
258
  <dict>
@@ -266,11 +270,11 @@ WantedBy=default.target
266
270
  </dict>
267
271
  <key>RunAtLoad</key><true/>
268
272
  <key>KeepAlive</key><true/>
269
- <key>StandardOutPath</key><string>${s}/node.out.log</string>
270
- <key>StandardErrorPath</key><string>${s}/node.err.log</string>
273
+ <key>StandardOutPath</key><string>${o}/node.out.log</string>
274
+ <key>StandardErrorPath</key><string>${o}/node.err.log</string>
271
275
  </dict>
272
276
  </plist>
273
- `}function ic(e=process.platform,t=Ge.homedir()){return e==="darwin"?{kind:"launchd",file:C.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:C.join(t,".config","systemd","user","bostrat-node.service")}}async function ac({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:s=xe}={}){let{kind:a,file:d}=ic(n);if(!e&&s.split(C.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){a==="systemd"?(await me("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),K.rmSync(d,{force:!0}),await me("systemctl",["--user","daemon-reload"])):(await me("launchctl",["unload","-w",d]).catch(()=>{}),K.rmSync(d,{force:!0})),r(`removed ${d}`);return}K.mkdirSync(C.dirname(d),{recursive:!0}),a==="systemd"?(K.writeFileSync(d,oc()),await me("systemctl",["--user","daemon-reload"]),t&&await me("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${d}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(K.mkdirSync(C.join(Ge.homedir(),"Library","Logs","bostrat"),{recursive:!0}),K.writeFileSync(d,sc()),t&&await me("launchctl",["load","-w",d]),r(`installed ${d}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function mp(e=process.argv.slice(2)){let t=e[0],n=Be();if(t==="--version"||t==="-v"||t==="version")return console.log(Ke),0;if(t==="init")return(await Za({envFile:n})).ok?0:1;if(t==="doctor"){let r={...vt(n),...process.env};return Qo(await Zo(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return rc({envFile:n}),null;if(t==="install-service")return await ac({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(go(),yo));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:s,updatePolicy:a}=await Promise.resolve().then(()=>(Yo(),Vo)),{detectInstallKind:d}=await Promise.resolve().then(()=>(Cn(),jo)),f=d(),m=e.indexOf("--to"),S=m>=0?String(e[m+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Ke,installKind:f,policy:a({kind:f}),status:await s()},null,2)),0;if(!S)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 p=await r({to:S,kind:f,reason:"cli",force:!0});return p.ok?(console.log(`\u2713 self-update ${p.from??"?"} \u2192 ${p.to} started (${p.kind}) \u2014 status: ${p.statusFile}; the node restarts when the install completes`),0):(console.error(`\u2717 not started: ${p.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
277
+ `}function kl(e=process.platform,t=Ve.homedir()){return e==="darwin"?{kind:"launchd",file:B.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:B.join(t,".config","systemd","user","bostrat-node.service")}}async function xl({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=Ae}={}){let{kind:i,file:c}=kl(n);if(!e&&o.split(B.sep).includes("_npx"))return r("\u2717 running from the npx cache \u2014 a service must point at a durable install."),r(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){i==="systemd"?(await we("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),K.rmSync(c,{force:!0}),await we("systemctl",["--user","daemon-reload"])):(await we("launchctl",["unload","-w",c]).catch(()=>{}),K.rmSync(c,{force:!0})),r(`removed ${c}`);return}K.mkdirSync(B.dirname(c),{recursive:!0}),i==="systemd"?(K.writeFileSync(c,vl()),await we("systemctl",["--user","daemon-reload"]),t&&await we("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${c}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(K.mkdirSync(B.join(Ve.homedir(),"Library","Logs","bostrat"),{recursive:!0}),K.writeFileSync(c,$l()),t&&await we("launchctl",["load","-w",c]),r(`installed ${c}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function nh(e=process.argv.slice(2)){let t=e[0],n=Be();if(t==="--version"||t==="-v"||t==="version")return console.log(qe),0;if(t==="init")return(await gl({envFile:n})).ok?0:1;if(t==="doctor"){let r={...At(n),...process.env};return Fs(await Ls(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return _l({envFile:n}),null;if(t==="install-service")return await xl({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(qo(),zo));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:i}=await Promise.resolve().then(()=>(Ds(),Ps)),{detectInstallKind:c}=await Promise.resolve().then(()=>(Vn(),xs)),p=c(),h=e.indexOf("--to"),m=h>=0?String(e[h+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:qe,installKind:p,policy:i({kind:p}),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 f=await r({to:m,kind:p,reason:"cli",force:!0});return f.ok?(console.log(`\u2713 self-update ${f.from??"?"} \u2192 ${f.to} started (${f.kind}) \u2014 status: ${f.statusFile}; the node restarts when the install completes`),0):(console.error(`\u2717 not started: ${f.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
274
278
 
275
279
  usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
276
280
 
@@ -279,4 +283,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
279
283
  run start the node in the foreground (sources node.env)
280
284
  install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
281
285
  fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
282
- self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{Qa as RESTART_SIGNAL,ec as ROLLBACK_GRACE_MS,tc as STALL_CHECK_MS,Kt as SUPERVISOR_PID_FILE,nc as createRunSupervisor,Za as init,ac as installService,sc as launchdPlist,mp as main,Qo as printDoctor,rc as runAgent,Zo as runDoctor,ic as servicePaths,oc as systemdUnit};
286
+ self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{yl as RESTART_SIGNAL,bl as ROLLBACK_GRACE_MS,Tl as STALL_CHECK_MS,Yt as SUPERVISOR_PID_FILE,Sl as createRunSupervisor,gl as init,xl as installService,$l as launchdPlist,nh as main,Fs as printDoctor,_l as runAgent,Ls as runDoctor,kl as servicePaths,vl as systemdUnit};