bostrat-node 1.9.0 → 1.9.2

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.
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import d from"node:fs/promises";var u=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function c(n,e,t){let l=await fetch(`${u}${e}`,{method:n,headers:t?{"content-type":"application/json"}:void 0,body:t?JSON.stringify(t):void 0}),r=await l.json().catch(()=>({}));if(!l.ok)throw new Error(r.error||`HTTP ${l.status}`);return r}function a(n){console.error(`[bostrat-changelog] ${n}`),process.exit(1)}var s=process.argv.slice(2),i=s.shift();if(i==="draft"){let n=null;for(let e=0;e<s.length;e++)s[e]==="--since"&&(n=s[++e]);try{let e=n?`?since=${encodeURIComponent(n)}`:"",{since:t,prs:l,excluded:r=[]}=await c("GET",`/api/changelog/draft${e}`),g=o=>{let h=o.mergedAt?` (merged ${new Date(o.mergedAt).toISOString()})`:"";return`- ${o.repo}#${o.number} \u2014 ${o.title||"(no title recorded)"}${h}${o.url?` ${o.url}`:""}`};if(!l.length){let o=r.length?` (${r.length} merge(s) excluded by the safe-content policy)`:"";console.log(`EMPTY WINDOW \u2014 nothing publishable merged since ${new Date(t).toISOString()}${o}; publish nothing.`),process.exit(0)}console.log(`Merged since ${new Date(t).toISOString()}:`);for(let o of l)console.log(g(o));if(r.length){console.log(`
3
- EXCLUDED (${r.length}, safe-content policy \u2014 do NOT summarize or look these up):`);for(let o of r)console.log(`- ${o.repo}#${o.number} [${o.excluded}]`)}}catch(e){a(e.message)}}else if(i==="publish"){let n=null,e=null;for(let t=0;t<s.length;t++)s[t]==="--day"?n=s[++t]:s[t].startsWith("--")||(e=s[t]);e||a("usage: bostrat-changelog publish <file.md> [--day YYYY-MM-DD]");try{let t=await d.readFile(e,"utf8").catch(()=>a(`cannot read ${e}`)),{entry:l}=await c("POST","/api/changelog/publish",{md:t,cwd:process.cwd(),...n?{day:n}:{}});console.log(`[bostrat-changelog] published ${l.day}: ${l.bullets.length} bullet(s)${l.title?` under "${l.title}"`:""}`),console.log("The operator sees it in Settings \u2192 Changelog \u2014 re-publishing the same day replaces this entry.")}catch(t){a(t.message)}}else if(i==="retract"){let n=null;for(let e=0;e<s.length;e++)s[e]==="--day"&&(n=s[++e]);n||a("usage: bostrat-changelog retract --day YYYY-MM-DD");try{let{entry:e}=await c("POST","/api/changelog/retract",{day:n,cwd:process.cwd()});console.log(`[bostrat-changelog] retracted ${e.day} \u2014 the day's published entry is removed (re-publish to restore).`)}catch(e){a(e.message)}}else a("usage: bostrat-changelog <draft|publish|retract> \u2026 (draft [--since 24h]; publish <file.md> [--day YYYY-MM-DD]; retract --day YYYY-MM-DD)");
2
+ import h from"node:fs/promises";var u=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;function f(){if(process.env.BOSTRAT_NODE_API_TOKEN)return process.env.BOSTRAT_NODE_API_TOKEN.trim();try{let t=process.getBuiltinModule("node:fs"),e=`${process.env.BOSTRAT_STATE_DIR||`${process.env.HOME}/.bostrat`}/api-token`;return t.readFileSync(e,"utf8").trim()}catch{return""}}async function i(t,e,n){let r=f(),c=await fetch(`${u}${e}`,{method:t,headers:{...n?{"content-type":"application/json"}:{},...r?{"x-bostrat-token":r}:{}},body:n?JSON.stringify(n):void 0}),a=await c.json().catch(()=>({}));if(!c.ok)throw new Error(a.error||`HTTP ${c.status}`);return a}function l(t){console.error(`[bostrat-changelog] ${t}`),process.exit(1)}var s=process.argv.slice(2),g=s.shift();if(g==="draft"){let t=null;for(let e=0;e<s.length;e++)s[e]==="--since"&&(t=s[++e]);try{let e=t?`?since=${encodeURIComponent(t)}`:"",{since:n,prs:r,excluded:c=[]}=await i("GET",`/api/changelog/draft${e}`),a=o=>{let d=o.mergedAt?` (merged ${new Date(o.mergedAt).toISOString()})`:"";return`- ${o.repo}#${o.number} \u2014 ${o.title||"(no title recorded)"}${d}${o.url?` ${o.url}`:""}`};if(!r.length){let o=c.length?` (${c.length} merge(s) excluded by the safe-content policy)`:"";console.log(`EMPTY WINDOW \u2014 nothing publishable merged since ${new Date(n).toISOString()}${o}; publish nothing.`),process.exit(0)}console.log(`Merged since ${new Date(n).toISOString()}:`);for(let o of r)console.log(a(o));if(c.length){console.log(`
3
+ EXCLUDED (${c.length}, safe-content policy \u2014 do NOT summarize or look these up):`);for(let o of c)console.log(`- ${o.repo}#${o.number} [${o.excluded}]`)}}catch(e){l(e.message)}}else if(g==="publish"){let t=null,e=null;for(let n=0;n<s.length;n++)s[n]==="--day"?t=s[++n]:s[n].startsWith("--")||(e=s[n]);e||l("usage: bostrat-changelog publish <file.md> [--day YYYY-MM-DD]");try{let n=await h.readFile(e,"utf8").catch(()=>l(`cannot read ${e}`)),{entry:r}=await i("POST","/api/changelog/publish",{md:n,cwd:process.cwd(),...t?{day:t}:{}});console.log(`[bostrat-changelog] published ${r.day}: ${r.bullets.length} bullet(s)${r.title?` under "${r.title}"`:""}`),console.log("The operator sees it in Settings \u2192 Changelog \u2014 re-publishing the same day replaces this entry.")}catch(n){l(n.message)}}else if(g==="retract"){let t=null;for(let e=0;e<s.length;e++)s[e]==="--day"&&(t=s[++e]);t||l("usage: bostrat-changelog retract --day YYYY-MM-DD");try{let{entry:e}=await i("POST","/api/changelog/retract",{day:t,cwd:process.cwd()});console.log(`[bostrat-changelog] retracted ${e.day} \u2014 the day's published entry is removed (re-publish to restore).`)}catch(e){l(e.message)}}else l("usage: bostrat-changelog <draft|publish|retract> \u2026 (draft [--since 24h]; publish <file.md> [--day YYYY-MM-DD]; retract --day YYYY-MM-DD)");
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- var l=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function n(i,t,s){let e=await fetch(`${l}${t}`,{method:i,headers:s?{"content-type":"application/json"}:void 0,body:s?JSON.stringify(s):void 0}),r=await e.json().catch(()=>({}));if(!e.ok)throw new Error(r.error||`HTTP ${e.status}`);return r}function c(i){console.error(`[bostrat-circuit] ${i}`),process.exit(1)}var a=process.argv.slice(2),o=a.shift();if(o==="link"){let i=a.join(" ").trim();i||c("usage: bostrat-circuit link <circuit-name-or-id>");try{let{circuit:t}=await n("POST","/api/circuits/link",{cwd:process.cwd(),ref:i});console.log(`[bostrat-circuit] linked to \u201C${t.name}\u201D (${t.id})`),console.log("This Track now rolls up on that circuit's ledger (a Track is in at most one circuit \u2014 link moves it).")}catch(t){c(t.message)}}else if(o==="unlink")try{await n("POST","/api/circuits/unlink",{cwd:process.cwd()}),console.log("[bostrat-circuit] unlinked \u2014 this Track is back in the Unassigned bucket")}catch(i){c(i.message)}else if(o==="ls")try{let{circuits:i}=await n("GET","/api/circuits");i.length||console.log("[bostrat-circuit] no circuits yet \u2014 create one on the Circuits page");for(let t of i)console.log(` ${t.id} ${t.status.padEnd(9)} ${t.name}`)}catch(i){c(i.message)}else c("usage: bostrat-circuit <link|unlink|ls> \u2026 (link <circuit-name-or-id>)");
2
+ var d=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function r(t,o,i){let s=await fetch(`${d}${o}`,{method:t,headers:i?{"content-type":"application/json"}:void 0,body:i?JSON.stringify(i):void 0}),n=await s.json().catch(()=>({}));if(!s.ok)throw new Error(n.error||`HTTP ${s.status}`);return n}function c(t){console.error(`[bostrat-circuit] ${t}`),process.exit(1)}var p=process.argv.slice(2),a=p.shift();if(a==="link"){let t=p.join(" ").trim();t||c("usage: bostrat-circuit link <circuit-name-or-id>");try{let{circuit:o}=await r("POST","/api/circuits/link",{cwd:process.cwd(),ref:t});console.log(`[bostrat-circuit] linked to \u201C${o.name}\u201D (${o.id})`),console.log("This Track now rolls up on that circuit's ledger (a Track is in at most one circuit \u2014 link moves it).")}catch(o){c(o.message)}}else if(a==="unlink")try{await r("POST","/api/circuits/unlink",{cwd:process.cwd()}),console.log("[bostrat-circuit] unlinked \u2014 this Track is back in the Unassigned bucket")}catch(t){c(t.message)}else if(a==="ls")try{let{circuits:t}=await r("GET","/api/circuits");t.length||console.log("[bostrat-circuit] no circuits yet \u2014 create one on the Circuits page");for(let o of t)console.log(` ${o.id} ${o.status.padEnd(9)} ${o.name}`)}catch(t){c(t.message)}else if(a==="propose")try{let t=p[0],o;if(!t||t==="-"){let e=[];for await(let l of process.stdin)e.push(l);o=Buffer.concat(e).toString("utf8")}else o=await(await import("node:fs/promises")).readFile(t,"utf8");let i;try{i=JSON.parse(o)}catch{c("plan must be JSON (a file path, or piped on stdin) \u2014 see the `bostrat-circuit` header for the shape")}let{proposal:s}=await r("POST","/api/planning/propose",{cwd:process.cwd(),plan:i,scope:"circuit"}),n={};for(let e of s.ops)n[e.op]=(n[e.op]||0)+1;let u=Object.entries(n).map(([e,l])=>`${l}\xD7 ${e}`).join(" \xB7 ");console.log(`[bostrat-circuit] proposed ${s.ops.length} op${s.ops.length===1?"":"s"} (${u}) \u2014 review card posted to the Track chat.`),console.log(" Nothing changes until you tap Apply."),console.log(" HOLD HERE: end your turn and wait \u2014 do not start or resume other work until the operator answers the card in chat.")}catch(t){c(t.message)}else c("usage: bostrat-circuit <link|unlink|ls|propose> \u2026 (link <circuit-name-or-id> \xB7 propose <plan.json>)");
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ var d=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function c(e,t,s){let o=await fetch(`${d}${t}`,{method:e,headers:s?{"content-type":"application/json"}:void 0,body:s?JSON.stringify(s):void 0}),n=await o.json().catch(()=>({}));if(!o.ok)throw new Error(n.error||`HTTP ${o.status}`);return n}function a(e){console.error(`[bostrat-roadmap] ${e}`),process.exit(1)}async function f(e){if(!e||e==="-"){let t=[];for await(let s of process.stdin)t.push(s);return Buffer.concat(t).toString("utf8")}return(await import("node:fs/promises")).readFile(e,"utf8")}var p=process.argv.slice(2),l=p.shift();if(l==="ls")try{let e=await c("GET","/api/roadmap"),t=o=>e.people.find(n=>n.personId===o)?.label??o,s=o=>e.circuits.find(n=>n.id===o)?.name??o;e.people.length||console.log(' (no roadmap rows yet \u2014 a slot proposal for "me" creates yours)');for(let o of e.people)console.log(` ${o.personId} ${o.kind==="user"?"user ":"placeholder"} ${o.label}`);console.log(e.slots.length?`
3
+ bookings:`:`
4
+ bookings: none`);for(let o of e.slots)console.log(` ${o.slotId} ${o.startDate} \u2192 ${o.endDate} ${t(o.personId)} \xB7 ${s(o.circuitId)}${o.estUsd!=null?` \xB7 est $${o.estUsd}`:""}`);if(e.reservations.length){console.log(`
5
+ reserved:`);for(let o of e.reservations)console.log(` ${o.reservationId} ${o.startDate} \u2192 ${o.endDate} ${t(o.personId)} \xB7 ${o.label}`)}if(e.tray.length){console.log(`
6
+ unslotted circuits:`);for(let o of e.tray)console.log(` ${o.id} ${String(o.type).padEnd(6)} ${o.name}`)}}catch(e){a(e.message)}else if(l==="propose")try{let e=await f(p[0]),t;try{t=JSON.parse(e)}catch{a("plan must be JSON (a file path, or piped on stdin) \u2014 see the `bostrat-roadmap` header for the shape")}let{proposal:s}=await c("POST","/api/planning/propose",{cwd:process.cwd(),plan:t}),o={};for(let r of s.ops)o[r.op]=(o[r.op]||0)+1;let n=Object.entries(o).map(([r,i])=>`${i}\xD7 ${r}`).join(" \xB7 ");console.log(`[bostrat-roadmap] proposed ${s.ops.length} op${s.ops.length===1?"":"s"} (${n}) \u2014 review card posted to the Track chat.`),s.snapped&&console.log(" (dates snapped to whole ISO weeks \u2014 the card shows the spans that will apply)"),s.createsMeRow&&console.log(" (you have no roadmap row yet \u2014 applying the card creates one for you)"),console.log(" Nothing changes until you tap Apply."),console.log(" HOLD HERE: end your turn and wait \u2014 do not start or resume other work until the operator answers the card in chat.")}catch(e){a(e.message)}else a("usage: bostrat-roadmap <ls|propose> \u2026 (propose <plan.json>, or - for stdin)");
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ var u=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`,c=process.argv.slice(2),n=c.shift(),r=s=>{console.error(`[bostrat-status] ${s}`),process.exit(1)},o=s=>{let t=c.indexOf(s);return t>=0?c[t+1]:null};async function i(s,t,e){let a=await fetch(`${u}${t}`,{method:s,headers:e?{"content-type":"application/json"}:void 0,body:e?JSON.stringify(e):void 0}),l=await a.json().catch(()=>({}));return a.ok||r(l.error||`HTTP ${a.status}`),l}try{if(n)if(n==="clear")await i("POST","/api/status",{cwd:process.cwd(),phase:null,reason:o("--reason")||"completed"}),console.log("[bostrat-status] phase cleared");else if(n==="set"){let s=c[0],t;if(s?.endsWith(".json")){let a=await import("node:fs/promises");t=JSON.parse(await a.readFile(s,"utf8"))}else(!s||s.startsWith("--"))&&r("usage: bostrat-status set <reconcile|fixing-ci|rebase|merge> [--summary text] [--pr N]"),t={phase:s,summary:o("--summary"),scope:o("--pr")?{pr:Number(o("--pr"))}:null};let e=await i("POST","/api/status",{cwd:process.cwd(),...t});console.log(`[bostrat-status] ${e.phase} declared`)}else r("usage: bostrat-status [set|clear]");else{let t=(await i("GET",`/api/status?cwd=${encodeURIComponent(process.cwd())}`)).status||{};console.log(`${t.kind||"idle"}${t.summary?` \u2014 ${t.summary}`:""} [${t.source||"fallback"}]`)}}catch(s){r(s?.message||String(s))}
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
- var Tr=Object.defineProperty;var v=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ut=(e,t)=>{for(var n in t)Tr(e,n,{get:t[n],enumerable:!0})};import He from"node:fs";import dt from"node:path";import _r from"node:os";function Pe(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,o;try{o=new URL(n)}catch{return t}let s={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[o.protocol];return s?(o.protocol=s,(o.pathname===""||o.pathname==="/")&&(o.pathname="/v1/node"),o.toString()):t}function Ke(e){let t;try{t=He.readFileSync(e,"utf8")}catch{return{}}let n={};for(let o of t.split(`
2
- `)){let s=o.trim();if(!s||s.startsWith("#"))continue;let c=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(s);if(!c)continue;let u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),n[c[1]]=u}return n}function Yt(e,t=process.env){let n=Ke(e);for(let[o,s]of Object.entries(n))o in t||(t[o]=s);return n}function qt(e,t,{header:n=""}={}){let o=[];n&&o.push(...n.split(`
1
+ var _r=Object.defineProperty;var k=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ut=(e,t)=>{for(var n in t)_r(e,n,{get:t[n],enumerable:!0})};import He from"node:fs";import dt from"node:path";import br from"node:os";function Pe(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,o;try{o=new URL(n)}catch{return t}let s={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[o.protocol];return s?(o.protocol=s,(o.pathname===""||o.pathname==="/")&&(o.pathname="/v1/node"),o.toString()):t}function Ke(e){let t;try{t=He.readFileSync(e,"utf8")}catch{return{}}let n={};for(let o of t.split(`
2
+ `)){let s=o.trim();if(!s||s.startsWith("#"))continue;let c=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(s);if(!c)continue;let u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),n[c[1]]=u}return n}function qt(e,t=process.env){let n=Ke(e);for(let[o,s]of Object.entries(n))o in t||(t[o]=s);return n}function Gt(e,t,{header:n=""}={}){let o=[];n&&o.push(...n.split(`
3
3
  `).map(s=>s?`# ${s}`:"#"));for(let[s,c]of Object.entries(t))c==null||c===""||o.push(`${s}=${c}`);He.mkdirSync(dt.dirname(e),{recursive:!0}),He.writeFileSync(e,o.join(`
4
4
  `)+`
5
- `,{mode:384}),He.chmodSync(e,384)}function Gt(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 ft,Se,pt=v(()=>{ft=process.env.BOSTRAT_STATE_DIR||dt.join(process.env.HOME||_r.tmpdir(),".bostrat"),Se=()=>dt.join(ft,"node.env")});var pe,We,ze=v(()=>{pe="BOSTRAT_HOOK_TOKEN",We="x-bostrat-hook"});var Vt=v(()=>{ze()});var Jt=v(()=>{});var Xt=v(()=>{});import ht from"node:path";import{execFile as br}from"node:child_process";import{promisify as Sr}from"node:util";var js,Zt,vr,Fs,Ls,Qt=v(()=>{js=Sr(br),Zt=process.env.HOME||"/home/globo",vr=ht.join(process.env.BOSTRAT_STATE_DIR||ht.join(Zt,".bostrat"),"repos"),Fs=[...(process.env.BOSTRAT_REPOS_ROOT||ht.join(Zt,"Documents")).split(","),vr].map(e=>e.trim()).filter(Boolean),Ls=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});import en from"node:path";import kr from"node:os";import{execFile as Ar}from"node:child_process";import{promisify as $r}from"node:util";var qs,xr,Gs,Vs,Js,mt=v(()=>{Qt();qs=$r(Ar),xr=process.env.BOSTRAT_STATE_DIR||en.join(process.env.HOME||kr.tmpdir(),".bostrat"),Gs=en.join(xr,"repos"),Vs=5*6e4,Js=10*6e4});var tn=v(()=>{mt()});import Or from"node:fs/promises";import De from"node:path";import Rr from"node:os";import{EventEmitter as Nr}from"node:events";function Ir(e){return e?.cwd?De.join(e.cwd,".bostrat","events"):De.join(nn,"events")}async function wt(e,t){let n,o;typeof e=="string"&&t?(n=e,o=t):(o=typeof e=="string"?e:e?.id,n=typeof e=="string"?De.join(nn,"events"):Ir(e));let s;try{s=await Or.readFile(Mr(n,o),"utf8")}catch{return[]}let c=[];for(let u of s.split(`
6
- `))if(u.trim())try{c.push(JSON.parse(Dr(u)?Cr(u):u))}catch{}return c}var Ce,nn,Mr,Pr,Dr,Cr,Ye=v(()=>{Ce=new Nr;Ce.setMaxListeners(0);nn=process.env.BOSTRAT_STATE_DIR||De.join(process.env.HOME||Rr.tmpdir(),".bostrat");Mr=(e,t)=>De.join(e,`${t}.ndjson`),Pr=/(?<!\\)((?:\\\\)*)\\u0000/g,Dr=e=>e.includes("\\u0000"),Cr=e=>e.replace(Pr,"$1\\ufffd")});import Fr from"node:os";import Lr from"node:path";import{execFile as Br}from"node:child_process";import{promisify as Ur}from"node:util";var pi,hi,mi,wi,yi,gi,rn=v(()=>{tn();Ye();pi=Ur(Br),hi=process.env.BOSTRAT_STATE_DIR||Lr.join(process.env.HOME||Fr.tmpdir(),".bostrat"),mi=25*1024,wi=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,yi=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,gi=Promise.resolve()});var on=v(()=>{});var ki,sn=v(()=>{mt();on();ki=60*6e4});var an=v(()=>{sn()});import Hr from"node:os";import cn from"node:path";var Kr,Ci,ji,yt=v(()=>{gt();Kr=process.env.BOSTRAT_DEBUG_DIR||cn.join(Hr.homedir(),".bostrat","debug"),Ci=cn.join(Kr,"handoff.jsonl"),ji=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import ln from"node:path";import Wr from"node:os";var qe,zr,Ki,un,Wi,zi,dn=v(()=>{ze();qe="BOSTRAT_NODE_URL",zr=process.env.BOSTRAT_STATE_DIR||ln.join(process.env.HOME||Wr.tmpdir(),".bostrat"),Ki=ln.join(zr,"git-hooks"),un=`#!/bin/sh
5
+ `,{mode:384}),He.chmodSync(e,384)}function Vt(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 ft,Se,pt=k(()=>{ft=process.env.BOSTRAT_STATE_DIR||dt.join(process.env.HOME||br.tmpdir(),".bostrat"),Se=()=>dt.join(ft,"node.env")});var fe,We,ze=k(()=>{fe="BOSTRAT_HOOK_TOKEN",We="x-bostrat-hook"});var Jt=k(()=>{ze()});var Xt=k(()=>{});var Zt=k(()=>{});import ht from"node:path";import{execFile as Sr}from"node:child_process";import{promisify as vr}from"node:util";var Fs,Qt,kr,Ls,Bs,en=k(()=>{Fs=vr(Sr),Qt=process.env.HOME||"/home/globo",kr=ht.join(process.env.BOSTRAT_STATE_DIR||ht.join(Qt,".bostrat"),"repos"),Ls=[...(process.env.BOSTRAT_REPOS_ROOT||ht.join(Qt,"Documents")).split(","),kr].map(e=>e.trim()).filter(Boolean),Bs=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});import tn from"node:path";import Ar from"node:os";import{execFile as $r}from"node:child_process";import{promisify as xr}from"node:util";var Gs,Er,Vs,Js,Xs,mt=k(()=>{en();Gs=xr($r),Er=process.env.BOSTRAT_STATE_DIR||tn.join(process.env.HOME||Ar.tmpdir(),".bostrat"),Vs=tn.join(Er,"repos"),Js=5*6e4,Xs=10*6e4});var nn=k(()=>{mt()});import Rr from"node:fs/promises";import De from"node:path";import Nr from"node:os";import{EventEmitter as Ir}from"node:events";function Mr(e){return e?.cwd?De.join(e.cwd,".bostrat","events"):De.join(rn,"events")}async function wt(e,t){let n,o;typeof e=="string"&&t?(n=e,o=t):(o=typeof e=="string"?e:e?.id,n=typeof e=="string"?De.join(rn,"events"):Mr(e));let s;try{s=await Rr.readFile(Pr(n,o),"utf8")}catch{return[]}let c=[];for(let u of s.split(`
6
+ `))if(u.trim())try{c.push(JSON.parse(Cr(u)?jr(u):u))}catch{}return c}var Ce,rn,Pr,Dr,Cr,jr,Ye=k(()=>{Ce=new Ir;Ce.setMaxListeners(0);rn=process.env.BOSTRAT_STATE_DIR||De.join(process.env.HOME||Nr.tmpdir(),".bostrat");Pr=(e,t)=>De.join(e,`${t}.ndjson`),Dr=/(?<!\\)((?:\\\\)*)\\u0000/g,Cr=e=>e.includes("\\u0000"),jr=e=>e.replace(Dr,"$1\\ufffd")});import Lr from"node:os";import Br from"node:path";import{execFile as Ur}from"node:child_process";import{promisify as Hr}from"node:util";var hi,mi,wi,yi,gi,Ti,on=k(()=>{nn();Ye();hi=Hr(Ur),mi=process.env.BOSTRAT_STATE_DIR||Br.join(process.env.HOME||Lr.tmpdir(),".bostrat"),wi=25*1024,yi=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,gi=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,Ti=Promise.resolve()});var sn=k(()=>{});var Ai,an=k(()=>{mt();sn();Ai=60*6e4});var cn=k(()=>{an()});import Kr from"node:os";import ln from"node:path";var Wr,ji,Fi,yt=k(()=>{gt();Wr=process.env.BOSTRAT_DEBUG_DIR||ln.join(Kr.homedir(),".bostrat","debug"),ji=ln.join(Wr,"handoff.jsonl"),Fi=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import un from"node:path";import zr from"node:os";var qe,Yr,Wi,dn,zi,Yi,fn=k(()=>{ze();qe="BOSTRAT_NODE_URL",Yr=process.env.BOSTRAT_STATE_DIR||un.join(process.env.HOME||zr.tmpdir(),".bostrat"),Wi=un.join(Yr,"git-hooks"),dn=`#!/bin/sh
7
7
  # bostrat git hook shim (agent/src/git-hooks.js) \u2014 chains to the repo's own hook,
8
8
  # then stamps/reports for rework attribution when running inside a bostrat box.
9
9
  hook=$(basename "$0")
@@ -18,28 +18,28 @@ esac
18
18
  if [ -x "$orig/$hook" ] && [ "$orig/$hook" != "$0" ]; then
19
19
  "$orig/$hook" "$@" || exit $?
20
20
  fi
21
- `,Wi=`${un}
21
+ `,zi=`${dn}
22
22
  # \u2500\u2500 bostrat: append provenance trailers (Layer 0). Skipped for merge commits
23
23
  # (nobody "wrote" a merge) and outside a box (no token / no node url).
24
- [ -z "$${pe}" ] && exit 0
24
+ [ -z "$${fe}" ] && exit 0
25
25
  [ -z "$${qe}" ] && exit 0
26
26
  [ "$2" = "merge" ] && exit 0
27
- trailers=$(curl -sS -m 3 -H "${We}: $${pe}" "$${qe}/api/git/trailers" 2>/dev/null) || exit 0
27
+ trailers=$(curl -sS -m 3 -H "${We}: $${fe}" "$${qe}/api/git/trailers" 2>/dev/null) || exit 0
28
28
  [ -z "$trailers" ] && exit 0
29
29
  printf '%s\\n' "$trailers" | while IFS= read -r line; do
30
30
  [ -n "$line" ] && git interpret-trailers --in-place --if-exists addIfDifferent --trailer "$line" "$1" >/dev/null 2>&1 || true
31
31
  done
32
32
  exit 0
33
- `,zi=`${un}
33
+ `,Yi=`${dn}
34
34
  # \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
35
- [ -z "$${pe}" ] && exit 0
35
+ [ -z "$${fe}" ] && exit 0
36
36
  [ -z "$${qe}" ] && exit 0
37
37
  sha=$(git rev-parse HEAD 2>/dev/null) || exit 0
38
38
  cwd=$(git rev-parse --show-toplevel 2>/dev/null)
39
39
  printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${qe}/api/git/committed" \\
40
- -H 'content-type: application/json' -H "${We}: $${pe}" --data-binary @- >/dev/null 2>&1 || true
40
+ -H 'content-type: application/json' -H "${We}: $${fe}" --data-binary @- >/dev/null 2>&1 || true
41
41
  exit 0
42
- `});import{execFile as qr}from"node:child_process";import{promisify as Gr}from"node:util";import Vr from"node:fs";function hn(e){return`/tmp/tmux-${e}/default`}function Xr({explicit:e,legacyExists:t,runtimeDir:n,uid:o}){if(e)return e;let s=hn(o);return t?s:n?`${n}/bostrat/tmux-default`:s}async function _t(e,{loginShell:t=!1,failOpen:n=!1}={}){let o=await Qr(e,{loginShell:t});return o===mn?!0:o===Tt?!1:n}async function Qr(e,{loginShell:t=!1,timeoutMs:n=Zr}={}){if(!e)return Tt;let o=t?process.env.SHELL||"/bin/sh":"sh",s=t?"-lic":"-c";try{return await Jr(o,[s,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),mn}catch(c){return c?.killed||c?.signal?pn:c?.code===1||c?.code===127?Tt:pn}}var Jr,pa,fn,ha,ma,wa,mn,Tt,pn,Zr,Ge,ya,ga,Ta,_a,ba,gt=v(()=>{Vt();Jt();Xt();rn();an();yt();ze();dn();Jr=Gr(qr),pa=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";fn=typeof process.getuid=="function"?process.getuid():0,ha=Xr({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Vr.existsSync(hn(fn))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:fn}),ma=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",wa=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions";mn="present",Tt="absent",pn="unknown",Zr=5e3;Ge={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"},ya=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,ga=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Ta=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,_a=Number(process.env.BOSTRAT_BOX_COLS)||120,ba=Number(process.env.BOSTRAT_BOX_ROWS)||40});var bn={};ut(bn,{NODE_IMAGE:()=>St,commandPlan:()=>gn,flyToml:()=>yn,flyWizard:()=>ao,parseFlyFlags:()=>Tn,stageConfig:()=>_n});import bt from"node:fs";import he from"node:path";import eo from"node:os";import to from"node:readline/promises";import{execFile as no}from"node:child_process";import{createRequire as ro}from"node:module";import{randomUUID as oo}from"node:crypto";function yn({app:e,region:t,nodeName:n=e,planeUrl:o=wn,image:s=St}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
42
+ `});import{execFile as Gr}from"node:child_process";import{promisify as Vr}from"node:util";import Jr from"node:fs";function mn(e){return`/tmp/tmux-${e}/default`}function Zr({explicit:e,legacyExists:t,runtimeDir:n,uid:o}){if(e)return e;let s=mn(o);return t?s:n?`${n}/bostrat/tmux-default`:s}async function _t(e,{loginShell:t=!1,failOpen:n=!1}={}){let o=await eo(e,{loginShell:t});return o===wn?!0:o===Tt?!1:n}async function eo(e,{loginShell:t=!1,timeoutMs:n=Qr}={}){if(!e)return Tt;let o=t?process.env.SHELL||"/bin/sh":"sh",s=t?"-lic":"-c";try{return await Xr(o,[s,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),wn}catch(c){return c?.killed||c?.signal?hn:c?.code===1||c?.code===127?Tt:hn}}var Xr,ha,pn,ma,wa,ya,wn,Tt,hn,Qr,Ge,ga,Ta,_a,ba,Sa,gt=k(()=>{Jt();Xt();Zt();on();cn();yt();ze();fn();Xr=Vr(Gr),ha=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";pn=typeof process.getuid=="function"?process.getuid():0,ma=Zr({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Jr.existsSync(mn(pn))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:pn}),wa=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",ya=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions";wn="present",Tt="absent",hn="unknown",Qr=5e3;Ge={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"},ga=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Ta=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,_a=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,ba=Number(process.env.BOSTRAT_BOX_COLS)||120,Sa=Number(process.env.BOSTRAT_BOX_ROWS)||40});var Sn={};ut(Sn,{NODE_IMAGE:()=>St,commandPlan:()=>Tn,flyToml:()=>gn,flyWizard:()=>co,parseFlyFlags:()=>_n,stageConfig:()=>bn});import bt from"node:fs";import pe from"node:path";import to from"node:os";import no from"node:readline/promises";import{execFile as ro}from"node:child_process";import{createRequire as oo}from"node:module";import{randomUUID as so}from"node:crypto";function gn({app:e,region:t,nodeName:n=e,planeUrl:o=yn,image:s=St}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
43
43
  # Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
44
44
  # No [http_service] and none should be added: the node dials OUT to the plane;
45
45
  # nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
@@ -79,48 +79,48 @@ swap_size_mb = 1024
79
79
  # Scale later with: fly scale memory 4096 -a ${e}
80
80
  size = "shared-cpu-2x"
81
81
  memory = "2gb"
82
- `}function gn({app:e,org:t,region:n,sizeGb:o,token:s,owner:c,dir:u}){let p=[`BOSTRAT_PLANE_TOKEN=${s}`,...c?[`BOSTRAT_OWNER=${c}`]:[]];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(o),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${o} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted>${c?" BOSTRAT_OWNER=\u2026":""} via stdin`,stdin:p.join(`
82
+ `}function Tn({app:e,org:t,region:n,sizeGb:o,token:s,owner:c,dir:u}){let p=[`BOSTRAT_PLANE_TOKEN=${s}`,...c?[`BOSTRAT_OWNER=${c}`]:[]];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(o),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${o} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted>${c?" BOSTRAT_OWNER=\u2026":""} via stdin`,stdin:p.join(`
83
83
  `)+`
84
- `},{argv:["deploy",u,"-c",he.join(u,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${u} -c ${he.join(u,"fly.toml")} -a ${e} --ha=false`}]}function Tn(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--owner":"owner","--image":"image"};for(let o=0;o<e.length;o++){let s=e[o];if(s==="--yes"||s==="-y")t.yes=!0;else if(n[s])t[n[s]]=e[++o]??"";else if(s.startsWith("--")&&s.includes("=")){let[c,...u]=s.split("=");n[c]?t[n[c]]=u.join("="):c==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function _n({app:e,dest:t,toml:n}){let o=t||he.join(eo.homedir(),".bostrat","fly",e);bt.mkdirSync(o,{recursive:!0});for(let s of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])bt.rmSync(he.join(o,s),{recursive:!0,force:!0});return bt.writeFileSync(he.join(o,"fly.toml"),n),{dir:o,manifest:["fly.toml"]}}async function io({ask:e,output:t,exec:n,flag:o}){if(o)return o;try{let{stdout:s}=await Ve(["orgs","list","--json"],{exec:n}),c=JSON.parse(s),u=Array.isArray(c)?c.map(p=>p.Slug||p.slug).filter(Boolean):Object.keys(c);if(u.length===1)return t.write(`Org: ${u[0]} (your only org)
85
- `),u[0];if(u.length>1)return await e(`Fly org (${u.join(" / ")})`,u[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function ao({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:o,stageDest:s}={}){let c=Tn(e),u=to.createInterface({input:t,output:n}),p=async(T,z)=>(await u.question(z?`${T} [${z}]: `:`${T}: `)).trim()||z||"",_=T=>(u.close(),T);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
84
+ `},{argv:["deploy",u,"-c",pe.join(u,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${u} -c ${pe.join(u,"fly.toml")} -a ${e} --ha=false`}]}function _n(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--owner":"owner","--image":"image"};for(let o=0;o<e.length;o++){let s=e[o];if(s==="--yes"||s==="-y")t.yes=!0;else if(n[s])t[n[s]]=e[++o]??"";else if(s.startsWith("--")&&s.includes("=")){let[c,...u]=s.split("=");n[c]?t[n[c]]=u.join("="):c==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function bn({app:e,dest:t,toml:n}){let o=t||pe.join(to.homedir(),".bostrat","fly",e);bt.mkdirSync(o,{recursive:!0});for(let s of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])bt.rmSync(pe.join(o,s),{recursive:!0,force:!0});return bt.writeFileSync(pe.join(o,"fly.toml"),n),{dir:o,manifest:["fly.toml"]}}async function ao({ask:e,output:t,exec:n,flag:o}){if(o)return o;try{let{stdout:s}=await Ve(["orgs","list","--json"],{exec:n}),c=JSON.parse(s),u=Array.isArray(c)?c.map(p=>p.Slug||p.slug).filter(Boolean):Object.keys(c);if(u.length===1)return t.write(`Org: ${u[0]} (your only org)
85
+ `),u[0];if(u.length>1)return await e(`Fly org (${u.join(" / ")})`,u[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function co({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:o,stageDest:s}={}){let c=_n(e),u=no.createInterface({input:t,output:n}),p=async(b,D)=>(await u.question(D?`${b} [${D}]: `:`${b}: `)).trim()||D||"",T=b=>(u.close(),b);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
86
86
  bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
87
87
 
88
- `);try{await Ve(["version"],{exec:o})}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"),_(1)}try{let{stdout:T}=await Ve(["auth","whoami"],{exec:o});n.write(`\u2713 signed in to Fly as ${T.trim()}
89
- `)}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"),_(1)}let m=await io({ask:p,output:n,exec:o,flag:c.org}),f=c.app||await p("App name",`bostrat-node-${oo().slice(0,4)}`),b=c.region||await p("Region (see `fly platform regions`)","iad"),x=c.sizeGb||Number(await p("Volume size GB (logins + repos live here)","10"))||10,g=c.name||f,k=c.planeUrl||wn,A=c.token||await p("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!A)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.
90
- `),_(1);let K=c.owner??await p("Owner userId (shown next to the token; empty = infer from token)",""),W=c.image||St,{dir:D}=_n({app:f,dest:s,toml:yn({app:f,region:b,nodeName:g,planeUrl:k,image:W})});n.write(`
91
- wrote ${he.join(D,"fly.toml")} \u2014 deploys the prebuilt node image ${W}
88
+ `);try{await Ve(["version"],{exec:o})}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"),T(1)}try{let{stdout:b}=await Ve(["auth","whoami"],{exec:o});n.write(`\u2713 signed in to Fly as ${b.trim()}
89
+ `)}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"),T(1)}let w=await ao({ask:p,output:n,exec:o,flag:c.org}),f=c.app||await p("App name",`bostrat-node-${so().slice(0,4)}`),_=c.region||await p("Region (see `fly platform regions`)","iad"),x=c.sizeGb||Number(await p("Volume size GB (logins + repos live here)","10"))||10,g=c.name||f,A=c.planeUrl||yn,v=c.token||await p("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!v)return n.write(`\u2717 a node token is required \u2014 mint one in the bostrat setup chat (Connect a node \u2192 Fly), then re-run with it.
90
+ `),T(1);let K=c.owner??await p("Owner userId (shown next to the token; empty = infer from token)",""),W=c.image||St,{dir:z}=bn({app:f,dest:s,toml:gn({app:f,region:_,nodeName:g,planeUrl:A,image:W})});n.write(`
91
+ wrote ${pe.join(z,"fly.toml")} \u2014 deploys the prebuilt node image ${W}
92
92
  (claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
93
93
 
94
94
  Plan (your flyctl, your org, your bill):
95
- `);let C=gn({app:f,org:m,region:b,sizeGb:x,token:A,owner:K,dir:D});for(let T of C)n.write(` $ ${T.display}
95
+ `);let P=Tn({app:f,org:w,region:_,sizeGb:x,token:v,owner:K,dir:z});for(let b of P)n.write(` $ ${b.display}
96
96
  `);if(!c.yes&&(await p(`
97
97
  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.
98
- `),_(1);for(let T of C){n.write(`
99
- \u2192 ${T.display}
100
- `);try{let{stdout:z,stderr:we}=await Ve(T.argv,{stdin:T.stdin,exec:o}),ce=`${z||""}${we||""}`.trim();ce&&n.write(ce.split(`
101
- `).map(Le=>` ${Le}`).join(`
98
+ `),T(1);for(let b of P){n.write(`
99
+ \u2192 ${b.display}
100
+ `);try{let{stdout:D,stderr:me}=await Ve(b.argv,{stdin:b.stdin,exec:o}),Le=`${D||""}${me||""}`.trim();Le&&n.write(Le.split(`
101
+ `).map(we=>` ${we}`).join(`
102
102
  `)+`
103
- `)}catch(z){let we=`${z?.stdout||""}${z?.stderr||""}${z?.message||""}`;if(T.tolerate&&T.tolerate.test(we)){n.write(` (already exists \u2014 continuing)
104
- `);continue}return n.write(`\u2717 failed: ${we.trim().split(`
103
+ `)}catch(D){let me=`${D?.stdout||""}${D?.stderr||""}${D?.message||""}`;if(b.tolerate&&b.tolerate.test(me)){n.write(` (already exists \u2014 continuing)
104
+ `);continue}return n.write(`\u2717 failed: ${me.trim().split(`
105
105
  `).slice(-4).join(`
106
106
  `)}
107
107
  fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
108
- `),_(1)}}return n.write(`
108
+ `),T(1)}}return n.write(`
109
109
  \u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
110
110
  chat: the node step advances on its own within a minute.
111
111
  logs: fly logs -a ${f}
112
- redeploy: fly deploy ${D} -c ${he.join(D,"fly.toml")} -a ${f} --ha=false
112
+ redeploy: fly deploy ${z} -c ${pe.join(z,"fly.toml")} -a ${f} --ha=false
113
113
  Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
114
114
  boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
115
- `),_(0)}var wn,so,St,Ve,Sn=v(()=>{wn="wss://plane.bostrat.ai/v1/node",so=ro(import.meta.url)("../package.json").version,St=`ghcr.io/globocodes/bostrat-node:${so}`;Ve=(e,{stdin:t,exec:n}={})=>new Promise((o,s)=>{if(n)return n(e,{stdin:t}).then(o,s);let c=no("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(u,p,_)=>u?s(Object.assign(u,{stdout:p,stderr:_})):o({stdout:p,stderr:_}));t!=null&&c.stdin?.end(t)})});function vn(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!lo.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let o=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(o))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return o}function uo(e){let t={};for(let[n,o]of Object.entries(e)){if(!Array.isArray(o)||o.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=o.map(s=>({...s,fromMs:vn(s.from,"from",n),toMs:vn(s.to,"to",n)}))}return t}var co,lo,Ra,Na,kn=v(()=>{co={"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-08-20",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."}],"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-08-20",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-08-17",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."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-03, re-verified 2026-08-17 (developers.openai.com pricing); 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-08-24",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)."}],"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-08-17",note:"verified 2026-08-17 (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-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}]},lo=/^\d{4}-\d{2}-\d{2}$/;Ra=uo(co),Na=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var An=v(()=>{kn()});import $n from"node:fs/promises";import On from"node:path";import fo from"node:os";function Nn(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function In(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Mn(e){let t=new Date(Nn(e));return t.setDate(t.getDate()+7),t.getTime()}function Pn(e){let t=new Date(In(e));return t.setMonth(t.getMonth()+1),t.getTime()}function yo(e=Date.now()){for(let[t,n]of Object.entries(mo)){let o=n.startOf(e);if(o!==Je[t]){Je[t]=o;for(let s of vt.values())s[t]=0;for(let s of xn)s.includes(`:${t}:`)&&!s.endsWith(`:${o}`)&&xn.delete(s)}}}function go(e){let t={};for(let[n,o]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let s={};for(let c of["weeklyUsd","monthlyUsd"]){let u=o?.[c];if(u==null||u==="")continue;let p=Number(u);if(!Number.isFinite(p)||p<=0)throw new Error(`${n}.${c} must be a positive number or null`);s[c]=p}Object.keys(s).length&&(t[n]=s)}return t}async function Dn(e,{source:t="local",updatedAt:n=Date.now()}={}){ve={caps:go(e),updatedAt:n,source:t};try{await $n.mkdir(Rn,{recursive:!0}),await $n.writeFile(po(),JSON.stringify(ve,null,2))}catch{}return To()}function To(e=Date.now()){yo(e);let t=new Set([...vt.keys(),...Object.keys(ve?.caps||{})]),n={};for(let o of t){let s=vt.get(o);n[o]={weeklyUsd:En(s?.weekly||0),monthlyUsd:En(s?.monthly||0)}}return{caps:ve?.caps||{},configured:!!ve,seeded:wo,updatedAt:ve?.updatedAt??null,spent:n,windows:{weekly:{start:Je.weekly,resetsAt:Mn(e)},monthly:{start:Je.monthly,resetsAt:Pn(e)}},warnPct:ho}}var Rn,po,ho,mo,ve,wo,Je,vt,xn,En,Cn=v(()=>{Ye();An();Rn=process.env.BOSTRAT_STATE_DIR||On.join(process.env.HOME||fo.tmpdir(),".bostrat"),po=()=>On.join(Rn,"usage-caps.json"),ho=.8;mo={weekly:{startOf:Nn,nextStart:Mn,capKey:"weeklyUsd"},monthly:{startOf:In,nextStart:Pn,capKey:"monthlyUsd"}},ve=null,wo=!1,Je={weekly:0,monthly:0},vt=new Map,xn=new Set;En=e=>Math.round(e*1e4)/1e4});var Yn={};ut(Yn,{detectInstallKind:()=>Ae,detectProviderAuth:()=>Wn,startPlaneLink:()=>Mo,updateCommandFor:()=>Fe,versionLt:()=>ke});import Kn from"node:fs";import je from"node:fs/promises";import _o from"node:http";import V from"node:path";import Xe from"node:os";import{createRequire as bo}from"node:module";import kt from"ws";function Ae({env:e=process.env,pkgDir:t=V.resolve(V.dirname(new URL(import.meta.url).pathname),".."),exists:n=Kn.existsSync}={}){let o=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(o)?o:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(V.join(t,"..",".git"))?"git-checkout":"dev"}function ke(e,t){let n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);if(n.some(Number.isNaN)||o.some(Number.isNaN))return!1;for(let s=0;s<Math.max(n.length,o.length);s++){let c=(n[s]||0)-(o[s]||0);if(c)return c<0}return!1}function Fe(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 Wn({home:e=process.env.HOME||Xe.homedir(),env:t=process.env}={}){let n=o=>{try{return Kn.statSync(o),!0}catch{return!1}};return{claude:n(V.join(e,".claude",".credentials.json")),codex:n(V.join(t.CODEX_HOME||V.join(e,".codex"),"auth.json"))}}function Mo({url:e,token:t,nodeId:n=Xe.hostname(),name:o=Xe.hostname(),listTracks:s,detectAgents:c=null,onTracksTransferred:u=null,sampleMetrics:p=null,metricsMs:_=Io,onUpdateAvailable:m=null,onUpdatePolicy:f=null,onHelloRefused:b=null,updatePolicy:x=null,installKind:g=Ae(),selfUrl:k=`http://127.0.0.1:${process.env.PORT||3362}`,onDegraded:A=null,onRecovered:K=null,onConnected:W=null,ingestMode:D=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:C=Eo,unackedRetryMs:T=xo,pingMs:z=$o,maxInflightEvents:we=Ro,httpTimeoutMs:ce=No,stallBackoffMinMs:Le=Oo,fetchImpl:It=globalThis.fetch,log:y=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof s!="function")throw new Error("plane-link: listTracks is required");e=Pe(e);let sr=k.replace(/^http/,"ws"),Mt=new Set,le=new Map,ue=new Map,tt=V.join(jn,"plane-link","cursor.json"),nt=V.join(jn,"plane-link","dead-letter.ndjson"),Pt=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),de={},ne={},$=new Map,Be=null,re=null,Q=0,Ee=0,Dt=0,Ct=Promise.resolve(),O="ws",ye=0,Y=!1,fe=0,rt=!1,B=se,ge=new Set,oe=[],j=null,X=null,q=!1,ot=!1,Oe=Fn,Re=null,Te=null,_e=null,ee=null,te=null,st=!1,Ue=0;async function ir(){try{de=JSON.parse(await je.readFile(tt,"utf8"))}catch{de={}}}function ar(){st=!0,!_e&&(_e=setTimeout(async()=>{if(_e=null,!!st){st=!1;try{await je.mkdir(V.dirname(tt),{recursive:!0}),await je.writeFile(tt,JSON.stringify(de))}catch(a){y.error("[plane-link] cursor flush failed:",a?.message||a)}}},Ao),_e.unref?.())}function N(a){return!X||X.readyState!==kt.OPEN?!1:(X.send(JSON.stringify(a)),!0)}function Ne(a){let l=Date.now();for(let{trackId:r,event:i}of a){let d=$.get(i.id);$.set(i.id,{trackId:r,seq:i.seq,event:i,sentAt:l,firstSentAt:d?.firstSentAt??l,retryAt:l+T,tries:(d?.tries??0)+1,nacks:d?.nacks??0})}return O==="http"?(dr(a),!0):N({v:I,ch:"events",type:"append",events:a})}function cr(a){let l=null;for(let r of $.values())r.trackId===a&&(l==null||r.seq<l)&&(l=r.seq);return l}function it(a){let l=ne[a];if(l==null)return;let r=cr(a),i=r==null?l:Math.min(l,r-1);i>(de[a]??0)&&(de[a]=i,ar())}function Ie(){if(Be=Date.now(),re!=null){let a=Date.now()-re;y.log(`[plane-link] spine sync recovered after ${Math.round(a/1e3)}s degraded (${Q} stall redial(s))`);let l=re;re=null,Q=0,Ee=0,Y=!1,fe=0;try{K?.({since:l,downMs:a})}catch(r){y.error(`[plane-link] onRecovered failed: ${r?.message||r}`)}}}function at(a){if(!Array.isArray(a)||!a.length)return;let l=new Set;for(let r of a){let i=$.get(r);i&&($.delete(r),(ne[i.trackId]??0)<i.seq&&(ne[i.trackId]=i.seq),l.add(i.trackId))}for(let r of l)it(r);Ie()}function jt(a,l){Dt++;let r={at:Date.now(),trackId:a.trackId,seq:a.seq,id:a.event?.id??null,type:a.event?.type??null,reason:l,event:a.event??null};y.error(`[plane-link] DEAD-LETTER ${a.trackId} seq ${a.seq} (${r.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${nt}`),Ct=Ct.then(async()=>{await je.mkdir(V.dirname(nt),{recursive:!0}),await je.appendFile(nt,JSON.stringify(r)+`
116
- `)}).catch(i=>y.error(`[plane-link] dead-letter write failed: ${i?.message||i}`))}function Ft(a,l,r,i=null){if(!Array.isArray(a)||!a.length)return;let d=new Set,h=Date.now();for(let w of a){let S=$.get(w);S&&(r?($.delete(w),jt(S,l),(ne[S.trackId]??0)<S.seq&&(ne[S.trackId]=S.seq),d.add(S.trackId)):(S.nacks++,S.retryAt=h+Math.max(1e3,Number(i)||T)))}for(let w of d)it(w);Ie()}function Lt(a=Date.now()){let l=1/0;for(let r of $.values())r.firstSentAt<l&&(l=r.firstSentAt);return l===1/0?0:a-l}function Bt(){if(!q||!$.size)return;let a=Date.now(),l=Lt(a);if(l<C||Be!=null&&a-Be<C||O==="http"&&Y||Ee>a)return;Q++;let r=Math.min(Le*2**(Q-1),Bn);if(re==null){re=a-l,y.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${$.size} event(s) in flight (${O} door) \u2014 the plane is not answering appends`);try{A?.({since:re,unacked:$.size,oldestAgeMs:l,mode:O})}catch(i){y.error(`[plane-link] onDegraded failed: ${i?.message||i}`)}}if(O==="http"){Y=!0,fe=a+r,y.error(`[plane-link] ingest circuit OPEN (stall #${Q}); probing /v1/ingest/health in ${Math.round(r/1e3)}s`);return}Ee=a+r,y.error(`[plane-link] closing the link and redialing in ${Math.round(r/1e3)}s (stall redial #${Q})`);try{X?.terminate()}catch{}}function ct(){if(!q)return;let a=Date.now();if(O==="http"&&Y)return;let l=[...$.values()].filter(i=>i.event&&i.retryAt<=a&&!(O==="http"&&ge.has(i.trackId)));if(!l.length)return;l.sort((i,d)=>i.trackId===d.trackId?i.seq-d.seq:i.trackId<d.trackId?-1:1),y.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let r=O==="http"?B:se;if(O==="http"){let i=new Map;for(let d of l)(i.get(d.trackId)??i.set(d.trackId,[]).get(d.trackId)).push(d);for(let[,d]of i){if(ye>=At)return;Ne(d.slice(0,r).map(h=>({trackId:h.trackId,event:h.event})))}return}for(let i=0;i<l.length;i+=r){let d=l.slice(i,i+r).map(h=>({trackId:h.trackId,event:h.event}));if(!Ne(d))return}}async function lr(a=null){for(;;){if(!q)return!1;let l=$.size<we,r=O!=="http"||ye<At&&!Y&&(!a||!ge.has(a));if(l&&r)return!0;await new Promise(i=>setTimeout(i,100))}}function lt(){if(j=null,!q||!oe.length)return;let a=oe;if(oe=[],O!=="http"){for(let r=0;r<a.length;r+=se)Ne(a.slice(r,r+se));return}let l=new Map;for(let r of a)(l.get(r.trackId)??l.set(r.trackId,[]).get(r.trackId)).push(r);for(let[r,i]of l){if(ge.has(r)||ye>=At||Y){oe.push(...i);continue}for(let d=0;d<i.length;d+=B)Ne(i.slice(d,d+B))}oe.length&&!j&&(j=setTimeout(lt,Un),j.unref?.())}let ur=a=>{let l=new Map;for(let{trackId:r,event:i}of a)(l.get(r)??l.set(r,[]).get(r)).push(i);return[...l].map(([r,i])=>({trackId:r,events:i}))},be=(a,l,r,{progress:i})=>{let d=Date.now();for(let{event:h}of a){let w=$.get(h.id);w&&(w.nacks++,w.retryAt=d+Math.max(1e3,r||T))}i&&Ie()};async function dr(a){let l=new Set(a.map(r=>r.trackId));for(let r of l)ge.add(r);ye++;try{let r=await It(`${Pt}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:ur(a)}),signal:AbortSignal.timeout(ce)}),i=(Number(r.headers.get("retry-after"))||0)*1e3;if(r.status===200){let d=await r.json();B=se;for(let h of d.results??[]){at(h.acked??[]);let w=(S,P)=>{let U=new Map;for(let E of S??[])(U.get(E.reason)??U.set(E.reason,[]).get(E.reason)).push(E.id);for(let[E,zt]of U)Ft(zt,E,P,d.retryAfterMs??null)};w(h.rejected,!0),w(h.deferred,!1)}at(d.discarded??[]),Ie();return}if(r.status===429){be(a,"overloaded",i||5e3,{progress:!0});return}if(r.status===413&&a.length>1){B=Math.max(1,Math.floor(a.length/2)),y.error(`[plane-link] ingest request too large (${a.length} events) \u2014 halving batches to ${B}`),be(a,"too_large",1e3,{progress:!0});return}if(r.status===413){let d=$.get(a[0].event.id);d&&($.delete(d.event.id),jt(d,"too_large"),(ne[d.trackId]??0)<d.seq&&(ne[d.trackId]=d.seq),it(d.trackId)),Ie();return}if(r.status===401||r.status===403){if(Date.now()-Ue>=Hn){Ue=Date.now();let d="";try{d=(await r.json())?.error??""}catch{}y.error(`[plane-link] plane refused ingest (HTTP ${r.status}${d?`: ${d}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}be(a,`http_${r.status}`,6e4,{progress:!1});return}if(r.status===400){y.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${a.length} event(s) for retry; this is a bug, not data`),be(a,"http_400",6e4,{progress:!1});return}be(a,`http_${r.status}`,i||5e3,{progress:!1})}catch(r){let i=r?.name==="TimeoutError"||r?.name==="AbortError";i&&a.length>1&&(B=Math.max(1,Math.floor(a.length/2)),y.error(`[plane-link] ingest request of ${a.length} event(s) outlived its ${ce} ms deadline \u2014 halving batches to ${B}`)),be(a,i?"timeout":"network",5e3,{progress:!1})}finally{ye--;for(let r of l)ge.delete(r)}}async function fr(){if(O!=="http"||!Y||!q||rt)return;let a=Date.now();if(!(fe>a)){rt=!0;try{let l=await It(`${Pt}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(ce)});if(!l.ok)throw new Error(`HTTP ${l.status}`);y.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Y=!1,fe=0,Ee=Date.now()+ce+T+1e3;for(let r of $.values())r.retryAt=Math.min(r.retryAt,Date.now());ct()}catch(l){Q++;let r=Math.min(Le*2**(Q-1),Bn);fe=Date.now()+r,y.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(r/1e3)}s`)}finally{rt=!1}}}function Ut(){let a=Date.now();return{mode:O,unacked:$.size,oldestUnackedAgeMs:Lt(a),lastProgressAt:Be,degradedSince:re,stallRedials:Q,deadLettered:Dt,http:O==="http"?{inFlight:ye,circuitOpen:Y,nextProbeInMs:Y?Math.max(0,fe-a):0,batchCap:B}:null}}async function Ht(){if(!p)return;let a;try{a=await p()}catch(l){y.error("[plane-link] metrics sample failed:",l?.message||l);return}a&&N({v:I,ch:"ctl",type:"metrics",metrics:{...a,planeLink:Ut()}})}function pr(){p&&(te&&clearInterval(te),Ht(),te=setInterval(Ht,_),te.unref?.())}async function hr(){let a;try{a=await s()}catch(l){y.error("[plane-link] backfill listTracks failed:",l?.message||l);return}N({v:I,ch:"ctl",type:"tracks",ids:a.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of a){if(!q)return;let r;try{r=await wt(l)}catch{continue}let i=de[l.id]??0,d=r.filter(w=>w.seq>i&&typeof w.id=="string"),h=O==="http"?B:se;for(let w=0;w<d.length;w+=h){if(!await lr(l.id))return;let S=d.slice(w,w+Math.min(h,O==="http"?B:se)).map(P=>({trackId:l.id,event:P}));if(!Ne(S))return}}}function Kt(a){!q||!a?.trackId||typeof a.id!="string"||(oe.push({trackId:a.trackId,event:a}),j||(j=setTimeout(lt,Un),j.unref?.()))}let Me=new Map;async function mr(a){let{reqId:l,method:r,path:i,headers:d={},body:h}=a,w=Object.fromEntries(Object.entries(d).filter(([,P])=>P!=null)),S=new AbortController;Me.set(l,S);try{if(a.host){await wr(a,w,S);return}let P=await fetch(k+i,{method:r,headers:w,body:h?Buffer.from(h,"base64"):void 0,signal:S.signal}),U=Object.fromEntries(P.headers);for(let E of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete U[E];if(U["content-type"]||(U["content-type"]="application/octet-stream"),N({v:I,ch:"control",type:"http_head",reqId:l,status:P.status,headers:U}),P.body){for await(let E of P.body)if(!N({v:I,ch:"control",type:"http_data",reqId:l,data:Buffer.from(E).toString("base64")}))break}N({v:I,ch:"control",type:"http_end",reqId:l,error:null})}finally{Me.delete(l)}}function wr(a,l,r){let{reqId:i,method:d,path:h,body:w}=a,S=new URL(k);return new Promise(P=>{let U=_o.request({host:S.hostname,port:S.port,method:d,path:h,headers:{...l,host:a.host},signal:r.signal},E=>{let{connection:zt,"keep-alive":bs,"transfer-encoding":Ss,upgrade:vs,...yr}=E.headers;N({v:I,ch:"control",type:"http_head",reqId:i,status:E.statusCode||502,headers:yr}),E.on("data",gr=>{N({v:I,ch:"control",type:"http_data",reqId:i,data:Buffer.from(gr).toString("base64")})||E.destroy()}),E.on("end",()=>{N({v:I,ch:"control",type:"http_end",reqId:i,error:null}),P()}),E.on("error",()=>{N({v:I,ch:"control",type:"http_end",reqId:i,error:"view upstream error"}),P()})});U.on("error",E=>{N({v:I,ch:"control",type:"http_end",reqId:i,error:E?.message||"view request failed"}),P()}),w&&U.write(Buffer.from(w,"base64")),U.end()})}function Wt(){if(ot)return;X=new kt(e,{headers:{authorization:`Bearer ${t}`}}),X.on("open",async()=>{let l=null;try{l=await c?.()||null}catch{l=null}N({v:I,ch:"ctl",type:"hello",nodeId:n,name:o,platform:process.platform,version:G,installKind:g,...typeof x=="function"?{updatePolicy:x()}:x?{updatePolicy:x}:{},providers:Wn(),...l?{agents:l}:{}})}),X.on("message",l=>{let r;try{r=JSON.parse(l)}catch{return}if(r.ch==="ctl"&&r.type==="hello_ok"){q=!0,Oe=Fn,Re=null,y.log(`[plane-link] connected to plane as ${n}`);try{W?.()}catch{}r.minNodeVersion&&G&&ke(G,r.minNodeVersion)&&y.error(`[plane-link] this node is bostrat-node ${G}; the plane asks for \u2265${r.minNodeVersion} \u2014 update with: ${Fe(g)}`);try{f?.(typeof r.updatePolicy=="string"?r.updatePolicy:null)}catch{}let i=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;if(i&&G&&ke(G,i)&&!Mt.has(i)){Mt.add(i),y.log(`[plane-link] bostrat-node ${i} is available (this node runs ${G}) \u2014 ${Fe(g)}`);try{m?.({current:G,latest:i,min:r.minNodeVersion??null,installKind:g,required:!!(r.minNodeVersion&&ke(G,r.minNodeVersion))})}catch(h){y.error(`[plane-link] update notice failed: ${h?.message||h}`)}}let d=r.ingest==="http";O=D==="ws"?"ws":D==="http"||d?"http":"ws",D==="http"&&!d&&y.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),O==="http"&&y.log("[plane-link] spine rides the HTTPS ingest door"),Y=!1,fe=0,B=se,ee&&clearInterval(ee),ee=setInterval(()=>{N({v:I,ch:"ctl",type:"ping"}),Bt(),fr().catch(()=>{}),ct(),oe.length&&!j&&lt()},z),ee.unref?.(),pr(),hr().catch(h=>y.error("[plane-link] backfill failed:",h?.message||h));return}if(r.ch==="ctl"&&r.type==="hello_refused"){let i=typeof r.minNodeVersion=="string"?r.minNodeVersion:null,d=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;y.error(`[plane-link] plane REFUSED this node: bostrat-node ${G??"?"} is below its minimum ${i??"?"} \u2014 ${r.fix||Fe(g)}`),Oe=Ln,Re=0;try{b?.({current:G,min:i,latest:d,fix:r.fix||Fe(g),installKind:g})}catch(h){y.error(`[plane-link] refusal handler failed: ${h?.message||h}`)}return}if(r.ch==="ctl"&&r.type==="update_policy"){try{f?.(typeof r.mode=="string"?r.mode:null)}catch{}return}if(r.ch==="ctl"&&r.type==="usage_caps"){Dn(r.caps??{},{source:"plane",updatedAt:r.updatedAt??Date.now()}).then(i=>y.log(`[plane-link] spend caps ${Object.keys(i.caps).length?`updated (${Object.keys(i.caps).join(", ")})`:"cleared"} from plane`)).catch(i=>y.error("[plane-link] spend-caps push rejected:",i?.message||i));return}if(r.ch==="ctl"&&r.type==="transferred"&&Array.isArray(r.tracks)){Promise.resolve().then(()=>u?.(r.tracks)).catch(i=>y.error("[plane-link] transfer notice failed:",i?.message||i));return}if(r.ch==="events"&&r.type==="ack"&&Array.isArray(r.ids)){at(r.ids);return}if(r.ch==="events"&&r.type==="nack"&&Array.isArray(r.ids)){Ft(r.ids,r.reason,r.permanent===!0,r.retryAfterMs??null);return}if(r.ch==="control"&&r.type==="http_open"){mr(r).catch(i=>N({v:I,ch:"control",type:"http_end",reqId:r.reqId,error:i?.message||"tunnel error"}));return}if(r.ch==="control"&&r.type==="http_cancel"){Me.get(r.reqId)?.abort();return}if(r.ch==="attach"&&r.type==="open"){let i=new kt(sr+r.path,Array.isArray(r.protocols)?r.protocols:[],r.host?{headers:{host:r.host}}:void 0);le.set(r.streamId,i),ue.set(r.streamId,[]),i.on("open",()=>{let h=ue.get(r.streamId)||[];ue.delete(r.streamId);for(let{buf:w,bin:S}of h)i.send(w,{binary:S})}),i.on("message",(h,w)=>{let S=w?h:Buffer.from(String(h));N({v:I,ch:"attach",type:"data",streamId:r.streamId,data:S.toString("base64"),...w?{bin:!0}:{}})});let d=()=>{ue.delete(r.streamId),le.delete(r.streamId)&&N({v:I,ch:"attach",type:"close",streamId:r.streamId})};i.on("close",d),i.on("error",d);return}if(r.ch==="attach"&&r.type==="data"){let i=le.get(r.streamId);if(!i)return;let d=Buffer.from(r.data,"base64"),h=r.bin===!0,w=ue.get(r.streamId);w?w.push({buf:d,bin:h}):i.send(d,{binary:h});return}if(r.ch==="attach"&&r.type==="close"){let i=le.get(r.streamId);le.delete(r.streamId),ue.delete(r.streamId),i?.close();return}});let a=()=>{q&&y.log("[plane-link] disconnected from plane"),q=!1,ee&&(clearInterval(ee),ee=null),te&&(clearInterval(te),te=null),$.clear(),ne={},oe=[],j&&(clearTimeout(j),j=null),ge.clear();for(let i of le.values())i.close();le.clear(),ue.clear();for(let i of Me.values())i.abort();if(Me.clear(),ot||Te)return;Re==null&&(Re=Date.now());let l=Date.now()-Re<So,r=Math.max(l?vo+Math.random()*ko:Oe,Ee-Date.now());Te=setTimeout(()=>{Te=null,Wt()},r),Te.unref?.(),l||(Oe=Math.min(Oe*2,Ln))};X.on("close",a),X.on("error",l=>{let r=/Unexpected server response: (\d+)/.exec(l?.message||"")?.[1];(r==="401"||r==="403")&&Date.now()-Ue>=Hn&&(Ue=Date.now(),y.error(`[plane-link] plane refused this node's credentials (HTTP ${r}) \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)`)),a()})}return Ce.on("event",Kt),ir().then(Wt),{stop:()=>{ot=!0,Ce.off("event",Kt),Te&&clearTimeout(Te),_e&&clearTimeout(_e),ee&&clearInterval(ee),te&&clearInterval(te),j&&clearTimeout(j),N({v:I,ch:"ctl",type:"bye",reason:"shutdown"}),X?.close()},status:()=>({connected:q,nodeId:n,cursor:{...de},inflight:$.size,...Ut()}),_tick:()=>{Bt(),ct()}}}var G,jn,I,Fn,Ln,So,vo,ko,se,Ao,$o,xo,zn,Eo,Oo,Bn,Ro,Un,No,At,Io,Hn,$t=v(()=>{Ye();Cn();pt();G=(()=>{try{return bo(import.meta.url)("../package.json").version||null}catch{return null}})(),jn=process.env.BOSTRAT_STATE_DIR||V.join(process.env.HOME||Xe.tmpdir(),".bostrat");I=1,Fn=1e3,Ln=3e4,So=6e4,vo=1500,ko=500,se=100,Ao=2e3,$o=25e3,xo=6e4,zn=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Eo=zn(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Oo=3e4,Bn=10*6e4,Ro=400,Un=250,No=zn(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),At=4,Io=6e4,Hn=6e4});import{execFile as Po}from"node:child_process";import{promisify as Do}from"node:util";function qn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var rc,oc,sc,Gn=v(()=>{yt();rc=Do(Po),oc=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,sc=Promise.resolve()});var Qn={};ut(Qn,{ACTIONABLE_KINDS:()=>et,SELF_UPDATE_DIR:()=>xt,createAutoUpdater:()=>Go,inFlight:()=>Ot,readStatus:()=>Et,selfUpdatePlan:()=>Xn,settleSelfUpdate:()=>qo,startSelfUpdate:()=>Zn,underService:()=>Jn,updatePolicy:()=>Ho});import Vn from"node:fs";import ie from"node:fs/promises";import Co from"node:os";import M from"node:path";import{spawn as jo}from"node:child_process";import{createRequire as Fo}from"node:module";function Ho({kind:e=Ae(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:et.has(e)?e==="git-checkout"||Jn(t)?"auto":"prompt":"off"}function Jn(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Xn({kind:e,to:t,from:n=Ze,statusFile:o=Qe,logFile:s=M.join(xt,"last.log"),port:c=Number(process.env.PORT)||3362,npmPrefix:u=null,serviceName:p=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:_=typeof process.getuid=="function"?process.getuid():0,liveDir:m=process.env.BOSTRAT_LIVE_CHECKOUT||M.resolve(M.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:f=Date.now()}={}){if(!et.has(e))throw new Error(`self-update: install kind "${e}" is not actionable here`);if(!/^\d+\.\d+\.\d+$/.test(String(t)))throw new Error(`self-update: bad target version "${t}"`);if(n&&!/^\d+\.\d+\.\d+$/.test(String(n)))throw new Error(`self-update: bad current version "${n}"`);let b=(K,W="")=>`write_status ${F(K)} ${W}`,x=process.platform==="darwin"?`launchctl kickstart -k gui/${_}/${p}`:`systemctl --user restart ${F(p)}`,g=`
115
+ `),T(0)}var yn,io,St,Ve,vn=k(()=>{yn="wss://plane.bostrat.ai/v1/node",io=oo(import.meta.url)("../package.json").version,St=`ghcr.io/globocodes/bostrat-node:${io}`;Ve=(e,{stdin:t,exec:n}={})=>new Promise((o,s)=>{if(n)return n(e,{stdin:t}).then(o,s);let c=ro("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(u,p,T)=>u?s(Object.assign(u,{stdout:p,stderr:T})):o({stdout:p,stderr:T}));t!=null&&c.stdin?.end(t)})});function kn(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!uo.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let o=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(o))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return o}function fo(e){let t={};for(let[n,o]of Object.entries(e)){if(!Array.isArray(o)||o.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=o.map(s=>({...s,fromMs:kn(s.from,"from",n),toMs:kn(s.to,"to",n)}))}return t}var lo,uo,Na,Ia,An=k(()=>{lo={"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-08-20",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."}],"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-08-20",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-08-17",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."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-03, re-verified 2026-08-17 (developers.openai.com pricing); 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-08-24",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)."}],"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-08-17",note:"verified 2026-08-17 (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-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}]},uo=/^\d{4}-\d{2}-\d{2}$/;Na=fo(lo),Ia=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var $n=k(()=>{An()});import xn from"node:fs/promises";import Rn from"node:path";import po from"node:os";function In(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Mn(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Pn(e){let t=new Date(In(e));return t.setDate(t.getDate()+7),t.getTime()}function Dn(e){let t=new Date(Mn(e));return t.setMonth(t.getMonth()+1),t.getTime()}function go(e=Date.now()){for(let[t,n]of Object.entries(wo)){let o=n.startOf(e);if(o!==Je[t]){Je[t]=o;for(let s of vt.values())s[t]=0;for(let s of En)s.includes(`:${t}:`)&&!s.endsWith(`:${o}`)&&En.delete(s)}}}function To(e){let t={};for(let[n,o]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let s={};for(let c of["weeklyUsd","monthlyUsd"]){let u=o?.[c];if(u==null||u==="")continue;let p=Number(u);if(!Number.isFinite(p)||p<=0)throw new Error(`${n}.${c} must be a positive number or null`);s[c]=p}Object.keys(s).length&&(t[n]=s)}return t}async function Cn(e,{source:t="local",updatedAt:n=Date.now()}={}){ve={caps:To(e),updatedAt:n,source:t};try{await xn.mkdir(Nn,{recursive:!0}),await xn.writeFile(ho(),JSON.stringify(ve,null,2))}catch{}return _o()}function _o(e=Date.now()){go(e);let t=new Set([...vt.keys(),...Object.keys(ve?.caps||{})]),n={};for(let o of t){let s=vt.get(o);n[o]={weeklyUsd:On(s?.weekly||0),monthlyUsd:On(s?.monthly||0)}}return{caps:ve?.caps||{},configured:!!ve,seeded:yo,updatedAt:ve?.updatedAt??null,spent:n,windows:{weekly:{start:Je.weekly,resetsAt:Pn(e)},monthly:{start:Je.monthly,resetsAt:Dn(e)}},warnPct:mo}}var Nn,ho,mo,wo,ve,yo,Je,vt,En,On,jn=k(()=>{Ye();$n();Nn=process.env.BOSTRAT_STATE_DIR||Rn.join(process.env.HOME||po.tmpdir(),".bostrat"),ho=()=>Rn.join(Nn,"usage-caps.json"),mo=.8;wo={weekly:{startOf:In,nextStart:Pn,capKey:"weeklyUsd"},monthly:{startOf:Mn,nextStart:Dn,capKey:"monthlyUsd"}},ve=null,yo=!1,Je={weekly:0,monthly:0},vt=new Map,En=new Set;On=e=>Math.round(e*1e4)/1e4});var qn={};ut(qn,{detectInstallKind:()=>Ae,detectProviderAuth:()=>zn,startPlaneLink:()=>Po,updateCommandFor:()=>Fe,versionLt:()=>ke});import Wn from"node:fs";import je from"node:fs/promises";import bo from"node:http";import V from"node:path";import Xe from"node:os";import{createRequire as So}from"node:module";import kt from"ws";function Ae({env:e=process.env,pkgDir:t=V.resolve(V.dirname(new URL(import.meta.url).pathname),".."),exists:n=Wn.existsSync}={}){let o=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(o)?o:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(V.join(t,"..",".git"))?"git-checkout":"dev"}function ke(e,t){let n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);if(n.some(Number.isNaN)||o.some(Number.isNaN))return!1;for(let s=0;s<Math.max(n.length,o.length);s++){let c=(n[s]||0)-(o[s]||0);if(c)return c<0}return!1}function Fe(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 zn({home:e=process.env.HOME||Xe.homedir(),env:t=process.env}={}){let n=o=>{try{return Wn.statSync(o),!0}catch{return!1}};return{claude:n(V.join(e,".claude",".credentials.json")),codex:n(V.join(t.CODEX_HOME||V.join(e,".codex"),"auth.json"))}}function Po({url:e,token:t,nodeId:n=Xe.hostname(),name:o=Xe.hostname(),listTracks:s,detectAgents:c=null,onTracksTransferred:u=null,sampleMetrics:p=null,metricsMs:T=Mo,onUpdateAvailable:w=null,onUpdatePolicy:f=null,onHelloRefused:_=null,updatePolicy:x=null,installKind:g=Ae(),selfUrl:A=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:v=null,onDegraded:K=null,onRecovered:W=null,onConnected:z=null,ingestMode:P=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:b=Oo,unackedRetryMs:D=Eo,pingMs:me=xo,maxInflightEvents:Le=No,httpTimeoutMs:we=Io,stallBackoffMinMs:It=Ro,fetchImpl:Mt=globalThis.fetch,log:y=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof s!="function")throw new Error("plane-link: listTracks is required");e=Pe(e);let ir=A.replace(/^http/,"ws"),Pt=new Set,ce=new Map,le=new Map,tt=V.join(Fn,"plane-link","cursor.json"),nt=V.join(Fn,"plane-link","dead-letter.ndjson"),Dt=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),ue={},ne={},$=new Map,Be=null,re=null,Q=0,Ee=0,Ct=0,jt=Promise.resolve(),O="ws",ye=0,Y=!1,de=0,rt=!1,B=se,ge=new Set,oe=[],j=null,X=null,q=!1,ot=!1,Oe=Ln,Re=null,Te=null,_e=null,ee=null,te=null,st=!1,Ue=0;async function ar(){try{ue=JSON.parse(await je.readFile(tt,"utf8"))}catch{ue={}}}function cr(){st=!0,!_e&&(_e=setTimeout(async()=>{if(_e=null,!!st){st=!1;try{await je.mkdir(V.dirname(tt),{recursive:!0}),await je.writeFile(tt,JSON.stringify(ue))}catch(a){y.error("[plane-link] cursor flush failed:",a?.message||a)}}},$o),_e.unref?.())}function N(a){return!X||X.readyState!==kt.OPEN?!1:(X.send(JSON.stringify(a)),!0)}function Ne(a){let l=Date.now();for(let{trackId:r,event:i}of a){let d=$.get(i.id);$.set(i.id,{trackId:r,seq:i.seq,event:i,sentAt:l,firstSentAt:d?.firstSentAt??l,retryAt:l+D,tries:(d?.tries??0)+1,nacks:d?.nacks??0})}return O==="http"?(fr(a),!0):N({v:I,ch:"events",type:"append",events:a})}function lr(a){let l=null;for(let r of $.values())r.trackId===a&&(l==null||r.seq<l)&&(l=r.seq);return l}function it(a){let l=ne[a];if(l==null)return;let r=lr(a),i=r==null?l:Math.min(l,r-1);i>(ue[a]??0)&&(ue[a]=i,cr())}function Ie(){if(Be=Date.now(),re!=null){let a=Date.now()-re;y.log(`[plane-link] spine sync recovered after ${Math.round(a/1e3)}s degraded (${Q} stall redial(s))`);let l=re;re=null,Q=0,Ee=0,Y=!1,de=0;try{W?.({since:l,downMs:a})}catch(r){y.error(`[plane-link] onRecovered failed: ${r?.message||r}`)}}}function at(a){if(!Array.isArray(a)||!a.length)return;let l=new Set;for(let r of a){let i=$.get(r);i&&($.delete(r),(ne[i.trackId]??0)<i.seq&&(ne[i.trackId]=i.seq),l.add(i.trackId))}for(let r of l)it(r);Ie()}function Ft(a,l){Ct++;let r={at:Date.now(),trackId:a.trackId,seq:a.seq,id:a.event?.id??null,type:a.event?.type??null,reason:l,event:a.event??null};y.error(`[plane-link] DEAD-LETTER ${a.trackId} seq ${a.seq} (${r.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${nt}`),jt=jt.then(async()=>{await je.mkdir(V.dirname(nt),{recursive:!0}),await je.appendFile(nt,JSON.stringify(r)+`
116
+ `)}).catch(i=>y.error(`[plane-link] dead-letter write failed: ${i?.message||i}`))}function Lt(a,l,r,i=null){if(!Array.isArray(a)||!a.length)return;let d=new Set,h=Date.now();for(let m of a){let S=$.get(m);S&&(r?($.delete(m),Ft(S,l),(ne[S.trackId]??0)<S.seq&&(ne[S.trackId]=S.seq),d.add(S.trackId)):(S.nacks++,S.retryAt=h+Math.max(1e3,Number(i)||D)))}for(let m of d)it(m);Ie()}function Bt(a=Date.now()){let l=1/0;for(let r of $.values())r.firstSentAt<l&&(l=r.firstSentAt);return l===1/0?0:a-l}function Ut(){if(!q||!$.size)return;let a=Date.now(),l=Bt(a);if(l<b||Be!=null&&a-Be<b||O==="http"&&Y||Ee>a)return;Q++;let r=Math.min(It*2**(Q-1),Un);if(re==null){re=a-l,y.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${$.size} event(s) in flight (${O} door) \u2014 the plane is not answering appends`);try{K?.({since:re,unacked:$.size,oldestAgeMs:l,mode:O})}catch(i){y.error(`[plane-link] onDegraded failed: ${i?.message||i}`)}}if(O==="http"){Y=!0,de=a+r,y.error(`[plane-link] ingest circuit OPEN (stall #${Q}); probing /v1/ingest/health in ${Math.round(r/1e3)}s`);return}Ee=a+r,y.error(`[plane-link] closing the link and redialing in ${Math.round(r/1e3)}s (stall redial #${Q})`);try{X?.terminate()}catch{}}function ct(){if(!q)return;let a=Date.now();if(O==="http"&&Y)return;let l=[...$.values()].filter(i=>i.event&&i.retryAt<=a&&!(O==="http"&&ge.has(i.trackId)));if(!l.length)return;l.sort((i,d)=>i.trackId===d.trackId?i.seq-d.seq:i.trackId<d.trackId?-1:1),y.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let r=O==="http"?B:se;if(O==="http"){let i=new Map;for(let d of l)(i.get(d.trackId)??i.set(d.trackId,[]).get(d.trackId)).push(d);for(let[,d]of i){if(ye>=At)return;Ne(d.slice(0,r).map(h=>({trackId:h.trackId,event:h.event})))}return}for(let i=0;i<l.length;i+=r){let d=l.slice(i,i+r).map(h=>({trackId:h.trackId,event:h.event}));if(!Ne(d))return}}async function ur(a=null){for(;;){if(!q)return!1;let l=$.size<Le,r=O!=="http"||ye<At&&!Y&&(!a||!ge.has(a));if(l&&r)return!0;await new Promise(i=>setTimeout(i,100))}}function lt(){if(j=null,!q||!oe.length)return;let a=oe;if(oe=[],O!=="http"){for(let r=0;r<a.length;r+=se)Ne(a.slice(r,r+se));return}let l=new Map;for(let r of a)(l.get(r.trackId)??l.set(r.trackId,[]).get(r.trackId)).push(r);for(let[r,i]of l){if(ge.has(r)||ye>=At||Y){oe.push(...i);continue}for(let d=0;d<i.length;d+=B)Ne(i.slice(d,d+B))}oe.length&&!j&&(j=setTimeout(lt,Hn),j.unref?.())}let dr=a=>{let l=new Map;for(let{trackId:r,event:i}of a)(l.get(r)??l.set(r,[]).get(r)).push(i);return[...l].map(([r,i])=>({trackId:r,events:i}))},be=(a,l,r,{progress:i})=>{let d=Date.now();for(let{event:h}of a){let m=$.get(h.id);m&&(m.nacks++,m.retryAt=d+Math.max(1e3,r||D))}i&&Ie()};async function fr(a){let l=new Set(a.map(r=>r.trackId));for(let r of l)ge.add(r);ye++;try{let r=await Mt(`${Dt}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:dr(a)}),signal:AbortSignal.timeout(we)}),i=(Number(r.headers.get("retry-after"))||0)*1e3;if(r.status===200){let d=await r.json();B=se;for(let h of d.results??[]){at(h.acked??[]);let m=(S,C)=>{let U=new Map;for(let E of S??[])(U.get(E.reason)??U.set(E.reason,[]).get(E.reason)).push(E.id);for(let[E,Yt]of U)Lt(Yt,E,C,d.retryAfterMs??null)};m(h.rejected,!0),m(h.deferred,!1)}at(d.discarded??[]),Ie();return}if(r.status===429){be(a,"overloaded",i||5e3,{progress:!0});return}if(r.status===413&&a.length>1){B=Math.max(1,Math.floor(a.length/2)),y.error(`[plane-link] ingest request too large (${a.length} events) \u2014 halving batches to ${B}`),be(a,"too_large",1e3,{progress:!0});return}if(r.status===413){let d=$.get(a[0].event.id);d&&($.delete(d.event.id),Ft(d,"too_large"),(ne[d.trackId]??0)<d.seq&&(ne[d.trackId]=d.seq),it(d.trackId)),Ie();return}if(r.status===401||r.status===403){if(Date.now()-Ue>=Kn){Ue=Date.now();let d="";try{d=(await r.json())?.error??""}catch{}y.error(`[plane-link] plane refused ingest (HTTP ${r.status}${d?`: ${d}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}be(a,`http_${r.status}`,6e4,{progress:!1});return}if(r.status===400){y.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${a.length} event(s) for retry; this is a bug, not data`),be(a,"http_400",6e4,{progress:!1});return}be(a,`http_${r.status}`,i||5e3,{progress:!1})}catch(r){let i=r?.name==="TimeoutError"||r?.name==="AbortError";i&&a.length>1&&(B=Math.max(1,Math.floor(a.length/2)),y.error(`[plane-link] ingest request of ${a.length} event(s) outlived its ${we} ms deadline \u2014 halving batches to ${B}`)),be(a,i?"timeout":"network",5e3,{progress:!1})}finally{ye--;for(let r of l)ge.delete(r)}}async function pr(){if(O!=="http"||!Y||!q||rt)return;let a=Date.now();if(!(de>a)){rt=!0;try{let l=await Mt(`${Dt}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(we)});if(!l.ok)throw new Error(`HTTP ${l.status}`);y.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Y=!1,de=0,Ee=Date.now()+we+D+1e3;for(let r of $.values())r.retryAt=Math.min(r.retryAt,Date.now());ct()}catch(l){Q++;let r=Math.min(It*2**(Q-1),Un);de=Date.now()+r,y.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(r/1e3)}s`)}finally{rt=!1}}}function Ht(){let a=Date.now();return{mode:O,unacked:$.size,oldestUnackedAgeMs:Bt(a),lastProgressAt:Be,degradedSince:re,stallRedials:Q,deadLettered:Ct,http:O==="http"?{inFlight:ye,circuitOpen:Y,nextProbeInMs:Y?Math.max(0,de-a):0,batchCap:B}:null}}async function Kt(){if(!p)return;let a;try{a=await p()}catch(l){y.error("[plane-link] metrics sample failed:",l?.message||l);return}a&&N({v:I,ch:"ctl",type:"metrics",metrics:{...a,planeLink:Ht()}})}function hr(){p&&(te&&clearInterval(te),Kt(),te=setInterval(Kt,T),te.unref?.())}async function mr(){let a;try{a=await s()}catch(l){y.error("[plane-link] backfill listTracks failed:",l?.message||l);return}N({v:I,ch:"ctl",type:"tracks",ids:a.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of a){if(!q)return;let r;try{r=await wt(l)}catch{continue}let i=ue[l.id]??0,d=r.filter(m=>m.seq>i&&typeof m.id=="string"),h=O==="http"?B:se;for(let m=0;m<d.length;m+=h){if(!await ur(l.id))return;let S=d.slice(m,m+Math.min(h,O==="http"?B:se)).map(C=>({trackId:l.id,event:C}));if(!Ne(S))return}}}function Wt(a){!q||!a?.trackId||typeof a.id!="string"||(oe.push({trackId:a.trackId,event:a}),j||(j=setTimeout(lt,Hn),j.unref?.()))}let Me=new Map;async function wr(a){let{reqId:l,method:r,path:i,headers:d={},body:h}=a,m=Object.fromEntries(Object.entries(d).filter(([,C])=>C!=null)),S=new AbortController;Me.set(l,S);try{if(a.host){await yr(a,m,S);return}v&&(m["x-bostrat-token"]=v);let C=await fetch(A+i,{method:r,headers:m,body:h?Buffer.from(h,"base64"):void 0,signal:S.signal}),U=Object.fromEntries(C.headers);for(let E of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete U[E];if(U["content-type"]||(U["content-type"]="application/octet-stream"),N({v:I,ch:"control",type:"http_head",reqId:l,status:C.status,headers:U}),C.body){for await(let E of C.body)if(!N({v:I,ch:"control",type:"http_data",reqId:l,data:Buffer.from(E).toString("base64")}))break}N({v:I,ch:"control",type:"http_end",reqId:l,error:null})}finally{Me.delete(l)}}function yr(a,l,r){let{reqId:i,method:d,path:h,body:m}=a,S=new URL(A);return new Promise(C=>{let U=bo.request({host:S.hostname,port:S.port,method:d,path:h,headers:{...l,host:a.host},signal:r.signal},E=>{let{connection:Yt,"keep-alive":Ss,"transfer-encoding":vs,upgrade:ks,...gr}=E.headers;N({v:I,ch:"control",type:"http_head",reqId:i,status:E.statusCode||502,headers:gr}),E.on("data",Tr=>{N({v:I,ch:"control",type:"http_data",reqId:i,data:Buffer.from(Tr).toString("base64")})||E.destroy()}),E.on("end",()=>{N({v:I,ch:"control",type:"http_end",reqId:i,error:null}),C()}),E.on("error",()=>{N({v:I,ch:"control",type:"http_end",reqId:i,error:"view upstream error"}),C()})});U.on("error",E=>{N({v:I,ch:"control",type:"http_end",reqId:i,error:E?.message||"view request failed"}),C()}),m&&U.write(Buffer.from(m,"base64")),U.end()})}function zt(){if(ot)return;X=new kt(e,{headers:{authorization:`Bearer ${t}`}}),X.on("open",async()=>{let l=null;try{l=await c?.()||null}catch{l=null}N({v:I,ch:"ctl",type:"hello",nodeId:n,name:o,platform:process.platform,version:G,installKind:g,...typeof x=="function"?{updatePolicy:x()}:x?{updatePolicy:x}:{},providers:zn(),...l?{agents:l}:{}})}),X.on("message",l=>{let r;try{r=JSON.parse(l)}catch{return}if(r.ch==="ctl"&&r.type==="hello_ok"){q=!0,Oe=Ln,Re=null,y.log(`[plane-link] connected to plane as ${n}`);try{z?.()}catch{}r.minNodeVersion&&G&&ke(G,r.minNodeVersion)&&y.error(`[plane-link] this node is bostrat-node ${G}; the plane asks for \u2265${r.minNodeVersion} \u2014 update with: ${Fe(g)}`);try{f?.(typeof r.updatePolicy=="string"?r.updatePolicy:null)}catch{}let i=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;if(i&&G&&ke(G,i)&&!Pt.has(i)){Pt.add(i),y.log(`[plane-link] bostrat-node ${i} is available (this node runs ${G}) \u2014 ${Fe(g)}`);try{w?.({current:G,latest:i,min:r.minNodeVersion??null,installKind:g,required:!!(r.minNodeVersion&&ke(G,r.minNodeVersion))})}catch(h){y.error(`[plane-link] update notice failed: ${h?.message||h}`)}}let d=r.ingest==="http";O=P==="ws"?"ws":P==="http"||d?"http":"ws",P==="http"&&!d&&y.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),O==="http"&&y.log("[plane-link] spine rides the HTTPS ingest door"),Y=!1,de=0,B=se,ee&&clearInterval(ee),ee=setInterval(()=>{N({v:I,ch:"ctl",type:"ping"}),Ut(),pr().catch(()=>{}),ct(),oe.length&&!j&&lt()},me),ee.unref?.(),hr(),mr().catch(h=>y.error("[plane-link] backfill failed:",h?.message||h));return}if(r.ch==="ctl"&&r.type==="hello_refused"){let i=typeof r.minNodeVersion=="string"?r.minNodeVersion:null,d=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;y.error(`[plane-link] plane REFUSED this node: bostrat-node ${G??"?"} is below its minimum ${i??"?"} \u2014 ${r.fix||Fe(g)}`),Oe=Bn,Re=0;try{_?.({current:G,min:i,latest:d,fix:r.fix||Fe(g),installKind:g})}catch(h){y.error(`[plane-link] refusal handler failed: ${h?.message||h}`)}return}if(r.ch==="ctl"&&r.type==="update_policy"){try{f?.(typeof r.mode=="string"?r.mode:null)}catch{}return}if(r.ch==="ctl"&&r.type==="usage_caps"){Cn(r.caps??{},{source:"plane",updatedAt:r.updatedAt??Date.now()}).then(i=>y.log(`[plane-link] spend caps ${Object.keys(i.caps).length?`updated (${Object.keys(i.caps).join(", ")})`:"cleared"} from plane`)).catch(i=>y.error("[plane-link] spend-caps push rejected:",i?.message||i));return}if(r.ch==="ctl"&&r.type==="transferred"&&Array.isArray(r.tracks)){Promise.resolve().then(()=>u?.(r.tracks)).catch(i=>y.error("[plane-link] transfer notice failed:",i?.message||i));return}if(r.ch==="events"&&r.type==="ack"&&Array.isArray(r.ids)){at(r.ids);return}if(r.ch==="events"&&r.type==="nack"&&Array.isArray(r.ids)){Lt(r.ids,r.reason,r.permanent===!0,r.retryAfterMs??null);return}if(r.ch==="control"&&r.type==="http_open"){wr(r).catch(i=>N({v:I,ch:"control",type:"http_end",reqId:r.reqId,error:i?.message||"tunnel error"}));return}if(r.ch==="control"&&r.type==="http_cancel"){Me.get(r.reqId)?.abort();return}if(r.ch==="attach"&&r.type==="open"){let i=new kt(ir+r.path,Array.isArray(r.protocols)?r.protocols:[],r.host?{headers:{host:r.host}}:void 0);ce.set(r.streamId,i),le.set(r.streamId,[]),i.on("open",()=>{let h=le.get(r.streamId)||[];le.delete(r.streamId);for(let{buf:m,bin:S}of h)i.send(m,{binary:S})}),i.on("message",(h,m)=>{let S=m?h:Buffer.from(String(h));N({v:I,ch:"attach",type:"data",streamId:r.streamId,data:S.toString("base64"),...m?{bin:!0}:{}})});let d=()=>{le.delete(r.streamId),ce.delete(r.streamId)&&N({v:I,ch:"attach",type:"close",streamId:r.streamId})};i.on("close",d),i.on("error",d);return}if(r.ch==="attach"&&r.type==="data"){let i=ce.get(r.streamId);if(!i)return;let d=Buffer.from(r.data,"base64"),h=r.bin===!0,m=le.get(r.streamId);m?m.push({buf:d,bin:h}):i.send(d,{binary:h});return}if(r.ch==="attach"&&r.type==="close"){let i=ce.get(r.streamId);ce.delete(r.streamId),le.delete(r.streamId),i?.close();return}});let a=()=>{q&&y.log("[plane-link] disconnected from plane"),q=!1,ee&&(clearInterval(ee),ee=null),te&&(clearInterval(te),te=null),$.clear(),ne={},oe=[],j&&(clearTimeout(j),j=null),ge.clear();for(let i of ce.values())i.close();ce.clear(),le.clear();for(let i of Me.values())i.abort();if(Me.clear(),ot||Te)return;Re==null&&(Re=Date.now());let l=Date.now()-Re<vo,r=Math.max(l?ko+Math.random()*Ao:Oe,Ee-Date.now());Te=setTimeout(()=>{Te=null,zt()},r),Te.unref?.(),l||(Oe=Math.min(Oe*2,Bn))};X.on("close",a),X.on("error",l=>{let r=/Unexpected server response: (\d+)/.exec(l?.message||"")?.[1];(r==="401"||r==="403")&&Date.now()-Ue>=Kn&&(Ue=Date.now(),y.error(`[plane-link] plane refused this node's credentials (HTTP ${r}) \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)`)),a()})}return Ce.on("event",Wt),ar().then(zt),{stop:()=>{ot=!0,Ce.off("event",Wt),Te&&clearTimeout(Te),_e&&clearTimeout(_e),ee&&clearInterval(ee),te&&clearInterval(te),j&&clearTimeout(j),N({v:I,ch:"ctl",type:"bye",reason:"shutdown"}),X?.close()},status:()=>({connected:q,nodeId:n,cursor:{...ue},inflight:$.size,...Ht()}),_tick:()=>{Ut(),ct()}}}var G,Fn,I,Ln,Bn,vo,ko,Ao,se,$o,xo,Eo,Yn,Oo,Ro,Un,No,Hn,Io,At,Mo,Kn,$t=k(()=>{Ye();jn();pt();G=(()=>{try{return So(import.meta.url)("../package.json").version||null}catch{return null}})(),Fn=process.env.BOSTRAT_STATE_DIR||V.join(process.env.HOME||Xe.tmpdir(),".bostrat");I=1,Ln=1e3,Bn=3e4,vo=6e4,ko=1500,Ao=500,se=100,$o=2e3,xo=25e3,Eo=6e4,Yn=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Oo=Yn(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Ro=3e4,Un=10*6e4,No=400,Hn=250,Io=Yn(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),At=4,Mo=6e4,Kn=6e4});import{execFile as Do}from"node:child_process";import{promisify as Co}from"node:util";function Gn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var oc,sc,ic,Vn=k(()=>{yt();oc=Co(Do),sc=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,ic=Promise.resolve()});var er={};ut(er,{ACTIONABLE_KINDS:()=>et,SELF_UPDATE_DIR:()=>xt,createAutoUpdater:()=>Vo,inFlight:()=>Ot,readStatus:()=>Et,selfUpdatePlan:()=>Zn,settleSelfUpdate:()=>Go,startSelfUpdate:()=>Qn,underService:()=>Xn,updatePolicy:()=>Ko});import Jn from"node:fs";import ie from"node:fs/promises";import jo from"node:os";import M from"node:path";import{spawn as Fo}from"node:child_process";import{createRequire as Lo}from"node:module";function Ko({kind:e=Ae(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:et.has(e)?e==="git-checkout"||Xn(t)?"auto":"prompt":"off"}function Xn(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Zn({kind:e,to:t,from:n=Ze,statusFile:o=Qe,logFile:s=M.join(xt,"last.log"),port:c=Number(process.env.PORT)||3362,npmPrefix:u=null,serviceName:p=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:T=typeof process.getuid=="function"?process.getuid():0,liveDir:w=process.env.BOSTRAT_LIVE_CHECKOUT||M.resolve(M.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:f=Date.now()}={}){if(!et.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 _=(K,W="")=>`write_status ${F(K)} ${W}`,x=process.platform==="darwin"?`launchctl kickstart -k gui/${T}/${p}`:`systemctl --user restart ${F(p)}`,g=`
117
117
  health() {
118
118
  for i in $(seq 1 45); do
119
119
  sleep 1
120
120
  if curl -sf -o /dev/null "http://127.0.0.1:${c}/api/health"; then return 0; fi
121
121
  done
122
122
  return 1
123
- }`,k=`#!/usr/bin/env bash
123
+ }`,A=`#!/usr/bin/env bash
124
124
  # bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
125
125
  # ${n??"?"} \u2192 ${t} (${e}). Status: ${o}
126
126
  set -u
@@ -137,15 +137,15 @@ write_status() { # <status> [error]
137
137
  }
138
138
  ${g}
139
139
  `;if(e==="npm-global"){let K=u?M.join(u,"bin","npm"):"npm",W=u?`export PATH=${F(M.join(u,"bin"))}:"$PATH"
140
- `:"",D=u?` --prefix ${F(u)}`:"",C=T=>`${F(K)} install -g "bostrat-node@${T}" --no-audit --no-fund${D}`;return k+W+`
141
- ${b("updating",'"" ')}
142
- if ! ${C("$TO")}; then
143
- ${b("failed",'"npm install failed"')}
140
+ `:"",z=u?` --prefix ${F(u)}`:"",P=b=>`${F(K)} install -g "bostrat-node@${b}" --no-audit --no-fund${z}`;return A+W+`
141
+ ${_("updating",'"" ')}
142
+ if ! ${P("$TO")}; then
143
+ ${_("failed",'"npm install failed"')}
144
144
  exit 1
145
145
  fi
146
- ${b("restarting")}
146
+ ${_("restarting")}
147
147
  if ! ${x}; then
148
- ${b("failed",'"service restart failed"')}
148
+ ${_("failed",'"service restart failed"')}
149
149
  exit 1
150
150
  fi
151
151
  if health; then
@@ -153,52 +153,52 @@ if health; then
153
153
  exit 0
154
154
  fi
155
155
  # \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
156
- ${b("rolling-back",'"agent did not answer on :'+c+' after the update"')}
157
- if [ -n "$FROM" ] && ${C("$FROM")} && ${x} && health; then
158
- ${b("rolled-back",'"agent did not answer on :'+c+' after the update; rolled back"')}
156
+ ${_("rolling-back",'"agent did not answer on :'+c+' after the update"')}
157
+ if [ -n "$FROM" ] && ${P("$FROM")} && ${x} && health; then
158
+ ${_("rolled-back",'"agent did not answer on :'+c+' after the update; rolled back"')}
159
159
  exit 1
160
160
  fi
161
- ${b("failed",'"agent did not answer after the update AND the rollback"')}
161
+ ${_("failed",'"agent did not answer after the update AND the rollback"')}
162
162
  exit 1
163
- `}let A=K=>`( cd ${F(m)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${K}" )`;return k+`
164
- LIVE=${F(m)}
163
+ `}let v=K=>`( cd ${F(w)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${K}" )`;return A+`
164
+ LIVE=${F(w)}
165
165
  TMP_SCRIPT="$(mktemp)"
166
166
  trap 'rm -f "$TMP_SCRIPT"' EXIT
167
167
  # "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
168
168
  # restart \u2192 health in one call): the agent it restarts settles "done" on boot,
169
169
  # and nothing here may write after that boot or the settle would repeat.
170
- ${b("restarting")}
171
- if ${A("$TO")}; then
170
+ ${_("restarting")}
171
+ if ${v("$TO")}; then
172
172
  exit 0
173
173
  fi
174
- ${b("rolling-back",'"deploy-pi.sh v$TO failed"')}
175
- if [ -n "$FROM" ] && ${A("$FROM")}; then
176
- ${b("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
174
+ ${_("rolling-back",'"deploy-pi.sh v$TO failed"')}
175
+ if [ -n "$FROM" ] && ${v("$FROM")}; then
176
+ ${_("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
177
177
  exit 1
178
178
  fi
179
- ${b("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
179
+ ${_("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
180
180
  exit 1
181
- `}async function Et(e=Qe){try{return JSON.parse(await ie.readFile(e,"utf8"))}catch{return null}}async function Zn({to:e,from:t=Ze,kind:n=Ae(),reason:o="manual",statusFile:s=Qe,spawnImpl:c=jo,now:u=Date.now,npmPrefix:p=void 0,log:_=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!et.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!ke(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let m=await Et(s);if(Ot(m))return{ok:!1,reason:`an update to ${m.to} is already in flight`,status:m};if(m&&m.to===e&&(m.status==="failed"||m.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${m.status} (${m.error||"no detail"}) \u2014 retried when a newer release exists`,status:m};await ie.mkdir(M.dirname(s),{recursive:!0});let f=p!==void 0?p:n==="npm-global"?qn(await Wo())||M.resolve(M.dirname(process.execPath),".."):null,b=Xn({kind:n,to:e,from:t,statusFile:s,npmPrefix:f,startedAt:u()}),x=M.join(M.dirname(s),`update-${e}.sh`),g=M.join(M.dirname(s),"last.log");await ie.writeFile(x,b,{mode:448}),await ie.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:o,startedAt:u(),updatedAt:u()}));let k=Vn.existsSync("/run/systemd/system")&&await zo("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",x]]:["setsid",["-f","bash","-c",`exec bash ${F(x)} >> ${F(g)} 2>&1`]];try{c(k[0],k[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(A){return await ie.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:o,startedAt:u(),updatedAt:u(),error:`could not spawn updater: ${A?.message||A}`})),{ok:!1,reason:`could not spawn updater: ${A?.message||A}`}}return _.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${o}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:x,statusFile:s}}async function Wo(){try{return await ie.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function zo(e){for(let t of String(process.env.PATH||"").split(M.delimiter))try{return await ie.access(M.join(t,e),Vn.constants.X_OK),!0}catch{}return!1}async function qo({statusFile:e=Qe,current:t=Ze,now:n=Date.now,staleMs:o=Yo}={}){let s=await Et(e);if(!s)return null;let c=u=>ie.writeFile(e,JSON.stringify(u)).catch(()=>{});if(Ot(s)){if(t&&s.to===t){let u={...s,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await c(u),u}if(n()-Number(s.updatedAt||s.startedAt||0)>o){let u={...s,status:"failed",error:`updater went silent while ${s.status} (no status change for ${Math.round(o/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await c(u),u}return null}if(["failed","rolled-back","done"].includes(s.status)&&!s.announced){let u={...s,announced:!0};return await c(u),u}return null}function Go({isBusy:e,start:t=Zn,onStuck:n=null,onStarted:o=null,tickMs:s=Uo,stuckMs:c=Bo,now:u=Date.now,setIntervalImpl:p=setInterval,clearIntervalImpl:_=clearInterval,log:m=console}={}){let f=null,b=()=>{f?.timer&&_(f.timer),f=null},x=async()=>{if(!f)return;let g=!0;try{g=await e()!==!1}catch{g=!0}if(g){if(!f.stuckFired&&u()-f.since>=c){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let k=f;b();let A=await t({to:k.to,from:k.from,kind:k.kind,reason:"auto"});m.log?.(`[self-update] stasis reached \u2192 ${A.ok?"started":`not started: ${A.reason}`}`);try{await o?.({...k,result:A})}catch{}};return{arm({to:g,from:k=Ze,kind:A=Ae()}){return f?.to===g?!1:(b(),f={to:g,from:k,kind:A,since:u(),stuckFired:!1,timer:p(x,s)},f.timer.unref?.(),!0)},tick:x,cancel:b,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var Ze,Lo,xt,Qe,Bo,Uo,et,F,Ko,Ot,Yo,er=v(()=>{$t();Gn();Ze=(()=>{try{return Fo(import.meta.url)("../package.json").version||null}catch{return null}})(),Lo=process.env.BOSTRAT_STATE_DIR||M.join(process.env.HOME||Co.tmpdir(),".bostrat"),xt=M.join(Lo,"self-update"),Qe=M.join(xt,"status.json"),Bo=1440*6e4,Uo=6e4,et=new Set(["npm-global","git-checkout"]);F=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Ko=new Set(["updating","restarting","rolling-back"]),Ot=e=>!!(e&&Ko.has(e.status));Yo=45*6e4});pt();gt();import J from"node:fs";import R from"node:path";import xe from"node:os";import{createRequire as Rt}from"node:module";import{execFile as Vo,spawn as Jo}from"node:child_process";import{promisify as Xo}from"node:util";import Zo from"node:readline/promises";import{randomUUID as Qo}from"node:crypto";import{fileURLToPath as es}from"node:url";var tr=(e,t)=>{let n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);if(n.some(Number.isNaN)||o.some(Number.isNaN))return!1;for(let s=0;s<Math.max(n.length,o.length);s++){let c=(n[s]||0)-(o[s]||0);if(c)return c<0}return!1},ae=Xo(Vo),Nt=R.dirname(es(import.meta.url)),me=R.resolve(Nt,".."),ts=R.join(Nt,"index.js"),ns="wss://plane.bostrat.ai/v1/node",$e=Rt(import.meta.url)("../package.json").version,L=(e,t)=>({name:e,level:"pass",detail:t}),Z=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),H=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function rs(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?L("node runtime",`${process.version} at ${process.execPath}`):H("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function os(e){let t;try{t=J.statSync(e)}catch{return Z("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?Z("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):L("node.env",`${e} (0600)`)}async function ss(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await ae(t,["-V"],{timeout:5e3});return L("tmux",`${t} (${n.trim()})`)}catch{return H("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function nr(e,{required:t=!1}={}){if(await _t(e,{loginShell:!0,failOpen:!1}))return L(e,"resolves on the login-shell PATH");let o="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",s=Ge[e]?`${Ge[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?H(e,o,s):Z(e,o,s)}async function is(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await ae(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return L("gh (GitHub CLI)",n)}catch{return Z("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",Ge.gh)}}async function as(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>nr(t)));return e.some(t=>t.level==="pass")||e.push(H("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 cs(){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,o])=>await _t(t,{failOpen:!1})?L(t,"resolves on the service PATH"):Z(t,`not on the service PATH \u2014 ${n}`,o)))}async function ls(){try{let t=Rt(R.join(me,"src","node-cli.js"))("node-pty");return await new Promise((n,o)=>{let s=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),c=setTimeout(()=>o(new Error("spawn timeout")),5e3);s.onExit(()=>{clearTimeout(c),n()})}),L("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=Rt(R.join(me,"package.json")),o=R.join(R.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");J.existsSync(o)&&!(J.statSync(o).mode&73)&&(t=`chmod +x ${o} # node-pty ships it non-executable`)}catch{}return H("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function us(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(J.existsSync(t))return L("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"?H:Z)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function ds(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?H("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"):L("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function fs(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return Z("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,o=Date.now(),s=Pe(e.BOSTRAT_PLANE_URL);return await new Promise(c=>{let u=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),p=m=>{clearTimeout(_);try{u.close()}catch{}c(m)},_=setTimeout(()=>p(H("plane link",`no hello_ok within 5s from ${s}`,"check the URL, the token, and the plane's IP gate")),5e3);u.on("open",()=>u.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${Qo().slice(0,8)}`,ephemeral:!0}))),u.on("message",m=>{try{let f=JSON.parse(m);f.type==="hello_ok"?f.minNodeVersion&&tr($e,f.minNodeVersion)?p(H("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${f.minNodeVersion} \u2014 this node is ${$e}; the real link is refused until it updates`,`bostrat-node self-update --to ${f.latestNodeVersion||f.minNodeVersion}`)):f.latestNodeVersion&&tr($e,f.latestNodeVersion)?p(Z("plane link",`hello_ok in ${Date.now()-o}ms (${s}); bostrat-node ${f.latestNodeVersion} is available (this node: ${$e})`,`bostrat-node self-update --to ${f.latestNodeVersion}`)):p(L("plane link",`hello_ok in ${Date.now()-o}ms (${s})`)):f.type==="error"&&p(H("plane link",`plane said: ${f.code} ${f.message||""}`,"check the token"))}catch{}}),u.on("error",m=>p(H("plane link",`${m?.message||m}`,"check the URL, the token, and the plane's IP gate")))})}function ps(){let e;try{e=JSON.parse(J.readFileSync(R.join(ft,"content-outbox.json"),"utf8"))}catch{return L("content outbox","empty \u2014 every deliverable has reached the plane")}let t=e.ops?.length||0,n=e.parked?.length||0;if(n){let o=e.parked[0];return H("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${o?.op} ${o?.family}/${o?.id}: ${o?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?Z("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):L("content outbox",t?`${t} op(s) in flight`:"drained")}function hs(e){return e.BOSTRAT_STATE_REMOTE?L("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):Z("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}async function rr(e,t={}){let n=[];return n.push(await rs()),n.push(os(t.envFile||Se())),n.push(await ss(e)),n.push(...await as()),n.push(await nr("git",{required:!0})),n.push(await is()),n.push(...await cs()),n.push(await ls()),n.push(us(e)),n.push(ds(e)),n.push(await fs(e,t)),n.push(ps()),n.push(hs(e)),n}function or(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let c of e)t(`${n[c.level]} ${c.name}: ${c.detail}`),c.fix&&c.level!=="pass"&&t(` fix: ${c.fix}`);let o=e.filter(c=>c.level==="fail").length,s=e.filter(c=>c.level==="warn").length;return t(o?`
181
+ `}async function Et(e=Qe){try{return JSON.parse(await ie.readFile(e,"utf8"))}catch{return null}}async function Qn({to:e,from:t=Ze,kind:n=Ae(),reason:o="manual",statusFile:s=Qe,spawnImpl:c=Fo,now:u=Date.now,npmPrefix:p=void 0,log:T=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!et.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!ke(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let w=await Et(s);if(Ot(w))return{ok:!1,reason:`an update to ${w.to} is already in flight`,status:w};if(w&&w.to===e&&(w.status==="failed"||w.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${w.status} (${w.error||"no detail"}) \u2014 retried when a newer release exists`,status:w};await ie.mkdir(M.dirname(s),{recursive:!0});let f=p!==void 0?p:n==="npm-global"?Gn(await zo())||M.resolve(M.dirname(process.execPath),".."):null,_=Zn({kind:n,to:e,from:t,statusFile:s,npmPrefix:f,startedAt:u()}),x=M.join(M.dirname(s),`update-${e}.sh`),g=M.join(M.dirname(s),"last.log");await ie.writeFile(x,_,{mode:448}),await ie.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:o,startedAt:u(),updatedAt:u()}));let A=Jn.existsSync("/run/systemd/system")&&await Yo("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",x]]:["setsid",["-f","bash","-c",`exec bash ${F(x)} >> ${F(g)} 2>&1`]];try{c(A[0],A[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(v){return await ie.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:o,startedAt:u(),updatedAt:u(),error:`could not spawn updater: ${v?.message||v}`})),{ok:!1,reason:`could not spawn updater: ${v?.message||v}`}}return T.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${o}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:x,statusFile:s}}async function zo(){try{return await ie.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Yo(e){for(let t of String(process.env.PATH||"").split(M.delimiter))try{return await ie.access(M.join(t,e),Jn.constants.X_OK),!0}catch{}return!1}async function Go({statusFile:e=Qe,current:t=Ze,now:n=Date.now,staleMs:o=qo}={}){let s=await Et(e);if(!s)return null;let c=u=>ie.writeFile(e,JSON.stringify(u)).catch(()=>{});if(Ot(s)){if(t&&s.to===t){let u={...s,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await c(u),u}if(n()-Number(s.updatedAt||s.startedAt||0)>o){let u={...s,status:"failed",error:`updater went silent while ${s.status} (no status change for ${Math.round(o/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await c(u),u}return null}if(["failed","rolled-back","done"].includes(s.status)&&!s.announced){let u={...s,announced:!0};return await c(u),u}return null}function Vo({isBusy:e,start:t=Qn,onStuck:n=null,onStarted:o=null,tickMs:s=Ho,stuckMs:c=Uo,now:u=Date.now,setIntervalImpl:p=setInterval,clearIntervalImpl:T=clearInterval,log:w=console}={}){let f=null,_=()=>{f?.timer&&T(f.timer),f=null},x=async()=>{if(!f)return;let g=!0;try{g=await e()!==!1}catch{g=!0}if(g){if(!f.stuckFired&&u()-f.since>=c){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let A=f;_();let v=await t({to:A.to,from:A.from,kind:A.kind,reason:"auto"});w.log?.(`[self-update] stasis reached \u2192 ${v.ok?"started":`not started: ${v.reason}`}`);try{await o?.({...A,result:v})}catch{}};return{arm({to:g,from:A=Ze,kind:v=Ae()}){return f?.to===g?!1:(_(),f={to:g,from:A,kind:v,since:u(),stuckFired:!1,timer:p(x,s)},f.timer.unref?.(),!0)},tick:x,cancel:_,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var Ze,Bo,xt,Qe,Uo,Ho,et,F,Wo,Ot,qo,tr=k(()=>{$t();Vn();Ze=(()=>{try{return Lo(import.meta.url)("../package.json").version||null}catch{return null}})(),Bo=process.env.BOSTRAT_STATE_DIR||M.join(process.env.HOME||jo.tmpdir(),".bostrat"),xt=M.join(Bo,"self-update"),Qe=M.join(xt,"status.json"),Uo=1440*6e4,Ho=6e4,et=new Set(["npm-global","git-checkout"]);F=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Wo=new Set(["updating","restarting","rolling-back"]),Ot=e=>!!(e&&Wo.has(e.status));qo=45*6e4});pt();gt();import J from"node:fs";import R from"node:path";import xe from"node:os";import{createRequire as Rt}from"node:module";import{execFile as Jo,spawn as Xo}from"node:child_process";import{promisify as Zo}from"node:util";import Qo from"node:readline/promises";import{randomUUID as es}from"node:crypto";import{fileURLToPath as ts}from"node:url";var nr=(e,t)=>{let n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);if(n.some(Number.isNaN)||o.some(Number.isNaN))return!1;for(let s=0;s<Math.max(n.length,o.length);s++){let c=(n[s]||0)-(o[s]||0);if(c)return c<0}return!1},ae=Zo(Jo),Nt=R.dirname(ts(import.meta.url)),he=R.resolve(Nt,".."),ns=R.join(Nt,"index.js"),rs="wss://plane.bostrat.ai/v1/node",$e=Rt(import.meta.url)("../package.json").version,L=(e,t)=>({name:e,level:"pass",detail:t}),Z=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),H=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function os(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?L("node runtime",`${process.version} at ${process.execPath}`):H("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function ss(e){let t;try{t=J.statSync(e)}catch{return Z("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?Z("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):L("node.env",`${e} (0600)`)}async function is(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await ae(t,["-V"],{timeout:5e3});return L("tmux",`${t} (${n.trim()})`)}catch{return H("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function rr(e,{required:t=!1}={}){if(await _t(e,{loginShell:!0,failOpen:!1}))return L(e,"resolves on the login-shell PATH");let o="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",s=Ge[e]?`${Ge[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?H(e,o,s):Z(e,o,s)}async function as(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await ae(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return L("gh (GitHub CLI)",n)}catch{return Z("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",Ge.gh)}}async function cs(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>rr(t)));return e.some(t=>t.level==="pass")||e.push(H("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 ls(){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,o])=>await _t(t,{failOpen:!1})?L(t,"resolves on the service PATH"):Z(t,`not on the service PATH \u2014 ${n}`,o)))}async function us(){try{let t=Rt(R.join(he,"src","node-cli.js"))("node-pty");return await new Promise((n,o)=>{let s=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),c=setTimeout(()=>o(new Error("spawn timeout")),5e3);s.onExit(()=>{clearTimeout(c),n()})}),L("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${he} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Rt(R.join(he,"package.json")),o=R.join(R.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");J.existsSync(o)&&!(J.statSync(o).mode&73)&&(t=`chmod +x ${o} # node-pty ships it non-executable`)}catch{}return H("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function ds(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(J.existsSync(t))return L("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"?H:Z)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function fs(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?H("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"):L("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function ps(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return Z("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,o=Date.now(),s=Pe(e.BOSTRAT_PLANE_URL);return await new Promise(c=>{let u=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),p=w=>{clearTimeout(T);try{u.close()}catch{}c(w)},T=setTimeout(()=>p(H("plane link",`no hello_ok within 5s from ${s}`,"check the URL, the token, and the plane's IP gate")),5e3);u.on("open",()=>u.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${es().slice(0,8)}`,ephemeral:!0}))),u.on("message",w=>{try{let f=JSON.parse(w);f.type==="hello_ok"?f.minNodeVersion&&nr($e,f.minNodeVersion)?p(H("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${f.minNodeVersion} \u2014 this node is ${$e}; the real link is refused until it updates`,`bostrat-node self-update --to ${f.latestNodeVersion||f.minNodeVersion}`)):f.latestNodeVersion&&nr($e,f.latestNodeVersion)?p(Z("plane link",`hello_ok in ${Date.now()-o}ms (${s}); bostrat-node ${f.latestNodeVersion} is available (this node: ${$e})`,`bostrat-node self-update --to ${f.latestNodeVersion}`)):p(L("plane link",`hello_ok in ${Date.now()-o}ms (${s})`)):f.type==="error"&&p(H("plane link",`plane said: ${f.code} ${f.message||""}`,"check the token"))}catch{}}),u.on("error",w=>p(H("plane link",`${w?.message||w}`,"check the URL, the token, and the plane's IP gate")))})}function hs(){let e;try{e=JSON.parse(J.readFileSync(R.join(ft,"content-outbox.json"),"utf8"))}catch{return L("content outbox","empty \u2014 every deliverable has reached the plane")}let t=e.ops?.length||0,n=e.parked?.length||0;if(n){let o=e.parked[0];return H("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${o?.op} ${o?.family}/${o?.id}: ${o?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?Z("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):L("content outbox",t?`${t} op(s) in flight`:"drained")}function ms(e){return e.BOSTRAT_STATE_REMOTE?L("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):Z("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}async function or(e,t={}){let n=[];return n.push(await os()),n.push(ss(t.envFile||Se())),n.push(await is(e)),n.push(...await cs()),n.push(await rr("git",{required:!0})),n.push(await as()),n.push(...await ls()),n.push(await us()),n.push(ds(e)),n.push(fs(e)),n.push(await ps(e,t)),n.push(hs()),n.push(ms(e)),n}function sr(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let c of e)t(`${n[c.level]} ${c.name}: ${c.detail}`),c.fix&&c.level!=="pass"&&t(` fix: ${c.fix}`);let o=e.filter(c=>c.level==="fail").length,s=e.filter(c=>c.level==="warn").length;return t(o?`
182
182
  FAIL \u2014 ${o} blocking, ${s} warnings`:`
183
- OK \u2014 0 blocking, ${s} warnings`),o===0}async function ms({envFile:e=Se(),input:t=process.stdin,output:n=process.stdout}={}){let o=Ke(e),s=Zo.createInterface({input:t,output:n}),c=async(C,T)=>(await s.question(T?`${C} [${T}]: `:`${C}: `)).trim()||T||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
183
+ OK \u2014 0 blocking, ${s} warnings`),o===0}async function ws({envFile:e=Se(),input:t=process.stdin,output:n=process.stdout}={}){let o=Ke(e),s=Qo.createInterface({input:t,output:n}),c=async(P,b)=>(await s.question(b?`${P} [${b}]: `:`${P}: `)).trim()||b||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
184
184
  you type those inside each box, later (box-auth-policy).
185
185
 
186
- `);let u=await c("Plane URL",o.BOSTRAT_PLANE_URL||ns),p=Pe(u);p!==u.trim()&&n.write(` \u2192 using ${p}
187
- `);let _=await c("Node token (minted plane-side; stored 0600)",o.BOSTRAT_PLANE_TOKEN),m=await c("Owner userId (just press Enter \u2014 the plane infers it from your token)",o.BOSTRAT_OWNER||"");m&&!/^user_[A-Za-z0-9]+$/.test(m)&&n.write(` ! that doesn't look like a Clerk userId (user_\u2026) \u2014 leave it empty next time and the plane infers the owner from the token; saved as typed.
188
- `);let f=await c("Node name",o.BOSTRAT_NODE_NAME||xe.hostname().split(".")[0]),b=await c("Repos root",o.BOSTRAT_REPOS_ROOT||R.join(xe.homedir(),"Documents")),x=await c("State remote (per-node private repo; empty = local-only)",o.BOSTRAT_STATE_REMOTE||""),g=(await c("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(`
186
+ `);let u=await c("Plane URL",o.BOSTRAT_PLANE_URL||rs),p=Pe(u);p!==u.trim()&&n.write(` \u2192 using ${p}
187
+ `);let T=await c("Node token (minted plane-side; stored 0600)",o.BOSTRAT_PLANE_TOKEN),w=await c("Owner userId (just press Enter \u2014 the plane infers it from your token)",o.BOSTRAT_OWNER||"");w&&!/^user_[A-Za-z0-9]+$/.test(w)&&n.write(` ! that doesn't look like a Clerk userId (user_\u2026) \u2014 leave it empty next time and the plane infers the owner from the token; saved as typed.
188
+ `);let f=await c("Node name",o.BOSTRAT_NODE_NAME||xe.hostname().split(".")[0]),_=await c("Repos root",o.BOSTRAT_REPOS_ROOT||R.join(xe.homedir(),"Documents")),x=await c("State remote (per-node private repo; empty = local-only)",o.BOSTRAT_STATE_REMOTE||""),g=(await c("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(`
189
189
  BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
190
190
  injected per box, stored 0600 in node.env, never sent to the plane.
191
191
  \u2022 create/copy a key: https://console.anthropic.com/settings/keys
192
192
  \u2022 set a monthly spend limit while you're there \u2014 the key is live.
193
193
 
194
- `);let k=g?await c("ANTHROPIC_API_KEY (starts sk-ant-)",o.ANTHROPIC_API_KEY):"";g&&k&&!/^sk-ant-/.test(k)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
195
- `),s.close();let A={...Gt(),...o,BOSTRAT_PLANE_URL:p,BOSTRAT_PLANE_TOKEN:_,BOSTRAT_OWNER:m,BOSTRAT_NODE_NAME:f,BOSTRAT_NODE_ID:o.BOSTRAT_NODE_ID||f,BOSTRAT_REPOS_ROOT:b,BOSTRAT_STATE_REMOTE:x,BOSTRAT_CLAUDE_USE_API_KEY:g?"1":"0",ANTHROPIC_API_KEY:g?k:o.ANTHROPIC_API_KEY};qt(e,A,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
194
+ `);let A=g?await c("ANTHROPIC_API_KEY (starts sk-ant-)",o.ANTHROPIC_API_KEY):"";g&&A&&!/^sk-ant-/.test(A)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
195
+ `),s.close();let v={...Vt(),...o,BOSTRAT_PLANE_URL:p,BOSTRAT_PLANE_TOKEN:T,BOSTRAT_OWNER:w,BOSTRAT_NODE_NAME:f,BOSTRAT_NODE_ID:o.BOSTRAT_NODE_ID||f,BOSTRAT_REPOS_ROOT:_,BOSTRAT_STATE_REMOTE:x,BOSTRAT_CLAUDE_USE_API_KEY:g?"1":"0",ANTHROPIC_API_KEY:g?A:o.ANTHROPIC_API_KEY};Gt(e,v,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
196
196
  0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
197
197
  Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
198
198
  wrote ${e}
199
199
 
200
- `);let K={...A,...process.env},W=await rr(K,{envFile:e}),D=or(W,C=>n.write(C+`
201
- `));return D&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:D,results:W}}function ws({envFile:e=Se()}={}){Yt(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=Jo(t,[ts],{cwd:me,stdio:"inherit",env:process.env});for(let o of["SIGINT","SIGTERM"])process.on(o,()=>n.kill(o));return n.on("exit",(o,s)=>process.exit(s?1:o??1)),n}function ys({agentDir:e=me,nodeBin:t=process.execPath,envFile:n=Se(),home:o=xe.homedir()}={}){let s=R.dirname(t),c=R.join(R.basename(Nt),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
200
+ `);let K={...v,...process.env},W=await or(K,{envFile:e}),z=sr(W,P=>n.write(P+`
201
+ `));return z&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:z,results:W}}function ys({envFile:e=Se()}={}){qt(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=Xo(t,[ns],{cwd:he,stdio:"inherit",env:process.env});for(let o of["SIGINT","SIGTERM"])process.on(o,()=>n.kill(o));return n.on("exit",(o,s)=>process.exit(s?1:o??1)),n}function gs({agentDir:e=he,nodeBin:t=process.execPath,envFile:n=Se(),home:o=xe.homedir()}={}){let s=R.dirname(t),c=R.join(R.basename(Nt),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
202
202
  # ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
203
203
  [Unit]
204
204
  Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
@@ -218,7 +218,7 @@ RestartSec=2
218
218
 
219
219
  [Install]
220
220
  WantedBy=default.target
221
- `}function gs({agentDir:e=me,nodeBin:t=process.execPath,home:n=xe.homedir()}={}){let o=R.dirname(t),s=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
221
+ `}function Ts({agentDir:e=he,nodeBin:t=process.execPath,home:n=xe.homedir()}={}){let o=R.dirname(t),s=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
222
222
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
223
223
  <plist version="1.0">
224
224
  <dict>
@@ -240,7 +240,7 @@ WantedBy=default.target
240
240
  <key>StandardErrorPath</key><string>${s}/node.err.log</string>
241
241
  </dict>
242
242
  </plist>
243
- `}function Ts(e=process.platform,t=xe.homedir()){return e==="darwin"?{kind:"launchd",file:R.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:R.join(t,".config","systemd","user","bostrat-node.service")}}async function _s({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:o=console.log,agentDir:s=me}={}){let{kind:c,file:u}=Ts(n);if(!e&&s.split(R.sep).includes("_npx"))return o("\u2717 running from the npx cache \u2014 a service must point at a durable install."),o(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){c==="systemd"?(await ae("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),J.rmSync(u,{force:!0}),await ae("systemctl",["--user","daemon-reload"])):(await ae("launchctl",["unload","-w",u]).catch(()=>{}),J.rmSync(u,{force:!0})),o(`removed ${u}`);return}J.mkdirSync(R.dirname(u),{recursive:!0}),c==="systemd"?(J.writeFileSync(u,ys()),await ae("systemctl",["--user","daemon-reload"]),t&&await ae("systemctl",["--user","enable","--now","bostrat-node.service"]),o(`installed ${u}${t?" (enabled + started)":""}`),o("logs: journalctl --user -u bostrat-node.service -f")):(J.mkdirSync(R.join(xe.homedir(),"Library","Logs","bostrat"),{recursive:!0}),J.writeFileSync(u,gs()),t&&await ae("launchctl",["load","-w",u]),o(`installed ${u}${t?" (loaded)":""}`),o("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function $c(e=process.argv.slice(2)){let t=e[0],n=Se();if(t==="--version"||t==="-v"||t==="version")return console.log($e),0;if(t==="init")return(await ms({envFile:n})).ok?0:1;if(t==="doctor"){let o={...Ke(n),...process.env};return or(await rr(o,{envFile:n}))?0:1}if(t==="run"||t==="start")return ws({envFile:n}),null;if(t==="install-service")return await _s({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:o}=await Promise.resolve().then(()=>(Sn(),bn));return await o({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:o,readStatus:s,updatePolicy:c}=await Promise.resolve().then(()=>(er(),Qn)),{detectInstallKind:u}=await Promise.resolve().then(()=>($t(),Yn)),p=u(),_=e.indexOf("--to"),m=_>=0?String(e[_+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:$e,installKind:p,policy:c({kind:p}),status:await s()},null,2)),0;if(!m)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let f=await o({to:m,kind:p,reason:"cli"});return f.ok?(console.log(`\u2713 self-update ${f.from??"?"} \u2192 ${f.to} started (${f.kind}) \u2014 status: ${f.statusFile}; the service restarts when the install completes`),0):(console.error(`\u2717 not started: ${f.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
243
+ `}function _s(e=process.platform,t=xe.homedir()){return e==="darwin"?{kind:"launchd",file:R.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:R.join(t,".config","systemd","user","bostrat-node.service")}}async function bs({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:o=console.log,agentDir:s=he}={}){let{kind:c,file:u}=_s(n);if(!e&&s.split(R.sep).includes("_npx"))return o("\u2717 running from the npx cache \u2014 a service must point at a durable install."),o(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){c==="systemd"?(await ae("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),J.rmSync(u,{force:!0}),await ae("systemctl",["--user","daemon-reload"])):(await ae("launchctl",["unload","-w",u]).catch(()=>{}),J.rmSync(u,{force:!0})),o(`removed ${u}`);return}J.mkdirSync(R.dirname(u),{recursive:!0}),c==="systemd"?(J.writeFileSync(u,gs()),await ae("systemctl",["--user","daemon-reload"]),t&&await ae("systemctl",["--user","enable","--now","bostrat-node.service"]),o(`installed ${u}${t?" (enabled + started)":""}`),o("logs: journalctl --user -u bostrat-node.service -f")):(J.mkdirSync(R.join(xe.homedir(),"Library","Logs","bostrat"),{recursive:!0}),J.writeFileSync(u,Ts()),t&&await ae("launchctl",["load","-w",u]),o(`installed ${u}${t?" (loaded)":""}`),o("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function xc(e=process.argv.slice(2)){let t=e[0],n=Se();if(t==="--version"||t==="-v"||t==="version")return console.log($e),0;if(t==="init")return(await ws({envFile:n})).ok?0:1;if(t==="doctor"){let o={...Ke(n),...process.env};return sr(await or(o,{envFile:n}))?0:1}if(t==="run"||t==="start")return ys({envFile:n}),null;if(t==="install-service")return await bs({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:o}=await Promise.resolve().then(()=>(vn(),Sn));return await o({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:o,readStatus:s,updatePolicy:c}=await Promise.resolve().then(()=>(tr(),er)),{detectInstallKind:u}=await Promise.resolve().then(()=>($t(),qn)),p=u(),T=e.indexOf("--to"),w=T>=0?String(e[T+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:$e,installKind:p,policy:c({kind:p}),status:await s()},null,2)),0;if(!w)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let f=await o({to:w,kind:p,reason:"cli"});return f.ok?(console.log(`\u2713 self-update ${f.from??"?"} \u2192 ${f.to} started (${f.kind}) \u2014 status: ${f.statusFile}; the service restarts when the install completes`),0):(console.error(`\u2717 not started: ${f.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
244
244
 
245
245
  usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
246
246
 
@@ -249,4 +249,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
249
249
  run start the node in the foreground (sources node.env)
250
250
  install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
251
251
  fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
252
- self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{ms as init,_s as installService,gs as launchdPlist,$c as main,or as printDoctor,ws as runAgent,rr as runDoctor,Ts as servicePaths,ys as systemdUnit};
252
+ self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{ws as init,bs as installService,Ts as launchdPlist,xc as main,sr as printDoctor,ys as runAgent,or as runDoctor,_s as servicePaths,gs as systemdUnit};