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