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