bostrat-node 1.10.7 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +69 -69
- package/dist/index.js +203 -203
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)){let s=
|
|
3
|
-
`).map(s=>s?`# ${s}`:"#"));for(let[s,c]of Object.entries(t))c==null||c===""||
|
|
1
|
+
var to=Object.defineProperty;var v=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Et=(e,t)=>{for(var n in t)to(e,n,{get:t[n],enumerable:!0})};import et from"node:fs";import Ot from"node:path";import no from"node:os";function Fe(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,r;try{r=new URL(n)}catch{return t}let s={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return s?(r.protocol=s,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function tt(e){let t;try{t=et.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
|
|
2
|
+
`)){let s=r.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 vn(e,t=process.env){let n=tt(e);for(let[r,s]of Object.entries(n))r in t||(t[r]=s);return n}function bn(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
|
|
3
|
+
`).map(s=>s?`# ${s}`:"#"));for(let[s,c]of Object.entries(t))c==null||c===""||r.push(`${s}=${c}`);et.mkdirSync(Ot.dirname(e),{recursive:!0}),et.writeFileSync(e,r.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`,{mode:384}),
|
|
6
|
-
`))if(u.trim())try{c.push(JSON.parse(
|
|
5
|
+
`,{mode:384}),et.chmodSync(e,384)}function An(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 Rt,ke,Nt=v(()=>{Rt=process.env.BOSTRAT_STATE_DIR||Ot.join(process.env.HOME||no.tmpdir(),".bostrat"),ke=()=>Ot.join(Rt,"node.env")});var me,nt,rt=v(()=>{me="BOSTRAT_HOOK_TOKEN",nt="x-bostrat-hook"});var kn=v(()=>{rt()});var $n=v(()=>{});var xn=v(()=>{});import It from"node:path";import{execFile as ro}from"node:child_process";import{promisify as oo}from"node:util";var Ei,En,so,Oi,Ri,On=v(()=>{Ei=oo(ro),En=process.env.HOME||"/home/globo",so=It.join(process.env.BOSTRAT_STATE_DIR||It.join(En,".bostrat"),"repos"),Oi=[...(process.env.BOSTRAT_REPOS_ROOT||It.join(En,"Documents")).split(","),so].map(e=>e.trim()).filter(Boolean),Ri=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function it(e=Date.now()){if(ye)return{tripped:!1,holdMs:1/0};if(we>e)return{tripped:!1,holdMs:we-e};if((!He||e-He>=ot.windowMs)&&(He=e,Ue=0),Ue++,Ue<ot.trip)return{tripped:!1,holdMs:0};st++;let t=Math.min(ot.minMs*2**(st-1),ot.maxMs);return we=e+t,Ue=0,He=0,{tripped:!0,holdMs:t}}function Rn(){Ue=0,He=0,st=0,we=0}function Ke(e=Date.now()){return ye?1/0:we>e?we-e:0}function at(e=Date.now()){return Ke(e)>0}function Mt(e={}){ye={at:Date.now(),...e},we=1/0}function Pt(){return ye}function Nn(e=Date.now()){return{held:at(e),holdMs:ye?null:Ke(e),holds:st,removed:ye?{...ye}:null}}var io,ot,Ue,He,st,we,ye,Dt=v(()=>{io={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},ot={...io},Ue=0,He=0,st=0,we=0,ye=null});import In from"node:path";import ao from"node:os";import{execFile as co}from"node:child_process";import{promisify as lo}from"node:util";var Fi,uo,Ui,Hi,Ki,Bt=v(()=>{On();Dt();Fi=lo(co),uo=process.env.BOSTRAT_STATE_DIR||In.join(process.env.HOME||ao.tmpdir(),".bostrat"),Ui=In.join(uo,"repos"),Hi=5*6e4,Ki=10*6e4});var Mn=v(()=>{Bt()});import fo from"node:fs/promises";import We from"node:path";import ho from"node:os";import{EventEmitter as mo}from"node:events";function wo(e){return e?.cwd?We.join(e.cwd,".bostrat","events"):We.join(Pn,"events")}async function Lt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?We.join(Pn,"events"):wo(e));let s;try{s=await fo.readFile(yo(n,r),"utf8")}catch{return[]}let c=[];for(let u of s.split(`
|
|
6
|
+
`))if(u.trim())try{c.push(JSON.parse(To(u)?_o(u):u))}catch{}return c}var ze,Pn,yo,go,To,_o,ct=v(()=>{ze=new mo;ze.setMaxListeners(0);Pn=process.env.BOSTRAT_STATE_DIR||We.join(process.env.HOME||ho.tmpdir(),".bostrat");yo=(e,t)=>We.join(e,`${t}.ndjson`),go=/(?<!\\)((?:\\\\)*)\\u0000/g,To=e=>e.includes("\\u0000"),_o=e=>e.replace(go,"$1\\ufffd")});import vo from"node:os";import bo from"node:path";import{execFile as Ao}from"node:child_process";import{promisify as ko}from"node:util";var ia,aa,ca,la,ua,da,Dn=v(()=>{Mn();ct();ia=ko(Ao),aa=process.env.BOSTRAT_STATE_DIR||bo.join(process.env.HOME||vo.tmpdir(),".bostrat"),ca=25*1024,la=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,ua=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,da=Promise.resolve()});var Bn=v(()=>{});var ya,Ln=v(()=>{Bt();Bn();ya=60*6e4});var Cn=v(()=>{Ln()});import $o from"node:os";import jn from"node:path";var xo,Oa,Ra,Ct=v(()=>{jt();xo=process.env.BOSTRAT_DEBUG_DIR||jn.join($o.homedir(),".bostrat","debug"),Oa=jn.join(xo,"handoff.jsonl"),Ra=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import Fn from"node:path";import Eo from"node:os";var lt,Oo,Ba,Un,La,Ca,Hn=v(()=>{rt();lt="BOSTRAT_NODE_URL",Oo=process.env.BOSTRAT_STATE_DIR||Fn.join(process.env.HOME||Eo.tmpdir(),".bostrat"),Ba=Fn.join(Oo,"git-hooks"),Un=`#!/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
|
-
`,
|
|
21
|
+
`,La=`${Un}
|
|
22
22
|
# \u2500\u2500 bostrat: append provenance trailers (Layer 0). Skipped for merge commits
|
|
23
23
|
# (nobody "wrote" a merge) and outside a box (no token / no node url).
|
|
24
|
-
[ -z "$${
|
|
25
|
-
[ -z "$${
|
|
24
|
+
[ -z "$${me}" ] && exit 0
|
|
25
|
+
[ -z "$${lt}" ] && exit 0
|
|
26
26
|
[ "$2" = "merge" ] && exit 0
|
|
27
|
-
trailers=$(curl -sS -m 3 -H "${
|
|
27
|
+
trailers=$(curl -sS -m 3 -H "${nt}: $${me}" "$${lt}/api/git/trailers" 2>/dev/null) || exit 0
|
|
28
28
|
[ -z "$trailers" ] && exit 0
|
|
29
29
|
printf '%s\\n' "$trailers" | while IFS= read -r line; do
|
|
30
30
|
[ -n "$line" ] && git interpret-trailers --in-place --if-exists addIfDifferent --trailer "$line" "$1" >/dev/null 2>&1 || true
|
|
31
31
|
done
|
|
32
32
|
exit 0
|
|
33
|
-
`,
|
|
33
|
+
`,Ca=`${Un}
|
|
34
34
|
# \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
|
|
35
|
-
[ -z "$${
|
|
36
|
-
[ -z "$${
|
|
35
|
+
[ -z "$${me}" ] && exit 0
|
|
36
|
+
[ -z "$${lt}" ] && exit 0
|
|
37
37
|
sha=$(git rev-parse HEAD 2>/dev/null) || exit 0
|
|
38
38
|
cwd=$(git rev-parse --show-toplevel 2>/dev/null)
|
|
39
|
-
printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${
|
|
40
|
-
-H 'content-type: application/json' -H "${
|
|
39
|
+
printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${lt}/api/git/committed" \\
|
|
40
|
+
-H 'content-type: application/json' -H "${nt}: $${me}" --data-binary @- >/dev/null 2>&1 || true
|
|
41
41
|
exit 0
|
|
42
|
-
`});import{execFile as
|
|
42
|
+
`});import{execFile as No}from"node:child_process";import{promisify as Io}from"node:util";import Mo from"node:fs";function zn(e){return`/tmp/tmux-${e}/default`}function Do({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let s=zn(r);return t?s:n?`${n}/bostrat/tmux-default`:s}async function Ut(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Lo(e,{loginShell:t});return r===Vn?!0:r===Ft?!1:n}async function Lo(e,{loginShell:t=!1,timeoutMs:n=Bo}={}){if(!e)return Ft;let r=t?process.env.SHELL||"/bin/sh":"sh",s=t?"-lic":"-c";try{return await Po(r,[s,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),Vn}catch(c){return c?.killed||c?.signal?Wn:c?.code===1||c?.code===127?Ft:Wn}}var Po,ic,Kn,ac,cc,lc,uc,Vn,Ft,Wn,Bo,ut,dc,pc,fc,hc,mc,jt=v(()=>{kn();$n();xn();Dn();Cn();Ct();rt();Hn();Po=Io(No),ic=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";Kn=typeof process.getuid=="function"?process.getuid():0,ac=Do({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Mo.existsSync(zn(Kn))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:Kn}),cc=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",lc=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",uc=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]);Vn="present",Ft="absent",Wn="unknown",Bo=5e3;ut={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"},dc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,pc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,fc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,hc=Number(process.env.BOSTRAT_BOX_COLS)||120,mc=Number(process.env.BOSTRAT_BOX_ROWS)||40});var nr={};Et(nr,{NODE_IMAGE:()=>Kt,commandPlan:()=>Qn,flyToml:()=>Zn,flyWizard:()=>Xo,parseFlyFlags:()=>er,stageConfig:()=>tr});import Ht from"node:fs";import ge from"node:path";import Wo from"node:os";import zo from"node:readline/promises";import{execFile as Vo}from"node:child_process";import{createRequire as qo}from"node:module";import{randomUUID as Go}from"node:crypto";function Zn({app:e,region:t,nodeName:n=e,planeUrl:r=Xn,image:s=Kt}){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.
|
|
@@ -61,7 +61,7 @@ swap_size_mb = 1024
|
|
|
61
61
|
# $HOME on the volume: your agent logins, repos, and node state survive
|
|
62
62
|
# machine replacement (the "your login stays on your node" promise).
|
|
63
63
|
HOME = "/data/home"
|
|
64
|
-
BOSTRAT_PLANE_URL = "${
|
|
64
|
+
BOSTRAT_PLANE_URL = "${r}"
|
|
65
65
|
BOSTRAT_NODE_ID = "${e}"
|
|
66
66
|
BOSTRAT_NODE_NAME = "${n}"
|
|
67
67
|
BOSTRAT_REPOS_ROOT = "/data/home/repos"
|
|
@@ -79,29 +79,29 @@ 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
|
|
82
|
+
`}function Qn({app:e,org:t,region:n,sizeGb:r,token:s,owner:c,dir:u}){let h=[`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(r),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${r} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted>${c?" BOSTRAT_OWNER=\u2026":""} via stdin`,stdin:h.join(`
|
|
83
83
|
`)+`
|
|
84
|
-
`},{argv:["deploy",u,"-c",
|
|
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
|
|
84
|
+
`},{argv:["deploy",u,"-c",ge.join(u,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${u} -c ${ge.join(u,"fly.toml")} -a ${e} --ha=false`}]}function er(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 r=0;r<e.length;r++){let s=e[r];if(s==="--yes"||s==="-y")t.yes=!0;else if(n[s])t[n[s]]=e[++r]??"";else if(s.startsWith("--")&&s.includes("=")){let[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 tr({app:e,dest:t,toml:n}){let r=t||ge.join(Wo.homedir(),".bostrat","fly",e);Ht.mkdirSync(r,{recursive:!0});for(let s of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])Ht.rmSync(ge.join(r,s),{recursive:!0,force:!0});return Ht.writeFileSync(ge.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function Jo({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:s}=await dt(["orgs","list","--json"],{exec:n}),c=JSON.parse(s),u=Array.isArray(c)?c.map(h=>h.Slug||h.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 Xo({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:s}={}){let c=er(e),u=zo.createInterface({input:t,output:n}),h=async(b,q)=>(await u.question(q?`${b} [${q}]: `:`${b}: `)).trim()||q||"",g=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
|
|
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"),g(1)}let T=await
|
|
90
|
-
`),g(1);let
|
|
91
|
-
wrote ${
|
|
88
|
+
`);try{await dt(["version"],{exec:r})}catch{return n.write("\u2717 `fly` (flyctl) is not installed or not on PATH.\n install: https://fly.io/docs/flyctl/install/ \u2014 then re-run `bostrat-node fly`\n"),g(1)}try{let{stdout:b}=await dt(["auth","whoami"],{exec:r});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"),g(1)}let T=await Jo({ask:h,output:n,exec:r,flag:c.org}),p=c.app||await h("App name",`bostrat-node-${Go().slice(0,4)}`),m=c.region||await h("Region (see `fly platform regions`)","iad"),B=c.sizeGb||Number(await h("Volume size GB (logins + repos live here)","10"))||10,A=c.name||p,k=c.planeUrl||Xn,S=c.token||await h("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!S)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
|
+
`),g(1);let M=c.owner??await h("Owner userId (shown next to the token; empty = infer from token)",""),j=c.image||Kt,{dir:K}=tr({app:p,dest:s,toml:Zn({app:p,region:m,nodeName:A,planeUrl:k,image:j})});n.write(`
|
|
91
|
+
wrote ${ge.join(K,"fly.toml")} \u2014 deploys the prebuilt node image ${j}
|
|
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
|
|
96
|
-
`);if(!c.yes&&(await
|
|
95
|
+
`);let P=Qn({app:p,org:T,region:m,sizeGb:B,token:S,owner:M,dir:K});for(let b of P)n.write(` $ ${b.display}
|
|
96
|
+
`);if(!c.yes&&(await h(`
|
|
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
|
-
`),g(1);for(let b of
|
|
98
|
+
`),g(1);for(let b of P){n.write(`
|
|
99
99
|
\u2192 ${b.display}
|
|
100
|
-
`);try{let{stdout:
|
|
101
|
-
`).map(
|
|
100
|
+
`);try{let{stdout:q,stderr:_e}=await dt(b.argv,{stdin:b.stdin,exec:r}),Ye=`${q||""}${_e||""}`.trim();Ye&&n.write(Ye.split(`
|
|
101
|
+
`).map(Ie=>` ${Ie}`).join(`
|
|
102
102
|
`)+`
|
|
103
|
-
`)}catch(
|
|
104
|
-
`);continue}return n.write(`\u2717 failed: ${
|
|
103
|
+
`)}catch(q){let _e=`${q?.stdout||""}${q?.stderr||""}${q?.message||""}`;if(b.tolerate&&b.tolerate.test(_e)){n.write(` (already exists \u2014 continuing)
|
|
104
|
+
`);continue}return n.write(`\u2717 failed: ${_e.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.
|
|
@@ -109,11 +109,11 @@ Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u201
|
|
|
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 ${p}
|
|
112
|
-
redeploy: fly deploy ${K} -c ${
|
|
112
|
+
redeploy: fly deploy ${K} -c ${ge.join(K,"fly.toml")} -a ${p} --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
|
-
`),g(0)}var qn,zo,Ut,ut,Qn=v(()=>{qn="wss://plane.bostrat.ai/v1/node",zo=Ko(import.meta.url)("../package.json").version,Ut=`ghcr.io/globocodes/bostrat-node:${zo}`;ut=(e,{stdin:t,exec:n}={})=>new Promise((o,s)=>{if(n)return n(e,{stdin:t}).then(o,s);let c=Ho("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(u,f,g)=>u?s(Object.assign(u,{stdout:f,stderr:g})):o({stdout:f,stderr:g}));t!=null&&c.stdin?.end(t)})});function er(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!Go.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 Jo(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:er(s.from,"from",n),toMs:er(s.to,"to",n)}))}return t}var Yo,Go,bc,Ac,tr=v(()=>{Yo={"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-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-09-07",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-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)."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-09-07",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed)."}]},Go=/^\d{4}-\d{2}-\d{2}$/;bc=Jo(Yo),Ac=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var nr=v(()=>{tr()});import rr from"node:fs/promises";import ir from"node:path";import Xo from"node:os";function cr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function lr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function ur(e){let t=new Date(cr(e));return t.setDate(t.getDate()+7),t.getTime()}function dr(e){let t=new Date(lr(e));return t.setMonth(t.getMonth()+1),t.getTime()}function ns(e=Date.now()){for(let[t,n]of Object.entries(es)){let o=n.startOf(e);if(o!==dt[t]){dt[t]=o;for(let s of Ht.values())s[t]=0;for(let s of or)s.includes(`:${t}:`)&&!s.endsWith(`:${o}`)&&or.delete(s)}}}function rs(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 f=Number(u);if(!Number.isFinite(f)||f<=0)throw new Error(`${n}.${c} must be a positive number or null`);s[c]=f}Object.keys(s).length&&(t[n]=s)}return t}async function pr(e,{source:t="local",updatedAt:n=Date.now()}={}){ke={caps:rs(e),updatedAt:n,source:t};try{await rr.mkdir(ar,{recursive:!0}),await rr.writeFile(Zo(),JSON.stringify(ke,null,2))}catch{}return os()}function os(e=Date.now()){ns(e);let t=new Set([...Ht.keys(),...Object.keys(ke?.caps||{})]),n={};for(let o of t){let s=Ht.get(o);n[o]={weeklyUsd:sr(s?.weekly||0),monthlyUsd:sr(s?.monthly||0)}}return{caps:ke?.caps||{},configured:!!ke,seeded:ts,updatedAt:ke?.updatedAt??null,spent:n,windows:{weekly:{start:dt.weekly,resetsAt:ur(e)},monthly:{start:dt.monthly,resetsAt:dr(e)}},warnPct:Qo}}var ar,Zo,Qo,es,ke,ts,dt,Ht,or,sr,fr=v(()=>{at();nr();ar=process.env.BOSTRAT_STATE_DIR||ir.join(process.env.HOME||Xo.tmpdir(),".bostrat"),Zo=()=>ir.join(ar,"usage-caps.json"),Qo=.8;es={weekly:{startOf:cr,nextStart:ur,capKey:"weeklyUsd"},monthly:{startOf:lr,nextStart:dr,capKey:"monthlyUsd"}},ke=null,ts=!1,dt={weekly:0,monthly:0},Ht=new Map,or=new Set;sr=e=>Math.round(e*1e4)/1e4});var vr={};$t(vr,{REMOVED_MARKER:()=>qt,detectInstallKind:()=>Ee,detectProviderAuth:()=>_r,maskToken:()=>Vt,readRemovedMarker:()=>Tr,startPlaneLink:()=>gs,updateCommandFor:()=>qe,versionLt:()=>xe});import $e from"node:fs";import Ve from"node:fs/promises";import ss from"node:http";import L from"node:path";import pt from"node:os";import{createRequire as is}from"node:module";import Kt from"ws";function Vt(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function Tr(e=qt){try{let t=JSON.parse($e.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function Ee({env:e=process.env,pkgDir:t=L.resolve(L.dirname(new URL(import.meta.url).pathname),".."),exists:n=$e.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(L.join(t,"..",".git"))?"git-checkout":"dev"}function xe(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 qe(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 _r({home:e=process.env.HOME||pt.homedir(),env:t=process.env}={}){let n=o=>{try{return $e.statSync(o),!0}catch{return!1}};return{claude:n(L.join(e,".claude",".credentials.json")),codex:n(L.join(t.CODEX_HOME||L.join(e,".codex"),"auth.json")),cursor:n(L.join(t.XDG_CONFIG_HOME||L.join(e,".config"),"cursor","auth.json"))}}function gs({url:e,token:t,nodeId:n=pt.hostname(),name:o=pt.hostname(),listTracks:s,detectAgents:c=null,onTracksTransferred:u=null,sampleMetrics:f=null,deliverySample:g=null,onHashKey:T=null,onViewBase:p=null,metricsMs:h=ys,onUpdateAvailable:D=null,onUpdatePolicy:A=null,onHelloRefused:k=null,updatePolicy:_=null,installKind:I=Ee(),selfUrl:j=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:K=null,removedMarkerFile:M=qt,onRemoved:b=null,onDegraded:V=null,onRecovered:Te=null,onConnected:Ye=null,ingestMode:Ne=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:en=fs,unackedRetryMs:Ge=ps,pingMs:Dr=ds,maxInflightEvents:Br=ms,httpTimeoutMs:Je=ws,stallBackoffMinMs:tn=hs,fetchImpl:nn=globalThis.fetch,log:w=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=je(e);let Lr=j.replace(/^http/,"ws"),rn=new Set,le=new Map,ue=new Map,wt=L.join(zt,"plane-link","cursor.json"),yt=L.join(zt,"plane-link","dead-letter.ndjson"),on=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),de={},ne={},$=new Map,Xe=null,re=null,Q=0,Ie=0,sn=0,an=Promise.resolve(),E="ws",_e=0,q=!1,pe=0,gt=!1,W=ie,Se=new Set,oe=[],F=null,X=null,Y=!1,Tt=!1,Me=hr,Pe=null,ve=null,be=null,ee=null,te=null,_t=!1,Ze=0,De=!1,se=Tr(M);if(se)if(se.tokenPreview===Vt(t))De=!0,Nt({reason:se.reason??"removed",at:se.at??null,nodeId:se.nodeId??n}),w.error(`[plane-link] this node was REMOVED from the plane (${se.reason??"removed"}${se.at?` at ${new Date(se.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${M} to force a dial.`);else try{$e.unlinkSync(M),w.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function St({reason:i="removed",at:l=Date.now(),via:r="ctl"}={}){if(!De){De=!0,Nt({reason:i,at:l,nodeId:n,via:r});try{$e.mkdirSync(L.dirname(M),{recursive:!0}),$e.writeFileSync(M,JSON.stringify({at:l,reason:i,via:r,nodeId:n,tokenPreview:Vt(t)},null,2))}catch(a){w.error(`[plane-link] could not write ${M}: ${a?.message||a}`)}w.error(`[plane-link] the plane REMOVED this node (${i}, via ${r}) \u2014 going dormant: no more dials, ingest or broker calls. Re-provision with a new node token to reconnect; the box and its data are untouched.`);try{b?.({reason:i,at:l,via:r})}catch{}wn({bye:!1})}}async function Cr(){try{de=JSON.parse(await Ve.readFile(wt,"utf8"))}catch{de={}}}function jr(){_t=!0,!be&&(be=setTimeout(async()=>{if(be=null,!!_t){_t=!1;try{await Ve.mkdir(L.dirname(wt),{recursive:!0}),await Ve.writeFile(wt,JSON.stringify(de))}catch(i){w.error("[plane-link] cursor flush failed:",i?.message||i)}}},us),be.unref?.())}function O(i){return!X||X.readyState!==Kt.OPEN?!1:(X.send(JSON.stringify(i)),!0)}function Be(i){let l=Date.now();for(let{trackId:r,event:a}of i){let d=$.get(a.id);$.set(a.id,{trackId:r,seq:a.seq,event:a,sentAt:l,firstSentAt:d?.firstSentAt??l,retryAt:l+Ge,tries:(d?.tries??0)+1,nacks:d?.nacks??0})}return E==="http"?(Kr(i),!0):O({v:R,ch:"events",type:"append",events:i})}function Fr(i){let l=null;for(let r of $.values())r.trackId===i&&(l==null||r.seq<l)&&(l=r.seq);return l}function vt(i){let l=ne[i];if(l==null)return;let r=Fr(i),a=r==null?l:Math.min(l,r-1);a>(de[i]??0)&&(de[i]=a,jr())}function Le(){if(Xe=Date.now(),re!=null){let i=Date.now()-re;w.log(`[plane-link] spine sync recovered after ${Math.round(i/1e3)}s degraded (${Q} stall redial(s))`);let l=re;re=null,Q=0,Ie=0,q=!1,pe=0;try{Te?.({since:l,downMs:i})}catch(r){w.error(`[plane-link] onRecovered failed: ${r?.message||r}`)}}}function bt(i){if(!Array.isArray(i)||!i.length)return;let l=new Set;for(let r of i){let a=$.get(r);a&&($.delete(r),(ne[a.trackId]??0)<a.seq&&(ne[a.trackId]=a.seq),l.add(a.trackId))}for(let r of l)vt(r);Le()}function cn(i,l){sn++;let r={at:Date.now(),trackId:i.trackId,seq:i.seq,id:i.event?.id??null,type:i.event?.type??null,reason:l,event:i.event??null};w.error(`[plane-link] DEAD-LETTER ${i.trackId} seq ${i.seq} (${r.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${yt}`),an=an.then(async()=>{await Ve.mkdir(L.dirname(yt),{recursive:!0}),await Ve.appendFile(yt,JSON.stringify(r)+`
|
|
116
|
-
`)}).catch(a=>w.error(`[plane-link] dead-letter write failed: ${a?.message||a}`))}function ln(i,l,r,a=null){if(!Array.isArray(i)||!i.length)return;let d=new Set,m=Date.now();for(let y of i){let S=$.get(y);S&&(r?($.delete(y),cn(S,l),(ne[S.trackId]??0)<S.seq&&(ne[S.trackId]=S.seq),d.add(S.trackId)):(S.nacks++,S.retryAt=m+Math.max(1e3,Number(a)||Ge)))}for(let y of d)vt(y);Le()}function un(i=Date.now()){let l=1/0;for(let r of $.values())r.firstSentAt<l&&(l=r.firstSentAt);return l===1/0?0:i-l}function dn(){if(!Y||!$.size)return;let i=Date.now(),l=un(i);if(l<en||Xe!=null&&i-Xe<en||E==="http"&&q||Ie>i)return;Q++;let r=Math.min(tn*2**(Q-1),wr);if(re==null){re=i-l,w.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${$.size} event(s) in flight (${E} door) \u2014 the plane is not answering appends`);try{V?.({since:re,unacked:$.size,oldestAgeMs:l,mode:E})}catch(a){w.error(`[plane-link] onDegraded failed: ${a?.message||a}`)}}if(E==="http"){q=!0,pe=i+r,w.error(`[plane-link] ingest circuit OPEN (stall #${Q}); probing /v1/ingest/health in ${Math.round(r/1e3)}s`);return}Ie=i+r,w.error(`[plane-link] closing the link and redialing in ${Math.round(r/1e3)}s (stall redial #${Q})`);try{X?.terminate()}catch{}}function At(){if(!Y)return;let i=Date.now();if(E==="http"&&q)return;let l=[...$.values()].filter(a=>a.event&&a.retryAt<=i&&!(E==="http"&&Se.has(a.trackId)));if(!l.length)return;l.sort((a,d)=>a.trackId===d.trackId?a.seq-d.seq:a.trackId<d.trackId?-1:1),w.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let r=E==="http"?W:ie;if(E==="http"){let a=new Map;for(let d of l)(a.get(d.trackId)??a.set(d.trackId,[]).get(d.trackId)).push(d);for(let[,d]of a){if(_e>=Wt)return;Be(d.slice(0,r).map(m=>({trackId:m.trackId,event:m.event})))}return}for(let a=0;a<l.length;a+=r){let d=l.slice(a,a+r).map(m=>({trackId:m.trackId,event:m.event}));if(!Be(d))return}}async function Ur(i=null){for(;;){if(!Y)return!1;let l=$.size<Br,r=E!=="http"||_e<Wt&&!q&&(!i||!Se.has(i));if(l&&r)return!0;await new Promise(a=>setTimeout(a,100))}}function kt(){if(F=null,!Y||!oe.length)return;let i=oe;if(oe=[],E!=="http"){for(let r=0;r<i.length;r+=ie)Be(i.slice(r,r+ie));return}let l=new Map;for(let r of i)(l.get(r.trackId)??l.set(r.trackId,[]).get(r.trackId)).push(r);for(let[r,a]of l){if(Se.has(r)||_e>=Wt||q){oe.push(...a);continue}for(let d=0;d<a.length;d+=W)Be(a.slice(d,d+W))}oe.length&&!F&&(F=setTimeout(kt,yr),F.unref?.())}let Hr=i=>{let l=new Map;for(let{trackId:r,event:a}of i)(l.get(r)??l.set(r,[]).get(r)).push(a);return[...l].map(([r,a])=>({trackId:r,events:a}))},fe=(i,l,r,{progress:a})=>{let d=Date.now();for(let{event:m}of i){let y=$.get(m.id);y&&(y.nacks++,y.retryAt=d+Math.max(1e3,r||Ge))}a&&Le()};async function Kr(i){let l=new Set(i.map(r=>r.trackId));for(let r of l)Se.add(r);_e++;try{let r=await nn(`${on}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:Hr(i)}),signal:AbortSignal.timeout(Je)}),a=(Number(r.headers.get("retry-after"))||0)*1e3;if(r.status===200){let d=await r.json();W=ie;for(let m of d.results??[]){bt(m.acked??[]);let y=(S,C)=>{let z=new Map;for(let x of S??[])(z.get(x.reason)??z.set(x.reason,[]).get(x.reason)).push(x.id);for(let[x,yn]of z)ln(yn,x,C,d.retryAfterMs??null)};y(m.rejected,!0),y(m.deferred,!1)}bt(d.discarded??[]),Le();return}if(r.status===429){fe(i,"overloaded",a||5e3,{progress:!0});return}if(r.status===413&&i.length>1){W=Math.max(1,Math.floor(i.length/2)),w.error(`[plane-link] ingest request too large (${i.length} events) \u2014 halving batches to ${W}`),fe(i,"too_large",1e3,{progress:!0});return}if(r.status===413){let d=$.get(i[0].event.id);d&&($.delete(d.event.id),cn(d,"too_large"),(ne[d.trackId]??0)<d.seq&&(ne[d.trackId]=d.seq),vt(d.trackId)),Le();return}if(r.status===410){St({reason:"removed",via:"410"}),fe(i,"http_410",6e4,{progress:!1});return}if(r.status===401||r.status===403){let{tripped:d,holdMs:m}=st();if(d&&w.error(`[plane-link] holding every plane call for ${Math.round(m/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Ze>=gr){Ze=Date.now();let y="";try{y=(await r.json())?.error??""}catch{}w.error(`[plane-link] plane refused ingest (HTTP ${r.status}${y?`: ${y}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}fe(i,`http_${r.status}`,Math.max(6e4,He()),{progress:!1});return}if(r.status===400){w.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${i.length} event(s) for retry; this is a bug, not data`),fe(i,"http_400",6e4,{progress:!1});return}fe(i,`http_${r.status}`,a||5e3,{progress:!1})}catch(r){let a=r?.name==="TimeoutError"||r?.name==="AbortError";a&&i.length>1&&(W=Math.max(1,Math.floor(i.length/2)),w.error(`[plane-link] ingest request of ${i.length} event(s) outlived its ${Je} ms deadline \u2014 halving batches to ${W}`)),fe(i,a?"timeout":"network",5e3,{progress:!1})}finally{_e--;for(let r of l)Se.delete(r)}}async function Wr(){if(E!=="http"||!q||!Y||gt)return;let i=Date.now();if(!(pe>i||it(i))){gt=!0;try{let l=await nn(`${on}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(Je)});if(!l.ok)throw new Error(`HTTP ${l.status}`);w.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),q=!1,pe=0,Ie=Date.now()+Je+Ge+1e3;for(let r of $.values())r.retryAt=Math.min(r.retryAt,Date.now());At()}catch(l){Q++;let r=Math.min(tn*2**(Q-1),wr);pe=Date.now()+r,w.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(r/1e3)}s`)}finally{gt=!1}}}function pn(){let i=Date.now();return{mode:E,unacked:$.size,oldestUnackedAgeMs:un(i),lastProgressAt:Xe,degradedSince:re,stallRedials:Q,deadLettered:sn,http:E==="http"?{inFlight:_e,circuitOpen:q,nextProbeInMs:q?Math.max(0,pe-i):0,batchCap:W}:null}}async function fn(){if(!f)return;let i;try{i=await f()}catch(r){w.error("[plane-link] metrics sample failed:",r?.message||r);return}let l=null;try{l=g?.()??null}catch{}i&&O({v:R,ch:"ctl",type:"metrics",metrics:{...i,planeLink:pn(),...l?{delivery:l}:{}}})}function zr(){f&&(te&&clearInterval(te),fn(),te=setInterval(fn,h),te.unref?.())}async function Vr(){let i;try{i=await s()}catch(l){w.error("[plane-link] backfill listTracks failed:",l?.message||l);return}O({v:R,ch:"ctl",type:"tracks",ids:i.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of i){if(!Y)return;let r;try{r=await Dt(l)}catch{continue}let a=de[l.id]??0,d=r.filter(y=>y.seq>a&&typeof y.id=="string"),m=E==="http"?W:ie;for(let y=0;y<d.length;y+=m){if(!await Ur(l.id))return;let S=d.slice(y,y+Math.min(m,E==="http"?W:ie)).map(C=>({trackId:l.id,event:C}));if(!Be(S))return}}}function hn(i){!Y||!i?.trackId||typeof i.id!="string"||(oe.push({trackId:i.trackId,event:i}),F||(F=setTimeout(kt,yr),F.unref?.()))}let Ce=new Map;async function qr(i){let{reqId:l,method:r,path:a,headers:d={},body:m}=i,y=Object.fromEntries(Object.entries(d).filter(([,C])=>C!=null)),S=new AbortController;Ce.set(l,S);try{if(i.host){await Yr(i,y,S);return}K&&(y["x-bostrat-token"]=K);let C=await fetch(j+a,{method:r,headers:y,body:m?Buffer.from(m,"base64"):void 0,signal:S.signal}),z=Object.fromEntries(C.headers);for(let x of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete z[x];if(z["content-type"]||(z["content-type"]="application/octet-stream"),O({v:R,ch:"control",type:"http_head",reqId:l,status:C.status,headers:z}),C.body){for await(let x of C.body)if(!O({v:R,ch:"control",type:"http_data",reqId:l,data:Buffer.from(x).toString("base64")}))break}O({v:R,ch:"control",type:"http_end",reqId:l,error:null})}finally{Ce.delete(l)}}function Yr(i,l,r){let{reqId:a,method:d,path:m,body:y}=i,S=new URL(j);return new Promise(C=>{let z=ss.request({host:S.hostname,port:S.port,method:d,path:m,headers:{...l,host:i.host},signal:r.signal},x=>{let{connection:yn,"keep-alive":ai,"transfer-encoding":ci,upgrade:li,...Gr}=x.headers;O({v:R,ch:"control",type:"http_head",reqId:a,status:x.statusCode||502,headers:Gr}),x.on("data",Jr=>{O({v:R,ch:"control",type:"http_data",reqId:a,data:Buffer.from(Jr).toString("base64")})||x.destroy()}),x.on("end",()=>{O({v:R,ch:"control",type:"http_end",reqId:a,error:null}),C()}),x.on("error",()=>{O({v:R,ch:"control",type:"http_end",reqId:a,error:"view upstream error"}),C()})});z.on("error",x=>{O({v:R,ch:"control",type:"http_end",reqId:a,error:x?.message||"view request failed"}),C()}),y&&z.write(Buffer.from(y,"base64")),z.end()})}function mn(){if(Tt||De)return;X=new Kt(e,{headers:{authorization:`Bearer ${t}`}}),X.on("open",async()=>{let l=null;try{l=await c?.()||null}catch{l=null}O({v:R,ch:"ctl",type:"hello",nodeId:n,name:o,platform:process.platform,version:G,installKind:I,...typeof _=="function"?{updatePolicy:_()}:_?{updatePolicy:_}:{},providers:_r(),...l?{agents:l}:{}})}),X.on("message",l=>{let r;try{r=JSON.parse(l)}catch{return}if(r.ch==="ctl"&&r.type==="hello_ok"){Y=!0,Me=hr,Pe=null,$n(),w.log(`[plane-link] connected to plane as ${n}`);try{Ye?.()}catch{}if(typeof r.hashKey=="string"&&r.hashKey)try{T?.(r.hashKey)}catch{}try{p?.(typeof r.viewBase=="string"&&r.viewBase?r.viewBase:null)}catch{}r.minNodeVersion&&G&&xe(G,r.minNodeVersion)&&w.error(`[plane-link] this node is bostrat-node ${G}; the plane asks for \u2265${r.minNodeVersion} \u2014 update with: ${qe(I)}`);try{A?.(typeof r.updatePolicy=="string"?r.updatePolicy:null)}catch{}let a=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;if(a&&G&&xe(G,a)&&!rn.has(a)){rn.add(a),w.log(`[plane-link] bostrat-node ${a} is available (this node runs ${G}) \u2014 ${qe(I)}`);try{D?.({current:G,latest:a,min:r.minNodeVersion??null,installKind:I,required:!!(r.minNodeVersion&&xe(G,r.minNodeVersion))})}catch(m){w.error(`[plane-link] update notice failed: ${m?.message||m}`)}}let d=r.ingest==="http";E=Ne==="ws"?"ws":Ne==="http"||d?"http":"ws",Ne==="http"&&!d&&w.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),E==="http"&&w.log("[plane-link] spine rides the HTTPS ingest door"),q=!1,pe=0,W=ie,ee&&clearInterval(ee),ee=setInterval(()=>{O({v:R,ch:"ctl",type:"ping"}),dn(),Wr().catch(()=>{}),At(),oe.length&&!F&&kt()},Dr),ee.unref?.(),zr(),Vr().catch(m=>w.error("[plane-link] backfill failed:",m?.message||m));return}if(r.ch==="ctl"&&r.type==="hello_refused"){let a=typeof r.minNodeVersion=="string"?r.minNodeVersion:null,d=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;w.error(`[plane-link] plane REFUSED this node: bostrat-node ${G??"?"} is below its minimum ${a??"?"} \u2014 ${r.fix||qe(I)}`),Me=mr,Pe=0;try{k?.({current:G,min:a,latest:d,fix:r.fix||qe(I),installKind:I})}catch(m){w.error(`[plane-link] refusal handler failed: ${m?.message||m}`)}return}if(r.ch==="ctl"&&r.type==="removed"){O({v:R,ch:"ctl",type:"removed_ack",nodeId:n}),St({reason:typeof r.reason=="string"?r.reason:"removed",at:Number(r.at)||Date.now(),via:"ctl"});return}if(r.ch==="ctl"&&r.type==="update_policy"){try{A?.(typeof r.mode=="string"?r.mode:null)}catch{}return}if(r.ch==="ctl"&&r.type==="usage_caps"){pr(r.caps??{},{source:"plane",updatedAt:r.updatedAt??Date.now()}).then(a=>w.log(`[plane-link] spend caps ${Object.keys(a.caps).length?`updated (${Object.keys(a.caps).join(", ")})`:"cleared"} from plane`)).catch(a=>w.error("[plane-link] spend-caps push rejected:",a?.message||a));return}if(r.ch==="ctl"&&r.type==="transferred"&&Array.isArray(r.tracks)){Promise.resolve().then(()=>u?.(r.tracks)).catch(a=>w.error("[plane-link] transfer notice failed:",a?.message||a));return}if(r.ch==="events"&&r.type==="ack"&&Array.isArray(r.ids)){bt(r.ids);return}if(r.ch==="events"&&r.type==="nack"&&Array.isArray(r.ids)){ln(r.ids,r.reason,r.permanent===!0,r.retryAfterMs??null);return}if(r.ch==="control"&&r.type==="http_open"){qr(r).catch(a=>O({v:R,ch:"control",type:"http_end",reqId:r.reqId,error:a?.message||"tunnel error"}));return}if(r.ch==="control"&&r.type==="http_cancel"){Ce.get(r.reqId)?.abort();return}if(r.ch==="attach"&&r.type==="open"){let a=new Kt(Lr+r.path,Array.isArray(r.protocols)?r.protocols:[],r.host?{headers:{host:r.host}}:void 0);le.set(r.streamId,a),ue.set(r.streamId,[]),a.on("open",()=>{let m=ue.get(r.streamId)||[];ue.delete(r.streamId);for(let{buf:y,bin:S}of m)a.send(y,{binary:S})}),a.on("message",(m,y)=>{let S=y?m:Buffer.from(String(m));O({v:R,ch:"attach",type:"data",streamId:r.streamId,data:S.toString("base64"),...y?{bin:!0}:{}})});let d=()=>{ue.delete(r.streamId),le.delete(r.streamId)&&O({v:R,ch:"attach",type:"close",streamId:r.streamId})};a.on("close",d),a.on("error",d);return}if(r.ch==="attach"&&r.type==="data"){let a=le.get(r.streamId);if(!a)return;let d=Buffer.from(r.data,"base64"),m=r.bin===!0,y=ue.get(r.streamId);y?y.push({buf:d,bin:m}):a.send(d,{binary:m});return}if(r.ch==="attach"&&r.type==="close"){let a=le.get(r.streamId);le.delete(r.streamId),ue.delete(r.streamId),a?.close();return}});let i=()=>{Y&&w.log("[plane-link] disconnected from plane"),Y=!1,ee&&(clearInterval(ee),ee=null),te&&(clearInterval(te),te=null),$.clear(),ne={},oe=[],F&&(clearTimeout(F),F=null),Se.clear();for(let a of le.values())a.close();le.clear(),ue.clear();for(let a of Ce.values())a.abort();if(Ce.clear(),Tt||ve)return;Pe==null&&(Pe=Date.now());let l=Date.now()-Pe<as,r=Math.max(l?cs+Math.random()*ls:Me,Ie-Date.now(),He());ve=setTimeout(()=>{ve=null,mn()},r),ve.unref?.(),l||(Me=Math.min(Me*2,mr))};X.on("close",i),X.on("error",l=>{let r=/Unexpected server response: (\d+)/.exec(l?.message||"")?.[1];if(r==="410"){St({reason:"removed",via:"410"});return}if(r==="401"||r==="403"){let{tripped:a,holdMs:d}=st();a?w.error(`[plane-link] holding every plane call for ${Math.round(d/6e4)} min \u2014 three credential refusals in a row (HTTP ${r}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(d/6e4)} min.`):Date.now()-Ze>=gr&&(Ze=Date.now(),w.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)`))}i()})}We.on("event",hn),Cr().then(mn);function wn({bye:i=!0}={}){Tt=!0,We.off("event",hn),ve&&clearTimeout(ve),be&&clearTimeout(be),ee&&clearInterval(ee),te&&clearInterval(te),F&&clearTimeout(F),i&&O({v:R,ch:"ctl",type:"bye",reason:"shutdown"}),X?.close()}return{stop:()=>wn(),status:()=>({connected:Y,nodeId:n,cursor:{...de},inflight:$.size,...pn(),auth:xn(),dormant:De,removed:It()}),_tick:()=>{dn(),At()}}}var G,zt,qt,R,hr,mr,as,cs,ls,ie,us,ds,ps,Sr,fs,hs,wr,ms,yr,ws,Wt,ys,gr,Yt=v(()=>{at();fr();Ot();Mt();G=(()=>{try{return is(import.meta.url)("../package.json").version||null}catch{return null}})(),zt=process.env.BOSTRAT_STATE_DIR||L.join(process.env.HOME||pt.tmpdir(),".bostrat"),qt=L.join(zt,"plane-link","removed.json");R=1,hr=1e3,mr=3e4,as=6e4,cs=1500,ls=500,ie=100,us=2e3,ds=25e3,ps=6e4,Sr=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},fs=Sr(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),hs=3e4,wr=10*6e4,ms=400,yr=250,ws=Sr(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Wt=4,ys=6e4,gr=6e4});import{execFile as Ts}from"node:child_process";import{promisify as _s}from"node:util";function br(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Xc,Zc,Qc,Ar=v(()=>{Bt();Xc=_s(Ts),Zc=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Qc=Promise.resolve()});var Or={};$t(Or,{ACTIONABLE_KINDS:()=>mt,SELF_UPDATE_DIR:()=>Gt,createAutoUpdater:()=>Ms,inFlight:()=>Xt,readStatus:()=>Jt,selfUpdatePlan:()=>xr,settleSelfUpdate:()=>Is,startSelfUpdate:()=>Er,underService:()=>$r,updatePolicy:()=>xs});import kr from"node:fs";import ae from"node:fs/promises";import Ss from"node:os";import P from"node:path";import{spawn as vs}from"node:child_process";import{createRequire as bs}from"node:module";function xs({kind:e=Ee(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:mt.has(e)?e==="git-checkout"||$r(t)?"auto":"prompt":"off"}function $r(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function xr({kind:e,to:t,from:n=ft,statusFile:o=ht,logFile:s=P.join(Gt,"last.log"),port:c=Number(process.env.PORT)||3362,npmPrefix:u=null,serviceName:f=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:g=typeof process.getuid=="function"?process.getuid():0,liveDir:T=process.env.BOSTRAT_LIVE_CHECKOUT||P.resolve(P.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:p=Date.now()}={}){if(!mt.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 h=(I,j="")=>`write_status ${U(I)} ${j}`,D=process.platform==="darwin"?`launchctl kickstart -k gui/${g}/${f}`:`systemctl --user restart ${U(f)}`,A=`
|
|
115
|
+
`),g(0)}var Xn,Yo,Kt,dt,rr=v(()=>{Xn="wss://plane.bostrat.ai/v1/node",Yo=qo(import.meta.url)("../package.json").version,Kt=`ghcr.io/globocodes/bostrat-node:${Yo}`;dt=(e,{stdin:t,exec:n}={})=>new Promise((r,s)=>{if(n)return n(e,{stdin:t}).then(r,s);let c=Vo("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(u,h,g)=>u?s(Object.assign(u,{stdout:h,stderr:g})):r({stdout:h,stderr:g}));t!=null&&c.stdin?.end(t)})});function or(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!Qo.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let r=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(r))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return r}function es(e){let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||r.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=r.map(s=>({...s,fromMs:or(s.from,"from",n),toMs:or(s.to,"to",n)}))}return t}var Zo,Qo,Ec,Oc,sr=v(()=>{Zo={"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-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-09-07",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-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)."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-09-07",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed)."}]},Qo=/^\d{4}-\d{2}-\d{2}$/;Ec=es(Zo),Oc=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var ir=v(()=>{sr()});import ar from"node:fs/promises";import ur from"node:path";import ts from"node:os";function pr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function fr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function hr(e){let t=new Date(pr(e));return t.setDate(t.getDate()+7),t.getTime()}function mr(e){let t=new Date(fr(e));return t.setMonth(t.getMonth()+1),t.getTime()}function is(e=Date.now()){for(let[t,n]of Object.entries(os)){let r=n.startOf(e);if(r!==pt[t]){pt[t]=r;for(let s of Wt.values())s[t]=0;for(let s of cr)s.includes(`:${t}:`)&&!s.endsWith(`:${r}`)&&cr.delete(s)}}}function as(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let s={};for(let c of["weeklyUsd","monthlyUsd"]){let u=r?.[c];if(u==null||u==="")continue;let h=Number(u);if(!Number.isFinite(h)||h<=0)throw new Error(`${n}.${c} must be a positive number or null`);s[c]=h}Object.keys(s).length&&(t[n]=s)}return t}async function wr(e,{source:t="local",updatedAt:n=Date.now()}={}){$e={caps:as(e),updatedAt:n,source:t};try{await ar.mkdir(dr,{recursive:!0}),await ar.writeFile(ns(),JSON.stringify($e,null,2))}catch{}return cs()}function cs(e=Date.now()){is(e);let t=new Set([...Wt.keys(),...Object.keys($e?.caps||{})]),n={};for(let r of t){let s=Wt.get(r);n[r]={weeklyUsd:lr(s?.weekly||0),monthlyUsd:lr(s?.monthly||0)}}return{caps:$e?.caps||{},configured:!!$e,seeded:ss,updatedAt:$e?.updatedAt??null,spent:n,windows:{weekly:{start:pt.weekly,resetsAt:hr(e)},monthly:{start:pt.monthly,resetsAt:mr(e)}},warnPct:rs}}var dr,ns,rs,os,$e,ss,pt,Wt,cr,lr,yr=v(()=>{ct();ir();dr=process.env.BOSTRAT_STATE_DIR||ur.join(process.env.HOME||ts.tmpdir(),".bostrat"),ns=()=>ur.join(dr,"usage-caps.json"),rs=.8;os={weekly:{startOf:pr,nextStart:hr,capKey:"weeklyUsd"},monthly:{startOf:fr,nextStart:mr,capKey:"monthlyUsd"}},$e=null,ss=!1,pt={weekly:0,monthly:0},Wt=new Map,cr=new Set;lr=e=>Math.round(e*1e4)/1e4});var $r={};Et($r,{REMOVED_MARKER:()=>Yt,detectInstallKind:()=>Oe,detectProviderAuth:()=>Ar,maskToken:()=>Gt,readRemovedMarker:()=>br,startPlaneLink:()=>bs,updateCommandFor:()=>Ge,versionLt:()=>Ee});import xe from"node:fs";import qe from"node:fs/promises";import ls from"node:http";import C from"node:path";import ft from"node:os";import{createRequire as us}from"node:module";import zt from"ws";function Gt(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function br(e=Yt){try{let t=JSON.parse(xe.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function Oe({env:e=process.env,pkgDir:t=C.resolve(C.dirname(new URL(import.meta.url).pathname),".."),exists:n=xe.existsSync}={}){let r=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(r)?r:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(C.join(t,"..",".git"))?"git-checkout":"dev"}function Ee(e,t){let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let s=0;s<Math.max(n.length,r.length);s++){let c=(n[s]||0)-(r[s]||0);if(c)return c<0}return!1}function Ge(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 Ar({home:e=process.env.HOME||ft.homedir(),env:t=process.env}={}){let n=r=>{try{return xe.statSync(r),!0}catch{return!1}};return{claude:n(C.join(e,".claude",".credentials.json")),codex:n(C.join(t.CODEX_HOME||C.join(e,".codex"),"auth.json")),cursor:n(C.join(t.XDG_CONFIG_HOME||C.join(e,".config"),"cursor","auth.json"))}}function bs({url:e,token:t,nodeId:n=ft.hostname(),name:r=ft.hostname(),listTracks:s,detectAgents:c=null,onTracksTransferred:u=null,sampleMetrics:h=null,deliverySample:g=null,onHashKey:T=null,onViewBase:p=null,metricsMs:m=vs,onUpdateAvailable:B=null,onUpdatePolicy:A=null,onHelloRefused:k=null,updatePolicy:S=null,installKind:M=Oe(),selfUrl:j=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:K=null,removedMarkerFile:P=Yt,onRemoved:b=null,onDegraded:q=null,onRecovered:_e=null,onConnected:Ye=null,ingestMode:Ie=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:nn=gs,unackedRetryMs:Je=ys,pingMs:rn=ms,deadLinkMs:yt=Math.round(rn*ws),maxInflightEvents:jr=_s,httpTimeoutMs:Xe=Ss,stallBackoffMinMs:on=Ts,fetchImpl:sn=globalThis.fetch,log:w=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=Fe(e);let Fr=j.replace(/^http/,"ws"),an=new Set,le=new Map,ue=new Map,gt=C.join(qt,"plane-link","cursor.json"),Tt=C.join(qt,"plane-link","dead-letter.ndjson"),cn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),de={},ne={},$=new Map,Ze=null,re=null,Q=0,Me=0,ln=0,un=Promise.resolve(),E="ws",Se=0,G=!1,pe=0,_t=!1,W=ie,ve=new Set,oe=[],F=null,z=null,Y=!1,St=!1,Pe=gr,De=null,be=null,Ae=null,ee=null,fe=0,dn=0,te=null,vt=!1,Qe=0,Be=!1,se=br(P);if(se)if(se.tokenPreview===Gt(t))Be=!0,Mt({reason:se.reason??"removed",at:se.at??null,nodeId:se.nodeId??n}),w.error(`[plane-link] this node was REMOVED from the plane (${se.reason??"removed"}${se.at?` at ${new Date(se.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${P} to force a dial.`);else try{xe.unlinkSync(P),w.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function bt({reason:i="removed",at:l=Date.now(),via:a="ctl"}={}){if(!Be){Be=!0,Mt({reason:i,at:l,nodeId:n,via:a});try{xe.mkdirSync(C.dirname(P),{recursive:!0}),xe.writeFileSync(P,JSON.stringify({at:l,reason:i,via:a,nodeId:n,tokenPreview:Gt(t)},null,2))}catch(o){w.error(`[plane-link] could not write ${P}: ${o?.message||o}`)}w.error(`[plane-link] the plane REMOVED this node (${i}, via ${a}) \u2014 going dormant: no more dials, ingest or broker calls. Re-provision with a new node token to reconnect; the box and its data are untouched.`);try{b?.({reason:i,at:l,via:a})}catch{}_n({bye:!1})}}async function Ur(){try{de=JSON.parse(await qe.readFile(gt,"utf8"))}catch{de={}}}function Hr(){vt=!0,!Ae&&(Ae=setTimeout(async()=>{if(Ae=null,!!vt){vt=!1;try{await qe.mkdir(C.dirname(gt),{recursive:!0}),await qe.writeFile(gt,JSON.stringify(de))}catch(i){w.error("[plane-link] cursor flush failed:",i?.message||i)}}},hs),Ae.unref?.())}function O(i){return!z||z.readyState!==zt.OPEN?!1:(z.send(JSON.stringify(i)),!0)}function Le(i){let l=Date.now();for(let{trackId:a,event:o}of i){let d=$.get(o.id);$.set(o.id,{trackId:a,seq:o.seq,event:o,sentAt:l,firstSentAt:d?.firstSentAt??l,retryAt:l+Je,tries:(d?.tries??0)+1,nacks:d?.nacks??0})}return E==="http"?(qr(i),!0):O({v:N,ch:"events",type:"append",events:i})}function Kr(i){let l=null;for(let a of $.values())a.trackId===i&&(l==null||a.seq<l)&&(l=a.seq);return l}function At(i){let l=ne[i];if(l==null)return;let a=Kr(i),o=a==null?l:Math.min(l,a-1);o>(de[i]??0)&&(de[i]=o,Hr())}function Ce(){if(Ze=Date.now(),re!=null){let i=Date.now()-re;w.log(`[plane-link] spine sync recovered after ${Math.round(i/1e3)}s degraded (${Q} stall redial(s))`);let l=re;re=null,Q=0,Me=0,G=!1,pe=0;try{_e?.({since:l,downMs:i})}catch(a){w.error(`[plane-link] onRecovered failed: ${a?.message||a}`)}}}function kt(i){if(!Array.isArray(i)||!i.length)return;let l=new Set;for(let a of i){let o=$.get(a);o&&($.delete(a),(ne[o.trackId]??0)<o.seq&&(ne[o.trackId]=o.seq),l.add(o.trackId))}for(let a of l)At(a);Ce()}function pn(i,l){ln++;let a={at:Date.now(),trackId:i.trackId,seq:i.seq,id:i.event?.id??null,type:i.event?.type??null,reason:l,event:i.event??null};w.error(`[plane-link] DEAD-LETTER ${i.trackId} seq ${i.seq} (${a.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${Tt}`),un=un.then(async()=>{await qe.mkdir(C.dirname(Tt),{recursive:!0}),await qe.appendFile(Tt,JSON.stringify(a)+`
|
|
116
|
+
`)}).catch(o=>w.error(`[plane-link] dead-letter write failed: ${o?.message||o}`))}function fn(i,l,a,o=null){if(!Array.isArray(i)||!i.length)return;let d=new Set,y=Date.now();for(let f of i){let _=$.get(f);_&&(a?($.delete(f),pn(_,l),(ne[_.trackId]??0)<_.seq&&(ne[_.trackId]=_.seq),d.add(_.trackId)):(_.nacks++,_.retryAt=y+Math.max(1e3,Number(o)||Je)))}for(let f of d)At(f);Ce()}function hn(i=Date.now()){let l=1/0;for(let a of $.values())a.firstSentAt<l&&(l=a.firstSentAt);return l===1/0?0:i-l}function Wr(i){if(!yt||!i||i!==z||!fe)return!1;let l=Date.now()-fe;if(l<=yt)return!1;dn++,w.error(`[plane-link] no frame from the plane for ${Math.round(l/1e3)}s \u2014 link is half-open; terminating and redialing`);try{i.terminate()}catch{}return!0}function mn(){if(!Y||!$.size)return;let i=Date.now(),l=hn(i);if(l<nn||Ze!=null&&i-Ze<nn||E==="http"&&G||Me>i)return;Q++;let a=Math.min(on*2**(Q-1),_r);if(re==null){re=i-l,w.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${$.size} event(s) in flight (${E} door) \u2014 the plane is not answering appends`);try{q?.({since:re,unacked:$.size,oldestAgeMs:l,mode:E})}catch(o){w.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(E==="http"){G=!0,pe=i+a,w.error(`[plane-link] ingest circuit OPEN (stall #${Q}); probing /v1/ingest/health in ${Math.round(a/1e3)}s`);return}Me=i+a,w.error(`[plane-link] closing the link and redialing in ${Math.round(a/1e3)}s (stall redial #${Q})`);try{z?.terminate()}catch{}}function $t(){if(!Y)return;let i=Date.now();if(E==="http"&&G)return;let l=[...$.values()].filter(o=>o.event&&o.retryAt<=i&&!(E==="http"&&ve.has(o.trackId)));if(!l.length)return;l.sort((o,d)=>o.trackId===d.trackId?o.seq-d.seq:o.trackId<d.trackId?-1:1),w.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let a=E==="http"?W:ie;if(E==="http"){let o=new Map;for(let d of l)(o.get(d.trackId)??o.set(d.trackId,[]).get(d.trackId)).push(d);for(let[,d]of o){if(Se>=Vt)return;Le(d.slice(0,a).map(y=>({trackId:y.trackId,event:y.event})))}return}for(let o=0;o<l.length;o+=a){let d=l.slice(o,o+a).map(y=>({trackId:y.trackId,event:y.event}));if(!Le(d))return}}async function zr(i=null){for(;;){if(!Y)return!1;let l=$.size<jr,a=E!=="http"||Se<Vt&&!G&&(!i||!ve.has(i));if(l&&a)return!0;await new Promise(o=>setTimeout(o,100))}}function xt(){if(F=null,!Y||!oe.length)return;let i=oe;if(oe=[],E!=="http"){for(let a=0;a<i.length;a+=ie)Le(i.slice(a,a+ie));return}let l=new Map;for(let a of i)(l.get(a.trackId)??l.set(a.trackId,[]).get(a.trackId)).push(a);for(let[a,o]of l){if(ve.has(a)||Se>=Vt||G){oe.push(...o);continue}for(let d=0;d<o.length;d+=W)Le(o.slice(d,d+W))}oe.length&&!F&&(F=setTimeout(xt,Sr),F.unref?.())}let Vr=i=>{let l=new Map;for(let{trackId:a,event:o}of i)(l.get(a)??l.set(a,[]).get(a)).push(o);return[...l].map(([a,o])=>({trackId:a,events:o}))},he=(i,l,a,{progress:o})=>{let d=Date.now();for(let{event:y}of i){let f=$.get(y.id);f&&(f.nacks++,f.retryAt=d+Math.max(1e3,a||Je))}o&&Ce()};async function qr(i){let l=new Set(i.map(a=>a.trackId));for(let a of l)ve.add(a);Se++;try{let a=await sn(`${cn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:Vr(i)}),signal:AbortSignal.timeout(Xe)}),o=(Number(a.headers.get("retry-after"))||0)*1e3;if(a.status===200){let d=await a.json();W=ie;for(let y of d.results??[]){kt(y.acked??[]);let f=(_,R)=>{let V=new Map;for(let x of _??[])(V.get(x.reason)??V.set(x.reason,[]).get(x.reason)).push(x.id);for(let[x,Sn]of V)fn(Sn,x,R,d.retryAfterMs??null)};f(y.rejected,!0),f(y.deferred,!1)}kt(d.discarded??[]),Ce();return}if(a.status===429){he(i,"overloaded",o||5e3,{progress:!0});return}if(a.status===413&&i.length>1){W=Math.max(1,Math.floor(i.length/2)),w.error(`[plane-link] ingest request too large (${i.length} events) \u2014 halving batches to ${W}`),he(i,"too_large",1e3,{progress:!0});return}if(a.status===413){let d=$.get(i[0].event.id);d&&($.delete(d.event.id),pn(d,"too_large"),(ne[d.trackId]??0)<d.seq&&(ne[d.trackId]=d.seq),At(d.trackId)),Ce();return}if(a.status===410){bt({reason:"removed",via:"410"}),he(i,"http_410",6e4,{progress:!1});return}if(a.status===401||a.status===403){let{tripped:d,holdMs:y}=it();if(d&&w.error(`[plane-link] holding every plane call for ${Math.round(y/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Qe>=vr){Qe=Date.now();let f="";try{f=(await a.json())?.error??""}catch{}w.error(`[plane-link] plane refused ingest (HTTP ${a.status}${f?`: ${f}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}he(i,`http_${a.status}`,Math.max(6e4,Ke()),{progress:!1});return}if(a.status===400){w.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${i.length} event(s) for retry; this is a bug, not data`),he(i,"http_400",6e4,{progress:!1});return}he(i,`http_${a.status}`,o||5e3,{progress:!1})}catch(a){let o=a?.name==="TimeoutError"||a?.name==="AbortError";o&&i.length>1&&(W=Math.max(1,Math.floor(i.length/2)),w.error(`[plane-link] ingest request of ${i.length} event(s) outlived its ${Xe} ms deadline \u2014 halving batches to ${W}`)),he(i,o?"timeout":"network",5e3,{progress:!1})}finally{Se--;for(let a of l)ve.delete(a)}}async function Gr(){if(E!=="http"||!G||!Y||_t)return;let i=Date.now();if(!(pe>i||at(i))){_t=!0;try{let l=await sn(`${cn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(Xe)});if(!l.ok)throw new Error(`HTTP ${l.status}`);w.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),G=!1,pe=0,Me=Date.now()+Xe+Je+1e3;for(let a of $.values())a.retryAt=Math.min(a.retryAt,Date.now());$t()}catch(l){Q++;let a=Math.min(on*2**(Q-1),_r);pe=Date.now()+a,w.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(a/1e3)}s`)}finally{_t=!1}}}function wn(){let i=Date.now();return{mode:E,unacked:$.size,oldestUnackedAgeMs:hn(i),lastProgressAt:Ze,degradedSince:re,stallRedials:Q,deadLettered:ln,http:E==="http"?{inFlight:Se,circuitOpen:G,nextProbeInMs:G?Math.max(0,pe-i):0,batchCap:W}:null}}async function yn(){if(!h)return;let i;try{i=await h()}catch(a){w.error("[plane-link] metrics sample failed:",a?.message||a);return}let l=null;try{l=g?.()??null}catch{}i&&O({v:N,ch:"ctl",type:"metrics",metrics:{...i,planeLink:wn(),...l?{delivery:l}:{}}})}function Yr(){h&&(te&&clearInterval(te),yn(),te=setInterval(yn,m),te.unref?.())}async function Jr(){let i;try{i=await s()}catch(l){w.error("[plane-link] backfill listTracks failed:",l?.message||l);return}O({v:N,ch:"ctl",type:"tracks",ids:i.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of i){if(!Y)return;let a;try{a=await Lt(l)}catch{continue}let o=de[l.id]??0,d=a.filter(f=>f.seq>o&&typeof f.id=="string"),y=E==="http"?W:ie;for(let f=0;f<d.length;f+=y){if(!await zr(l.id))return;let _=d.slice(f,f+Math.min(y,E==="http"?W:ie)).map(R=>({trackId:l.id,event:R}));if(!Le(_))return}}}function gn(i){!Y||!i?.trackId||typeof i.id!="string"||(oe.push({trackId:i.trackId,event:i}),F||(F=setTimeout(xt,Sr),F.unref?.()))}let je=new Map;async function Xr(i){let{reqId:l,method:a,path:o,headers:d={},body:y}=i,f=Object.fromEntries(Object.entries(d).filter(([,R])=>R!=null)),_=new AbortController;je.set(l,_);try{if(i.host){await Zr(i,f,_);return}K&&(f["x-bostrat-token"]=K);let R=await fetch(j+o,{method:a,headers:f,body:y?Buffer.from(y,"base64"):void 0,signal:_.signal}),V=Object.fromEntries(R.headers);for(let x of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete V[x];if(V["content-type"]||(V["content-type"]="application/octet-stream"),O({v:N,ch:"control",type:"http_head",reqId:l,status:R.status,headers:V}),R.body){for await(let x of R.body)if(!O({v:N,ch:"control",type:"http_data",reqId:l,data:Buffer.from(x).toString("base64")}))break}O({v:N,ch:"control",type:"http_end",reqId:l,error:null})}finally{je.delete(l)}}function Zr(i,l,a){let{reqId:o,method:d,path:y,body:f}=i,_=new URL(j);return new Promise(R=>{let V=ls.request({host:_.hostname,port:_.port,method:d,path:y,headers:{...l,host:i.host},signal:a.signal},x=>{let{connection:Sn,"keep-alive":pi,"transfer-encoding":fi,upgrade:hi,...Qr}=x.headers;O({v:N,ch:"control",type:"http_head",reqId:o,status:x.statusCode||502,headers:Qr}),x.on("data",eo=>{O({v:N,ch:"control",type:"http_data",reqId:o,data:Buffer.from(eo).toString("base64")})||x.destroy()}),x.on("end",()=>{O({v:N,ch:"control",type:"http_end",reqId:o,error:null}),R()}),x.on("error",()=>{O({v:N,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),R()})});V.on("error",x=>{O({v:N,ch:"control",type:"http_end",reqId:o,error:x?.message||"view request failed"}),R()}),f&&V.write(Buffer.from(f,"base64")),V.end()})}function Tn(){if(St||Be)return;z=new zt(e,{headers:{authorization:`Bearer ${t}`}});let i=z;fe=0,i.on("ping",()=>{fe=Date.now()}),i.on("pong",()=>{fe=Date.now()}),z.on("open",async()=>{let a=null;try{a=await c?.()||null}catch{a=null}O({v:N,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:J,installKind:M,...typeof S=="function"?{updatePolicy:S()}:S?{updatePolicy:S}:{},providers:Ar(),...a?{agents:a}:{}})}),z.on("message",a=>{fe=Date.now();let o;try{o=JSON.parse(a)}catch{return}if(o.ch==="ctl"&&o.type==="hello_ok"){Y=!0,Pe=gr,De=null,Rn(),w.log(`[plane-link] connected to plane as ${n}`);try{Ye?.()}catch{}if(typeof o.hashKey=="string"&&o.hashKey)try{T?.(o.hashKey)}catch{}try{p?.(typeof o.viewBase=="string"&&o.viewBase?o.viewBase:null)}catch{}o.minNodeVersion&&J&&Ee(J,o.minNodeVersion)&&w.error(`[plane-link] this node is bostrat-node ${J}; the plane asks for \u2265${o.minNodeVersion} \u2014 update with: ${Ge(M)}`);try{A?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}let d=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;if(d&&J&&Ee(J,d)&&!an.has(d)){an.add(d),w.log(`[plane-link] bostrat-node ${d} is available (this node runs ${J}) \u2014 ${Ge(M)}`);try{B?.({current:J,latest:d,min:o.minNodeVersion??null,installKind:M,required:!!(o.minNodeVersion&&Ee(J,o.minNodeVersion))})}catch(f){w.error(`[plane-link] update notice failed: ${f?.message||f}`)}}let y=o.ingest==="http";E=Ie==="ws"?"ws":Ie==="http"||y?"http":"ws",Ie==="http"&&!y&&w.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),E==="http"&&w.log("[plane-link] spine rides the HTTPS ingest door"),G=!1,pe=0,W=ie,ee&&clearInterval(ee),fe=Date.now(),ee=setInterval(()=>{Wr(i)||(O({v:N,ch:"ctl",type:"ping"}),mn(),Gr().catch(()=>{}),$t(),oe.length&&!F&&xt())},rn),ee.unref?.(),Yr(),Jr().catch(f=>w.error("[plane-link] backfill failed:",f?.message||f));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let d=typeof o.minNodeVersion=="string"?o.minNodeVersion:null,y=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;w.error(`[plane-link] plane REFUSED this node: bostrat-node ${J??"?"} is below its minimum ${d??"?"} \u2014 ${o.fix||Ge(M)}`),Pe=Tr,De=0;try{k?.({current:J,min:d,latest:y,fix:o.fix||Ge(M),installKind:M})}catch(f){w.error(`[plane-link] refusal handler failed: ${f?.message||f}`)}return}if(o.ch==="ctl"&&o.type==="removed"){O({v:N,ch:"ctl",type:"removed_ack",nodeId:n}),bt({reason:typeof o.reason=="string"?o.reason:"removed",at:Number(o.at)||Date.now(),via:"ctl"});return}if(o.ch==="ctl"&&o.type==="update_policy"){try{A?.(typeof o.mode=="string"?o.mode:null)}catch{}return}if(o.ch==="ctl"&&o.type==="usage_caps"){wr(o.caps??{},{source:"plane",updatedAt:o.updatedAt??Date.now()}).then(d=>w.log(`[plane-link] spend caps ${Object.keys(d.caps).length?`updated (${Object.keys(d.caps).join(", ")})`:"cleared"} from plane`)).catch(d=>w.error("[plane-link] spend-caps push rejected:",d?.message||d));return}if(o.ch==="ctl"&&o.type==="transferred"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>u?.(o.tracks)).catch(d=>w.error("[plane-link] transfer notice failed:",d?.message||d));return}if(o.ch==="events"&&o.type==="ack"&&Array.isArray(o.ids)){kt(o.ids);return}if(o.ch==="events"&&o.type==="nack"&&Array.isArray(o.ids)){fn(o.ids,o.reason,o.permanent===!0,o.retryAfterMs??null);return}if(o.ch==="control"&&o.type==="http_open"){Xr(o).catch(d=>O({v:N,ch:"control",type:"http_end",reqId:o.reqId,error:d?.message||"tunnel error"}));return}if(o.ch==="control"&&o.type==="http_cancel"){je.get(o.reqId)?.abort();return}if(o.ch==="attach"&&o.type==="open"){let d=new zt(Fr+o.path,Array.isArray(o.protocols)?o.protocols:[],o.host?{headers:{host:o.host}}:void 0);le.set(o.streamId,d),ue.set(o.streamId,[]),d.on("open",()=>{let f=ue.get(o.streamId)||[];ue.delete(o.streamId);for(let{buf:_,bin:R}of f)d.send(_,{binary:R})}),d.on("message",(f,_)=>{let R=_?f:Buffer.from(String(f));O({v:N,ch:"attach",type:"data",streamId:o.streamId,data:R.toString("base64"),..._?{bin:!0}:{}})});let y=()=>{ue.delete(o.streamId),le.delete(o.streamId)&&O({v:N,ch:"attach",type:"close",streamId:o.streamId})};d.on("close",y),d.on("error",y);return}if(o.ch==="attach"&&o.type==="data"){let d=le.get(o.streamId);if(!d)return;let y=Buffer.from(o.data,"base64"),f=o.bin===!0,_=ue.get(o.streamId);_?_.push({buf:y,bin:f}):d.send(y,{binary:f});return}if(o.ch==="attach"&&o.type==="close"){let d=le.get(o.streamId);le.delete(o.streamId),ue.delete(o.streamId),d?.close();return}});let l=()=>{Y&&w.log("[plane-link] disconnected from plane"),Y=!1,ee&&(clearInterval(ee),ee=null),te&&(clearInterval(te),te=null),$.clear(),ne={},oe=[],F&&(clearTimeout(F),F=null),ve.clear();for(let d of le.values())d.close();le.clear(),ue.clear();for(let d of je.values())d.abort();if(je.clear(),St||be)return;De==null&&(De=Date.now());let a=Date.now()-De<ds,o=Math.max(a?ps+Math.random()*fs:Pe,Me-Date.now(),Ke());be=setTimeout(()=>{be=null,Tn()},o),be.unref?.(),a||(Pe=Math.min(Pe*2,Tr))};z.on("close",l),z.on("error",a=>{let o=/Unexpected server response: (\d+)/.exec(a?.message||"")?.[1];if(o==="410"){bt({reason:"removed",via:"410"});return}if(o==="401"||o==="403"){let{tripped:d,holdMs:y}=it();d?w.error(`[plane-link] holding every plane call for ${Math.round(y/6e4)} min \u2014 three credential refusals in a row (HTTP ${o}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(y/6e4)} min.`):Date.now()-Qe>=vr&&(Qe=Date.now(),w.error(`[plane-link] plane refused this node's credentials (HTTP ${o}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`))}l()})}ze.on("event",gn),Ur().then(Tn);function _n({bye:i=!0}={}){St=!0,ze.off("event",gn),be&&clearTimeout(be),Ae&&clearTimeout(Ae),ee&&clearInterval(ee),te&&clearInterval(te),F&&clearTimeout(F),i&&O({v:N,ch:"ctl",type:"bye",reason:"shutdown"}),z?.close()}return{stop:()=>_n(),status:()=>({connected:Y,nodeId:n,cursor:{...de},inflight:$.size,...wn(),auth:Nn(),dormant:Be,removed:Pt(),deadLinkMs:yt,deadLinkRedials:dn}),_tick:()=>{mn(),$t()}}}var J,qt,Yt,N,gr,Tr,ds,ps,fs,ie,hs,ms,ws,ys,kr,gs,Ts,_r,_s,Sr,Ss,Vt,vs,vr,Jt=v(()=>{ct();yr();Nt();Dt();J=(()=>{try{return us(import.meta.url)("../package.json").version||null}catch{return null}})(),qt=process.env.BOSTRAT_STATE_DIR||C.join(process.env.HOME||ft.tmpdir(),".bostrat"),Yt=C.join(qt,"plane-link","removed.json");N=1,gr=1e3,Tr=3e4,ds=6e4,ps=1500,fs=500,ie=100,hs=2e3,ms=25e3,ws=2.5,ys=6e4,kr=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},gs=kr(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Ts=3e4,_r=10*6e4,_s=400,Sr=250,Ss=kr(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Vt=4,vs=6e4,vr=6e4});import{execFile as As}from"node:child_process";import{promisify as ks}from"node:util";function xr(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var nl,rl,ol,Er=v(()=>{Ct();nl=ks(As),rl=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,ol=Promise.resolve()});var Mr={};Et(Mr,{ACTIONABLE_KINDS:()=>wt,SELF_UPDATE_DIR:()=>Xt,createAutoUpdater:()=>Cs,inFlight:()=>Qt,readStatus:()=>Zt,selfUpdatePlan:()=>Nr,settleSelfUpdate:()=>Ls,startSelfUpdate:()=>Ir,underService:()=>Rr,updatePolicy:()=>Is});import Or from"node:fs";import ae from"node:fs/promises";import $s from"node:os";import D from"node:path";import{spawn as xs}from"node:child_process";import{createRequire as Es}from"node:module";function Is({kind:e=Oe(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:wt.has(e)?e==="git-checkout"||Rr(t)?"auto":"prompt":"off"}function Rr(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Nr({kind:e,to:t,from:n=ht,statusFile:r=mt,logFile:s=D.join(Xt,"last.log"),port:c=Number(process.env.PORT)||3362,npmPrefix:u=null,serviceName:h=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:g=typeof process.getuid=="function"?process.getuid():0,liveDir:T=process.env.BOSTRAT_LIVE_CHECKOUT||D.resolve(D.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:p=Date.now()}={}){if(!wt.has(e))throw new Error(`self-update: install kind "${e}" is not actionable here`);if(!/^\d+\.\d+\.\d+$/.test(String(t)))throw new Error(`self-update: bad target version "${t}"`);if(n&&!/^\d+\.\d+\.\d+$/.test(String(n)))throw new Error(`self-update: bad current version "${n}"`);let m=(M,j="")=>`write_status ${U(M)} ${j}`,B=process.platform==="darwin"?`launchctl kickstart -k gui/${g}/${h}`:`systemctl --user restart ${U(h)}`,A=`
|
|
117
117
|
health() {
|
|
118
118
|
for i in $(seq 1 45); do
|
|
119
119
|
sleep 1
|
|
@@ -122,11 +122,11 @@ health() {
|
|
|
122
122
|
return 1
|
|
123
123
|
}`,k=`#!/usr/bin/env bash
|
|
124
124
|
# bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
|
|
125
|
-
# ${n??"?"} \u2192 ${t} (${e}). Status: ${
|
|
125
|
+
# ${n??"?"} \u2192 ${t} (${e}). Status: ${r}
|
|
126
126
|
set -u
|
|
127
127
|
FROM=${U(n??"")}
|
|
128
128
|
TO=${U(t)}
|
|
129
|
-
STATUS_FILE=${U(
|
|
129
|
+
STATUS_FILE=${U(r)}
|
|
130
130
|
STARTED_AT=${Number(p)}
|
|
131
131
|
write_status() { # <status> [error]
|
|
132
132
|
local err="\${2:-}"
|
|
@@ -136,16 +136,16 @@ write_status() { # <status> [error]
|
|
|
136
136
|
"\${err:+,\\"error\\":\\"$err\\"}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
|
|
137
137
|
}
|
|
138
138
|
${A}
|
|
139
|
-
`;if(e==="npm-global"){let
|
|
140
|
-
`:"",K=u?` --prefix ${U(u)}`:"",
|
|
141
|
-
${
|
|
142
|
-
if ! ${
|
|
143
|
-
${
|
|
139
|
+
`;if(e==="npm-global"){let M=u?D.join(u,"bin","npm"):"npm",j=u?`export PATH=${U(D.join(u,"bin"))}:"$PATH"
|
|
140
|
+
`:"",K=u?` --prefix ${U(u)}`:"",P=b=>`${U(M)} install -g "bostrat-node@${b}" --no-audit --no-fund${K}`;return k+j+`
|
|
141
|
+
${m("updating",'"" ')}
|
|
142
|
+
if ! ${P("$TO")}; then
|
|
143
|
+
${m("failed",'"npm install failed"')}
|
|
144
144
|
exit 1
|
|
145
145
|
fi
|
|
146
|
-
${
|
|
147
|
-
if ! ${
|
|
148
|
-
${
|
|
146
|
+
${m("restarting")}
|
|
147
|
+
if ! ${B}; then
|
|
148
|
+
${m("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
|
-
${
|
|
157
|
-
if [ -n "$FROM" ] && ${
|
|
158
|
-
${
|
|
156
|
+
${m("rolling-back",'"agent did not answer on :'+c+' after the update"')}
|
|
157
|
+
if [ -n "$FROM" ] && ${P("$FROM")} && ${B} && health; then
|
|
158
|
+
${m("rolled-back",'"agent did not answer on :'+c+' after the update; rolled back"')}
|
|
159
159
|
exit 1
|
|
160
160
|
fi
|
|
161
|
-
${
|
|
161
|
+
${m("failed",'"agent did not answer after the update AND the rollback"')}
|
|
162
162
|
exit 1
|
|
163
|
-
`}let
|
|
163
|
+
`}let S=M=>`( cd ${U(T)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${M}" )`;return k+`
|
|
164
164
|
LIVE=${U(T)}
|
|
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
|
-
${
|
|
171
|
-
if ${
|
|
170
|
+
${m("restarting")}
|
|
171
|
+
if ${S("$TO")}; then
|
|
172
172
|
exit 0
|
|
173
173
|
fi
|
|
174
|
-
${
|
|
175
|
-
if [ -n "$FROM" ] && ${
|
|
176
|
-
${
|
|
174
|
+
${m("rolling-back",'"deploy-pi.sh v$TO failed"')}
|
|
175
|
+
if [ -n "$FROM" ] && ${S("$FROM")}; then
|
|
176
|
+
${m("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
|
|
177
177
|
exit 1
|
|
178
178
|
fi
|
|
179
|
-
${
|
|
179
|
+
${m("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
|
|
180
180
|
exit 1
|
|
181
|
-
`}async function Jt(e=ht){try{return JSON.parse(await ae.readFile(e,"utf8"))}catch{return null}}async function Er({to:e,from:t=ft,kind:n=Ee(),reason:o="manual",statusFile:s=ht,spawnImpl:c=vs,now:u=Date.now,npmPrefix:f=void 0,log:g=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!mt.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!xe(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let T=await Jt(s);if(Xt(T))return{ok:!1,reason:`an update to ${T.to} is already in flight`,status:T};if(T&&T.to===e&&(T.status==="failed"||T.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${T.status} (${T.error||"no detail"}) \u2014 retried when a newer release exists`,status:T};await ae.mkdir(P.dirname(s),{recursive:!0});let p=f!==void 0?f:n==="npm-global"?br(await Os())||P.resolve(P.dirname(process.execPath),".."):null,h=xr({kind:n,to:e,from:t,statusFile:s,npmPrefix:p,startedAt:u()}),D=P.join(P.dirname(s),`update-${e}.sh`),A=P.join(P.dirname(s),"last.log");await ae.writeFile(D,h,{mode:448}),await ae.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:o,startedAt:u(),updatedAt:u()}));let k=kr.existsSync("/run/systemd/system")&&await Rs("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",D]]:["setsid",["-f","bash","-c",`exec bash ${U(D)} >> ${U(A)} 2>&1`]];try{c(k[0],k[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(_){return await ae.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:o,startedAt:u(),updatedAt:u(),error:`could not spawn updater: ${_?.message||_}`})),{ok:!1,reason:`could not spawn updater: ${_?.message||_}`}}return g.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${o}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:D,statusFile:s}}async function Os(){try{return await ae.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Rs(e){for(let t of String(process.env.PATH||"").split(P.delimiter))try{return await ae.access(P.join(t,e),kr.constants.X_OK),!0}catch{}return!1}async function Is({statusFile:e=ht,current:t=ft,now:n=Date.now,staleMs:o=Ns}={}){let s=await Jt(e);if(!s)return null;let c=u=>ae.writeFile(e,JSON.stringify(u)).catch(()=>{});if(Xt(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 Ms({isBusy:e,start:t=Er,onStuck:n=null,onStarted:o=null,tickMs:s=$s,stuckMs:c=ks,now:u=Date.now,setIntervalImpl:f=setInterval,clearIntervalImpl:g=clearInterval,log:T=console}={}){let p=null,h=()=>{p?.timer&&g(p.timer),p=null},D=async()=>{if(!p)return;let A=!0;try{A=await e()!==!1}catch{A=!0}if(A){if(!p.stuckFired&&u()-p.since>=c){p.stuckFired=!0;try{await n?.({to:p.to,from:p.from,since:p.since})}catch{}}return}let k=p;h();let _=await t({to:k.to,from:k.from,kind:k.kind,reason:"auto"});T.log?.(`[self-update] stasis reached \u2192 ${_.ok?"started":`not started: ${_.reason}`}`);try{await o?.({...k,result:_})}catch{}};return{arm({to:A,from:k=ft,kind:_=Ee()}){return p?.to===A?!1:(h(),p={to:A,from:k,kind:_,since:u(),stuckFired:!1,timer:f(D,s)},p.timer.unref?.(),!0)},tick:D,cancel:h,get armed(){return p?{to:p.to,from:p.from,kind:p.kind,since:p.since}:null}}}var ft,As,Gt,ht,ks,$s,mt,U,Es,Xt,Ns,Rr=v(()=>{Yt();Ar();ft=(()=>{try{return bs(import.meta.url)("../package.json").version||null}catch{return null}})(),As=process.env.BOSTRAT_STATE_DIR||P.join(process.env.HOME||Ss.tmpdir(),".bostrat"),Gt=P.join(As,"self-update"),ht=P.join(Gt,"status.json"),ks=1440*6e4,$s=6e4,mt=new Set(["npm-global","git-checkout"]);U=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Es=new Set(["updating","restarting","rolling-back"]),Xt=e=>!!(e&&Es.has(e.status));Ns=45*6e4});Ot();Lt();import J from"node:fs";import N from"node:path";import Re from"node:os";import{createRequire as Zt}from"node:module";import{execFile as Ps,spawn as Ds}from"node:child_process";import{promisify as Bs}from"node:util";import Ls from"node:readline/promises";import{randomUUID as Cs}from"node:crypto";import{fileURLToPath as js}from"node:url";import Po from"node:fs";import Kn from"node:path";import Do from"node:os";var Bo=()=>process.env.BOSTRAT_STATE_DIR||Kn.join(process.env.HOME||Do.tmpdir(),".bostrat"),Lo=()=>Kn.join(Bo(),"plane-link","public-host.json");var ze=null;function Co(){if(ze)return ze;try{let e=JSON.parse(Po.readFileSync(Lo(),"utf8"));ze={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{ze={viewBase:null}}return ze}function jo(e,t){let n=String(e||"").trim();if(!n)return null;let o=/^(https?):\/\/(.+?)\/?$/i.exec(n),s=o?o[1].toLowerCase():t,c=(o?o[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return c?{proto:s,host:c}:null}function Wn(){return Co().viewBase}function zn(e=process.env.BOSTRAT_PUBLIC_HOST){return jo(e,"https")}function Vn(e=process.env.BOSTRAT_PLANE_URL){let t=String(e||"").trim();if(!t)return null;let n=/^(wss?|https?):\/\/([^/?#]+)/i.exec(t);return n?`${/^(wss|https)$/i.test(n[1])?"https":"http"}://${n[2]}`:null}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},ce=Bs(Ps),Qt=N.dirname(js(import.meta.url)),ge=N.resolve(Qt,".."),Fs=N.join(Qt,"index.js"),Us="wss://plane.bostrat.ai/v1/node",Oe=Zt(import.meta.url)("../package.json").version,B=(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 Hs(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?B("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 Ks(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}`):B("node.env",`${e} (0600)`)}async function Ws(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await ce(t,["-V"],{timeout:5e3});return B("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 Ir(e,{required:t=!1}={}){if(await jt(e,{loginShell:!0,failOpen:!1}))return B(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=lt[e]?`${lt[e]}${e==="cursor-agent"?" # installs to ~/.local/bin \u2014 ensure your login shell has it on PATH":""}`:`install ${e} so \`$SHELL -lic 'command -v ${e}'\` finds it`;return t?H(e,o,s):Z(e,o,s)}async function zs(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await ce(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return B("gh (GitHub CLI)",n)}catch{return Z("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",lt.gh)}}async function Vs(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Ir(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 qs(){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 jt(t,{failOpen:!1})?B(t,"resolves on the service PATH"):Z(t,`not on the service PATH \u2014 ${n}`,o)))}async function Ys(){try{let t=Zt(N.join(ge,"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()})}),B("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${ge} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Zt(N.join(ge,"package.json")),o=N.join(N.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 Gs(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(J.existsSync(t))return B("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 Js(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"):B("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function Xs(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=je(e.BOSTRAT_PLANE_URL);return await new Promise(c=>{let u=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),f=null,g=p=>{clearTimeout(T);try{u.close()}catch{}c(f?{...p,viewBase:f}:p)},T=setTimeout(()=>g(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-${Cs().slice(0,8)}`,ephemeral:!0}))),u.on("message",p=>{try{let h=JSON.parse(p);h.type==="hello_ok"?(typeof h.viewBase=="string"&&h.viewBase&&(f=h.viewBase),h.minNodeVersion&&Nr(Oe,h.minNodeVersion)?g(H("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${h.minNodeVersion} \u2014 this node is ${Oe}; the real link is refused until it updates`,`bostrat-node self-update --to ${h.latestNodeVersion||h.minNodeVersion}`)):h.latestNodeVersion&&Nr(Oe,h.latestNodeVersion)?g(Z("plane link",`hello_ok in ${Date.now()-o}ms (${s}); bostrat-node ${h.latestNodeVersion} is available (this node: ${Oe})`,`bostrat-node self-update --to ${h.latestNodeVersion}`)):g(B("plane link",`hello_ok in ${Date.now()-o}ms (${s})`))):h.type==="error"&&g(H("plane link",`plane said: ${h.code} ${h.message||""}`,"check the token"))}catch{}}),u.on("error",p=>g(H("plane link",`${p?.message||p}`,"check the URL, the token, and the plane's IP gate")))})}function Zs(){let e;try{e=JSON.parse(J.readFileSync(N.join(Et,"content-outbox.json"),"utf8"))}catch{return B("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"):B("content outbox",t?`${t} op(s) in flight`:"drained")}function Qs(e){return e.BOSTRAT_STATE_REMOTE?B("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):Z("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}function ei(e,t){let n=t?.viewBase??null,o=Wn(),s=zn(e.BOSTRAT_PUBLIC_HOST),c=(()=>{let u=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(u)return`${u.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let f=Vn(e.BOSTRAT_PLANE_URL);return f?`${f}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let u=s&&s.host!==n?`; BOSTRAT_PUBLIC_HOST=${s.host} is set but the plane's value wins`:"";return B("public host",`views https://<slug>.${n}/ (plane hello_ok)${u} \xB7 track links ${c}`)}return o?B("public host",`views https://<slug>.${o}/ (persisted from the last hello) \xB7 track links ${c}`):s?B("public host",`views ${s.proto}://<slug>.${s.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${c}`):H("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${c}`,"link a plane that sets PLANE_VIEW_BASE (bostrat-node init), or set BOSTRAT_PUBLIC_HOST in node.env for a plane-less node")}async function Mr(e,t={}){let n=[];n.push(await Hs()),n.push(Ks(t.envFile||Ae())),n.push(await Ws(e)),n.push(...await Vs()),n.push(await Ir("git",{required:!0})),n.push(await zs()),n.push(...await qs()),n.push(await Ys()),n.push(Gs(e)),n.push(Js(e));let o=await Xs(e,t);return n.push(o),n.push(ei(e,o)),n.push(Zs()),n.push(Qs(e)),n}function Pr(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
|
-
FAIL \u2014 ${
|
|
183
|
-
OK \u2014 0 blocking, ${s} warnings`),
|
|
181
|
+
`}async function Zt(e=mt){try{return JSON.parse(await ae.readFile(e,"utf8"))}catch{return null}}async function Ir({to:e,from:t=ht,kind:n=Oe(),reason:r="manual",statusFile:s=mt,spawnImpl:c=xs,now:u=Date.now,npmPrefix:h=void 0,log:g=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!wt.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Ee(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let T=await Zt(s);if(Qt(T))return{ok:!1,reason:`an update to ${T.to} is already in flight`,status:T};if(T&&T.to===e&&(T.status==="failed"||T.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${T.status} (${T.error||"no detail"}) \u2014 retried when a newer release exists`,status:T};await ae.mkdir(D.dirname(s),{recursive:!0});let p=h!==void 0?h:n==="npm-global"?xr(await Ps())||D.resolve(D.dirname(process.execPath),".."):null,m=Nr({kind:n,to:e,from:t,statusFile:s,npmPrefix:p,startedAt:u()}),B=D.join(D.dirname(s),`update-${e}.sh`),A=D.join(D.dirname(s),"last.log");await ae.writeFile(B,m,{mode:448}),await ae.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,startedAt:u(),updatedAt:u()}));let k=Or.existsSync("/run/systemd/system")&&await Ds("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",B]]:["setsid",["-f","bash","-c",`exec bash ${U(B)} >> ${U(A)} 2>&1`]];try{c(k[0],k[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(S){return await ae.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,startedAt:u(),updatedAt:u(),error:`could not spawn updater: ${S?.message||S}`})),{ok:!1,reason:`could not spawn updater: ${S?.message||S}`}}return g.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:B,statusFile:s}}async function Ps(){try{return await ae.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Ds(e){for(let t of String(process.env.PATH||"").split(D.delimiter))try{return await ae.access(D.join(t,e),Or.constants.X_OK),!0}catch{}return!1}async function Ls({statusFile:e=mt,current:t=ht,now:n=Date.now,staleMs:r=Bs}={}){let s=await Zt(e);if(!s)return null;let c=u=>ae.writeFile(e,JSON.stringify(u)).catch(()=>{});if(Qt(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)>r){let u={...s,status:"failed",error:`updater went silent while ${s.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await 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 Cs({isBusy:e,start:t=Ir,onStuck:n=null,onStarted:r=null,tickMs:s=Ns,stuckMs:c=Rs,now:u=Date.now,setIntervalImpl:h=setInterval,clearIntervalImpl:g=clearInterval,log:T=console}={}){let p=null,m=()=>{p?.timer&&g(p.timer),p=null},B=async()=>{if(!p)return;let A=!0;try{A=await e()!==!1}catch{A=!0}if(A){if(!p.stuckFired&&u()-p.since>=c){p.stuckFired=!0;try{await n?.({to:p.to,from:p.from,since:p.since})}catch{}}return}let k=p;m();let S=await t({to:k.to,from:k.from,kind:k.kind,reason:"auto"});T.log?.(`[self-update] stasis reached \u2192 ${S.ok?"started":`not started: ${S.reason}`}`);try{await r?.({...k,result:S})}catch{}};return{arm({to:A,from:k=ht,kind:S=Oe()}){return p?.to===A?!1:(m(),p={to:A,from:k,kind:S,since:u(),stuckFired:!1,timer:h(B,s)},p.timer.unref?.(),!0)},tick:B,cancel:m,get armed(){return p?{to:p.to,from:p.from,kind:p.kind,since:p.since}:null}}}var ht,Os,Xt,mt,Rs,Ns,wt,U,Ms,Qt,Bs,Pr=v(()=>{Jt();Er();ht=(()=>{try{return Es(import.meta.url)("../package.json").version||null}catch{return null}})(),Os=process.env.BOSTRAT_STATE_DIR||D.join(process.env.HOME||$s.tmpdir(),".bostrat"),Xt=D.join(Os,"self-update"),mt=D.join(Xt,"status.json"),Rs=1440*6e4,Ns=6e4,wt=new Set(["npm-global","git-checkout"]);U=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Ms=new Set(["updating","restarting","rolling-back"]),Qt=e=>!!(e&&Ms.has(e.status));Bs=45*6e4});Nt();jt();import X from"node:fs";import I from"node:path";import Ne from"node:os";import{createRequire as en}from"node:module";import{execFile as js,spawn as Fs}from"node:child_process";import{promisify as Us}from"node:util";import Hs from"node:readline/promises";import{randomUUID as Ks}from"node:crypto";import{fileURLToPath as Ws}from"node:url";import Co from"node:fs";import qn from"node:path";import jo from"node:os";var Fo=()=>process.env.BOSTRAT_STATE_DIR||qn.join(process.env.HOME||jo.tmpdir(),".bostrat"),Uo=()=>qn.join(Fo(),"plane-link","public-host.json");var Ve=null;function Ho(){if(Ve)return Ve;try{let e=JSON.parse(Co.readFileSync(Uo(),"utf8"));Ve={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{Ve={viewBase:null}}return Ve}function Ko(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),s=r?r[1].toLowerCase():t,c=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return c?{proto:s,host:c}:null}function Gn(){return Ho().viewBase}function Yn(e=process.env.BOSTRAT_PUBLIC_HOST){return Ko(e,"https")}function Jn(e=process.env.BOSTRAT_PLANE_URL){let t=String(e||"").trim();if(!t)return null;let n=/^(wss?|https?):\/\/([^/?#]+)/i.exec(t);return n?`${/^(wss|https)$/i.test(n[1])?"https":"http"}://${n[2]}`:null}var Dr=(e,t)=>{let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let s=0;s<Math.max(n.length,r.length);s++){let c=(n[s]||0)-(r[s]||0);if(c)return c<0}return!1},ce=Us(js),tn=I.dirname(Ws(import.meta.url)),Te=I.resolve(tn,".."),zs=I.join(tn,"index.js"),Vs="wss://plane.bostrat.ai/v1/node",Re=en(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 qs(){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 Gs(e){let t;try{t=X.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 Ys(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await ce(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 Br(e,{required:t=!1}={}){if(await Ut(e,{loginShell:!0,failOpen:!1}))return L(e,"resolves on the login-shell PATH");let r="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",s=ut[e]?`${ut[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,r,s):Z(e,r,s)}async function Js(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await ce(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",ut.gh)}}async function Xs(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Br(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 Zs(){let e=[...process.platform==="linux"?[["fuser","stopped views can't free their ports (they leak, and the port can't be reused)","apt install psmisc"]]:[],["pgrep","agent-swap can't detect an idle pane shell \u2014 swaps may misfire","apt install procps"],["npm","codex auto-update and `npm run` views are unavailable","install Node.js with npm on the service PATH"]];return Promise.all(e.map(async([t,n,r])=>await Ut(t,{failOpen:!1})?L(t,"resolves on the service PATH"):Z(t,`not on the service PATH \u2014 ${n}`,r)))}async function Qs(){try{let t=en(I.join(Te,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let s=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),c=setTimeout(()=>r(new Error("spawn timeout")),5e3);s.onExit(()=>{clearTimeout(c),n()})}),L("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${Te} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=en(I.join(Te,"package.json")),r=I.join(I.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");X.existsSync(r)&&!(X.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return H("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function ei(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(X.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 ti(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 ni(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return Z("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),s=Fe(e.BOSTRAT_PLANE_URL);return await new Promise(c=>{let u=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),h=null,g=p=>{clearTimeout(T);try{u.close()}catch{}c(h?{...p,viewBase:h}:p)},T=setTimeout(()=>g(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-${Ks().slice(0,8)}`,ephemeral:!0}))),u.on("message",p=>{try{let m=JSON.parse(p);m.type==="hello_ok"?(typeof m.viewBase=="string"&&m.viewBase&&(h=m.viewBase),m.minNodeVersion&&Dr(Re,m.minNodeVersion)?g(H("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${m.minNodeVersion} \u2014 this node is ${Re}; the real link is refused until it updates`,`bostrat-node self-update --to ${m.latestNodeVersion||m.minNodeVersion}`)):m.latestNodeVersion&&Dr(Re,m.latestNodeVersion)?g(Z("plane link",`hello_ok in ${Date.now()-r}ms (${s}); bostrat-node ${m.latestNodeVersion} is available (this node: ${Re})`,`bostrat-node self-update --to ${m.latestNodeVersion}`)):g(L("plane link",`hello_ok in ${Date.now()-r}ms (${s})`))):m.type==="error"&&g(H("plane link",`plane said: ${m.code} ${m.message||""}`,"check the token"))}catch{}}),u.on("error",p=>g(H("plane link",`${p?.message||p}`,"check the URL, the token, and the plane's IP gate")))})}function ri(){let e;try{e=JSON.parse(X.readFileSync(I.join(Rt,"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 r=e.parked[0];return H("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?Z("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):L("content outbox",t?`${t} op(s) in flight`:"drained")}function oi(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")}function si(e,t){let n=t?.viewBase??null,r=Gn(),s=Yn(e.BOSTRAT_PUBLIC_HOST),c=(()=>{let u=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(u)return`${u.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let h=Jn(e.BOSTRAT_PLANE_URL);return h?`${h}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let u=s&&s.host!==n?`; BOSTRAT_PUBLIC_HOST=${s.host} is set but the plane's value wins`:"";return L("public host",`views https://<slug>.${n}/ (plane hello_ok)${u} \xB7 track links ${c}`)}return r?L("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${c}`):s?L("public host",`views ${s.proto}://<slug>.${s.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${c}`):H("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${c}`,"link a plane that sets PLANE_VIEW_BASE (bostrat-node init), or set BOSTRAT_PUBLIC_HOST in node.env for a plane-less node")}async function Lr(e,t={}){let n=[];n.push(await qs()),n.push(Gs(t.envFile||ke())),n.push(await Ys(e)),n.push(...await Xs()),n.push(await Br("git",{required:!0})),n.push(await Js()),n.push(...await Zs()),n.push(await Qs()),n.push(ei(e)),n.push(ti(e));let r=await ni(e,t);return n.push(r),n.push(si(e,r)),n.push(ri()),n.push(oi(e)),n}function Cr(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 r=e.filter(c=>c.level==="fail").length,s=e.filter(c=>c.level==="warn").length;return t(r?`
|
|
182
|
+
FAIL \u2014 ${r} blocking, ${s} warnings`:`
|
|
183
|
+
OK \u2014 0 blocking, ${s} warnings`),r===0}async function ii({envFile:e=ke(),input:t=process.stdin,output:n=process.stdout}={}){let r=tt(e),s=Hs.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",
|
|
187
|
-
`);let g=await c("Node token (minted plane-side; stored 0600)",
|
|
188
|
-
`);let p=await c("Node name",
|
|
186
|
+
`);let u=await c("Plane URL",r.BOSTRAT_PLANE_URL||Vs),h=Fe(u);h!==u.trim()&&n.write(` \u2192 using ${h}
|
|
187
|
+
`);let g=await c("Node token (minted plane-side; stored 0600)",r.BOSTRAT_PLANE_TOKEN),T=await c("Owner userId (just press Enter \u2014 the plane infers it from your token)",r.BOSTRAT_OWNER||"");T&&!/^user_[A-Za-z0-9]+$/.test(T)&&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 p=await c("Node name",r.BOSTRAT_NODE_NAME||Ne.hostname().split(".")[0]),m=await c("Repos root",r.BOSTRAT_REPOS_ROOT||I.join(Ne.homedir(),"Documents")),B=await c("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),A=(await c("Route NEW claude boxes through a BYO API key? (y/N)",r.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");A&&n.write(`
|
|
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=A?await c("ANTHROPIC_API_KEY (starts sk-ant-)",
|
|
195
|
-
`),s.close();let
|
|
194
|
+
`);let k=A?await c("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";A&&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 S={...An(),...r,BOSTRAT_PLANE_URL:h,BOSTRAT_PLANE_TOKEN:g,BOSTRAT_OWNER:T,BOSTRAT_NODE_NAME:p,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||p,BOSTRAT_REPOS_ROOT:m,BOSTRAT_STATE_REMOTE:B,BOSTRAT_CLAUDE_USE_API_KEY:A?"1":"0",ANTHROPIC_API_KEY:A?k:r.ANTHROPIC_API_KEY};bn(e,S,{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
|
|
201
|
-
`));return K&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:K,results:j}}function
|
|
200
|
+
`);let M={...S,...process.env},j=await Lr(M,{envFile:e}),K=Cr(j,P=>n.write(P+`
|
|
201
|
+
`));return K&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:K,results:j}}function ai({envFile:e=ke()}={}){vn(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=Fs(t,[zs],{cwd:Te,stdio:"inherit",env:process.env});for(let r of["SIGINT","SIGTERM"])process.on(r,()=>n.kill(r));return n.on("exit",(r,s)=>process.exit(s?1:r??1)),n}function ci({agentDir:e=Te,nodeBin:t=process.execPath,envFile:n=ke(),home:r=Ne.homedir()}={}){let s=I.dirname(t),c=I.join(I.basename(tn),"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)
|
|
@@ -212,13 +212,13 @@ ExecStart=${t} --disable-warning=ExperimentalWarning ${c}
|
|
|
212
212
|
EnvironmentFile=${n}
|
|
213
213
|
# systemd's user PATH omits ~/.local/bin (cursor-agent, bostrat-view) and the
|
|
214
214
|
# nvm bin dir \u2014 both are load-bearing for box spawning.
|
|
215
|
-
Environment=PATH=${
|
|
215
|
+
Environment=PATH=${r}/.local/bin:${s}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
|
216
216
|
Restart=on-failure
|
|
217
217
|
RestartSec=2
|
|
218
218
|
|
|
219
219
|
[Install]
|
|
220
220
|
WantedBy=default.target
|
|
221
|
-
`}function
|
|
221
|
+
`}function li({agentDir:e=Te,nodeBin:t=process.execPath,home:n=Ne.homedir()}={}){let r=I.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>
|
|
@@ -232,7 +232,7 @@ WantedBy=default.target
|
|
|
232
232
|
<key>WorkingDirectory</key><string>${e}</string>
|
|
233
233
|
<key>EnvironmentVariables</key>
|
|
234
234
|
<dict>
|
|
235
|
-
<key>PATH</key><string>${n}/.local/bin:${
|
|
235
|
+
<key>PATH</key><string>${n}/.local/bin:${r}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
|
|
236
236
|
</dict>
|
|
237
237
|
<key>RunAtLoad</key><true/>
|
|
238
238
|
<key>KeepAlive</key><true/>
|
|
@@ -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
|
|
243
|
+
`}function ui(e=process.platform,t=Ne.homedir()){return e==="darwin"?{kind:"launchd",file:I.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:I.join(t,".config","systemd","user","bostrat-node.service")}}async function di({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:s=Te}={}){let{kind:c,file:u}=ui(n);if(!e&&s.split(I.sep).includes("_npx"))return r("\u2717 running from the npx cache \u2014 a service must point at a durable install."),r(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){c==="systemd"?(await ce("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),X.rmSync(u,{force:!0}),await ce("systemctl",["--user","daemon-reload"])):(await ce("launchctl",["unload","-w",u]).catch(()=>{}),X.rmSync(u,{force:!0})),r(`removed ${u}`);return}X.mkdirSync(I.dirname(u),{recursive:!0}),c==="systemd"?(X.writeFileSync(u,ci()),await ce("systemctl",["--user","daemon-reload"]),t&&await ce("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${u}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(X.mkdirSync(I.join(Ne.homedir(),"Library","Logs","bostrat"),{recursive:!0}),X.writeFileSync(u,li()),t&&await ce("launchctl",["load","-w",u]),r(`installed ${u}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function $l(e=process.argv.slice(2)){let t=e[0],n=ke();if(t==="--version"||t==="-v"||t==="version")return console.log(Re),0;if(t==="init")return(await ii({envFile:n})).ok?0:1;if(t==="doctor"){let r={...tt(n),...process.env};return Cr(await Lr(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return ai({envFile:n}),null;if(t==="install-service")return await di({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(rr(),nr));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:s,updatePolicy:c}=await Promise.resolve().then(()=>(Pr(),Mr)),{detectInstallKind:u}=await Promise.resolve().then(()=>(Jt(),$r)),h=u(),g=e.indexOf("--to"),T=g>=0?String(e[g+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Re,installKind:h,policy:c({kind:h}),status:await s()},null,2)),0;if(!T)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let p=await r({to:T,kind:h,reason:"cli"});return p.ok?(console.log(`\u2713 self-update ${p.from??"?"} \u2192 ${p.to} started (${p.kind}) \u2014 status: ${p.statusFile}; the service restarts when the install completes`),0):(console.error(`\u2717 not started: ${p.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
|
|
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{
|
|
252
|
+
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{ii as init,di as installService,li as launchdPlist,$l as main,Cr as printDoctor,ai as runAgent,Lr as runDoctor,ui as servicePaths,ci as systemdUnit};
|