bostrat-node 1.16.5 → 1.16.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/bostrat-audit +6 -4
- package/bin/bostrat-estimate +4 -3
- package/bin/bostrat-secret +6 -0
- package/dist/cli.js +104 -92
- package/dist/index.js +355 -302
- package/node-entrypoint.sh +39 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let
|
|
3
|
-
`).map(o=>o?`# ${o}`:"#"));for(let[o,
|
|
1
|
+
var ea=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 En=(e,t)=>{for(var n in t)ea(e,n,{get:t[n],enumerable:!0})};import Ct from"node:fs";import On from"node:path";import ta from"node:os";function pt(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,r;try{r=new URL(n)}catch{return t}let o={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return o?(r.protocol=o,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function jt(e){let t;try{t=Ct.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
|
|
2
|
+
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!s)continue;let a=s[2].trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n[s[1]]=a}return n}function Qr(e,t=process.env){let n=jt(e);for(let[r,o]of Object.entries(n))r in t||(t[r]=o);return n}function eo(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
|
|
3
|
+
`).map(o=>o?`# ${o}`:"#"));for(let[o,s]of Object.entries(t))s==null||s===""||r.push(`${o}=${s}`);Ct.mkdirSync(On.dirname(e),{recursive:!0}),Ct.writeFileSync(e,r.join(`
|
|
4
4
|
`)+`
|
|
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
|
-
`))
|
|
5
|
+
`,{mode:384}),Ct.chmodSync(e,384)}function to(e=process.platform){return e==="darwin"?{BOSTRAT_TMUX_BIN:"/opt/homebrew/bin/tmux",BOSTRAT_TMUX_SOCKET:`/tmp/tmux-${process.getuid?.()??501}/bostrat`,BOSTRAT_CHROMIUM_BIN:"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"}:{}}var Bt,Ue,Rn=O(()=>{Bt=process.env.BOSTRAT_STATE_DIR||On.join(process.env.HOME||ta.tmpdir(),".bostrat"),Ue=()=>On.join(Bt,"node.env")});var cd,Ft=O(()=>{cd=16*1024});var le,ht,Lt=O(()=>{le="BOSTRAT_HOOK_TOKEN",ht="x-bostrat-hook"});var na,dd,no=O(()=>{na=(e,t)=>{if(e==null||e==="")return t;let n=Number(e);return Number.isFinite(n)&&n>=0?n:t},dd=na(process.env.BOSTRAT_HOOK_FOLD_MS,250)});function ca(e,t=oa){let n=String(e??""),r=n.split(/\s*(?:;|&&|\|\||\||\n)\s*/).map(o=>o.trim()).filter(Boolean);return Number.isFinite(t)&&n.length>=t&&r.length&&r.pop(),r}function Ut(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function fo(e){let t=0;for(;t<e.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]);)t++;return{cmd:e[t]??null,rest:e.slice(t+1),at:t}}function co(e){let t=Ut(e),n=t.findIndex(m=>m==="git"||m.endsWith("/git"));if(n<0)return null;for(n++;n<t.length&&t[n].startsWith("-");)(t[n]==="-C"||t[n]==="-c")&&n++,n++;if(t[n]!=="push")return null;let r=[],o=[];for(let m=n+1;m<t.length;m++){let h=t[m];h.startsWith("-")?(r.push(h),(h==="-o"||h==="--push-option"||h==="--repo"||h==="--receive-pack"||h==="--exec")&&m++):o.push(h)}let s=r.some(m=>m==="--force"||/^-[a-zA-Z]+$/.test(m)&&m.includes("f"))||o.some(m=>m.startsWith("+")),a=r.some(m=>m.startsWith("--force-with-lease")||m.startsWith("--force-if-includes")),u=o[0]??null,p=o.slice(1).map(m=>m.replace(/^["']|["']$/g,"").replace(/^\+/,"")).map(m=>m.includes(":")?m.slice(m.indexOf(":")+1):m).filter(m=>m&&!m.startsWith("$"));return{force:s,lease:a,remote:u,dsts:p}}function mo(e){let{cmd:t,at:n}=fo(e);if(t==="sudo"){for(n++;n<e.length&&e[n].startsWith("-");)n++;t=e[n]??null}return{cmd:t,at:n}}function wo(e,t){let n=String(e??"").match(t);if(!n)return null;let r=n[1],o=r.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");if(new RegExp(`>{1,2}\\s*["']?[^\\s"']*${o}`).test(e))return"redirect";let s=Ut(e),{cmd:a}=mo(s);return!a||!s.some(u=>u.includes(r))?null:/^(?:rm|mv|truncate|chmod|chown|tee|install|shred|unlink|ln|mkdir|touch)$/.test(a)?a:a==="sed"&&s.some(u=>/^-[a-zA-Z]*i/.test(u))?"sed -i":a==="cp"&&s[s.length-1].includes(r)?"cp":/^(?:python3?|perl|node|ruby)$/.test(a)&&/open\([^)]*['"][wa]|writeFile|write_text|appendFile|fs\.write/.test(e)?`${a} write`:null}function _a(e){let t=Ut(e),{cmd:n,at:r}=mo(t);if(!n)return null;let o=t.slice(r+1);if(n==="crontab"||n.endsWith("/crontab")){let a=!1,u=!1;for(let p=0;p<o.length;p++){if(o[p]==="-u"){p++;continue}o[p]==="-l"||/^-(?:h|V|T|-help|-version)$/.test(o[p])?a=!0:u=!0}return u||!a?"crontab":null}if(n==="systemctl"||n.endsWith("/systemctl")){let a=o.find(u=>!u.startsWith("-"));return a&&pa.test(a)?`systemctl ${a}`:null}if((n==="loginctl"||n.endsWith("/loginctl"))&&o.includes("enable-linger"))return"loginctl enable-linger";if(n==="at"&&o.length&&/^(?:now|midnight|noon|teatime|today|tomorrow|next|\d|-[fqmvt])/.test(o[0]))return"at";let s=wo(e,ho);return s?`${s} unit/cron path`:null}function xa(e){let t=new Set;for(let n of String(e??"").matchAll(ga))t.add(n[1].toLowerCase());return[...t]}var ra,oa,ro,oo,so,io,ao,wd,sa,ia,Nn,aa,Ae,In,la,ua,da,fa,po,ho,pa,ha,ma,wa,ga,lo,uo,ya,ba,Sa,Ta,Z,mt,Mn,go,gd,yd,yo=O(()=>{no();ra="BP-AU-R4",oa=160,ro=200,oo=5,so=8,io=5,ao=10*6e4,wd=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"]),sa=5e3,ia=new Set(["tool.called","tool.failed"]),Nn=new Set(["Write","Edit","NotebookEdit"]),aa=e=>String(e??"").replace(/\s+/g," ").trim(),Ae=(e,t=120)=>aa(e).slice(0,t);In=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,la=new RegExp(`${In}/\\.ssh(?:/|\\b)`),ua=new RegExp(`${In}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),da=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,fa=/^\.env\.(?:example|sample|template|dist)$/,po=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,ho=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${In}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),pa=/^(?: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)$/,ha=/^\/tmp\/|\/\.bostrat\/tmp\//,ma=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,wa=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,ga=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,lo=e=>la.test(e)||ua.test(e),uo=e=>[...String(e??"").matchAll(da)].some(t=>!fa.test(t[1])),ya=e=>po.test(e),ba=e=>ho.test(e),Sa=e=>(e.startsWith("/")||e.startsWith("~"))&&!ha.test(e);Ta=e=>wo(e,po);Z=(e,t,n,r)=>Object.freeze({severity:e,requirement:ra,note:t,measured:n,detect:r}),mt=(e,t)=>{let n=0,r=null;for(let o of e.calls)if(o.head)for(let s of ca(o.head,e.headCap)){let a=t(s,o);a&&(n++,r??=Ae(a))}return n?{count:n,sample:r}:null},Mn=(e,t)=>{let n=0,r=null;for(let o of e.calls){let s=t(o);s&&(n++,r??=Ae(s))}return n?{count:n,sample:r}:null},go=Object.freeze({"force-push":Z("high","git push --force / -f / +refspec in a command head (--force-with-lease, the Track's own rebase flow, is not one)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 1,080 logs 2026-08\u219210 \xB7 58 --force-with-lease pushes excluded by design \u2192 high",(e,t)=>mt(t,n=>{let r=co(n);return r&&r.force&&!r.lease?n:null})),"protected-config-write":Z("high","a write to the box's own harness: .claude/settings*.json, a .claude/hooks/ script or the Track's .bostrat/events/ log \u2014 by a file tool, a redirect, rm/mv/tee/sed -i, or a scripted open-for-write (reads are not hits)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 165 reads of those paths (cat, grep, python json.loads) excluded by design \u2192 high",(e,t)=>{let n=0,r=null;for(let s of t.calls)Nn.has(s.tool)&&s.path&&ya(s.path)&&(n++,r??=Ae(`${s.tool} ${s.path}`));let o=mt(t,s=>{let a=Ta(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"persistence-install":Z("medium","a shell segment that installs something the OS runs on its own \u2014 crontab (install / edit / remove; -l is a read), a mutating systemctl verb (enable / start / restart / daemon-reload \u2026; status / show / cat / list / is-* are reads), loginctl enable-linger, at / batch \u2014 or a write (file tool, redirect, cp / mv / tee / ln / sed -i) into a systemd unit or cron directory: how a process outlives its turn by the OS's hand (BP-AU-D6's other half)","2026-10-21 fleet replay \xB7 11 hits / 99,122 hook calls \xB7 10 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-asked service work on the operator's own Pi (systemctl --user restart/stop/start of bostrat-node, tmp-sweep, a samba disable, one `crontab -` install for a backfill) \xB7 the bare `at` word a quoted `|` regex leaves in a segment (4 hits) excluded by design \u2192 medium (rail), the guard's deny when opted in",(e,t)=>{let n=0,r=null;for(let s of t.calls)Nn.has(s.tool)&&s.path&&ba(s.path)&&(n++,r??=Ae(`${s.tool} ${s.path}`));let o=mt(t,s=>{let a=_a(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"push-outside-track":Z("medium","git push to a protected branch (main/master/develop/release\u2026), to a branch that is not a Track branch, or to a remote other than origin/upstream \u2014 a Track's own code leaves on its track/ branch or the WIP shadow ref","2026-10-21 fleet replay \xB7 7 hits / 98,690 hook calls \xB7 4 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-instructed work on another repo (two dep/ branches, a fork's multiplayer branch, one HEAD:main) \u2192 medium, not a page",(e,t)=>mt(t,n=>{let r=co(n);return r&&(r.remote&&!/^(?:origin|upstream)$/.test(r.remote)&&!r.remote.startsWith("$")&&!r.remote.startsWith("-")||r.dsts.some(o=>ma.test(o)||!wa.test(o)))?n:null})),"credential-read":Z("medium","a command head or file path naming SSH material (~/.ssh) or a vendor auth file (~/.claude.json, ~/.claude/.credentials.json, ~/.codex/auth.json, ~/.cursor) \u2014 the box-auth policy's denylist shapes; ~/.claude/projects (transcripts) is not one","2026-10-21 fleet replay \xB7 12 hits / 98,690 hook calls \xB7 8 Tracks \xB7 3 in the last 14 d \xB7 every hit an operator-asked inspection on the operator's own node (ssh config for a host alias, stat/keys of ~/.claude.json) \u2192 medium until a 14-day window reads 0",(e,t)=>Mn(t,n=>n.head&&lo(n.head)?n.head:n.path&&lo(n.path)?`${n.tool} ${n.path}`:null)),"dotenv-read":Z("low","a command head or file path naming a .env file (.env, .env.local, .env.production \u2026; the committed .env.example / .sample / .template are not ones)","2026-10-21 fleet replay \xB7 309 hits / 98,690 hook calls \xB7 44 Tracks \xB7 0 in the last 14 d \xB7 all of them an instructed `source \u2026/almanac/.env` on the operator's other repos \u2192 low (report only)",(e,t)=>Mn(t,n=>n.head&&uo(n.head)?n.head:n.path&&uo(n.path)?`${n.tool} ${n.path}`:null)),"privileged-command":Z("medium","a shell segment whose command is sudo or docker (after any VAR=value prefix) \u2014 host-level reach from inside a box","2026-10-21 fleet replay \xB7 220 hits (183 events) / 98,690 hook calls \xB7 57 Tracks \xB7 3 in the last 14 d \xB7 sudo = the operator's own journalctl/systemctl asks on the Pi, docker = instructed compose/psql work on the operator's other services \u2192 medium (a hosted node's first hit is the number to watch)",(e,t)=>mt(t,n=>{let{cmd:r}=fo(Ut(n));return r==="sudo"||r==="docker"?n:null})),"write-outside-workspace":Z("low","a file tool (Write / Edit / NotebookEdit) on an absolute path \u2014 the hook strips the box's workspace prefix, so an absolute path is outside it \u2014 that is not the box's scratch dir (/tmp/\u2026, \u2026/.bostrat/tmp/\u2026)","2026-10-21 fleet replay \xB7 106 hits / 98,690 hook calls \xB7 10 Tracks \xB7 44 in the last 14 d \xB7 the operator's other repos and Agent-tool worktrees under .bostrat/repos on the operator's own node \u2192 low (report only)",(e,t)=>Mn(t,n=>Nn.has(n.tool)&&n.path&&Sa(n.path)?`${n.tool} ${n.path}`:null)),"egress-new-host":Z("low","a command head reaching, by URL, a host no box in the fleet has reached before (this projection's lifetime, seeded from the warm tails; KNOWN_HOSTS + PLANE_AUDIT_KNOWN_HOSTS never count) \u2014 a baseline-growth signal, so each host is reported once","2026-10-21 fleet replay \xB7 140 first sightings / 98,690 hook calls \xB7 69 Tracks \xB7 8 in the last 14 d \xB7 198 if the baseline were per Track \xB7 every host a vendor API, a docs site or the operator's own services \u2192 low (report only)",(e,t)=>{let n=0,r=null;for(let o of t.calls)if(o.head)for(let s of xa(o.head))t.state.known.has(s)||t.state.hosts.has(s)||(t.state.hosts.add(s),t.state.hosts.size>sa&&t.state.hosts.delete(t.state.hosts.values().next().value),n++,r??=Ae(`${s} \xB7 ${o.head}`));return n?{count:n,sample:r}:null}),"spend-spike":Z("low",`a cost.recorded turn over ${so}\xD7 the Track's running median (its last ${ro} cost events, at least ${oo} of them) and over $${io} \u2014 a turn that cost far more than this Track's turns do`,"2026-10-21 fleet replay \xB7 114 hits / 8,421 cost events \xB7 64 Tracks \xB7 2 in the last 14 d \xB7 every hit a long build turn after short prompts (a $25\u201378 turn on a $0.37 median) \u2014 real spend, no one's attack \u2192 low (report only)",(e,t)=>{if(e.type!=="cost.recorded")return null;let n=t.track.costs,r=Number(e.payload?.usd);if(!Number.isFinite(r)||r<0)return null;let o=null;if(n.length>=oo&&r>=io){let s=[...n].sort((u,p)=>u-p),a=s[Math.floor(s.length/2)];r>so*a&&(o={count:1,sample:`$${r.toFixed(2)} vs median $${a.toFixed(2)} over ${n.length} turns${e.payload?.model?` \xB7 ${e.payload.model}`:""}`})}return n.push(r),n.length>ro&&n.shift(),o}),"peer-injected-call":Z("medium",`a tool call within ${ao/6e4} min of a peer.message on the same box with no operator or node-typed turn in between \u2014 the cross-session injection vector (peer-message.js); a peer is never a root (BP-AU-D1)`,"2026-10-21 fleet replay \xB7 0 peer.message events in 288,395 \xB7 the replay cannot bound this rule's rate, so it stays medium (rail) until a window with peer traffic has been measured; the shape itself is BP-AU-D1's stated R4 case",(e,t)=>{if(!t.calls.length)return null;let n=t.track.peer.get(t.boxKey);if(n==null||t.ts-n>ao||t.ts<n)return null;let r=t.calls[0];return{count:t.count,sample:Ae(`${Math.round((t.ts-n)/1e3)}s after a peer message \xB7 ${r.tool}${r.head?`: ${r.head}`:r.path?` ${r.path}`:""}`)}}),"foreign-session-call":Z("medium","a hook-recorded tool call from a claude session that is not the box's own (payload.foreignSession, BP-AU-I12): a nested or stray CLI driving the box's hooks \u2014 R3 never roots it, this names it","2026-10-21 fleet replay \xB7 14 hits / 98,744 hook calls \xB7 3 Tracks \xB7 4 in the last 14 d \xB7 all the xscout loop's nested claude prompts, I12's own acceptance case \u2192 medium (rail), not a page",(e,t)=>{if(!t.calls.length||!e.payload?.foreignSession)return null;let n=t.calls[0];return{count:t.count,sample:Ae(`session ${String(e.payload.sessionId||"?").slice(0,8)} \xB7 ${n.tool}${n.head?`: ${n.head}`:n.path?` ${n.path}`:""}`)}})}),gd=Object.freeze(Object.keys(go)),yd=new Set([...ia,"cost.recorded","peer.message","turn.user"])});function Aa(e){let t=String(e??"").trim().toLowerCase();if($a.has(t))return{enabled:!1,rules:[],unknown:[]};if(va.has(t))return{enabled:!0,rules:[...Pn],unknown:[]};let n=[],r=[];for(let o of t.split(",")){let s=o.trim();s&&(Pn.includes(s)?n.includes(s)||n.push(s):r.push(s))}return{enabled:n.length>0,rules:n,unknown:r}}function bo(e){return e?.enabled?`on \xB7 denies ${e.rules.length===Pn.length?"the high set: ":""}${e.rules.join(", ")}${e.unknown.length?` \xB7 ignoring unknown ${e.unknown.join(", ")}`:""} \xB7 fail-open (an unanswered hook allows)`:"off (BOSTRAT_AUDIT_GUARD unset \u2014 PreToolUse records, never denies)"}var Pn,$a,va,Dn,Cn=O(()=>{yo();Pn=Object.freeze(["force-push","protected-config-write","credential-read","persistence-install"]),$a=new Set(["","off","0","false","no","none"]),va=new Set(["on","1","true","yes","all"]);Dn=(e=process.env)=>Aa(e.BOSTRAT_AUDIT_GUARD)});import He from"node:fs";import To from"node:fs/promises";import Wt from"node:os";import V from"node:path";import{execFile as _o}from"node:child_process";import{promisify as ka}from"node:util";function vo(e){try{return He.readFileSync(e,"utf8").split(`
|
|
6
|
+
`).filter(t=>t&&!t.startsWith("#")).map(t=>t.split(":"))}catch{return[]}}function Ao(e,t=process.env){let r=vo(t.BOSTRAT_PASSWD_FILE||"/etc/passwd").find(o=>o[0]===String(e)||o[2]===String(e));return r?{name:r[0],uid:Number(r[2]),gid:Number(r[3]),home:r[5]||null,shell:r[6]||null}:null}function ko(e,t=process.env){let n=vo(t.BOSTRAT_GROUP_FILE||"/etc/group"),r=new Set;for(let o of n)Number(o[2])===e.gid&&r.add(o[0]),(o[3]||"").split(",").includes(e.name)&&r.add(o[0]);return[...r].sort()}function wt(e=process.env){let t=String(e[Ln]||"").trim();if(Ra.has(t.toLowerCase()))return null;let n=`${t}|${e.BOSTRAT_PASSWD_FILE||""}|${e.BOSTRAT_GROUP_FILE||""}|${e.BOSTRAT_BOX_HOME_VIEW||""}`;if(Bn?.key===n)return Bn.value;let r;if(!Oa.test(t))r={name:t,error:`${Ln}="${t}" is not a valid user name`};else{let o=Ao(t,e),s=Ht();if(!o)r={name:t,error:`user "${t}" does not exist \u2014 run scripts/pi/box-user-setup.sh (or the image's useradd)`};else if(o.uid===0)r={name:t,error:`user "${t}" is root`};else if(o.uid===s)r={name:t,error:`user "${t}" is the node's own uid`};else if(!o.home||o.home==="/"||o.home==="/nonexistent")r={name:t,error:`user "${t}" has no home directory`};else{let a=ko(o,e),u=a.filter(p=>xo.includes(p));r=u.length?{name:t,error:`user "${t}" is in ${u.join(", ")} \u2014 a box user must hold no route to root`}:{...o,groups:a,nodeUid:s,rootNode:s===0}}}return Bn={key:n,value:r},r}function We(e=process.env){let t=wt(e);return t&&!t.error?t.home:Wt.homedir()}function So(e=process.env){let t=wt(e);return!t||t.error||t.rootNode?We(e):e.BOSTRAT_BOX_HOME_VIEW||V.join($o(e),"box-home")}function Na(e,t=process.env){let n=wt(t);return!n||n.error?e:n.rootNode?["setpriv",`--reuid=${n.uid}`,`--regid=${n.gid}`,"--init-groups","--","env",`HOME=${n.home}`,`USER=${n.name}`,`LOGNAME=${n.name}`,...e]:["sudo","-n","-H","-u",n.name,"--",...e]}async function jn(e,{env:t=process.env,input:n=null,timeout:r=15e3}={}){let[o,...s]=Na(e,t);return n==null?Un(o,s,{timeout:r}):new Promise((a,u)=>{_o(o,s,{timeout:r},(m,h,g)=>m?u(m):a({stdout:h,stderr:g})).stdin.end(n)})}function Ma(e){return e.BOSTRAT_SETFACL_BIN?e.BOSTRAT_SETFACL_BIN:(Fn===void 0&&(Fn=["/usr/bin/setfacl","/bin/setfacl"].find(t=>He.existsSync(t))||null),Fn)}function Ia(e=process.env){let t=Wt.homedir(),n=$o(e);return[V.join(t,".ssh"),V.join(t,".claude.json"),V.join(t,".claude",".credentials.json"),V.join(t,".codex","auth.json"),V.join(t,".config","gh","hosts.yml"),V.join(t,".cursor","cli-config.json"),V.join(n,"node.env"),V.join(n,"api-token"),V.join(n,"plane-link"),V.join(n,"secure-inputs")]}async function Eo({env:e=process.env,probe:t=!0}={}){let n=wt(e),r=await Ca(e);if(!n){let s=Ao(Ht(),e)||{name:Wt.userInfo().username,uid:Ht(),gid:-1},a=s.uid===0?["root"]:ko(s,e).filter(m=>xo.includes(m)),u=s.uid!==0&&t?await Da():!1,p=[...a,...u&&!a.includes("sudo")?["sudo (sudoers)"]:[]];return{level:p.length?"root-capable":"node-uid",user:s.name,routes:p,problems:[],auditd:r}}if(n.error)return{level:"misconfigured",user:n.name,error:n.error,problems:[n.error],auditd:r};let o=[];if(t){try{let{stdout:p}=await jn(["id","-u"],{env:e,timeout:5e3});Number(p.trim())!==n.uid&&o.push(`switching to ${n.name} landed as uid ${p.trim()}`)}catch(p){o.push(`the node cannot switch to ${n.name} (${n.rootNode?"setpriv":"sudo -n -u"} failed: ${Pa(p)})`)}if(!o.length){await jn(["sudo","-n","true"],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&o.push(`${n.name} can sudo`);let p=[];for(let m of Ia(e))He.existsSync(m)&&await jn(["test","-r",m],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&p.push(m);p.length&&o.push(`${n.name} can read ${p.join(", ")}`)}Ma(e)||o.push("setfacl is missing (apt install acl)");let s=So(e);s!==n.home&&!He.existsSync(V.join(s,".claude"))&&o.push(`the read-only mirror of ${n.home} is not mounted at ${s} \u2014 the node cannot read box transcripts`);let a=V.join(n.home,".claude","settings.json"),u=await To.stat(a).catch(()=>null);u&&u.uid===n.uid&&o.push(`${a} is owned by ${n.name} \u2014 the box can rewrite its own hooks`)}return{level:"uid",user:n.name,uid:n.uid,home:n.home,view:So(e),problems:o,auditd:r}}async function Da(){try{return await Un("sudo",["-n","true"],{timeout:3e3}),!0}catch{return!1}}async function Ca(e=process.env,{ask:t=!0}={}){let n=e.BOSTRAT_AUDIT_LOG||"/var/log/audit/audit.log",r=!1;try{await To.access(n,He.constants.R_OK),r=!0}catch{}let o=e.BOSTRAT_AUDIT_RULES_FILE||"/etc/audit/rules.d/bostrat-box.rules",s=He.existsSync(o),a=null;if(t&&s){let u=Ht()===0?["auditctl",["-l"]]:["sudo",["-n","auditctl","-l"]];try{let{stdout:p}=await Un(u[0],u[1],{timeout:5e3});a=p.includes(`key=${Ea}`)}catch{a=null}}else s||(a=!1);return{log:n,readable:r,configured:s,rule:a,rulesFile:o}}function Oo(e){let t=e.auditd||{},n=t.rule===!0&&t.readable?"auditd execve logging on":t.rule===!0?"auditd rule loaded, but the node cannot read the log":t.configured&&t.rule===null?`auditd rule configured (not verifiable without root)${t.readable?"":", log unreadable"}`:t.configured?"auditd rule configured but NOT loaded":"no auditd";if(e.level==="uid"){let r=e.problems.length?` \u2014 ${e.problems.length} problem(s): ${e.problems.join("; ")}`:"";return`boxes run as ${e.user} (uid ${e.uid}, no route to root), event log + hook settings read-only to them; ${n}${r}`}return e.level==="misconfigured"?`${Ln} is set but unusable \u2014 boxes are REFUSED: ${e.error}`:e.level==="root-capable"?`boxes run as ${e.user} (${e.routes.join(", ")}) \u2014 root-capable: an agent can defeat node-side evidence; ${n}`:`boxes run as the node's uid (${e.user}) \u2014 no route to root, but they can rewrite the node's event log and hooks; ${n}`}var Un,Ln,Ea,xo,Oa,Ra,$o,Ht,Bn,gt,Fn,Pa,ke=O(()=>{Un=ka(_o),Ln="BOSTRAT_BOX_USER",Ea="bostrat-box",xo=Object.freeze(["root","sudo","wheel","admin","docker","lxd","libvirt","disk"]),Oa=/^[a-z_][a-z0-9_-]{0,31}$/,Ra=new Set(["","off","0","false","no","none"]),$o=e=>e.BOSTRAT_STATE_DIR||V.join(e.HOME||Wt.homedir(),".bostrat");Ht=()=>typeof process.getuid=="function"?process.getuid():0,Bn=null;gt=(e=process.env)=>{let t=wt(e);return!!(t&&!t.error)};Pa=e=>String(e?.stderr||e?.message||e).trim().split(`
|
|
7
|
+
`)[0].slice(0,160)});import Fa from"node:os";import Hn from"node:path";function No(){return gt()?Hn.join(We(),".claude.json"):process.env.CLAUDE_CONFIG_DIR?Hn.join(process.env.CLAUDE_CONFIG_DIR,".claude.json"):Hn.join(Fa.homedir(),".claude.json")}var Wn=O(()=>{Lt();Cn();ke()});import La from"node:os";import Kn from"node:path";function Mo(){if(gt())return Kn.join(We(),".codex","config.toml");let e=process.env.CODEX_HOME||Kn.join(La.homedir(),".codex");return Kn.join(e,"config.toml")}var Ua,Hd,Gn=O(()=>{ke();Ua="check_for_update_on_startup",Hd=`${Ua} = false`});import Wa from"node:os";import Io from"node:path";var Ka,qd,Yd,zn=O(()=>{Vn();Ft();Ka=process.env.BOSTRAT_DEBUG_DIR||Io.join(Wa.homedir(),".bostrat","debug"),qd=Io.join(Ka,"handoff.jsonl"),Yd=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as za}from"node:child_process";import{promisify as Va}from"node:util";function qn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var tf,nf,rf,of,Yn=O(()=>{zn();tf=Va(za),nf=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,rf=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,of=Promise.resolve()});var Po=O(()=>{ke()});import Xn from"node:path";import{execFile as qa}from"node:child_process";import{promisify as Ya}from"node:util";var ff,Do,Xa,pf,hf,Co=O(()=>{ff=Ya(qa),Do=process.env.HOME||"/home/globo",Xa=Xn.join(process.env.BOSTRAT_STATE_DIR||Xn.join(Do,".bostrat"),"repos"),pf=[...(process.env.BOSTRAT_REPOS_ROOT||Xn.join(Do,"Documents")).split(","),Xa].map(e=>e.trim()).filter(Boolean),hf=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function zt(e=Date.now()){if(Oe)return{tripped:!1,holdMs:1/0};if(Ee>e)return{tripped:!1,holdMs:Ee-e};if((!bt||e-bt>=Kt.windowMs)&&(bt=e,yt=0),yt++,yt<Kt.trip)return{tripped:!1,holdMs:0};Gt++;let t=Math.min(Kt.minMs*2**(Gt-1),Kt.maxMs);return Ee=e+t,yt=0,bt=0,{tripped:!0,holdMs:t}}function Bo(){yt=0,bt=0,Gt=0,Ee=0}function St(e=Date.now()){return Oe?1/0:Ee>e?Ee-e:0}function Vt(e=Date.now()){return St(e)>0}function Jn(e={}){Oe={at:Date.now(),...e},Ee=1/0}function Zn(){return Oe}function jo(e=Date.now()){return{held:Vt(e),holdMs:Oe?null:St(e),holds:Gt,removed:Oe?{...Oe}:null}}var Ja,Kt,yt,bt,Gt,Ee,Oe,Qn=O(()=>{Ja={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},Kt={...Ja},yt=0,bt=0,Gt=0,Ee=0,Oe=null});import Fo from"node:path";import Za from"node:os";import{execFile as Qa}from"node:child_process";import{promisify as ec}from"node:util";var $f,tc,vf,Af,kf,er=O(()=>{Co();Qn();$f=ec(Qa),tc=process.env.BOSTRAT_STATE_DIR||Fo.join(process.env.HOME||Za.tmpdir(),".bostrat"),vf=Fo.join(tc,"repos"),Af=5*6e4,kf=10*6e4});var Lo=O(()=>{er()});var Uo=O(()=>{});import rc from"node:fs/promises";import Tt from"node:path";import oc from"node:os";import{EventEmitter as sc}from"node:events";function ic(e){return e?.cwd?Tt.join(e.cwd,".bostrat","events"):Tt.join(Ho,"events")}async function qt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?Tt.join(Ho,"events"):ic(e));let o;try{o=await rc.readFile(ac(n,r),"utf8")}catch{return[]}return dc(o)}function dc(e){let t=[];for(let n of e.split(`
|
|
8
|
+
`))if(n.trim())try{t.push(JSON.parse(lc(n)?uc(n):n))}catch{}return t}var _t,Ho,ac,cc,lc,uc,Yt=O(()=>{Uo();Ft();_t=new sc;_t.setMaxListeners(0);Ho=process.env.BOSTRAT_STATE_DIR||Tt.join(process.env.HOME||oc.tmpdir(),".bostrat");ac=(e,t)=>Tt.join(e,`${t}.ndjson`),cc=/(?<!\\)((?:\\\\)*)\\u0000/g,lc=e=>e.includes("\\u0000"),uc=e=>e.replace(cc,"$1\\ufffd")});import pc from"node:os";import hc from"node:path";import{execFile as mc}from"node:child_process";import{promisify as wc}from"node:util";var Jf,Zf,Qf,ep,tp,np,Wo=O(()=>{Lo();Yt();Jf=wc(mc),Zf=process.env.BOSTRAT_STATE_DIR||hc.join(process.env.HOME||pc.tmpdir(),".bostrat"),Qf=25*1024,ep=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,tp=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,np=Promise.resolve()});var Xt=O(()=>{});var ap,Go=O(()=>{er();Xt();ap=60*6e4});var zo=O(()=>{Go()});import Vo from"node:path";import gc from"node:os";var Ke,yc,Tp,tr,_p,xp,$p,qo=O(()=>{Lt();ke();Ke="BOSTRAT_NODE_URL",yc=process.env.BOSTRAT_STATE_DIR||Vo.join(process.env.HOME||gc.tmpdir(),".bostrat"),Tp=Vo.join(yc,"git-hooks"),tr=`#!/bin/sh
|
|
7
9
|
# bostrat git hook shim (agent/src/git-hooks.js) \u2014 chains to the repo's own hook,
|
|
8
10
|
# then stamps/reports for rework attribution when running inside a bostrat box.
|
|
9
11
|
hook=$(basename "$0")
|
|
@@ -18,37 +20,37 @@ esac
|
|
|
18
20
|
if [ -x "$orig/$hook" ] && [ "$orig/$hook" != "$0" ]; then
|
|
19
21
|
"$orig/$hook" "$@" || exit $?
|
|
20
22
|
fi
|
|
21
|
-
`,
|
|
23
|
+
`,_p=`${tr}
|
|
22
24
|
# \u2500\u2500 bostrat: append provenance trailers (Layer 0). Skipped for merge commits
|
|
23
25
|
# (nobody "wrote" a merge) and outside a box (no token / no node url).
|
|
24
|
-
[ -z "$${
|
|
25
|
-
[ -z "$${
|
|
26
|
+
[ -z "$${le}" ] && exit 0
|
|
27
|
+
[ -z "$${Ke}" ] && exit 0
|
|
26
28
|
[ "$2" = "merge" ] && exit 0
|
|
27
|
-
trailers=$(curl -sS -m 3 -H "${
|
|
29
|
+
trailers=$(curl -sS -m 3 -H "${ht}: $${le}" "$${Ke}/api/git/trailers" 2>/dev/null) || exit 0
|
|
28
30
|
[ -z "$trailers" ] && exit 0
|
|
29
31
|
printf '%s\\n' "$trailers" | while IFS= read -r line; do
|
|
30
32
|
[ -n "$line" ] && git interpret-trailers --in-place --if-exists addIfDifferent --trailer "$line" "$1" >/dev/null 2>&1 || true
|
|
31
33
|
done
|
|
32
34
|
exit 0
|
|
33
|
-
|
|
35
|
+
`,xp=`${tr}
|
|
34
36
|
# \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
|
|
35
|
-
[ -z "$${
|
|
36
|
-
[ -z "$${
|
|
37
|
+
[ -z "$${le}" ] && exit 0
|
|
38
|
+
[ -z "$${Ke}" ] && exit 0
|
|
37
39
|
sha=$(git rev-parse HEAD 2>/dev/null) || exit 0
|
|
38
40
|
cwd=$(git rev-parse --show-toplevel 2>/dev/null)
|
|
39
|
-
printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${
|
|
40
|
-
-H 'content-type: application/json' -H "${
|
|
41
|
+
printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${Ke}/api/git/committed" \\
|
|
42
|
+
-H 'content-type: application/json' -H "${ht}: $${le}" --data-binary @- >/dev/null 2>&1 || true
|
|
41
43
|
exit 0
|
|
42
|
-
|
|
44
|
+
`,$p=`${tr}
|
|
43
45
|
# \u2500\u2500 bostrat: the tree moved \u2014 let the node re-read this workspace's lockfiles.
|
|
44
|
-
[ -z "$${
|
|
45
|
-
[ -z "$${
|
|
46
|
+
[ -z "$${le}" ] && exit 0
|
|
47
|
+
[ -z "$${Ke}" ] && exit 0
|
|
46
48
|
[ "$hook" = "post-checkout" ] && [ "$3" != "1" ] && exit 0
|
|
47
|
-
curl -sS -m 3 -X POST "$${
|
|
48
|
-
-H 'content-type: application/json' -H "${
|
|
49
|
+
curl -sS -m 3 -X POST "$${Ke}/api/deps/refresh" \\
|
|
50
|
+
-H 'content-type: application/json' -H "${ht}: $${le}" --data-binary '{}' >/dev/null 2>&1 || true
|
|
49
51
|
exit 0
|
|
50
|
-
`});import
|
|
51
|
-
`)[0]})`}}let r=
|
|
52
|
+
`});import xt from"node:fs/promises";import Jt from"node:os";import Ge from"node:path";import{execFile as bc}from"node:child_process";import{promisify as Sc}from"node:util";function Zo(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function Qo(e=process.env){let t=String(e.BOSTRAT_BOX_CGROUPS??"").trim().toLowerCase();return["1","on","true","yes"].includes(t)?"on":["0","off","false","no"].includes(t)?"off":"auto"}function Ac(e=process.env){let t=Qo(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function es(e=Jt.totalmem()){return Math.max(e-_c*$t,Math.floor(e/2))}function kc(e=Jt.totalmem(),t=process.env){let n=Number(t.BOSTRAT_BOX_MEMORY_MAX_MB);return Number.isFinite(n)&&n>=256?Math.floor(n)*$t:Math.min($c*$t,es(e))}function Ec(e=process.env){return Ge.join(Zo(e),xc)}async function Oc(e){return(await xt.readFile(e,"utf8")).trim()}async function ts({env:e=process.env,totalBytes:t=Jt.totalmem(),force:n=!1,platform:r=process.platform}={}){if(!n&&!Ac(e))return ze=Qo(e)==="off"?{available:!1,reason:"disabled (BOSTRAT_BOX_CGROUPS=0)"}:await Rc({env:e,totalBytes:t,platform:r}),ze;let o=Zo(e),s=Ec(e);try{let a;try{a=(await Oc(Ge.join(o,"cgroup.controllers"))).split(/\s+/).filter(Boolean)}catch(h){throw new Error(`no cgroup v2 tree at ${o} (${h?.code||h?.message||h})`)}let u=["cpu","memory"].filter(h=>a.includes(h));if(!u.length)throw new Error(`cgroup v2 at ${o} offers neither cpu nor memory (controllers: ${a.join(" ")||"none"})`);await xt.mkdir(s,{recursive:!0});let p=`+${u.join(" +")}`;for(let h of[Ge.join(o,"cgroup.subtree_control"),Ge.join(s,"cgroup.subtree_control")])try{await xt.writeFile(h,p)}catch(g){throw new Error(`cannot enable ${p} in ${h} (${g?.code||g?.message||g})`)}let m=es(t);u.includes("cpu")&&await xt.writeFile(Ge.join(s,"cpu.weight"),String(Yo)),u.includes("memory")&&await xt.writeFile(Ge.join(s,"memory.max"),String(m)),ze={available:!0,backend:"cgroupfs",path:s,controllers:u,cpuWeight:u.includes("cpu")?Yo:null,memoryMaxMb:u.includes("memory")?Math.round(m/$t):null}}catch(a){ze={available:!1,reason:a?.message||String(a)}}return ze}async function Rc({env:e=process.env,totalBytes:t=Jt.totalmem(),platform:n=process.platform}={}){if(n!=="linux")return{available:!1,reason:`not a Fly/container node, and no systemd on ${n}`};try{await Tc(Xo(e),["--user","show","--property=Version","--value"],{timeout:3e3})}catch(o){return{available:!1,reason:`not a Fly/container node, and no systemd user manager to ask (${String(o?.stderr||o?.code||o?.message||o).trim().split(`
|
|
53
|
+
`)[0]})`}}let r=kc(t,e);return{available:!0,backend:"systemd",path:null,controllers:["memory"],cpuWeight:null,memoryMaxMb:Math.round(r/$t),swapMaxMb:vc,systemctl:Xo(e),procRoot:e.BOSTRAT_PROC_ROOT||"/proc"}}function ns(e=ze){let t=`nice ${Jo} floor on every box`;if(!e)return`${t}; cgroup ceiling not probed yet`;if(e.available&&e.backend==="systemd")return`${t}; memory ceiling on each box's tmux-spawn scope, set through the systemd user manager (MemoryMax ${e.memoryMaxMb} MB, MemorySwapMax ${e.swapMaxMb} MB)`;if(e.available){let n=[];return e.cpuWeight!=null&&n.push(`cpu.weight ${e.cpuWeight}`),e.memoryMaxMb!=null&&n.push(`memory.max ${e.memoryMaxMb} MB`),`${t}; cgroup ceiling at ${e.path} (${n.join(", ")})`}return`${t}; cgroup ceiling unavailable \u2014 ${e.reason}`}var Tc,Jo,Yo,_c,xc,$c,vc,$t,ze,Xo,nr=O(()=>{Tc=Sc(bc),Jo=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),Yo=50,_c=768,xc="bostrat-boxes",$c=4096,vc=512,$t=1024*1024;ze=null;Xo=(e=process.env)=>e.BOSTRAT_SYSTEMCTL_BIN||"systemctl"});import{execFile as Nc}from"node:child_process";import{promisify as Mc}from"node:util";import ss from"node:fs";import Ic from"node:os";function is(e){return`/tmp/tmux-${e}/default`}function Dc({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=is(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function or(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Bc(e,{loginShell:t});return r===as?!0:r===rr?!1:n}async function Bc(e,{loginShell:t=!1,timeoutMs:n=Cc}={}){if(!e)return rr;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await Pc(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),as}catch(s){return s?.killed||s?.signal?os:s?.code===1||s?.code===127?rr:os}}var Pc,mh,rs,wh,gh,yh,bh,Sh,as,rr,os,Cc,Zt,Th,_h,xh,$h,vh,Ah,Vn=O(()=>{Ft();Wn();Gn();Yn();Po();Wo();zo();zn();Lt();qo();nr();ke();Pc=Mc(Nc),mh=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";rs=typeof process.getuid=="function"?process.getuid():0,wh=Dc({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return ss.existsSync(is(rs))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:rs}),gh=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",yh=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",bh=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),Sh=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);as="present",rr="absent",os="unknown",Cc=5e3;Zt={claude:"npm install -g @anthropic-ai/claude-code",codex:"npm install -g @openai/codex","cursor-agent":"curl https://cursor.com/install -fsS | bash",gh:"apt install gh (Debian: enable cli.github.com/packages) / brew install gh \u2014 see https://github.com/cli/cli#installation"},Th=(()=>{try{let e=Ic.homedir();if(e&&ss.existsSync(e))return e}catch{}return"/"})(),_h=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,xh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,$h=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,vh=Number(process.env.BOSTRAT_BOX_COLS)||120,Ah=Number(process.env.BOSTRAT_BOX_ROWS)||40});var Ms={};En(Ms,{NODE_IMAGE:()=>cr,commandPlan:()=>Os,flyToml:()=>Es,flyWizard:()=>al,parseFlyFlags:()=>Rs,stageConfig:()=>Ns});import ar from"node:fs";import Re from"node:path";import el from"node:os";import tl from"node:readline/promises";import{execFile as nl}from"node:child_process";import{createRequire as rl}from"node:module";import{randomUUID as ol}from"node:crypto";function Es({app:e,region:t,nodeName:n=e,planeUrl:r=ks,image:o=cr}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
|
|
52
54
|
# Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
|
|
53
55
|
# No [http_service] and none should be added: the node dials OUT to the plane;
|
|
54
56
|
# nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
|
|
@@ -88,92 +90,102 @@ swap_size_mb = 1024
|
|
|
88
90
|
# Scale later with: fly scale memory 4096 -a ${e}
|
|
89
91
|
size = "shared-cpu-2x"
|
|
90
92
|
memory = "2gb"
|
|
91
|
-
`}function
|
|
93
|
+
`}function Os({app:e,org:t,region:n,sizeGb:r,token:o,dir:s}){let a=[`BOSTRAT_PLANE_TOKEN=${o}`];return[{argv:["apps","create",e,"-o",t],display:`fly apps create ${e} -o ${t}`,tolerate:/already|taken|exists/i},{argv:["volumes","create","node_data","-a",e,"-r",n,"-s",String(r),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${r} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted> via stdin`,stdin:a.join(`
|
|
92
94
|
`)+`
|
|
93
|
-
`},{argv:["deploy",
|
|
94
|
-
`),
|
|
95
|
+
`},{argv:["deploy",s,"-c",Re.join(s,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${s} -c ${Re.join(s,"fly.toml")} -a ${e} --ha=false`}]}function Rs(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--image":"image"};for(let r=0;r<e.length;r++){let o=e[r];if(o==="--yes"||o==="-y")t.yes=!0;else if(n[o])t[n[o]]=e[++r]??"";else if(o.startsWith("--")&&o.includes("=")){let[s,...a]=o.split("=");n[s]?t[n[s]]=a.join("="):s==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function Ns({app:e,dest:t,toml:n}){let r=t||Re.join(el.homedir(),".bostrat","fly",e);ar.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])ar.rmSync(Re.join(r,o),{recursive:!0,force:!0});return ar.writeFileSync(Re.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function il({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await en(["orgs","list","--json"],{exec:n}),s=JSON.parse(o),a=Array.isArray(s)?s.map(u=>u.Slug||u.slug).filter(Boolean):Object.keys(s);if(a.length===1)return t.write(`Org: ${a[0]} (your only org)
|
|
96
|
+
`),a[0];if(a.length>1)return await e(`Fly org (${a.join(" / ")})`,a[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function al({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:o}={}){let s=Rs(e),a=tl.createInterface({input:t,output:n}),u=async(_,k)=>(await a.question(k?`${_} [${k}]: `:`${_}: `)).trim()||k||"",p=_=>(a.close(),_);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
|
|
95
97
|
bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
|
|
96
98
|
|
|
97
|
-
`);try{await
|
|
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"),
|
|
99
|
-
`),
|
|
100
|
-
wrote ${
|
|
99
|
+
`);try{await en(["version"],{exec:r})}catch{return n.write("\u2717 `fly` (flyctl) is not installed or not on PATH.\n install: https://fly.io/docs/flyctl/install/ \u2014 then re-run `bostrat-node fly`\n"),p(1)}try{let{stdout:_}=await en(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${_.trim()}
|
|
100
|
+
`)}catch{return n.write("\u2717 not signed in to Fly. Run `fly auth login` (or `fly auth signup`) and re-run `bostrat-node fly`.\n"),p(1)}let m=await il({ask:u,output:n,exec:r,flag:s.org}),h=s.app||await u("App name",`bostrat-node-${ol().slice(0,4)}`),g=s.region||await u("Region (see `fly platform regions`)","iad"),A=s.sizeGb||Number(await u("Volume size GB (logins + repos live here)","10"))||10,x=s.name||h,y=s.planeUrl||ks,v=s.token||await u("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!v)return n.write(`\u2717 a node token is required \u2014 mint one in the bostrat setup chat (Connect a node \u2192 Fly), then re-run with it.
|
|
101
|
+
`),p(1);let N=s.image||cr,{dir:I}=Ns({app:h,dest:o,toml:Es({app:h,region:g,nodeName:x,planeUrl:y,image:N})});n.write(`
|
|
102
|
+
wrote ${Re.join(I,"fly.toml")} \u2014 deploys the prebuilt node image ${N}
|
|
101
103
|
(claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
|
|
102
104
|
|
|
103
105
|
Plan (your flyctl, your org, your bill):
|
|
104
|
-
`);let
|
|
105
|
-
`);if(!
|
|
106
|
+
`);let b=Os({app:h,org:m,region:g,sizeGb:A,token:v,dir:I});for(let _ of b)n.write(` $ ${_.display}
|
|
107
|
+
`);if(!s.yes&&(await u(`
|
|
106
108
|
Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u2014 nothing was created. Re-run any time; the staged context is kept.
|
|
107
|
-
`),
|
|
108
|
-
\u2192 ${
|
|
109
|
-
`);try{let{stdout:k,stderr:
|
|
110
|
-
`).map(
|
|
109
|
+
`),p(1);for(let _ of b){n.write(`
|
|
110
|
+
\u2192 ${_.display}
|
|
111
|
+
`);try{let{stdout:k,stderr:E}=await en(_.argv,{stdin:_.stdin,exec:r}),R=`${k||""}${E||""}`.trim();R&&n.write(R.split(`
|
|
112
|
+
`).map(P=>` ${P}`).join(`
|
|
111
113
|
`)+`
|
|
112
|
-
`)}catch(k){let
|
|
113
|
-
`);continue}return n.write(`\u2717 failed: ${
|
|
114
|
+
`)}catch(k){let E=`${k?.stdout||""}${k?.stderr||""}${k?.message||""}`;if(_.tolerate&&_.tolerate.test(E)){n.write(` (already exists \u2014 continuing)
|
|
115
|
+
`);continue}return n.write(`\u2717 failed: ${E.trim().split(`
|
|
114
116
|
`).slice(-4).join(`
|
|
115
117
|
`)}
|
|
116
118
|
fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
|
|
117
|
-
`),
|
|
119
|
+
`),p(1)}}return n.write(`
|
|
118
120
|
\u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
|
|
119
121
|
chat: the node step advances on its own within a minute.
|
|
120
|
-
logs: fly logs -a ${
|
|
121
|
-
redeploy: fly deploy ${
|
|
122
|
+
logs: fly logs -a ${h}
|
|
123
|
+
redeploy: fly deploy ${I} -c ${Re.join(I,"fly.toml")} -a ${h} --ha=false
|
|
122
124
|
Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
|
|
123
125
|
boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
|
|
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
|
+
`),p(0)}var ks,sl,cr,en,Is=O(()=>{ks="wss://plane.bostrat.ai/v1/node",sl=rl(import.meta.url)("../package.json").version,cr=`ghcr.io/globocodes/bostrat-node:${sl}`;en=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let s=nl("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(a,u,p)=>a?o(Object.assign(a,{stdout:u,stderr:p})):r({stdout:u,stderr:p}));t!=null&&s.stdin?.end(t)})});function Ps(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!ll.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 ul(e){let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||r.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=r.map(o=>({...o,fromMs:Ps(o.from,"from",n),toMs:Ps(o.to,"to",n)}))}return t}var cl,ll,em,tm,Ds=O(()=>{cl={"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."}]},ll=/^\d{4}-\d{2}-\d{2}$/;em=ul(cl),tm=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var Cs=O(()=>{Ds()});import Bs from"node:fs/promises";import Ls from"node:path";import dl from"node:os";function Hs(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Ws(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Ks(e){let t=new Date(Hs(e));return t.setDate(t.getDate()+7),t.getTime()}function Gs(e){let t=new Date(Ws(e));return t.setMonth(t.getMonth()+1),t.getTime()}function wl(e=Date.now()){for(let[t,n]of Object.entries(hl)){let r=n.startOf(e);if(r!==tn[t]){tn[t]=r;for(let o of lr.values())o[t]=0;for(let o of js)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&js.delete(o)}}}function gl(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let o={};for(let s of["weeklyUsd","monthlyUsd"]){let a=r?.[s];if(a==null||a==="")continue;let u=Number(a);if(!Number.isFinite(u)||u<=0)throw new Error(`${n}.${s} must be a positive number or null`);o[s]=u}Object.keys(o).length&&(t[n]=o)}return t}async function zs(e,{source:t="local",updatedAt:n=Date.now()}={}){qe={caps:gl(e),updatedAt:n,source:t};try{await Bs.mkdir(Us,{recursive:!0}),await Bs.writeFile(fl(),JSON.stringify(qe,null,2))}catch{}return yl()}function yl(e=Date.now()){wl(e);let t=new Set([...lr.keys(),...Object.keys(qe?.caps||{})]),n={};for(let r of t){let o=lr.get(r);n[r]={weeklyUsd:Fs(o?.weekly||0),monthlyUsd:Fs(o?.monthly||0)}}return{caps:qe?.caps||{},configured:!!qe,seeded:ml,updatedAt:qe?.updatedAt??null,spent:n,windows:{weekly:{start:tn.weekly,resetsAt:Ks(e)},monthly:{start:tn.monthly,resetsAt:Gs(e)}},warnPct:pl}}var Us,fl,pl,hl,qe,ml,tn,lr,js,Fs,Vs=O(()=>{Yt();Cs();Us=process.env.BOSTRAT_STATE_DIR||Ls.join(process.env.HOME||dl.tmpdir(),".bostrat"),fl=()=>Ls.join(Us,"usage-caps.json"),pl=.8;hl={weekly:{startOf:Hs,nextStart:Ks,capKey:"weeklyUsd"},monthly:{startOf:Ws,nextStart:Gs,capKey:"monthlyUsd"}},qe=null,ml=!1,tn={weekly:0,monthly:0},lr=new Map,js=new Set;Fs=e=>Math.round(e*1e4)/1e4});import bl from"node:fs";import ge from"node:fs/promises";import Zs from"node:os";import Xe from"node:path";function ei(e){return fr.add(e),()=>fr.delete(e)}function nn(){return{entries:structuredClone(dr),at:Date.now()}}function vl(e,t,n){if(e.transport==="http"){let o=Object.fromEntries(Object.entries(e.headers||{}).map(([s,a])=>[s,Ye(a,t)]));return{...n==="claude"?{type:"http"}:{},url:Ye(e.url,t),...Object.keys(o).length?{headers:o}:{}}}let r=Object.fromEntries((e.env||[]).map(o=>[o,t[o]]));return{...n==="claude"?{type:"stdio"}:{},command:e.command,args:(e.args||[]).map(o=>Ye(o,t)),...Object.keys(r).length?{env:r}:{}}}function Al(e,t){let n=[`[mcp_servers.${e.name}]`];if(e.transport==="http"){n.push(`url = ${kt(Ye(e.url,t))}`);let r=Object.fromEntries(Object.entries(e.headers||{}).map(([o,s])=>[o,Ye(s,t)]));Object.keys(r).length&&n.push(`http_headers = ${Ys(r)}`)}else{n.push(`command = ${kt(e.command)}`),n.push(`args = [${(e.args||[]).map(o=>kt(Ye(o,t))).join(", ")}]`);let r=Object.fromEntries((e.env||[]).map(o=>[o,t[o]]));Object.keys(r).length&&n.push(`env = ${Ys(r)}`)}return n.join(`
|
|
127
|
+
`)+`
|
|
128
|
+
|
|
129
|
+
`}function ti(e){let t=[],n=`(?:[A-Za-z0-9_-]+|"[^"
|
|
130
|
+
]*"|'[^'
|
|
131
|
+
]*')`,r=new RegExp(`^[ \\t]*\\[\\[?[ \\t]*${n}(?:[ \\t]*\\.[ \\t]*${n})*[ \\t]*\\]\\]?[ \\t]*(?:#.*)?$`,"gm"),o=0,s;for(;s=r.exec(e);)s.index===0&&o===0||(t.push(e.slice(o,s.index)),o=s.index);return t.push(e.slice(o)),t}function ni(e){let t=/^[ \t]*\[\s*mcp_servers\s*\.\s*(?:"([^"]+)"|([A-Za-z0-9_-]+))\s*[\].]/.exec(e);return t?t[1]??t[2]:null}function kl(e){return new Set(ti(String(e||"")).map(ni).filter(Boolean))}function El(e,t,n){let r=String(e||""),o=new Set,s="";for(let a of ti(r)){let u=ni(a);if(u&&t.has(u)){o.has(u)||(s+=t.get(u),o.add(u));continue}u&&n.has(u)||(s+=a)}for(let[a,u]of t)o.has(a)||(s&&!s.endsWith(`
|
|
132
|
+
`)&&(s+=`
|
|
133
|
+
`),s&&!s.endsWith(`
|
|
134
|
+
|
|
135
|
+
`)&&(s+=`
|
|
136
|
+
`),s+=u);return s}async function Ol(e){try{return await ge.readFile(e,"utf8")}catch(t){if(t?.code==="ENOENT")return null;throw t}}async function pr(e,t){await ge.mkdir(Xe.dirname(e),{recursive:!0});let n=`${e}.bostrat-${process.pid}.tmp`,r=384;try{r=(await ge.stat(e)).mode&511}catch{}await ge.writeFile(n,t,{mode:r}),await ge.rename(n,e)}async function Rl(e,t,n,r){let o={},s=e==="claude"?No():e==="codex"?Mo():_l(),a=y=>{for(let v of t.keys())o[v]=y};if(e!=="claude"&&!bl.existsSync(Xe.dirname(s)))return a("cli-absent"),{managed:[],states:o};let u;try{u=await Ol(s)}catch{return a("error"),{managed:n,states:o}}let p=new Set(n);if(e==="codex"){let y=kl(u??""),v=new Map;for(let[b,_]of t)y.has(b)&&!p.has(b)?o[b]="conflict":v.set(b,Al(_,r));let N=new Set([...p].filter(b=>!t.has(b))),I=El(u??"",v,N);try{I!==(u??"")&&await pr(s,I)}catch{for(let b of v.keys())o[b]="error";return{managed:n,states:o}}for(let b of v.keys())o[b]="applied";return{managed:[...v.keys()].sort(),states:o}}let m={};if(u!=null&&u.trim()){try{m=JSON.parse(u)}catch{return a("error"),{managed:n,states:o}}if(!m||typeof m!="object"||Array.isArray(m))return a("error"),{managed:n,states:o}}let h=m.mcpServers&&typeof m.mcpServers=="object"?{...m.mcpServers}:{},g=[];for(let[y,v]of t){if(Object.hasOwn(h,y)&&!p.has(y)){o[y]="conflict";continue}h[y]=vl(v,r,e),g.push(y)}for(let y of p)t.has(y)||delete h[y];let A={...m,mcpServers:h};!Object.keys(h).length&&!m.mcpServers&&delete A.mcpServers;let x=JSON.stringify(m.mcpServers??{})!==JSON.stringify(h);try{x&&await pr(s,JSON.stringify(A,null,2))}catch{for(let y of g)o[y]="error";return{managed:n,states:o}}for(let y of g)o[y]="applied";return{managed:g.sort(),states:o}}async function Nl(){let e=Tl();try{(await ge.stat(e)).mode&63&&await ge.chmod(e,384).catch(()=>{});let n=JSON.parse(await ge.readFile(e,"utf8"));return Object.fromEntries(Object.entries(n||{}).filter(([,r])=>typeof r=="string"&&r!==""))}catch{return{}}}function ri(e){return(Array.isArray(e)?e:[]).filter(t=>t&&xl.test(t.name)&&(t.transport==="http"?typeof t.url=="string":typeof t.command=="string"))}async function Xs(){let e=await Nl(),t=ri(we.entries),n={};for(let s of t){let a=(s.env||[]).filter(u=>e[u]==null);n[s.name]={rev:Number(s.updatedAt)||0,clis:{},missingEnv:a}}let r={...we.managed};for(let s of ur){let a=new Map(t.filter(p=>(p.clis||ur).includes(s)&&!n[p.name].missingEnv.length).map(p=>[p.name,p])),u=await Rl(s,a,we.managed?.[s]??[],e);r[s]=u.managed;for(let[p,m]of Object.entries(u.states))n[p].clis[s]=m}for(let s of t)if(n[s.name].missingEnv.length)for(let a of s.clis||ur)n[s.name].clis[a]="missing-secret";we={...we,managed:r},await Ml();let o=JSON.stringify(n)!==JSON.stringify(dr);if(dr=n,o)for(let s of fr)try{s(nn())}catch{}return nn()}async function Ml(){let e=JSON.stringify(we,null,2);if(e!==Js)try{await pr(Sl(),e),Js=e}catch(t){console.error("[mcp-config] cache write failed:",t?.message||t)}}function Il(){let e=qs.then(Xs,Xs);return qs=e.catch(()=>{}),e}function oi(e,{updatedAt:t=Date.now()}={}){return we={...we,entries:ri(e),updatedAt:t},Il()}var Qs,Sl,Tl,_l,ur,xl,$l,we,dr,qs,fr,Ye,kt,Ys,Js,si=O(()=>{Wn();Gn();Qs=()=>process.env.BOSTRAT_STATE_DIR||Xe.join(process.env.HOME||Zs.tmpdir(),".bostrat"),Sl=()=>Xe.join(Qs(),"mcp-config.json"),Tl=()=>Xe.join(Qs(),"mcp-env.json"),_l=()=>Xe.join(Zs.homedir(),".cursor","mcp.json"),ur=["claude","codex","cursor"],xl=/^[a-z0-9][a-z0-9_-]{0,47}$/,$l=/\$\{([A-Za-z_][A-Za-z0-9_]{0,63})\}/g,we={entries:[],updatedAt:null,managed:{claude:[],codex:[],cursor:[]}},dr={},qs=Promise.resolve(),fr=new Set;Ye=(e,t)=>String(e).replace($l,(n,r)=>t[r]??"");kt=e=>JSON.stringify(String(e)),Ys=e=>`{ ${Object.entries(e).map(([t,n])=>`${kt(t)} = ${kt(n)}`).join(", ")} }`;Js=null});import ii from"node:fs/promises";import li from"node:path";import Pl from"node:os";function Cl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("refresh-flow patch must be an object");let t={};for(let[n,r]of Object.entries(e)){if(!(n in hr))throw new Error(`unknown refresh-flow field "${n}" \u2014 fields: ${di.join(", ")}`);if(r===null||r===""||r===void 0){t[n]=null;continue}switch(n){case"contextFull":case"limitHit":if(typeof r!="string"||!ai.includes(r))throw new Error(`${n} must be one of ${ai.join(", ")}`);t[n]=r;break;case"contextFullPct":{let o=Number(r);if(!Number.isFinite(o)||o<1||o>100)throw new Error("contextFullPct must be a number from 1 to 100");t[n]=Math.round(o);break}case"contextFullTokens":{let o=Number(r);if(!Number.isFinite(o)||o<=0)throw new Error("contextFullTokens must be a positive number of tokens or null");t[n]=Math.round(o);break}case"fallback":{if(typeof r!="object"||Array.isArray(r))throw new Error("fallback must be an object of provider \u2192 [providers]");let o={};for(let[s,a]of Object.entries(r)){if(!ci.test(s))throw new Error(`bad provider key "${s}" in fallback`);if(!Array.isArray(a)||a.some(p=>typeof p!="string"||!ci.test(p)))throw new Error(`fallback.${s} must be a list of provider keys`);let u=[...new Set(a.filter(p=>p!==s))];u.length&&(o[s]=u)}t[n]=Object.keys(o).length?o:null;break}default:throw new Error(`unknown refresh-flow field "${n}"`)}}return t}function Bl(e){let t={...hr};for(let n of di){let r=e?.[n];r!=null&&(t[n]=r)}return t}function Fl(){return Bl(Je?.flow)}function fi(){return{flow:Fl(),configured:!!Je,source:Je?.source??null,updatedAt:Je?.updatedAt??null}}async function Ll(){try{await ii.mkdir(ui,{recursive:!0}),await ii.writeFile(Dl(),JSON.stringify(Je,null,2))}catch{}}function pi(e=null){for(let t of jl)try{t(fi(),e)}catch{}}function hi(e){pi({rejected:String(e||"rejected by the plane")})}async function mi(e,{source:t="plane",updatedAt:n=Date.now()}={}){return Je={flow:Cl(e||{}),updatedAt:n,source:t},await Ll(),pi(),fi()}var ui,Dl,ai,hr,di,ci,Je,jl,wi=O(()=>{ui=process.env.BOSTRAT_STATE_DIR||li.join(process.env.HOME||Pl.tmpdir(),".bostrat"),Dl=()=>li.join(ui,"refresh-flow.json"),ai=["prompt","auto","off"],hr=Object.freeze({contextFull:"prompt",contextFullPct:75,contextFullTokens:null,limitHit:"prompt",fallback:null}),di=Object.keys(hr),ci=/^[a-z][a-z0-9-]{0,31}$/;Je=null,jl=new Set});var $i={};En($i,{REMOVED_MARKER:()=>Sr,detectInstallKind:()=>et,detectProviderAuth:()=>xi,maskToken:()=>br,readRemovedMarker:()=>_i,startPlaneLink:()=>ou,updateCommandFor:()=>Ot,versionLt:()=>Qe});import Ze from"node:fs";import Et from"node:fs/promises";import Ul from"node:http";import K from"node:path";import on from"node:os";import{createRequire as Hl}from"node:module";import mr from"ws";function br(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function _i(e=Sr){try{let t=JSON.parse(Ze.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function et({env:e=process.env,pkgDir:t=K.resolve(K.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ze.existsSync}={}){let r=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(r)?r:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(K.join(t,"..",".git"))?"git-checkout":"dev"}function Qe(e,t){let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let o=0;o<Math.max(n.length,r.length);o++){let s=(n[o]||0)-(r[o]||0);if(s)return s<0}return!1}function Ot(e){switch(e){case"npm-global":return"npm install -g bostrat-node && restart the bostrat-node service";case"git-checkout":return"scripts/deploy-pi.sh (or The Bakery \u2192 Deploy to Pi \u2192 bostrat)";case"container":return"Links \u2192 Fly \u2192 Update (or the plane's auto-update while the node sleeps)";default:return"update this node's bostrat-node checkout/install"}}function xi({home:e=process.env.HOME||on.homedir(),env:t=process.env}={}){let n=r=>{try{return Ze.statSync(r),!0}catch{return!1}};return{claude:n(K.join(e,".claude",".credentials.json")),codex:n(K.join(t.CODEX_HOME||K.join(e,".codex"),"auth.json")),cursor:n(K.join(t.XDG_CONFIG_HOME||K.join(e,".config"),"cursor","auth.json"))}}function ou({url:e,token:t,nodeId:n=on.hostname(),name:r=on.hostname(),listTracks:o,detectAgents:s=null,onTracksTransferred:a=null,onTracksMoves:u=null,sampleMetrics:p=null,deliverySample:m=null,onHashKey:h=null,onViewBase:g=null,metricsMs:A=ru,onUpdateAvailable:x=null,onUpdatePolicy:y=null,onConflictProbe:v=null,restart:N=null,onRestarted:I=null,onHelloRefused:b=null,updatePolicy:_=null,installKind:k=et(),selfUrl:E=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:R=null,removedMarkerFile:P=Sr,onRemoved:Me=null,onDegraded:rt=null,onRecovered:Ie=null,onRefused:fn=null,onConnected:Nt=null,ingestMode:Pe=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:ot=Xl,unackedRetryMs:De=Yl,pingMs:st=Vl,deadLinkMs:M=Math.round(st*ql),maxInflightEvents:ue=eu,httpTimeoutMs:de=tu,fanoutActive:fe=null,fanoutBatchCap:it=nu,stallBackoffMinMs:Mr=Ql,fetchImpl:Ir=globalThis.fetch,log:S=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof o!="function")throw new Error("plane-link: listTracks is required");e=pt(e);let ji=E.replace(/^http/,"ws"),Pr=new Set,Dr=c=>{let d=typeof c.latestNodeVersion=="string"?c.latestNodeVersion:null;if(!(!(d&&te&&Qe(te,d))||Pr.has(d))){Pr.add(d),S.log(`[plane-link] bostrat-node ${d} is available (this node runs ${te}) \u2014 ${Ot(k)}`);try{x?.({current:te,latest:d,min:c.minNodeVersion??null,installKind:k,required:!!(c.minNodeVersion&&Qe(te,c.minNodeVersion))})}catch(f){S.error(`[plane-link] update notice failed: ${f?.message||f}`)}}},Se=new Map,Te=new Map,pn=K.join(yr,"plane-link","cursor.json"),hn=K.join(yr,"plane-link","dead-letter.ndjson"),Cr=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),oe={},ne={},C=new Map,Mt=null,pe=null,se=0,at=0,Br=0,It={},jr=new Set,Fr=Promise.resolve(),H="ws",Ce=0,ee=!1,_e=0,mn=!1,he=rn,Be=new Set,ie=[],Y=null,X=null,J=!1,wn=!1,ct=gi,lt=null,gn=N&&typeof N=="object"?N:null,je=null,Fe=null,ae=null,xe=0,Lr=0,ce=null,yn=!1,Pt=0,ut=!1,me=_i(P);if(me)if(me.tokenPreview===br(t))ut=!0,Jn({reason:me.reason??"removed",at:me.at??null,nodeId:me.nodeId??n}),S.error(`[plane-link] this node was REMOVED from the plane (${me.reason??"removed"}${me.at?` at ${new Date(me.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${P} to force a dial.`);else try{Ze.unlinkSync(P),S.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function bn({reason:c="removed",at:d=Date.now(),via:f="ctl"}={}){if(!ut){ut=!0,Jn({reason:c,at:d,nodeId:n,via:f});try{Ze.mkdirSync(K.dirname(P),{recursive:!0}),Ze.writeFileSync(P,JSON.stringify({at:d,reason:c,via:f,nodeId:n,tokenPreview:br(t)},null,2))}catch(i){S.error(`[plane-link] could not write ${P}: ${i?.message||i}`)}S.error(`[plane-link] the plane REMOVED this node (${c}, via ${f}) \u2014 going dormant: no more dials, ingest or broker calls. Re-provision with a new node token to reconnect; the box and its data are untouched.`);try{Me?.({reason:c,at:d,via:f})}catch{}Jr({bye:!1})}}async function Fi(){try{oe=JSON.parse(await Et.readFile(pn,"utf8"))}catch{oe={}}}function Ur(){yn=!0,!Fe&&(Fe=setTimeout(async()=>{if(Fe=null,!!yn){yn=!1;try{await Et.mkdir(K.dirname(pn),{recursive:!0}),await Et.writeFile(pn,JSON.stringify(oe))}catch(c){S.error("[plane-link] cursor flush failed:",c?.message||c)}}},zl),Fe.unref?.())}function Sn(){try{return!!fe?.()}catch{return!1}}function Tn(){let c=H==="http"?he:rn;return Sn()?Math.min(c,it):c}function B(c){return!X||X.readyState!==mr.OPEN?!1:(X.send(JSON.stringify(c)),!0)}let Li=ei(c=>B({v:j,ch:"ctl",type:"mcp_status",mcp:c}));function Le(c){let d=Date.now();for(let{trackId:i,event:l}of c){let w=C.get(l.id);C.set(l.id,{trackId:i,seq:l.seq,event:l,sentAt:d,firstSentAt:w?.firstSentAt??d,retryAt:d+De,tries:(w?.tries??0)+1,nacks:w?.nacks??0})}let f=c.map(({trackId:i,event:l})=>({trackId:i,event:Zl(l)}));return H==="http"?(zi(f),!0):B({v:j,ch:"events",type:"append",events:f})}function Ui(c){let d=null;for(let f of C.values())f.trackId===c&&(d==null||f.seq<d)&&(d=f.seq);return d}function _n(c){let d=ne[c];if(d==null)return;let f=Ui(c),i=f==null?d:Math.min(d,f-1);i>(oe[c]??0)&&(oe[c]=i,Ur())}function dt(){if(Mt=Date.now(),pe!=null){let c=Date.now()-pe;S.log(`[plane-link] spine sync recovered after ${Math.round(c/1e3)}s degraded (${se} stall redial(s))`);let d=pe;pe=null,se=0,at=0,ee=!1,_e=0;try{Ie?.({since:d,downMs:c})}catch(f){S.error(`[plane-link] onRecovered failed: ${f?.message||f}`)}}}function xn(c){if(!Array.isArray(c)||!c.length)return;let d=new Set;for(let f of c){let i=C.get(f);i&&(C.delete(f),(ne[i.trackId]??0)<i.seq&&(ne[i.trackId]=i.seq),d.add(i.trackId))}for(let f of d)_n(f);dt()}function Hr(c,d){Br++;let f={at:Date.now(),trackId:c.trackId,seq:c.seq,id:c.event?.id??null,type:c.event?.type??null,reason:d,event:c.event??null};S.error(`[plane-link] DEAD-LETTER ${c.trackId} seq ${c.seq} (${f.type??"?"}): plane rejected it permanently (${d}) \u2014 kept in ${hn}`),Fr=Fr.then(async()=>{await Et.mkdir(K.dirname(hn),{recursive:!0}),await Et.appendFile(hn,JSON.stringify(f)+`
|
|
137
|
+
`)}).catch(i=>S.error(`[plane-link] dead-letter write failed: ${i?.message||i}`))}function Hi(c,d){if(It[c]=(It[c]??0)+1,jr.has(c))return;jr.add(c);let f=Jl[c]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";S.error(`[plane-link] REFUSED by the plane (${c}) on track ${d}: events are being dropped, not stored \u2014 ${f}`);try{fn?.({reason:c,trackId:d,count:It[c],hint:f})}catch(i){S.error(`[plane-link] onRefused failed: ${i?.message||i}`)}}function $n(c,d,f,i=null){if(!Array.isArray(c)||!c.length)return;let l=new Set,w=Date.now();for(let T of c){let $=C.get(T);$&&(f?(C.delete(T),Hr($,d),String(d).startsWith(wr)&&Hi(String(d).slice(wr.length),$.trackId),(ne[$.trackId]??0)<$.seq&&(ne[$.trackId]=$.seq),l.add($.trackId)):($.nacks++,$.retryAt=w+Math.max(1e3,Number(i)||De)))}for(let T of l)_n(T);dt()}function Wr(c=Date.now()){let d=1/0;for(let f of C.values())f.firstSentAt<d&&(d=f.firstSentAt);return d===1/0?0:c-d}function Wi(c){if(!M||!c||c!==X||!xe)return!1;let d=Date.now()-xe;if(d<=M)return!1;Lr++,S.error(`[plane-link] no frame from the plane for ${Math.round(d/1e3)}s \u2014 link is half-open; terminating and redialing`);try{c.terminate()}catch{}return!0}function Kr(){if(!J||!C.size)return;let c=Date.now(),d=Wr(c);if(d<ot||Mt!=null&&c-Mt<ot||H==="http"&&ee||at>c)return;se++;let f=Math.min(Mr*2**(se-1),bi);if(pe==null){pe=c-d,S.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(d/1e3)}s with ${C.size} event(s) in flight (${H} door) \u2014 the plane is not answering appends`);try{rt?.({since:pe,unacked:C.size,oldestAgeMs:d,mode:H})}catch(i){S.error(`[plane-link] onDegraded failed: ${i?.message||i}`)}}if(H==="http"){ee=!0,_e=c+f,S.error(`[plane-link] ingest circuit OPEN (stall #${se}); probing /v1/ingest/health in ${Math.round(f/1e3)}s`);return}at=c+f,S.error(`[plane-link] closing the link and redialing in ${Math.round(f/1e3)}s (stall redial #${se})`);try{X?.terminate()}catch{}}function vn(){if(!J)return;let c=Date.now();if(H==="http"&&ee)return;let d=[...C.values()].filter(i=>i.event&&i.retryAt<=c&&!(H==="http"&&Be.has(i.trackId)));if(!d.length)return;d.sort((i,l)=>i.trackId===l.trackId?i.seq-l.seq:i.trackId<l.trackId?-1:1),S.log(`[plane-link] re-sending ${d.length} unacked event(s) the plane never confirmed`);let f=Tn();if(H==="http"){let i=new Map;for(let l of d)(i.get(l.trackId)??i.set(l.trackId,[]).get(l.trackId)).push(l);for(let[,l]of i){if(Ce>=gr)return;Le(l.slice(0,f).map(w=>({trackId:w.trackId,event:w.event})))}return}for(let i=0;i<d.length;i+=f){let l=d.slice(i,i+f).map(w=>({trackId:w.trackId,event:w.event}));if(!Le(l))return}}async function Ki(c=null){for(;;){if(!J)return!1;let d=C.size<ue,f=H!=="http"||Ce<gr&&!ee&&(!c||!Be.has(c));if(d&&f)return!0;await new Promise(i=>setTimeout(i,100))}}function An(){if(Y=null,!J||!ie.length)return;let c=ie;ie=[];let d=Tn();if(H!=="http"){for(let l=0;l<c.length;l+=d)Le(c.slice(l,l+d));return}let f=Sn(),i=new Map;for(let l of c)(i.get(l.trackId)??i.set(l.trackId,[]).get(l.trackId)).push(l);for(let[l,w]of i){if(Be.has(l)||Ce>=gr||ee){ie.push(...w);continue}if(f){Le(w.slice(0,d)),ie.push(...w.slice(d));continue}for(let T=0;T<w.length;T+=d)Le(w.slice(T,T+d))}ie.length&&!Y&&(Y=setTimeout(An,Si),Y.unref?.())}let Gi=c=>{let d=new Map;for(let{trackId:f,event:i}of c)(d.get(f)??d.set(f,[]).get(f)).push(i);return[...d].map(([f,i])=>({trackId:f,events:i}))},$e=(c,d,f,{progress:i})=>{let l=Date.now();for(let{event:w}of c){let T=C.get(w.id);T&&(T.nacks++,T.retryAt=l+Math.max(1e3,f||De))}i&&dt()};async function zi(c){let d=new Set(c.map(f=>f.trackId));for(let f of d)Be.add(f);Ce++;try{let f=await Ir(`${Cr}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:Gi(c)}),signal:AbortSignal.timeout(de)}),i=(Number(f.headers.get("retry-after"))||0)*1e3;if(f.status===200){let l=await f.json();he=rn;for(let $ of l.results??[]){xn($.acked??[]);let L=(re,z)=>{let Dt=new Map;for(let ve of re??[])(Dt.get(ve.reason)??Dt.set(ve.reason,[]).get(ve.reason)).push(ve.id);for(let[ve,Zr]of Dt)$n(Zr,ve,z,l.retryAfterMs??null)};L($.rejected,!0),L($.deferred,!1)}let w=new Set,T=new Map;for(let $ of Array.isArray(l.refused)?l.refused:[])!$||typeof $.id!="string"||(w.add($.id),(T.get($.reason)??T.set($.reason,[]).get($.reason)).push($.id));for(let[$,L]of T)$n(L,`${wr}${$}`,!0);xn((l.discarded??[]).filter($=>!w.has($))),dt();return}if(f.status===429){$e(c,"overloaded",i||5e3,{progress:!0});return}if(f.status===413&&c.length>1){he=Math.max(1,Math.floor(c.length/2)),S.error(`[plane-link] ingest request too large (${c.length} events) \u2014 halving batches to ${he}`),$e(c,"too_large",1e3,{progress:!0});return}if(f.status===413){let l=C.get(c[0].event.id);l&&(C.delete(l.event.id),Hr(l,"too_large"),(ne[l.trackId]??0)<l.seq&&(ne[l.trackId]=l.seq),_n(l.trackId)),dt();return}if(f.status===410){bn({reason:"removed",via:"410"}),$e(c,"http_410",6e4,{progress:!1});return}if(f.status===401||f.status===403){let{tripped:l,holdMs:w}=zt();if(l&&S.error(`[plane-link] holding every plane call for ${Math.round(w/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Pt>=Ti){Pt=Date.now();let T="";try{T=(await f.json())?.error??""}catch{}S.error(`[plane-link] plane refused ingest (HTTP ${f.status}${T?`: ${T}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}$e(c,`http_${f.status}`,Math.max(6e4,St()),{progress:!1});return}if(f.status===400){S.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${c.length} event(s) for retry; this is a bug, not data`),$e(c,"http_400",6e4,{progress:!1});return}$e(c,`http_${f.status}`,i||5e3,{progress:!1})}catch(f){let i=f?.name==="TimeoutError"||f?.name==="AbortError";i&&c.length>1&&(he=Math.max(1,Math.floor(c.length/2)),S.error(`[plane-link] ingest request of ${c.length} event(s) outlived its ${de} ms deadline \u2014 halving batches to ${he}`)),$e(c,i?"timeout":"network",5e3,{progress:!1})}finally{Ce--;for(let f of d)Be.delete(f)}}async function Vi(){if(H!=="http"||!ee||!J||mn)return;let c=Date.now();if(!(_e>c||Vt(c))){mn=!0;try{let d=await Ir(`${Cr}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(de)});if(!d.ok)throw new Error(`HTTP ${d.status}`);S.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),ee=!1,_e=0,at=Date.now()+de+De+1e3;for(let f of C.values())f.retryAt=Math.min(f.retryAt,Date.now());vn()}catch(d){se++;let f=Math.min(Mr*2**(se-1),bi);_e=Date.now()+f,S.error(`[plane-link] ingest door still not answering (${d?.message||d}); next probe in ${Math.round(f/1e3)}s`)}finally{mn=!1}}}function Gr(){let c=Date.now();return{mode:H,unacked:C.size,oldestUnackedAgeMs:Wr(c),lastProgressAt:Mt,degradedSince:pe,stallRedials:se,deadLettered:Br,fanoutCap:Sn()?it:null,http:H==="http"?{inFlight:Ce,circuitOpen:ee,nextProbeInMs:ee?Math.max(0,_e-c):0,batchCap:he}:null}}async function zr(){if(!p)return;let c;try{c=await p()}catch(f){S.error("[plane-link] metrics sample failed:",f?.message||f);return}let d=null;try{d=m?.()??null}catch{}c&&B({v:j,ch:"ctl",type:"metrics",metrics:{...c,planeLink:Gr(),...d?{delivery:d}:{}}})}function qi(){p&&(ce&&clearInterval(ce),zr(),ce=setInterval(zr,A),ce.unref?.())}async function Yi(){let c;try{c=await o()}catch(d){S.error("[plane-link] backfill listTracks failed:",d?.message||d);return}B({v:j,ch:"ctl",type:"tracks",ids:c.filter(d=>!d.transferredTo).map(d=>d.id).filter(d=>typeof d=="string")});for(let d of c)if(!J||!await Vr(d))return}async function Vr(c){let d;try{d=await qt(c)}catch{return!0}let f=oe[c.id]??0,i=d.filter(l=>l.seq>f&&typeof l.id=="string");for(let l=0;l<i.length;){if(!await Ki(c.id))return!1;let w=i.slice(l,l+Tn()).map(T=>({trackId:c.id,event:T}));if(!Le(w))return!1;l+=w.length}return!0}let kn=new Map;async function qr(c,d){if(kn.get(c)===d)return!1;kn.set(c,d);let f=null;try{f=(await o()).find(T=>T?.id===c)??null}catch{return!1}if(!f)return!1;let i;try{i=await qt(f)}catch{return!1}let l=[...i].reverse().find(T=>(T?.type==="track.transferred"||T?.type==="track.recovered")&&T.payload?.toNode===n);if(!l||!Number.isFinite(l.seq))return!1;let w=l.seq-1;return(oe[c]??0)>w&&(oe[c]=w,Ur()),(ne[c]??0)>w&&(ne[c]=w),S.log(`[plane-link] re-sending ${c}'s move-commit (seq ${l.seq}, ${l.type}) \u2014 the plane's move record predates this node's adoption`),J?Vr(f):!1}function Yr(c){!J||!c?.trackId||typeof c.id!="string"||(ie.push({trackId:c.trackId,event:c}),Y||(Y=setTimeout(An,Si),Y.unref?.()))}let ft=new Map;async function Xi(c){let{reqId:d,method:f,path:i,headers:l={},body:w}=c,T=Object.fromEntries(Object.entries(l).filter(([,L])=>L!=null)),$=new AbortController;ft.set(d,$);try{if(c.host){await Ji(c,T,$);return}R&&(T["x-bostrat-token"]=R);let L=await fetch(E+i,{method:f,headers:T,body:w?Buffer.from(w,"base64"):void 0,signal:$.signal}),re=Object.fromEntries(L.headers);for(let z of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete re[z];if(re["content-type"]||(re["content-type"]="application/octet-stream"),B({v:j,ch:"control",type:"http_head",reqId:d,status:L.status,headers:re}),L.body){for await(let z of L.body)if(!B({v:j,ch:"control",type:"http_data",reqId:d,data:Buffer.from(z).toString("base64")}))break}B({v:j,ch:"control",type:"http_end",reqId:d,error:null})}finally{ft.delete(d)}}function Ji(c,d,f){let{reqId:i,method:l,path:w,body:T}=c,$=new URL(E);return new Promise(L=>{let re=Ul.request({host:$.hostname,port:$.port,method:l,path:w,headers:{...d,host:c.host},signal:f.signal},z=>{let{connection:Dt,"keep-alive":ve,"transfer-encoding":Zr,upgrade:nd,...Zi}=z.headers;B({v:j,ch:"control",type:"http_head",reqId:i,status:z.statusCode||502,headers:Zi}),z.on("data",Qi=>{B({v:j,ch:"control",type:"http_data",reqId:i,data:Buffer.from(Qi).toString("base64")})||z.destroy()}),z.on("end",()=>{B({v:j,ch:"control",type:"http_end",reqId:i,error:null}),L()}),z.on("error",()=>{B({v:j,ch:"control",type:"http_end",reqId:i,error:"view upstream error"}),L()})});re.on("error",z=>{B({v:j,ch:"control",type:"http_end",reqId:i,error:z?.message||"view request failed"}),L()}),T&&re.write(Buffer.from(T,"base64")),re.end()})}function Xr(){if(wn||ut)return;X=new mr(e,{headers:{authorization:`Bearer ${t}`}});let c=X;xe=0,c.on("ping",()=>{xe=Date.now()}),c.on("pong",()=>{xe=Date.now()}),X.on("open",async()=>{let f=null;try{f=await s?.()||null}catch{f=null}B({v:j,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:te,installKind:k,...typeof _=="function"?{updatePolicy:_()}:_?{updatePolicy:_}:{},providers:xi(),...f?{agents:f}:{},mcp:nn(),...gn?{restart:gn}:{}})}),X.on("message",f=>{xe=Date.now();let i;try{i=JSON.parse(f)}catch{return}if(i.ch==="ctl"&&i.type==="hello_ok"){kn.clear(),J=!0,ct=gi,lt=null,gn=null,Bo(),S.log(`[plane-link] connected to plane as ${n}`);try{Nt?.()}catch{}if(typeof i.hashKey=="string"&&i.hashKey)try{h?.(i.hashKey)}catch{}try{g?.(typeof i.viewBase=="string"&&i.viewBase?i.viewBase:null)}catch{}i.minNodeVersion&&te&&Qe(te,i.minNodeVersion)&&S.error(`[plane-link] this node is bostrat-node ${te}; the plane asks for \u2265${i.minNodeVersion} \u2014 update with: ${Ot(k)}`);try{y?.(typeof i.updatePolicy=="string"?i.updatePolicy:null)}catch{}Dr(i);let l=i.ingest==="http";H=Pe==="ws"?"ws":Pe==="http"||l?"http":"ws",Pe==="http"&&!l&&S.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),H==="http"&&S.log("[plane-link] spine rides the HTTPS ingest door"),ee=!1,_e=0,he=rn,ae&&clearInterval(ae),xe=Date.now(),ae=setInterval(()=>{Wi(c)||(B({v:j,ch:"ctl",type:"ping"}),Kr(),Vi().catch(()=>{}),vn(),ie.length&&!Y&&An())},st),ae.unref?.(),qi(),Yi().catch(w=>S.error("[plane-link] backfill failed:",w?.message||w));return}if(i.ch==="ctl"&&i.type==="hello_refused"){let l=typeof i.minNodeVersion=="string"?i.minNodeVersion:null,w=typeof i.latestNodeVersion=="string"?i.latestNodeVersion:null;S.error(`[plane-link] plane REFUSED this node: bostrat-node ${te??"?"} is below its minimum ${l??"?"} \u2014 ${i.fix||Ot(k)}`),ct=yi,lt=0;try{b?.({current:te,min:l,latest:w,fix:i.fix||Ot(k),installKind:k})}catch(T){S.error(`[plane-link] refusal handler failed: ${T?.message||T}`)}return}if(i.ch==="ctl"&&i.type==="removed"){B({v:j,ch:"ctl",type:"removed_ack",nodeId:n}),bn({reason:typeof i.reason=="string"?i.reason:"removed",at:Number(i.at)||Date.now(),via:"ctl"});return}if(i.ch==="ctl"&&i.type==="update_available"){Dr(i);return}if(i.ch==="ctl"&&i.type==="update_policy"){try{y?.(typeof i.mode=="string"?i.mode:null)}catch{}return}if(i.ch==="ctl"&&i.type==="conflict_probe"&&Array.isArray(i.trackIds)){try{v?.(i.trackIds.filter(l=>typeof l=="string"&&l).slice(0,200))}catch{}return}if(i.ch==="ctl"&&i.type==="restarted"){Promise.resolve().then(()=>I?.({kind:i.kind,at:i.at,reason:i.reason})).catch(l=>S.error("[plane-link] restart notice failed:",l?.message||l));return}if(i.ch==="ctl"&&i.type==="usage_caps"){zs(i.caps??{},{source:"plane",updatedAt:i.updatedAt??Date.now()}).then(l=>S.log(`[plane-link] spend caps ${Object.keys(l.caps).length?`updated (${Object.keys(l.caps).join(", ")})`:"cleared"} from plane`)).catch(l=>S.error("[plane-link] spend-caps push rejected:",l?.message||l));return}if(i.ch==="ctl"&&i.type==="mcp_config"){oi(i.entries??[],{updatedAt:i.updatedAt??Date.now()}).then(l=>S.log(`[plane-link] mcp config applied: ${Object.keys(l.entries).length} entr${Object.keys(l.entries).length===1?"y":"ies"}`)).catch(l=>S.error("[plane-link] mcp config apply failed:",l?.message||l));return}if(i.ch==="ctl"&&i.type==="refresh_flow"){mi(i.flow??{},{source:"plane",updatedAt:i.updatedAt??Date.now()}).then(l=>S.log(`[plane-link] refresh flow from plane: contextFull=${l.flow.contextFull} rung=${l.flow.contextFullTokens?`${l.flow.contextFullTokens} tokens`:`${l.flow.contextFullPct}%`}`)).catch(l=>S.error("[plane-link] refresh-flow push rejected:",l?.message||l));return}if(i.ch==="ctl"&&i.type==="refresh_flow_rejected"){hi(typeof i.error=="string"?i.error:"rejected by the plane");return}if(i.ch==="ctl"&&i.type==="transferred"&&Array.isArray(i.tracks)){Promise.resolve().then(()=>a?.(i.tracks)).then(async l=>{for(let w of Array.isArray(l)?l:[])w?.stale&&w.id&&await qr(w.id,w.since??null)}).catch(l=>S.error("[plane-link] transfer notice failed:",l?.message||l));return}if(i.ch==="ctl"&&i.type==="moves"&&Array.isArray(i.tracks)){Promise.resolve().then(()=>u?.(i.tracks)).then(async l=>{for(let w of Array.isArray(l)?l:[])w?.stale&&w.id&&await qr(w.id,w.since??null)}).catch(l=>S.error("[plane-link] move-record reconcile failed:",l?.message||l));return}if(i.ch==="events"&&i.type==="ack"&&Array.isArray(i.ids)){xn(i.ids);return}if(i.ch==="events"&&i.type==="nack"&&Array.isArray(i.ids)){$n(i.ids,i.reason,i.permanent===!0,i.retryAfterMs??null);return}if(i.ch==="control"&&i.type==="http_open"){Xi(i).catch(l=>B({v:j,ch:"control",type:"http_end",reqId:i.reqId,error:l?.message||"tunnel error"}));return}if(i.ch==="control"&&i.type==="http_cancel"){ft.get(i.reqId)?.abort();return}if(i.ch==="attach"&&i.type==="open"){let l=new mr(ji+i.path,Array.isArray(i.protocols)?i.protocols:[],i.host?{headers:{host:i.host}}:void 0);Se.set(i.streamId,l),Te.set(i.streamId,[]),l.on("open",()=>{let T=Te.get(i.streamId)||[];Te.delete(i.streamId);for(let{buf:$,bin:L}of T)l.send($,{binary:L})}),l.on("message",(T,$)=>{let L=$?T:Buffer.from(String(T));B({v:j,ch:"attach",type:"data",streamId:i.streamId,data:L.toString("base64"),...$?{bin:!0}:{}})});let w=()=>{Te.delete(i.streamId),Se.delete(i.streamId)&&B({v:j,ch:"attach",type:"close",streamId:i.streamId})};l.on("close",w),l.on("error",w);return}if(i.ch==="attach"&&i.type==="data"){let l=Se.get(i.streamId);if(!l)return;let w=Buffer.from(i.data,"base64"),T=i.bin===!0,$=Te.get(i.streamId);$?$.push({buf:w,bin:T}):l.send(w,{binary:T});return}if(i.ch==="attach"&&i.type==="close"){let l=Se.get(i.streamId);Se.delete(i.streamId),Te.delete(i.streamId),l?.close();return}});let d=()=>{J&&S.log("[plane-link] disconnected from plane"),J=!1,ae&&(clearInterval(ae),ae=null),ce&&(clearInterval(ce),ce=null),C.clear(),ne={},ie=[],Y&&(clearTimeout(Y),Y=null),Be.clear();for(let l of Se.values())l.close();Se.clear(),Te.clear();for(let l of ft.values())l.abort();if(ft.clear(),wn||je)return;lt==null&&(lt=Date.now());let f=Date.now()-lt<Wl,i=Math.max(f?Kl+Math.random()*Gl:ct,at-Date.now(),St());je=setTimeout(()=>{je=null,Xr()},i),je.unref?.(),f||(ct=Math.min(ct*2,yi))};X.on("close",d),X.on("error",f=>{let i=/Unexpected server response: (\d+)/.exec(f?.message||"")?.[1];if(i==="410"){bn({reason:"removed",via:"410"});return}if(i==="401"||i==="403"){let{tripped:l,holdMs:w}=zt();l?S.error(`[plane-link] holding every plane call for ${Math.round(w/6e4)} min \u2014 three credential refusals in a row (HTTP ${i}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(w/6e4)} min.`):Date.now()-Pt>=Ti&&(Pt=Date.now(),S.error(`[plane-link] plane refused this node's credentials (HTTP ${i}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`))}d()})}_t.on("event",Yr),Fi().then(Xr);function Jr({bye:c=!0}={}){wn=!0,_t.off("event",Yr),Li(),je&&clearTimeout(je),Fe&&clearTimeout(Fe),ae&&clearInterval(ae),ce&&clearInterval(ce),Y&&clearTimeout(Y),c&&B({v:j,ch:"ctl",type:"bye",reason:"shutdown"}),X?.close()}return{stop:()=>Jr(),setRefreshFlow:c=>B({v:j,ch:"ctl",type:"refresh_flow_set",patch:c}),status:()=>({connected:J,nodeId:n,cursor:{...oe},inflight:C.size,...Gr(),auth:jo(),dormant:ut,removed:Zn(),deadLinkMs:M,deadLinkRedials:Lr,refused:{...It}}),_tick:()=>{Kr(),vn()}}}var te,yr,Sr,j,gi,yi,Wl,Kl,Gl,rn,zl,Vl,ql,Yl,Tr,Xl,wr,Jl,Zl,Ql,bi,eu,Si,tu,gr,nu,ru,Ti,_r=O(()=>{Yt();Vs();si();wi();Rn();Qn();te=(()=>{try{return Hl(import.meta.url)("../package.json").version||null}catch{return null}})(),yr=process.env.BOSTRAT_STATE_DIR||K.join(process.env.HOME||on.tmpdir(),".bostrat"),Sr=K.join(yr,"plane-link","removed.json");j=1,gi=1e3,yi=3e4,Wl=6e4,Kl=1500,Gl=500,rn=100,zl=2e3,Vl=25e3,ql=2.5,Yl=6e4,Tr=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Xl=Tr(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),wr="refused:",Jl={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"},Zl=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},Ql=3e4,bi=10*6e4,eu=400,Si=250,tu=Tr(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),gr=4,nu=Math.max(1,Math.round(Tr(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),ru=6e4,Ti=6e4});var vi=O(()=>{Yn()});var Mi={};En(Mi,{ACTIONABLE_KINDS:()=>un,INSTALL_ATTEMPTS:()=>sn,INSTALL_RETRY_STEP_S:()=>Ai,REGISTRY_RETRY_ATTEMPTS:()=>vr,REGISTRY_WAIT_POLLS:()=>xr,REGISTRY_WAIT_STEP_S:()=>$r,RESTART_SIGNAL:()=>Ei,SELF_UPDATE_DIR:()=>cn,SUPERVISOR_PID_FILE:()=>ki,createAutoUpdater:()=>bu,inFlight:()=>Or,readStatus:()=>Er,restartCommand:()=>Oi,restartStrategy:()=>kr,selfUpdatePlan:()=>Ri,settleSelfUpdate:()=>yu,startSelfUpdate:()=>Ni,underService:()=>Ar,updatePolicy:()=>fu});import Rt from"node:fs";import ye from"node:fs/promises";import su from"node:os";import U from"node:path";import{spawn as iu,execFileSync as au}from"node:child_process";import{createRequire as cu}from"node:module";function fu({kind:e=et(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:un.has(e)?e==="git-checkout"||Ar(t)?"auto":"prompt":"off"}function Ar(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function kr({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=ki,readFile:s=u=>Rt.readFileSync(u,"utf8"),alive:a=pu}={}){let u=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(Ar(e))return u;let p=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(p)&&p>0)){try{p=Number(String(s(o)).trim())}catch{p=NaN}Number.isInteger(p)&&p>0&&a(p)||(p=NaN)}return Number.isInteger(p)&&p>0?{mode:"supervisor",pid:p}:u}function pu(e){try{process.kill(e,0)}catch{return!1}try{let t=au("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 Oi(e){switch(e?.mode){case"systemd":return`systemctl --user restart ${Q(e.serviceName||"bostrat-node.service")}`;case"launchd":return`launchctl kickstart -k gui/${Number(e.uid)||0}/${e.serviceName||"com.bostrat.node"}`;case"supervisor":return`kill -${Ei.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function Ri({kind:e,to:t,from:n=an,statusFile:r=ln,logFile:o=U.join(cn,"last.log"),port:s=Number(process.env.PORT)||3362,npmPrefix:a=null,serviceName:u=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:p=typeof process.getuid=="function"?process.getuid():0,restart:m=kr({env:{},platform:process.platform,uid:p,serviceName:u,readFile:()=>{throw new Error("no pidfile")}}),liveDir:h=process.env.BOSTRAT_LIVE_CHECKOUT||U.resolve(U.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:g=Date.now(),attempts:A=1}={}){if(!un.has(e))throw new Error(`self-update: install kind "${e}" is not actionable here`);if(!/^\d+\.\d+\.\d+$/.test(String(t)))throw new Error(`self-update: bad target version "${t}"`);if(n&&!/^\d+\.\d+\.\d+$/.test(String(n)))throw new Error(`self-update: bad current version "${n}"`);let x=(b,_="")=>`write_status ${Q(b)} ${_}`,y=Oi(m),v=`
|
|
126
138
|
health() {
|
|
127
139
|
for i in $(seq 1 45); do
|
|
128
140
|
sleep 1
|
|
129
|
-
if curl -sf -o /dev/null "http://127.0.0.1:${
|
|
141
|
+
if curl -sf -o /dev/null "http://127.0.0.1:${s}/api/health"; then return 0; fi
|
|
130
142
|
done
|
|
131
143
|
return 1
|
|
132
|
-
}`,
|
|
144
|
+
}`,N=`#!/usr/bin/env bash
|
|
133
145
|
# bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
|
|
134
146
|
# ${n??"?"} \u2192 ${t} (${e}). Status: ${r}
|
|
135
147
|
set -u
|
|
136
|
-
FROM=${
|
|
137
|
-
TO=${
|
|
138
|
-
STATUS_FILE=${
|
|
148
|
+
FROM=${Q(n??"")}
|
|
149
|
+
TO=${Q(t)}
|
|
150
|
+
STATUS_FILE=${Q(r)}
|
|
139
151
|
STARTED_AT=${Number(g)}
|
|
140
|
-
ATTEMPTS=${Number(
|
|
152
|
+
ATTEMPTS=${Number(A)||1}
|
|
141
153
|
write_status() { # <status> [error] [retryable]
|
|
142
154
|
local err="\${2:-}"
|
|
143
155
|
err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
|
|
144
156
|
printf '{"status":"%s","from":"%s","to":"%s","kind":"%s","attempts":%s,"startedAt":%s,"updatedAt":%s%s%s}\\n' \\
|
|
145
|
-
"$1" "$FROM" "$TO" ${
|
|
157
|
+
"$1" "$FROM" "$TO" ${Q(e)} "$ATTEMPTS" "$STARTED_AT" "$(date +%s000)" \\
|
|
146
158
|
"\${err:+,\\"error\\":\\"$err\\"}" "\${3:+,\\"retryable\\":true}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
|
|
147
159
|
}
|
|
148
|
-
${
|
|
149
|
-
`;if(e==="npm-global"){let
|
|
150
|
-
`:"",k=
|
|
160
|
+
${v}
|
|
161
|
+
`;if(e==="npm-global"){let b=a?U.join(a,"bin","npm"):"npm",_=a?`export PATH=${Q(U.join(a,"bin"))}:"$PATH"
|
|
162
|
+
`:"",k=a?` --prefix ${Q(a)}`:"",E=Me=>`${Q(b)} install -g "bostrat-node@${Me}" --no-audit --no-fund${k}`,R=`
|
|
151
163
|
install_target() {
|
|
152
|
-
for i in $(seq 1 ${
|
|
153
|
-
if ${
|
|
154
|
-
[ "$i" -lt ${
|
|
164
|
+
for i in $(seq 1 ${sn}); do
|
|
165
|
+
if ${E("$TO")}; then return 0; fi
|
|
166
|
+
[ "$i" -lt ${sn} ] && sleep ${Ai}
|
|
155
167
|
done
|
|
156
168
|
return 1
|
|
157
|
-
}`,
|
|
169
|
+
}`,P=`
|
|
158
170
|
wait_for_registry() {
|
|
159
|
-
for i in $(seq 1 ${
|
|
160
|
-
if [ "$(${
|
|
161
|
-
sleep ${
|
|
171
|
+
for i in $(seq 1 ${xr}); do
|
|
172
|
+
if [ "$(${Q(b)} view "bostrat-node@$TO" version --prefer-online 2>/dev/null)" = "$TO" ]; then return 0; fi
|
|
173
|
+
sleep ${$r}
|
|
162
174
|
done
|
|
163
175
|
return 1
|
|
164
|
-
}`;return
|
|
165
|
-
${
|
|
176
|
+
}`;return N+_+P+R+`
|
|
177
|
+
${x("updating",'"" ')}
|
|
166
178
|
if ! wait_for_registry; then
|
|
167
|
-
${
|
|
179
|
+
${x("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(xr*$r/60)} min, attempt $ATTEMPTS of ${vr})" retryable`)}
|
|
168
180
|
exit 1
|
|
169
181
|
fi
|
|
170
182
|
if ! install_target; then
|
|
171
|
-
${
|
|
183
|
+
${x("failed",`"npm install failed (${sn} attempts)"`)}
|
|
172
184
|
exit 1
|
|
173
185
|
fi
|
|
174
|
-
${
|
|
175
|
-
if ! ${
|
|
176
|
-
${
|
|
186
|
+
${x("restarting")}
|
|
187
|
+
if ! ${y}; then
|
|
188
|
+
${x("failed",`"restart failed (${y.replace(/"/g,"")})"`)}
|
|
177
189
|
exit 1
|
|
178
190
|
fi
|
|
179
191
|
if health; then
|
|
@@ -181,54 +193,54 @@ if health; then
|
|
|
181
193
|
exit 0
|
|
182
194
|
fi
|
|
183
195
|
# \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
|
|
184
|
-
${
|
|
185
|
-
if [ -n "$FROM" ] && ${
|
|
186
|
-
${
|
|
196
|
+
${x("rolling-back",'"agent did not answer on :'+s+' after the update"')}
|
|
197
|
+
if [ -n "$FROM" ] && ${E("$FROM")} && ${y} && health; then
|
|
198
|
+
${x("rolled-back",'"agent did not answer on :'+s+' after the update; rolled back"')}
|
|
187
199
|
exit 1
|
|
188
200
|
fi
|
|
189
|
-
${
|
|
201
|
+
${x("failed",'"agent did not answer after the update AND the rollback"')}
|
|
190
202
|
exit 1
|
|
191
|
-
`}let
|
|
192
|
-
LIVE=${
|
|
203
|
+
`}let I=b=>`( cd ${Q(h)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${b}" )`;return N+`
|
|
204
|
+
LIVE=${Q(h)}
|
|
193
205
|
TMP_SCRIPT="$(mktemp)"
|
|
194
206
|
trap 'rm -f "$TMP_SCRIPT"' EXIT
|
|
195
207
|
# "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
|
|
196
208
|
# restart \u2192 health in one call): the agent it restarts settles "done" on boot,
|
|
197
209
|
# and nothing here may write after that boot or the settle would repeat.
|
|
198
|
-
${
|
|
199
|
-
if ${
|
|
210
|
+
${x("restarting")}
|
|
211
|
+
if ${I("$TO")}; then
|
|
200
212
|
exit 0
|
|
201
213
|
fi
|
|
202
|
-
${
|
|
203
|
-
if [ -n "$FROM" ] && ${
|
|
204
|
-
${
|
|
214
|
+
${x("rolling-back",'"deploy-pi.sh v$TO failed"')}
|
|
215
|
+
if [ -n "$FROM" ] && ${I("$FROM")}; then
|
|
216
|
+
${x("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
|
|
205
217
|
exit 1
|
|
206
218
|
fi
|
|
207
|
-
${
|
|
219
|
+
${x("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
|
|
208
220
|
exit 1
|
|
209
|
-
`}async function
|
|
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?`
|
|
221
|
+
`}async function Er(e=ln){try{return JSON.parse(await ye.readFile(e,"utf8"))}catch{return null}}async function Ni({to:e,from:t=an,kind:n=et(),reason:r="manual",force:o=!1,statusFile:s=ln,spawnImpl:a=iu,now:u=Date.now,npmPrefix:p=void 0,log:m=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!un.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Qe(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let h=await Er(s);if(Or(h))return{ok:!1,reason:`an update to ${h.to} is already in flight`,status:h};let g=h?.to===e?Number(h.attempts)||1:0;if(!o&&h&&h.to===e&&(h.status==="failed"||h.status==="rolled-back")&&!(h.status==="failed"&&h.retryable===!0&&g<vr))return{ok:!1,reason:`update to ${e} already ${h.status} (${h.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:h};let A=h?.to===e&&(h.status==="failed"||h.status==="rolled-back")?g+1:1;await ye.mkdir(U.dirname(s),{recursive:!0});let x=p!==void 0?p:n==="npm-global"?qn(await mu())||U.resolve(U.dirname(process.execPath),".."):null,y=kr(),v=Ri({kind:n,to:e,from:t,statusFile:s,npmPrefix:x,startedAt:u(),attempts:A,restart:y}),N=U.join(U.dirname(s),`update-${e}.sh`),I=U.join(U.dirname(s),"last.log");await ye.writeFile(N,v,{mode:448}),await ye.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:A,startedAt:u(),updatedAt:u()}));let b=Rt.existsSync("/run/systemd/system")&&await wu("systemd-run"),_=b?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",N]]:["bash",[N]],k=async R=>{let P=`could not spawn updater: ${R?.message||R}`;return await ye.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,attempts:A,startedAt:u(),updatedAt:u(),error:P})).catch(()=>{}),m.error?.(`[self-update] ${P}`),P},E=null;try{b||(E=Rt.openSync(I,"a"));let R=a(_[0],_[1],{detached:!0,stdio:b?"ignore":["ignore",E,E]});R.on?.("error",P=>{k(P)}),R.unref?.()}catch(R){return{ok:!1,reason:await k(R)}}finally{E!==null&&Rt.closeSync(E)}return m.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}, restart via ${y.mode}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:N,statusFile:s}}async function mu(){try{return await ye.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function wu(e){for(let t of String(process.env.PATH||"").split(U.delimiter))try{return await ye.access(U.join(t,e),Rt.constants.X_OK),!0}catch{}return!1}async function yu({statusFile:e=ln,current:t=an,now:n=Date.now,staleMs:r=gu}={}){let o=await Er(e);if(!o)return null;let s=a=>ye.writeFile(e,JSON.stringify(a)).catch(()=>{});if(Or(o)){if(t&&o.to===t){let a={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await s(a),a}if(n()-Number(o.updatedAt||o.startedAt||0)>r){let a={...o,status:"failed",error:`updater went silent while ${o.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await s(a),a}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let a={...o,announced:!0};return await s(a),a}return null}function bu({isBusy:e,start:t=Ni,onStuck:n=null,onStarted:r=null,tickMs:o=du,stuckMs:s=uu,now:a=Date.now,setIntervalImpl:u=setInterval,clearIntervalImpl:p=clearInterval,log:m=console}={}){let h=null,g=()=>{h?.timer&&p(h.timer),h=null},A=async()=>{if(!h)return;let x=!0;try{x=await e()!==!1}catch{x=!0}if(x){if(!h.stuckFired&&a()-h.since>=s){h.stuckFired=!0;try{await n?.({to:h.to,from:h.from,since:h.since})}catch{}}return}let y=h;g();let v=await t({to:y.to,from:y.from,kind:y.kind,reason:"auto"});m.log?.(`[self-update] stasis reached \u2192 ${v.ok?"started":`not started: ${v.reason}`}`);try{await r?.({...y,result:v})}catch{}};return{arm({to:x,from:y=an,kind:v=et()}){return h?.to===x?!1:(g(),h={to:x,from:y,kind:v,since:a(),stuckFired:!1,timer:u(A,o)},h.timer.unref?.(),!0)},tick:A,cancel:g,get armed(){return h?{to:h.to,from:h.from,kind:h.kind,since:h.since}:null}}}var an,lu,cn,ln,uu,du,xr,$r,vr,sn,Ai,ki,Ei,un,Q,hu,Or,gu,Ii=O(()=>{_r();vi();an=(()=>{try{return cu(import.meta.url)("../package.json").version||null}catch{return null}})(),lu=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||su.tmpdir(),".bostrat"),cn=U.join(lu,"self-update"),ln=U.join(cn,"status.json"),uu=1440*6e4,du=6e4,xr=60,$r=15,vr=3,sn=6,Ai=20,ki=U.join(cn,"supervisor.pid"),Ei="SIGUSR2",un=new Set(["npm-global","git-checkout"]);Q=e=>`'${String(e).replace(/'/g,"'\\''")}'`;hu=new Set(["updating","restarting","rolling-back"]),Or=e=>!!(e&&hu.has(e.status));gu=45*6e4});Rn();Vn();nr();import G from"node:fs";import F from"node:path";import nt from"node:os";import{createRequire as Rr}from"node:module";import{execFile as Su,spawn as Tu}from"node:child_process";import{promisify as _u}from"node:util";import xu from"node:readline/promises";import{randomUUID as $u}from"node:crypto";import{fileURLToPath as vu}from"node:url";import Qt from"node:fs";import Ve from"node:fs/promises";import jc from"node:os";import vt from"node:path";import Fc from"node:readline";import{spawn as Lc}from"node:child_process";var Uc="^(ugrep|rg|2\\.1\\.[0-9]+|cursor-agent|codex|npm|node|MainThread)",Hc="^(bostrat-|tmux|earlyoom|systemd|sshd)",Wc=()=>["-m","10","-s","70","-r","600","--prefer",Uc,"--avoid",Hc],cs="BOSTRAT_OOM_GUARD_OWNER",Kc=6e4,Gc=5e3;function ls(e=process.env){return!["0","off","false","no"].includes(String(e.BOSTRAT_OOM_GUARD??"").trim().toLowerCase())}function us(e=process.env){let t=e.BOSTRAT_STATE_DIR||vt.join(e.HOME||jc.tmpdir(),".bostrat");return vt.join(t,"oom-guard.pid")}function ds(e=process.env){if(e.BOSTRAT_EARLYOOM_BIN)return Qt.existsSync(e.BOSTRAT_EARLYOOM_BIN)?e.BOSTRAT_EARLYOOM_BIN:null;let t=[...String(e.PATH||"").split(":").filter(Boolean),"/usr/bin","/usr/sbin","/usr/local/bin","/bin"];for(let n of t){let r=vt.join(n,"earlyoom");if(Qt.existsSync(r))return r}return null}async function fs({procRoot:e="/proc"}={}){let t=[];try{t=await Ve.readdir(e)}catch{return[]}let n=[];for(let r of t){if(!/^\d+$/.test(r))continue;(await Ve.readFile(vt.join(e,r,"comm"),"utf8").catch(()=>"")).trim()==="earlyoom"&&n.push({pid:Number(r)})}return n}async function ps(e){let t=Number((await Ve.readFile(e,"utf8").catch(()=>"")).trim());return Number.isInteger(t)&&t>0?t:null}async function hs({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc"}={}){if(!ls(e))return{state:"off"};if(t!=="linux")return{state:"unsupported",platform:t};let r=await fs({procRoot:n}),o=await ps(us(e)),s=r.find(u=>u.pid===o);if(s)return{state:"own",pid:s.pid};if(r.length)return{state:"host",pid:r[0].pid};let a=ds(e);return a?{state:"stopped",bin:a}:{state:"absent"}}function sr(e){switch(e?.state){case"own":return`earlyoom running under the node (pid ${e.pid}; acts at 10% memory available and 70% swap free)`;case"host":return`the host's own earlyoom is running (pid ${e.pid}) \u2014 the node starts none beside it`;case"stopped":return`earlyoom is installed (${e.bin}) and not running \u2014 the node starts it at boot`;case"absent":return"none \u2014 earlyoom is not installed, so memory exhaustion is left to the kernel's OOM killer";case"off":return"disabled (BOSTRAT_OOM_GUARD=0)";case"unsupported":return`not available on ${e.platform}`;default:return"not checked yet"}}function ms({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc",log:r=console.log,spawnImpl:o=Lc,checkMs:s=Kc,relaunchMs:a=Gc}={}){let u=null,p={state:null},m=null,h=!1,g="",A=us(e),x=b=>{p=b;let _=`[oom-guard] ${sr(b)}`;return _!==g&&r(_),g=_,b},y=b=>{h||(clearTimeout(m),m=setTimeout(()=>v().catch(()=>{}),b),m.unref?.())},v=async()=>{if(h||u)return p;if(!ls(e))return x({state:"off"});if(t!=="linux")return x({state:"unsupported",platform:t});let b=await ps(A),_=await fs({procRoot:n});if(b&&_.some(R=>R.pid===b)){try{process.kill(b,"SIGTERM")}catch{}_=_.filter(R=>R.pid!==b)}if(_.length)return y(s),x({state:"host",pid:_[0].pid});let k=ds(e);if(!k)return y(s),x({state:"absent"});let E;try{E=o(k,Wc(),{stdio:["ignore","pipe","pipe"]})}catch(R){return r(`[oom-guard] could not start ${k}: ${R?.message||R}`),y(s),p}u=E;for(let R of[E.stdout,E.stderr])R&&Fc.createInterface({input:R}).on("line",P=>r(`[earlyoom] ${P}`));return E.on("error",R=>{r(`[oom-guard] ${k}: ${R?.message||R}`),!(u!==E||E.pid)&&(u=null,y(s))}),E.on("exit",(R,P)=>{u===E&&(u=null,Ve.rm(A,{force:!0}).catch(()=>{}),!h&&(r(`[oom-guard] earlyoom exited (${P||`code ${R}`}) \u2014 relaunching in ${Math.round(a/1e3)} s`),p={state:"stopped",bin:k},g="",y(a)))}),E.pid&&(await Ve.mkdir(vt.dirname(A),{recursive:!0}).catch(()=>{}),await Ve.writeFile(A,`${E.pid}
|
|
222
|
+
`).catch(()=>{})),y(s),x({state:"own",pid:E.pid})},N=()=>{u&&(u.kill("SIGTERM"),Qt.rmSync(A,{force:!0}))};return process.on("exit",N),{ready:v().catch(()=>p),status:()=>p,stop(){h=!0,clearTimeout(m),process.off("exit",N);let b=u;u=null,b&&(b.kill("SIGTERM"),Qt.rmSync(A,{force:!0}))}}}Cn();import zc from"node:fs";import ws from"node:path";import Vc from"node:os";var qc=()=>process.env.BOSTRAT_STATE_DIR||ws.join(process.env.HOME||Vc.tmpdir(),".bostrat"),Yc=()=>ws.join(qc(),"plane-link","public-host.json");var At=null;function Xc(){if(At)return At;try{let e=JSON.parse(zc.readFileSync(Yc(),"utf8"));At={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{At={viewBase:null}}return At}function Jc(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),o=r?r[1].toLowerCase():t,s=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return s?{proto:o,host:s}:null}function gs(){return Xc().viewBase}function ys(e=process.env.BOSTRAT_PUBLIC_HOST){return Jc(e,"https")}function bs(e=process.env.BOSTRAT_PLANE_URL){let t=String(e||"").trim();if(!t)return null;let n=/^(wss?|https?):\/\/([^/?#]+)/i.exec(t);return n?`${/^(wss|https)$/i.test(n[1])?"https":"http"}://${n[2]}`:null}Xt();import Zc from"node:fs";import Qc from"node:os";import Ss from"node:path";var Ts=3*6e4;function ir(e=process.env){let t=e.BOSTRAT_STATE_DIR||Ss.join(e.HOME||Qc.tmpdir(),".bostrat");return Ss.join(t,"heartbeat.json")}function _s(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return Ts;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):Ts}function xs(e=ir()){try{let t=JSON.parse(Zc.readFileSync(e,"utf8"));if(!t||typeof t!="object")return null;let n=Number(t.ts),r=Number(t.pid);if(!Number.isFinite(n)||!Number.isFinite(r))return null;let o=Number(t.loopLagMs);return{pid:r,ts:n,loopLagMs:Number.isFinite(o)?o:null}}catch{return null}}Xt();var vs="BOSTRAT_RESTART_NOTICE",Gh=2*6e4;var $s=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function As({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:$s(e),staleS:$s(t)!=null?Math.round(t/1e3):null})}ke();var Pi=(e,t)=>{let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let o=0;o<Math.max(n.length,r.length);o++){let s=(n[o]||0)-(r[o]||0);if(s)return s<0}return!1},be=_u(Su),Nr=F.dirname(vu(import.meta.url)),Ne=F.resolve(Nr,".."),Au=F.join(Nr,"index.js"),ku="wss://plane.bostrat.ai/v1/node",tt=Rr(import.meta.url)("../package.json").version,D=(e,t)=>({name:e,level:"pass",detail:t}),W=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),q=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function Eu(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?D("node runtime",`${process.version} at ${process.execPath}`):q("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Ou(e){return e.BOSTRAT_OWNER?W("owner stamp",`BOSTRAT_OWNER=${String(e.BOSTRAT_OWNER).slice(0,12)}\u2026 is set \u2014 ignored by this release; on older releases it got every event refused (forgedUserId)`,"remove BOSTRAT_OWNER from node.env and any shell rc, then restart the node"):D("owner stamp","none (the plane infers the owner from the token)")}function Ru(e){let t;try{t=G.statSync(e)}catch{return W("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?W("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):D("node.env",`${e} (0600)`)}async function Nu(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await be(t,["-V"],{timeout:5e3});return D("tmux",`${t} (${n.trim()})`)}catch{return q("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Di(e,{required:t=!1}={}){if(await or(e,{loginShell:!0,failOpen:!1}))return D(e,"resolves on the login-shell PATH");let r="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",o=Zt[e]?`${Zt[e]}${e==="cursor-agent"?" # installs to ~/.local/bin \u2014 ensure your login shell has it on PATH":""}`:`install ${e} so \`$SHELL -lic 'command -v ${e}'\` finds it`;return t?q(e,r,o):W(e,r,o)}async function Mu(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await be(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return D("gh (GitHub CLI)",n)}catch{return W("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",Zt.gh)}}async function Iu(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Di(t)));return e.some(t=>t.level==="pass")||e.push(q("agent CLIs","no agent CLI found at all \u2014 a node with nothing to drive","install at least one of claude / codex / cursor-agent")),e}async function Pu(){let e=[...process.platform==="linux"?[["fuser","stopped views can't free their ports (they leak, and the port can't be reused)","apt install psmisc"]]:[],["pgrep","agent-swap can't detect an idle pane shell \u2014 swaps may misfire","apt install procps"],["npm","codex auto-update and `npm run` views are unavailable","install Node.js with npm on the service PATH"]];return Promise.all(e.map(async([t,n,r])=>await or(t,{failOpen:!1})?D(t,"resolves on the service PATH"):W(t,`not on the service PATH \u2014 ${n}`,r)))}async function Du(){try{let t=Rr(F.join(Ne,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let o=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),s=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(s),n()})}),D("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${Ne} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Rr(F.join(Ne,"package.json")),r=F.join(F.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");G.existsSync(r)&&!(G.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return q("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function Cu(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(G.existsSync(t))return D("chromium (mocks)",t);let n=process.platform==="darwin"?"brew install --cask chromium (or set BOSTRAT_CHROMIUM_BIN to Chrome.app's inner binary)":"apt install chromium fonts-dejavu-core fonts-liberation (or set BOSTRAT_CHROMIUM_BIN)";return(e.BOSTRAT_INSTALL_KIND==="container"?q:W)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function Bu(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?q("claude lane","BOSTRAT_CLAUDE_USE_API_KEY=1 but ANTHROPIC_API_KEY is empty","add the key to node.env or set the flag to 0"):D("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function ju(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return W("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),o=pt(e.BOSTRAT_PLANE_URL);return await new Promise(s=>{let a=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),u=null,p=h=>{clearTimeout(m);try{a.close()}catch{}s(u?{...h,viewBase:u}:h)},m=setTimeout(()=>p(q("plane link",`no hello_ok within 5s from ${o}`,"check the URL, the token, and the plane's IP gate")),5e3);a.on("open",()=>a.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${$u().slice(0,8)}`,ephemeral:!0}))),a.on("message",h=>{try{let g=JSON.parse(h);g.type==="hello_ok"?(typeof g.viewBase=="string"&&g.viewBase&&(u=g.viewBase),g.minNodeVersion&&Pi(tt,g.minNodeVersion)?p(q("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${g.minNodeVersion} \u2014 this node is ${tt}; the real link is refused until it updates`,`bostrat-node self-update --to ${g.latestNodeVersion||g.minNodeVersion}`)):g.latestNodeVersion&&Pi(tt,g.latestNodeVersion)?p(W("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${g.latestNodeVersion} is available (this node: ${tt})`,`bostrat-node self-update --to ${g.latestNodeVersion}`)):p(D("plane link",`hello_ok in ${Date.now()-r}ms (${o})`))):g.type==="error"&&p(q("plane link",`plane said: ${g.code} ${g.message||""}`,"check the token"))}catch{}}),a.on("error",h=>p(q("plane link",`${h?.message||h}`,"check the URL, the token, and the plane's IP gate")))})}function Fu(){let e;try{e=JSON.parse(G.readFileSync(F.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 q("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?W("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):D("content outbox",t?`${t} op(s) in flight`:"drained")}async function Lu(e){let t=await ts({env:e}),n=ns(t);return t.available?D("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?W("box caps",n,"boxes run under nice only on this node; if Fly's init mounts /sys/fs/cgroup read-only this is the expected state (blueprint BP-NG-I4)"):D("box caps",n)}async function Uu(e){let t=await hs({env:e}),n=sr(t);return t.state==="absent"?W("oom guard",n,"install earlyoom (apt install earlyoom) \u2014 the node starts it with its own tuning at the next boot"):D("oom guard",n)}async function Hu(e){let t=await Eo({env:e}),n=Oo(t);return t.level==="misconfigured"?q("box containment",n,"fix the user (scripts/pi/box-user-setup.sh) or unset BOSTRAT_BOX_USER in node.env, then restart"):t.level==="root-capable"?W("box containment",n,"opt in to a dedicated box uid: BP-AU-I10 runbook (scripts/pi/box-user-setup.sh, then BOSTRAT_BOX_USER in node.env)"):t.level==="uid"&&(t.problems.length||t.auditd?.rule!==!0||!t.auditd?.readable)?W("box containment",n,"re-run scripts/pi/box-user-setup.sh (idempotent) \u2014 it installs the auditd rule, the log group and the mirror"):D("box containment",n)}function Wu(e){let t=Dn(e),n=bo(t);return t.unknown?.length?W("audit guard",n,`BOSTRAT_AUDIT_GUARD names unknown rule(s): ${t.unknown.join(", ")}`):D("audit guard",n)}function Ku(e){return e.BOSTRAT_STATE_REMOTE?D("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):W("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}function Gu(e,t){let n=t?.viewBase??null,r=gs(),o=ys(e.BOSTRAT_PUBLIC_HOST),s=(()=>{let a=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(a)return`${a.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let u=bs(e.BOSTRAT_PLANE_URL);return u?`${u}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let a=o&&o.host!==n?`; BOSTRAT_PUBLIC_HOST=${o.host} is set but the plane's value wins`:"";return D("public host",`views https://<slug>.${n}/ (plane hello_ok)${a} \xB7 track links ${s}`)}return r?D("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${s}`):o?D("public host",`views ${o.proto}://<slug>.${o.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${s}`):q("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${s}`,"link a plane that sets PLANE_VIEW_BASE (bostrat-node init), or set BOSTRAT_PUBLIC_HOST in node.env for a plane-less node")}async function Ci(e,t={}){let n=[];n.push(await Eu()),n.push(Ru(t.envFile||Ue())),n.push(await Nu(e)),n.push(await Lu(e)),n.push(await Uu(e)),n.push(Wu(e)),n.push(await Hu(e)),n.push(...await Iu()),n.push(await Di("git",{required:!0})),n.push(await Mu()),n.push(...await Pu()),n.push(await Du()),n.push(Cu(e)),n.push(Bu(e)),n.push(Ou(e));let r=await ju(e,t);return n.push(r),n.push(Gu(e,r)),n.push(Fu()),n.push(Ku(e)),n}function Bi(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let s of e)t(`${n[s.level]} ${s.name}: ${s.detail}`),s.fix&&s.level!=="pass"&&t(` fix: ${s.fix}`);let r=e.filter(s=>s.level==="fail").length,o=e.filter(s=>s.level==="warn").length;return t(r?`
|
|
211
223
|
FAIL \u2014 ${r} blocking, ${o} warnings`:`
|
|
212
|
-
OK \u2014 0 blocking, ${o} warnings`),r===0}async function
|
|
224
|
+
OK \u2014 0 blocking, ${o} warnings`),r===0}async function zu({envFile:e=Ue(),input:t=process.stdin,output:n=process.stdout}={}){let r=jt(e),o=xu.createInterface({input:t,output:n}),s=async(b,_)=>(await o.question(_?`${b} [${_}]: `:`${b}: `)).trim()||_||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
|
|
213
225
|
you type those inside each box, later (box-auth-policy).
|
|
214
226
|
|
|
215
|
-
`);let
|
|
216
|
-
`);let
|
|
217
|
-
`);let m=await
|
|
227
|
+
`);let a=await s("Plane URL",r.BOSTRAT_PLANE_URL||ku),u=pt(a);u!==a.trim()&&n.write(` \u2192 using ${u}
|
|
228
|
+
`);let p=await s("Node token (minted plane-side; stored 0600)",r.BOSTRAT_PLANE_TOKEN);r.BOSTRAT_OWNER&&n.write(` \u2192 dropping BOSTRAT_OWNER from node.env \u2014 the plane infers the owner from the token; a stale id here got every event refused.
|
|
229
|
+
`);let m=await s("Node name",r.BOSTRAT_NODE_NAME||nt.hostname().split(".")[0]),h=await s("Repos root",r.BOSTRAT_REPOS_ROOT||F.join(nt.homedir(),"Documents")),g=await s("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),A=(await s("Route NEW claude boxes through a BYO API key? (y/N)",r.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");A&&n.write(`
|
|
218
230
|
BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
|
|
219
231
|
injected per box, stored 0600 in node.env, never sent to the plane.
|
|
220
232
|
\u2022 create/copy a key: https://console.anthropic.com/settings/keys
|
|
221
233
|
\u2022 set a monthly spend limit while you're there \u2014 the key is live.
|
|
222
234
|
|
|
223
|
-
`);let
|
|
224
|
-
`),o.close();let
|
|
235
|
+
`);let x=A?await s("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";A&&x&&!/^sk-ant-/.test(x)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
|
|
236
|
+
`),o.close();let y={...to(),...r,BOSTRAT_PLANE_URL:u,BOSTRAT_PLANE_TOKEN:p,BOSTRAT_NODE_NAME:m,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||m,BOSTRAT_REPOS_ROOT:h,BOSTRAT_STATE_REMOTE:g,BOSTRAT_CLAUDE_USE_API_KEY:A?"1":"0",ANTHROPIC_API_KEY:A?x:r.ANTHROPIC_API_KEY};delete y.BOSTRAT_OWNER,eo(e,y,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
|
|
225
237
|
0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
|
|
226
238
|
Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
|
|
227
239
|
wrote ${e}
|
|
228
240
|
|
|
229
|
-
`);let
|
|
230
|
-
`));return
|
|
231
|
-
`)}catch{}let r=
|
|
241
|
+
`);let v={...y,...process.env},N=await Ci(v,{envFile:e}),I=Bi(N,b=>n.write(b+`
|
|
242
|
+
`));return I&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:I,results:N}}var Vu="SIGUSR2",qu=5*6e4,Yu=1e4,dn=F.join(Bt,"self-update","supervisor.pid");function Xu({spawnChild:e,exit:t=m=>process.exit(m),now:n=Date.now,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:o=clearTimeout,killGraceMs:s=15e3,rollbackGraceMs:a=qu,stall:u=null,log:p=console}={}){let m=null,h=0,g=!1,A="update",x=0,y=null,v=null,N=null,I=0,b=0,_=0,k=!1,E=u&&u.staleMs>0?u.staleMs:0,R=u?.checkMs>0?u.checkMs:Yu,P=()=>{y&&o(y),y=null},Me=()=>{m.kill("SIGTERM"),v=r(()=>m?.kill("SIGKILL"),s),v.unref?.()},rt=null,Ie=0,fn=()=>{let M=null;try{M=u.readHeartbeat()}catch{}return M&&M.pid===m.pid&&Number.isFinite(M.ts)&&M.ts!==rt&&(rt=M.ts,Ie=Math.max(Ie,Math.min(M.ts,n()))),n()-Ie},Nt=()=>{if(!m||k||g||!E)return!1;let M=fn();return M<E?!1:(b++,_=M,p.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 #${b})`),A="stall",g=!0,Me(),!0)},Pe=()=>{E&&(N&&o(N),N=r(()=>{N=null,Nt(),Pe()},R),N.unref?.())},ot=(M=null)=>{let ue=e(M);return m=ue,h=n(),rt=null,Ie=h,ue.on("exit",(de,fe)=>De(ue,de,fe)),N||Pe(),ue},De=(M,ue,de)=>{if(M!==m)return;if(m=null,v&&o(v),v=null,g){g=!1,st(A);return}let fe=de?1:ue??1;if(!k&&fe!==0&&n()<x){let it=x-n();p.error?.(`[bostrat-node] the agent exited (code ${fe}) right after a self-update restart \u2014 holding ${Math.ceil(it/1e3)} s for the updater's rollback signal`),y=r(()=>t(fe),it);return}t(fe)},st=(M="update")=>{I++,M==="stall"?p.log?.(`[bostrat-node] relaunched the agent after a stall (restart #${I}, stall relaunch #${b})`):(x=n()+a,p.log?.(`[bostrat-node] restarting the agent (self-update, restart #${I})`)),A="update",ot(M==="stall"?{at:n(),staleMs:_}:null)};return{start:()=>ot(),restart(){if(k=!1,P(),A="update",!m){st("update");return}g||(g=!0,Me())},checkStall:Nt,forward(M){k=!0,m?m.kill(M):(P(),t(1))},get child(){return m},get state(){return{alive:!!m,restartPending:g,restartReason:A,holding:!!y,restarts:I,stallRelaunches:b,stopping:k}}}}function Ju({envFile:e=Ue()}={}){Qr(e),process.title="bostrat-node";let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n={...process.env,BOSTRAT_RUN_SUPERVISOR_PID:String(process.pid),[cs]:"supervisor"};ms();try{G.mkdirSync(F.dirname(dn),{recursive:!0}),G.writeFileSync(dn,`${process.pid}
|
|
243
|
+
`)}catch{}let r=_s(process.env),o=ir(process.env);console.log(r?`[bostrat-node] stall watchdog: relaunch the agent after ${Math.round(r/1e3)} s without a heartbeat (${o})`:"[bostrat-node] stall watchdog: off (BOSTRAT_HEARTBEAT_STALE_MS)");let s=Xu({spawnChild:a=>Tu(t,[Au],{cwd:Ne,stdio:"inherit",env:a?{...n,[vs]:As(a)}:n}),stall:r?{readHeartbeat:()=>xs(o),staleMs:r}:null});for(let a of["SIGINT","SIGTERM"])process.on(a,()=>s.forward(a));return process.on(Vu,()=>s.restart()),process.on("exit",()=>{try{G.readFileSync(dn,"utf8").trim()===String(process.pid)&&G.rmSync(dn,{force:!0})}catch{}}),s.start()}function Zu({agentDir:e=Ne,nodeBin:t=process.execPath,envFile:n=Ue(),home:r=nt.homedir()}={}){let o=F.dirname(t),s=F.join(F.basename(Nr),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
|
|
232
244
|
# ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
|
|
233
245
|
[Unit]
|
|
234
246
|
Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
|
|
@@ -238,7 +250,7 @@ After=default.target
|
|
|
238
250
|
Type=simple
|
|
239
251
|
WorkingDirectory=${e}
|
|
240
252
|
# Pinned runtime: node-pty is compiled against exactly this node (SEGV trap).
|
|
241
|
-
ExecStart=${t} --disable-warning=ExperimentalWarning ${
|
|
253
|
+
ExecStart=${t} --disable-warning=ExperimentalWarning ${s}
|
|
242
254
|
EnvironmentFile=${n}
|
|
243
255
|
# systemd's user PATH omits ~/.local/bin (cursor-agent, bostrat-view) and the
|
|
244
256
|
# nvm bin dir \u2014 both are load-bearing for box spawning.
|
|
@@ -252,7 +264,7 @@ RestartSec=2
|
|
|
252
264
|
|
|
253
265
|
[Install]
|
|
254
266
|
WantedBy=default.target
|
|
255
|
-
`}function
|
|
267
|
+
`}function Qu({agentDir:e=Ne,nodeBin:t=process.execPath,home:n=nt.homedir()}={}){let r=F.dirname(t),o=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
|
|
256
268
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
257
269
|
<plist version="1.0">
|
|
258
270
|
<dict>
|
|
@@ -274,7 +286,7 @@ WantedBy=default.target
|
|
|
274
286
|
<key>StandardErrorPath</key><string>${o}/node.err.log</string>
|
|
275
287
|
</dict>
|
|
276
288
|
</plist>
|
|
277
|
-
`}function
|
|
289
|
+
`}function ed(e=process.platform,t=nt.homedir()){return e==="darwin"?{kind:"launchd",file:F.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:F.join(t,".config","systemd","user","bostrat-node.service")}}async function td({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=Ne}={}){let{kind:s,file:a}=ed(n);if(!e&&o.split(F.sep).includes("_npx"))return r("\u2717 running from the npx cache \u2014 a service must point at a durable install."),r(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){s==="systemd"?(await be("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),G.rmSync(a,{force:!0}),await be("systemctl",["--user","daemon-reload"])):(await be("launchctl",["unload","-w",a]).catch(()=>{}),G.rmSync(a,{force:!0})),r(`removed ${a}`);return}G.mkdirSync(F.dirname(a),{recursive:!0}),s==="systemd"?(G.writeFileSync(a,Zu()),await be("systemctl",["--user","daemon-reload"]),t&&await be("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${a}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(G.mkdirSync(F.join(nt.homedir(),"Library","Logs","bostrat"),{recursive:!0}),G.writeFileSync(a,Qu()),t&&await be("launchctl",["load","-w",a]),r(`installed ${a}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function gw(e=process.argv.slice(2)){let t=e[0],n=Ue();if(t==="--version"||t==="-v"||t==="version")return console.log(tt),0;if(t==="init")return(await zu({envFile:n})).ok?0:1;if(t==="doctor"){let r={...jt(n),...process.env};return Bi(await Ci(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return Ju({envFile:n}),null;if(t==="install-service")return await td({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(Is(),Ms));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:s}=await Promise.resolve().then(()=>(Ii(),Mi)),{detectInstallKind:a}=await Promise.resolve().then(()=>(_r(),$i)),u=a(),p=e.indexOf("--to"),m=p>=0?String(e[p+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:tt,installKind:u,policy:s({kind:u}),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 h=await r({to:m,kind:u,reason:"cli",force:!0});return h.ok?(console.log(`\u2713 self-update ${h.from??"?"} \u2192 ${h.to} started (${h.kind}) \u2014 status: ${h.statusFile}; the node restarts when the install completes`),0):(console.error(`\u2717 not started: ${h.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
|
|
278
290
|
|
|
279
291
|
usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
|
|
280
292
|
|
|
@@ -283,4 +295,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
|
|
|
283
295
|
run start the node in the foreground (sources node.env)
|
|
284
296
|
install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
|
|
285
297
|
fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
|
|
286
|
-
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{
|
|
298
|
+
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{Vu as RESTART_SIGNAL,qu as ROLLBACK_GRACE_MS,Yu as STALL_CHECK_MS,dn as SUPERVISOR_PID_FILE,Xu as createRunSupervisor,zu as init,td as installService,Qu as launchdPlist,gw as main,Bi as printDoctor,Ju as runAgent,Ci as runDoctor,ed as servicePaths,Zu as systemdUnit};
|