bostrat-node 1.9.8 → 1.9.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +54 -54
- package/dist/index.js +196 -196
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)){let s=o.trim();if(!s||s.startsWith("#"))continue;let l=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(s);if(!l)continue;let u=l[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),n[l[1]]=u}return n}function
|
|
3
|
-
`).map(s=>s?`# ${s}`:"#"));for(let[s,l]of Object.entries(t))l==null||l===""||o.push(`${s}=${l}`);
|
|
1
|
+
var zr=Object.defineProperty;var S=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var At=(e,t)=>{for(var n in t)zr(e,n,{get:t[n],enumerable:!0})};import Ze from"node:fs";import $t from"node:path";import Yr from"node:os";function Le(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,o;try{o=new URL(n)}catch{return t}let s={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[o.protocol];return s?(o.protocol=s,(o.pathname===""||o.pathname==="/")&&(o.pathname="/v1/node"),o.toString()):t}function Qe(e){let t;try{t=Ze.readFileSync(e,"utf8")}catch{return{}}let n={};for(let o of t.split(`
|
|
2
|
+
`)){let s=o.trim();if(!s||s.startsWith("#"))continue;let l=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(s);if(!l)continue;let u=l[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),n[l[1]]=u}return n}function wn(e,t=process.env){let n=Qe(e);for(let[o,s]of Object.entries(n))o in t||(t[o]=s);return n}function yn(e,t,{header:n=""}={}){let o=[];n&&o.push(...n.split(`
|
|
3
|
+
`).map(s=>s?`# ${s}`:"#"));for(let[s,l]of Object.entries(t))l==null||l===""||o.push(`${s}=${l}`);Ze.mkdirSync($t.dirname(e),{recursive:!0}),Ze.writeFileSync(e,o.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`,{mode:384}),
|
|
6
|
-
`))if(u.trim())try{l.push(JSON.parse(
|
|
5
|
+
`,{mode:384}),Ze.chmodSync(e,384)}function gn(e=process.platform){return e==="darwin"?{BOSTRAT_TMUX_BIN:"/opt/homebrew/bin/tmux",BOSTRAT_TMUX_SOCKET:`/tmp/tmux-${process.getuid?.()??501}/bostrat`,BOSTRAT_CHROMIUM_BIN:"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"}:{}}var xt,Ae,Et=S(()=>{xt=process.env.BOSTRAT_STATE_DIR||$t.join(process.env.HOME||Yr.tmpdir(),".bostrat"),Ae=()=>$t.join(xt,"node.env")});var he,et,tt=S(()=>{he="BOSTRAT_HOOK_TOKEN",et="x-bostrat-hook"});var Tn=S(()=>{tt()});var _n=S(()=>{});var bn=S(()=>{});import Ot from"node:path";import{execFile as qr}from"node:child_process";import{promisify as Gr}from"node:util";var ui,Sn,Vr,di,fi,vn=S(()=>{ui=Gr(qr),Sn=process.env.HOME||"/home/globo",Vr=Ot.join(process.env.BOSTRAT_STATE_DIR||Ot.join(Sn,".bostrat"),"repos"),di=[...(process.env.BOSTRAT_REPOS_ROOT||Ot.join(Sn,"Documents")).split(","),Vr].map(e=>e.trim()).filter(Boolean),fi=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function ot(e=Date.now()){if(we)return{tripped:!1,holdMs:1/0};if(me>e)return{tripped:!1,holdMs:me-e};if((!Ue||e-Ue>=nt.windowMs)&&(Ue=e,Be=0),Be++,Be<nt.trip)return{tripped:!1,holdMs:0};rt++;let t=Math.min(nt.minMs*2**(rt-1),nt.maxMs);return me=e+t,Be=0,Ue=0,{tripped:!0,holdMs:t}}function kn(){Be=0,Ue=0,rt=0,me=0}function He(e=Date.now()){return we?1/0:me>e?me-e:0}function st(e=Date.now()){return He(e)>0}function Rt(e={}){we={at:Date.now(),...e},me=1/0}function Nt(){return we}function An(e=Date.now()){return{held:st(e),holdMs:we?null:He(e),holds:rt,removed:we?{...we}:null}}var Jr,nt,Be,Ue,rt,me,we,It=S(()=>{Jr={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},nt={...Jr},Be=0,Ue=0,rt=0,me=0,we=null});import $n from"node:path";import Xr from"node:os";import{execFile as Zr}from"node:child_process";import{promisify as Qr}from"node:util";var Si,eo,vi,ki,Ai,Mt=S(()=>{vn();It();Si=Qr(Zr),eo=process.env.BOSTRAT_STATE_DIR||$n.join(process.env.HOME||Xr.tmpdir(),".bostrat"),vi=$n.join(eo,"repos"),ki=5*6e4,Ai=10*6e4});var xn=S(()=>{Mt()});import no from"node:fs/promises";import Ke from"node:path";import ro from"node:os";import{EventEmitter as oo}from"node:events";function so(e){return e?.cwd?Ke.join(e.cwd,".bostrat","events"):Ke.join(En,"events")}async function Pt(e,t){let n,o;typeof e=="string"&&t?(n=e,o=t):(o=typeof e=="string"?e:e?.id,n=typeof e=="string"?Ke.join(En,"events"):so(e));let s;try{s=await no.readFile(io(n,o),"utf8")}catch{return[]}let l=[];for(let u of s.split(`
|
|
6
|
+
`))if(u.trim())try{l.push(JSON.parse(co(u)?lo(u):u))}catch{}return l}var We,En,io,ao,co,lo,it=S(()=>{We=new oo;We.setMaxListeners(0);En=process.env.BOSTRAT_STATE_DIR||Ke.join(process.env.HOME||ro.tmpdir(),".bostrat");io=(e,t)=>Ke.join(e,`${t}.ndjson`),ao=/(?<!\\)((?:\\\\)*)\\u0000/g,co=e=>e.includes("\\u0000"),lo=e=>e.replace(ao,"$1\\ufffd")});import fo from"node:os";import po from"node:path";import{execFile as ho}from"node:child_process";import{promisify as mo}from"node:util";var Hi,Ki,Wi,zi,Yi,qi,On=S(()=>{xn();it();Hi=mo(ho),Ki=process.env.BOSTRAT_STATE_DIR||po.join(process.env.HOME||fo.tmpdir(),".bostrat"),Wi=25*1024,zi=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,Yi=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,qi=Promise.resolve()});var Rn=S(()=>{});var Qi,Nn=S(()=>{Mt();Rn();Qi=60*6e4});var In=S(()=>{Nn()});import wo from"node:os";import Mn from"node:path";var yo,da,fa,Dt=S(()=>{jt();yo=process.env.BOSTRAT_DEBUG_DIR||Mn.join(wo.homedir(),".bostrat","debug"),da=Mn.join(yo,"handoff.jsonl"),fa=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import Pn from"node:path";import go from"node:os";var at,To,ga,Dn,Ta,_a,jn=S(()=>{tt();at="BOSTRAT_NODE_URL",To=process.env.BOSTRAT_STATE_DIR||Pn.join(process.env.HOME||go.tmpdir(),".bostrat"),ga=Pn.join(To,"git-hooks"),Dn=`#!/bin/sh
|
|
7
7
|
# bostrat git hook shim (agent/src/git-hooks.js) \u2014 chains to the repo's own hook,
|
|
8
8
|
# then stamps/reports for rework attribution when running inside a bostrat box.
|
|
9
9
|
hook=$(basename "$0")
|
|
@@ -18,28 +18,28 @@ esac
|
|
|
18
18
|
if [ -x "$orig/$hook" ] && [ "$orig/$hook" != "$0" ]; then
|
|
19
19
|
"$orig/$hook" "$@" || exit $?
|
|
20
20
|
fi
|
|
21
|
-
`,
|
|
21
|
+
`,Ta=`${Dn}
|
|
22
22
|
# \u2500\u2500 bostrat: append provenance trailers (Layer 0). Skipped for merge commits
|
|
23
23
|
# (nobody "wrote" a merge) and outside a box (no token / no node url).
|
|
24
24
|
[ -z "$${he}" ] && exit 0
|
|
25
|
-
[ -z "$${
|
|
25
|
+
[ -z "$${at}" ] && exit 0
|
|
26
26
|
[ "$2" = "merge" ] && exit 0
|
|
27
|
-
trailers=$(curl -sS -m 3 -H "${
|
|
27
|
+
trailers=$(curl -sS -m 3 -H "${et}: $${he}" "$${at}/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
|
+
`,_a=`${Dn}
|
|
34
34
|
# \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
|
|
35
35
|
[ -z "$${he}" ] && exit 0
|
|
36
|
-
[ -z "$${
|
|
36
|
+
[ -z "$${at}" ] && 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 "$${at}/api/git/committed" \\
|
|
40
|
+
-H 'content-type: application/json' -H "${et}: $${he}" --data-binary @- >/dev/null 2>&1 || true
|
|
41
41
|
exit 0
|
|
42
|
-
`});import{execFile as
|
|
42
|
+
`});import{execFile as bo}from"node:child_process";import{promisify as So}from"node:util";import vo from"node:fs";function Ln(e){return`/tmp/tmux-${e}/default`}function Ao({explicit:e,legacyExists:t,runtimeDir:n,uid:o}){if(e)return e;let s=Ln(o);return t?s:n?`${n}/bostrat/tmux-default`:s}async function Ft(e,{loginShell:t=!1,failOpen:n=!1}={}){let o=await xo(e,{loginShell:t});return o===Bn?!0:o===Ct?!1:n}async function xo(e,{loginShell:t=!1,timeoutMs:n=$o}={}){if(!e)return Ct;let o=t?process.env.SHELL||"/bin/sh":"sh",s=t?"-lic":"-c";try{return await ko(o,[s,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),Bn}catch(l){return l?.killed||l?.signal?Fn:l?.code===1||l?.code===127?Ct:Fn}}var ko,Ha,Cn,Ka,Wa,za,Ya,Bn,Ct,Fn,$o,ct,qa,Ga,Va,Ja,Xa,jt=S(()=>{Tn();_n();bn();On();In();Dt();tt();jn();ko=So(bo),Ha=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";Cn=typeof process.getuid=="function"?process.getuid():0,Ka=Ao({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return vo.existsSync(Ln(Cn))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:Cn}),Wa=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",za=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Ya=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]);Bn="present",Ct="absent",Fn="unknown",$o=5e3;ct={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"},qa=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Ga=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Va=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Ja=Number(process.env.BOSTRAT_BOX_COLS)||120,Xa=Number(process.env.BOSTRAT_BOX_ROWS)||40});var Yn={};At(Yn,{NODE_IMAGE:()=>Bt,commandPlan:()=>Kn,flyToml:()=>Hn,flyWizard:()=>Do,parseFlyFlags:()=>Wn,stageConfig:()=>zn});import Lt from"node:fs";import ye from"node:path";import Eo from"node:os";import Oo from"node:readline/promises";import{execFile as Ro}from"node:child_process";import{createRequire as No}from"node:module";import{randomUUID as Io}from"node:crypto";function Hn({app:e,region:t,nodeName:n=e,planeUrl:o=Un,image:s=Bt}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
|
|
43
43
|
# Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
|
|
44
44
|
# No [http_service] and none should be added: the node dials OUT to the plane;
|
|
45
45
|
# nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
|
|
@@ -79,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 Kn({app:e,org:t,region:n,sizeGb:o,token:s,owner:l,dir:u}){let p=[`BOSTRAT_PLANE_TOKEN=${s}`,...l?[`BOSTRAT_OWNER=${l}`]:[]];return[{argv:["apps","create",e,"-o",t],display:`fly apps create ${e} -o ${t}`,tolerate:/already|taken|exists/i},{argv:["volumes","create","node_data","-a",e,"-r",n,"-s",String(o),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${o} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted>${l?" BOSTRAT_OWNER=\u2026":""} via stdin`,stdin:p.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",ye.join(u,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${u} -c ${ye.join(u,"fly.toml")} -a ${e} --ha=false`}]}function Wn(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--owner":"owner","--image":"image"};for(let o=0;o<e.length;o++){let s=e[o];if(s==="--yes"||s==="-y")t.yes=!0;else if(n[s])t[n[s]]=e[++o]??"";else if(s.startsWith("--")&&s.includes("=")){let[l,...u]=s.split("=");n[l]?t[n[l]]=u.join("="):l==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function zn({app:e,dest:t,toml:n}){let o=t||ye.join(Eo.homedir(),".bostrat","fly",e);Lt.mkdirSync(o,{recursive:!0});for(let s of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])Lt.rmSync(ye.join(o,s),{recursive:!0,force:!0});return Lt.writeFileSync(ye.join(o,"fly.toml"),n),{dir:o,manifest:["fly.toml"]}}async function Po({ask:e,output:t,exec:n,flag:o}){if(o)return o;try{let{stdout:s}=await lt(["orgs","list","--json"],{exec:n}),l=JSON.parse(s),u=Array.isArray(l)?l.map(p=>p.Slug||p.slug).filter(Boolean):Object.keys(l);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 Do({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:o,stageDest:s}={}){let l=Wn(e),u=Oo.createInterface({input:t,output:n}),p=async(k,Y)=>(await u.question(Y?`${k} [${Y}]: `:`${k}: `)).trim()||Y||"",T=k=>(u.close(),k);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"),T(1)}let
|
|
90
|
-
`),T(1);let
|
|
91
|
-
wrote ${
|
|
88
|
+
`);try{await lt(["version"],{exec:o})}catch{return n.write("\u2717 `fly` (flyctl) is not installed or not on PATH.\n install: https://fly.io/docs/flyctl/install/ \u2014 then re-run `bostrat-node fly`\n"),T(1)}try{let{stdout:k}=await lt(["auth","whoami"],{exec:o});n.write(`\u2713 signed in to Fly as ${k.trim()}
|
|
89
|
+
`)}catch{return n.write("\u2717 not signed in to Fly. Run `fly auth login` (or `fly auth signup`) and re-run `bostrat-node fly`.\n"),T(1)}let y=await Po({ask:p,output:n,exec:o,flag:l.org}),f=l.app||await p("App name",`bostrat-node-${Io().slice(0,4)}`),_=l.region||await p("Region (see `fly platform regions`)","iad"),I=l.sizeGb||Number(await p("Volume size GB (logins + repos live here)","10"))||10,A=l.name||f,v=l.planeUrl||Un,g=l.token||await p("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!g)return n.write(`\u2717 a node token is required \u2014 mint one in the bostrat setup chat (Connect a node \u2192 Fly), then re-run with it.
|
|
90
|
+
`),T(1);let j=l.owner??await p("Owner userId (shown next to the token; empty = infer from token)",""),U=l.image||Bt,{dir:P}=zn({app:f,dest:s,toml:Hn({app:f,region:_,nodeName:A,planeUrl:v,image:U})});n.write(`
|
|
91
|
+
wrote ${ye.join(P,"fly.toml")} \u2014 deploys the prebuilt node image ${U}
|
|
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
|
|
95
|
+
`);let H=Kn({app:f,org:y,region:_,sizeGb:I,token:g,owner:j,dir:P});for(let k of H)n.write(` $ ${k.display}
|
|
96
96
|
`);if(!l.yes&&(await p(`
|
|
97
97
|
Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u2014 nothing was created. Re-run any time; the staged context is kept.
|
|
98
|
-
`),T(1);for(let
|
|
99
|
-
\u2192 ${
|
|
100
|
-
`);try{let{stdout:
|
|
101
|
-
`).map(
|
|
98
|
+
`),T(1);for(let k of H){n.write(`
|
|
99
|
+
\u2192 ${k.display}
|
|
100
|
+
`);try{let{stdout:Y,stderr:Te}=await lt(k.argv,{stdin:k.stdin,exec:o}),_e=`${Y||""}${Te||""}`.trim();_e&&n.write(_e.split(`
|
|
101
|
+
`).map(qe=>` ${qe}`).join(`
|
|
102
102
|
`)+`
|
|
103
|
-
`)}catch(
|
|
104
|
-
`);continue}return n.write(`\u2717 failed: ${
|
|
103
|
+
`)}catch(Y){let Te=`${Y?.stdout||""}${Y?.stderr||""}${Y?.message||""}`;if(k.tolerate&&k.tolerate.test(Te)){n.write(` (already exists \u2014 continuing)
|
|
104
|
+
`);continue}return n.write(`\u2717 failed: ${Te.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,42 +109,42 @@ 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 ${f}
|
|
112
|
-
redeploy: fly deploy ${
|
|
112
|
+
redeploy: fly deploy ${P} -c ${ye.join(P,"fly.toml")} -a ${f} --ha=false
|
|
113
113
|
Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
|
|
114
114
|
boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
|
|
115
|
-
`),T(0)}var gn,co,vt,Ve,kn=k(()=>{gn="wss://plane.bostrat.ai/v1/node",co=io(import.meta.url)("../package.json").version,vt=`ghcr.io/globocodes/bostrat-node:${co}`;Ve=(e,{stdin:t,exec:n}={})=>new Promise((o,s)=>{if(n)return n(e,{stdin:t}).then(o,s);let l=so("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(u,p,T)=>u?s(Object.assign(u,{stdout:p,stderr:T})):o({stdout:p,stderr:T}));t!=null&&l.stdin?.end(t)})});function An(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!po.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 ho(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:An(s.from,"from",n),toMs:An(s.to,"to",n)}))}return t}var fo,po,Ma,Pa,$n=k(()=>{fo={"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"GA rates; verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-08-17",note:"$2/$10 is the standard price (intro pricing made permanent; the 2026-09-01 $3/$15 increase was cancelled) \u2014 verified 2026-08-17 against platform.claude.com/docs/en/about-claude/pricing."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-03, re-verified 2026-08-17 (developers.openai.com pricing); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-08-24",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-terra":[{from:null,to:"2026-08-16",input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:2,output:12,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:"2026-08-16",input:1,output:6,cacheWrite:1.25,cacheRead:.1,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:.2,output:1.2,cacheWrite:.25,cacheRead:.02,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}]},po=/^\d{4}-\d{2}-\d{2}$/;Ma=ho(fo),Pa=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var xn=k(()=>{$n()});import En from"node:fs/promises";import Nn from"node:path";import mo from"node:os";function Mn(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Pn(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Dn(e){let t=new Date(Mn(e));return t.setDate(t.getDate()+7),t.getTime()}function jn(e){let t=new Date(Pn(e));return t.setMonth(t.getMonth()+1),t.getTime()}function _o(e=Date.now()){for(let[t,n]of Object.entries(go)){let o=n.startOf(e);if(o!==Je[t]){Je[t]=o;for(let s of kt.values())s[t]=0;for(let s of On)s.includes(`:${t}:`)&&!s.endsWith(`:${o}`)&&On.delete(s)}}}function bo(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 l of["weeklyUsd","monthlyUsd"]){let u=o?.[l];if(u==null||u==="")continue;let p=Number(u);if(!Number.isFinite(p)||p<=0)throw new Error(`${n}.${l} must be a positive number or null`);s[l]=p}Object.keys(s).length&&(t[n]=s)}return t}async function Cn(e,{source:t="local",updatedAt:n=Date.now()}={}){ve={caps:bo(e),updatedAt:n,source:t};try{await En.mkdir(In,{recursive:!0}),await En.writeFile(wo(),JSON.stringify(ve,null,2))}catch{}return So()}function So(e=Date.now()){_o(e);let t=new Set([...kt.keys(),...Object.keys(ve?.caps||{})]),n={};for(let o of t){let s=kt.get(o);n[o]={weeklyUsd:Rn(s?.weekly||0),monthlyUsd:Rn(s?.monthly||0)}}return{caps:ve?.caps||{},configured:!!ve,seeded:To,updatedAt:ve?.updatedAt??null,spent:n,windows:{weekly:{start:Je.weekly,resetsAt:Dn(e)},monthly:{start:Je.monthly,resetsAt:jn(e)}},warnPct:yo}}var In,wo,yo,go,ve,To,Je,kt,On,Rn,Fn=k(()=>{qe();xn();In=process.env.BOSTRAT_STATE_DIR||Nn.join(process.env.HOME||mo.tmpdir(),".bostrat"),wo=()=>Nn.join(In,"usage-caps.json"),yo=.8;go={weekly:{startOf:Mn,nextStart:Dn,capKey:"weeklyUsd"},monthly:{startOf:Pn,nextStart:jn,capKey:"monthlyUsd"}},ve=null,To=!1,Je={weekly:0,monthly:0},kt=new Map,On=new Set;Rn=e=>Math.round(e*1e4)/1e4});var Gn={};dt(Gn,{detectInstallKind:()=>Ae,detectProviderAuth:()=>qn,startPlaneLink:()=>jo,updateCommandFor:()=>Fe,versionLt:()=>ke});import zn from"node:fs";import Ce from"node:fs/promises";import vo from"node:http";import V from"node:path";import Xe from"node:os";import{createRequire as ko}from"node:module";import At from"ws";function Ae({env:e=process.env,pkgDir:t=V.resolve(V.dirname(new URL(import.meta.url).pathname),".."),exists:n=zn.existsSync}={}){let o=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(o)?o:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(V.join(t,"..",".git"))?"git-checkout":"dev"}function ke(e,t){let n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);if(n.some(Number.isNaN)||o.some(Number.isNaN))return!1;for(let s=0;s<Math.max(n.length,o.length);s++){let l=(n[s]||0)-(o[s]||0);if(l)return l<0}return!1}function Fe(e){switch(e){case"npm-global":return"npm install -g bostrat-node && restart the bostrat-node service";case"git-checkout":return"scripts/deploy-pi.sh (or The Bakery \u2192 Deploy to Pi \u2192 bostrat)";case"container":return"Links \u2192 Fly \u2192 Update (or the plane's auto-update while the node sleeps)";default:return"update this node's bostrat-node checkout/install"}}function qn({home:e=process.env.HOME||Xe.homedir(),env:t=process.env}={}){let n=o=>{try{return zn.statSync(o),!0}catch{return!1}};return{claude:n(V.join(e,".claude",".credentials.json")),codex:n(V.join(t.CODEX_HOME||V.join(e,".codex"),"auth.json"))}}function jo({url:e,token:t,nodeId:n=Xe.hostname(),name:o=Xe.hostname(),listTracks:s,detectAgents:l=null,onTracksTransferred:u=null,sampleMetrics:p=null,deliverySample:T=null,onHashKey:w=null,metricsMs:f=Do,onUpdateAvailable:_=null,onUpdatePolicy:R=null,onHelloRefused:A=null,updatePolicy:S=null,installKind:g=Ae(),selfUrl:D=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:B=null,onDegraded:z=null,onRecovered:U=null,onConnected:v=null,ingestMode:j=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:ce=No,unackedRetryMs:le=Ro,pingMs:tt=Oo,maxInflightEvents:ar=Mo,httpTimeoutMs:Le=Po,stallBackoffMinMs:Mt=Io,fetchImpl:Pt=globalThis.fetch,log:y=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof s!="function")throw new Error("plane-link: listTracks is required");e=Pe(e);let cr=D.replace(/^http/,"ws"),Dt=new Set,ue=new Map,de=new Map,nt=V.join(Ln,"plane-link","cursor.json"),rt=V.join(Ln,"plane-link","dead-letter.ndjson"),jt=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),fe={},ne={},$=new Map,Be=null,re=null,Q=0,Ee=0,Ct=0,Ft=Promise.resolve(),E="ws",ye=0,q=!1,pe=0,ot=!1,H=se,ge=new Set,oe=[],C=null,X=null,Y=!1,st=!1,Oe=Bn,Re=null,Te=null,_e=null,ee=null,te=null,it=!1,Ue=0;async function lr(){try{fe=JSON.parse(await Ce.readFile(nt,"utf8"))}catch{fe={}}}function ur(){it=!0,!_e&&(_e=setTimeout(async()=>{if(_e=null,!!it){it=!1;try{await Ce.mkdir(V.dirname(nt),{recursive:!0}),await Ce.writeFile(nt,JSON.stringify(fe))}catch(a){y.error("[plane-link] cursor flush failed:",a?.message||a)}}},Eo),_e.unref?.())}function N(a){return!X||X.readyState!==At.OPEN?!1:(X.send(JSON.stringify(a)),!0)}function Ne(a){let c=Date.now();for(let{trackId:r,event:i}of a){let d=$.get(i.id);$.set(i.id,{trackId:r,seq:i.seq,event:i,sentAt:c,firstSentAt:d?.firstSentAt??c,retryAt:c+le,tries:(d?.tries??0)+1,nacks:d?.nacks??0})}return E==="http"?(hr(a),!0):N({v:I,ch:"events",type:"append",events:a})}function dr(a){let c=null;for(let r of $.values())r.trackId===a&&(c==null||r.seq<c)&&(c=r.seq);return c}function at(a){let c=ne[a];if(c==null)return;let r=dr(a),i=r==null?c:Math.min(c,r-1);i>(fe[a]??0)&&(fe[a]=i,ur())}function Ie(){if(Be=Date.now(),re!=null){let a=Date.now()-re;y.log(`[plane-link] spine sync recovered after ${Math.round(a/1e3)}s degraded (${Q} stall redial(s))`);let c=re;re=null,Q=0,Ee=0,q=!1,pe=0;try{U?.({since:c,downMs:a})}catch(r){y.error(`[plane-link] onRecovered failed: ${r?.message||r}`)}}}function ct(a){if(!Array.isArray(a)||!a.length)return;let c=new Set;for(let r of a){let i=$.get(r);i&&($.delete(r),(ne[i.trackId]??0)<i.seq&&(ne[i.trackId]=i.seq),c.add(i.trackId))}for(let r of c)at(r);Ie()}function Lt(a,c){Ct++;let r={at:Date.now(),trackId:a.trackId,seq:a.seq,id:a.event?.id??null,type:a.event?.type??null,reason:c,event:a.event??null};y.error(`[plane-link] DEAD-LETTER ${a.trackId} seq ${a.seq} (${r.type??"?"}): plane rejected it permanently (${c}) \u2014 kept in ${rt}`),Ft=Ft.then(async()=>{await Ce.mkdir(V.dirname(rt),{recursive:!0}),await Ce.appendFile(rt,JSON.stringify(r)+`
|
|
116
|
-
`)}).catch(i=>y.error(`[plane-link] dead-letter write failed: ${i?.message||i}`))}function Bt(a,c,r,i=null){if(!Array.isArray(a)||!a.length)return;let d=new Set,h=Date.now();for(let m of a){let b=$.get(m);b&&(r?($.delete(m),Lt(b,c),(ne[b.trackId]??0)<b.seq&&(ne[b.trackId]=b.seq),d.add(b.trackId)):(b.nacks++,b.retryAt=h+Math.max(1e3,Number(i)||le)))}for(let m of d)at(m);Ie()}function Ut(a=Date.now()){let c=1/0;for(let r of $.values())r.firstSentAt<c&&(c=r.firstSentAt);return c===1/0?0:a-c}function Ht(){if(!Y||!$.size)return;let a=Date.now(),c=Ut(a);if(c<ce||Be!=null&&a-Be<ce||E==="http"&&q||Ee>a)return;Q++;let r=Math.min(Mt*2**(Q-1),Hn);if(re==null){re=a-c,y.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(c/1e3)}s with ${$.size} event(s) in flight (${E} door) \u2014 the plane is not answering appends`);try{z?.({since:re,unacked:$.size,oldestAgeMs:c,mode:E})}catch(i){y.error(`[plane-link] onDegraded failed: ${i?.message||i}`)}}if(E==="http"){q=!0,pe=a+r,y.error(`[plane-link] ingest circuit OPEN (stall #${Q}); probing /v1/ingest/health in ${Math.round(r/1e3)}s`);return}Ee=a+r,y.error(`[plane-link] closing the link and redialing in ${Math.round(r/1e3)}s (stall redial #${Q})`);try{X?.terminate()}catch{}}function lt(){if(!Y)return;let a=Date.now();if(E==="http"&&q)return;let c=[...$.values()].filter(i=>i.event&&i.retryAt<=a&&!(E==="http"&&ge.has(i.trackId)));if(!c.length)return;c.sort((i,d)=>i.trackId===d.trackId?i.seq-d.seq:i.trackId<d.trackId?-1:1),y.log(`[plane-link] re-sending ${c.length} unacked event(s) the plane never confirmed`);let r=E==="http"?H:se;if(E==="http"){let i=new Map;for(let d of c)(i.get(d.trackId)??i.set(d.trackId,[]).get(d.trackId)).push(d);for(let[,d]of i){if(ye>=$t)return;Ne(d.slice(0,r).map(h=>({trackId:h.trackId,event:h.event})))}return}for(let i=0;i<c.length;i+=r){let d=c.slice(i,i+r).map(h=>({trackId:h.trackId,event:h.event}));if(!Ne(d))return}}async function fr(a=null){for(;;){if(!Y)return!1;let c=$.size<ar,r=E!=="http"||ye<$t&&!q&&(!a||!ge.has(a));if(c&&r)return!0;await new Promise(i=>setTimeout(i,100))}}function ut(){if(C=null,!Y||!oe.length)return;let a=oe;if(oe=[],E!=="http"){for(let r=0;r<a.length;r+=se)Ne(a.slice(r,r+se));return}let c=new Map;for(let r of a)(c.get(r.trackId)??c.set(r.trackId,[]).get(r.trackId)).push(r);for(let[r,i]of c){if(ge.has(r)||ye>=$t||q){oe.push(...i);continue}for(let d=0;d<i.length;d+=H)Ne(i.slice(d,d+H))}oe.length&&!C&&(C=setTimeout(ut,Kn),C.unref?.())}let pr=a=>{let c=new Map;for(let{trackId:r,event:i}of a)(c.get(r)??c.set(r,[]).get(r)).push(i);return[...c].map(([r,i])=>({trackId:r,events:i}))},be=(a,c,r,{progress:i})=>{let d=Date.now();for(let{event:h}of a){let m=$.get(h.id);m&&(m.nacks++,m.retryAt=d+Math.max(1e3,r||le))}i&&Ie()};async function hr(a){let c=new Set(a.map(r=>r.trackId));for(let r of c)ge.add(r);ye++;try{let r=await Pt(`${jt}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:pr(a)}),signal:AbortSignal.timeout(Le)}),i=(Number(r.headers.get("retry-after"))||0)*1e3;if(r.status===200){let d=await r.json();H=se;for(let h of d.results??[]){ct(h.acked??[]);let m=(b,P)=>{let K=new Map;for(let x of b??[])(K.get(x.reason)??K.set(x.reason,[]).get(x.reason)).push(x.id);for(let[x,Yt]of K)Bt(Yt,x,P,d.retryAfterMs??null)};m(h.rejected,!0),m(h.deferred,!1)}ct(d.discarded??[]),Ie();return}if(r.status===429){be(a,"overloaded",i||5e3,{progress:!0});return}if(r.status===413&&a.length>1){H=Math.max(1,Math.floor(a.length/2)),y.error(`[plane-link] ingest request too large (${a.length} events) \u2014 halving batches to ${H}`),be(a,"too_large",1e3,{progress:!0});return}if(r.status===413){let d=$.get(a[0].event.id);d&&($.delete(d.event.id),Lt(d,"too_large"),(ne[d.trackId]??0)<d.seq&&(ne[d.trackId]=d.seq),at(d.trackId)),Ie();return}if(r.status===401||r.status===403){if(Date.now()-Ue>=Wn){Ue=Date.now();let d="";try{d=(await r.json())?.error??""}catch{}y.error(`[plane-link] plane refused ingest (HTTP ${r.status}${d?`: ${d}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}be(a,`http_${r.status}`,6e4,{progress:!1});return}if(r.status===400){y.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${a.length} event(s) for retry; this is a bug, not data`),be(a,"http_400",6e4,{progress:!1});return}be(a,`http_${r.status}`,i||5e3,{progress:!1})}catch(r){let i=r?.name==="TimeoutError"||r?.name==="AbortError";i&&a.length>1&&(H=Math.max(1,Math.floor(a.length/2)),y.error(`[plane-link] ingest request of ${a.length} event(s) outlived its ${Le} ms deadline \u2014 halving batches to ${H}`)),be(a,i?"timeout":"network",5e3,{progress:!1})}finally{ye--;for(let r of c)ge.delete(r)}}async function mr(){if(E!=="http"||!q||!Y||ot)return;let a=Date.now();if(!(pe>a)){ot=!0;try{let c=await Pt(`${jt}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(Le)});if(!c.ok)throw new Error(`HTTP ${c.status}`);y.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),q=!1,pe=0,Ee=Date.now()+Le+le+1e3;for(let r of $.values())r.retryAt=Math.min(r.retryAt,Date.now());lt()}catch(c){Q++;let r=Math.min(Mt*2**(Q-1),Hn);pe=Date.now()+r,y.error(`[plane-link] ingest door still not answering (${c?.message||c}); next probe in ${Math.round(r/1e3)}s`)}finally{ot=!1}}}function Kt(){let a=Date.now();return{mode:E,unacked:$.size,oldestUnackedAgeMs:Ut(a),lastProgressAt:Be,degradedSince:re,stallRedials:Q,deadLettered:Ct,http:E==="http"?{inFlight:ye,circuitOpen:q,nextProbeInMs:q?Math.max(0,pe-a):0,batchCap:H}:null}}async function Wt(){if(!p)return;let a;try{a=await p()}catch(r){y.error("[plane-link] metrics sample failed:",r?.message||r);return}let c=null;try{c=T?.()??null}catch{}a&&N({v:I,ch:"ctl",type:"metrics",metrics:{...a,planeLink:Kt(),...c?{delivery:c}:{}}})}function wr(){p&&(te&&clearInterval(te),Wt(),te=setInterval(Wt,f),te.unref?.())}async function yr(){let a;try{a=await s()}catch(c){y.error("[plane-link] backfill listTracks failed:",c?.message||c);return}N({v:I,ch:"ctl",type:"tracks",ids:a.filter(c=>!c.transferredTo).map(c=>c.id).filter(c=>typeof c=="string")});for(let c of a){if(!Y)return;let r;try{r=await yt(c)}catch{continue}let i=fe[c.id]??0,d=r.filter(m=>m.seq>i&&typeof m.id=="string"),h=E==="http"?H:se;for(let m=0;m<d.length;m+=h){if(!await fr(c.id))return;let b=d.slice(m,m+Math.min(h,E==="http"?H:se)).map(P=>({trackId:c.id,event:P}));if(!Ne(b))return}}}function zt(a){!Y||!a?.trackId||typeof a.id!="string"||(oe.push({trackId:a.trackId,event:a}),C||(C=setTimeout(ut,Kn),C.unref?.()))}let Me=new Map;async function gr(a){let{reqId:c,method:r,path:i,headers:d={},body:h}=a,m=Object.fromEntries(Object.entries(d).filter(([,P])=>P!=null)),b=new AbortController;Me.set(c,b);try{if(a.host){await Tr(a,m,b);return}B&&(m["x-bostrat-token"]=B);let P=await fetch(D+i,{method:r,headers:m,body:h?Buffer.from(h,"base64"):void 0,signal:b.signal}),K=Object.fromEntries(P.headers);for(let x of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete K[x];if(K["content-type"]||(K["content-type"]="application/octet-stream"),N({v:I,ch:"control",type:"http_head",reqId:c,status:P.status,headers:K}),P.body){for await(let x of P.body)if(!N({v:I,ch:"control",type:"http_data",reqId:c,data:Buffer.from(x).toString("base64")}))break}N({v:I,ch:"control",type:"http_end",reqId:c,error:null})}finally{Me.delete(c)}}function Tr(a,c,r){let{reqId:i,method:d,path:h,body:m}=a,b=new URL(D);return new Promise(P=>{let K=vo.request({host:b.hostname,port:b.port,method:d,path:h,headers:{...c,host:a.host},signal:r.signal},x=>{let{connection:Yt,"keep-alive":ks,"transfer-encoding":As,upgrade:$s,..._r}=x.headers;N({v:I,ch:"control",type:"http_head",reqId:i,status:x.statusCode||502,headers:_r}),x.on("data",br=>{N({v:I,ch:"control",type:"http_data",reqId:i,data:Buffer.from(br).toString("base64")})||x.destroy()}),x.on("end",()=>{N({v:I,ch:"control",type:"http_end",reqId:i,error:null}),P()}),x.on("error",()=>{N({v:I,ch:"control",type:"http_end",reqId:i,error:"view upstream error"}),P()})});K.on("error",x=>{N({v:I,ch:"control",type:"http_end",reqId:i,error:x?.message||"view request failed"}),P()}),m&&K.write(Buffer.from(m,"base64")),K.end()})}function qt(){if(st)return;X=new At(e,{headers:{authorization:`Bearer ${t}`}}),X.on("open",async()=>{let c=null;try{c=await l?.()||null}catch{c=null}N({v:I,ch:"ctl",type:"hello",nodeId:n,name:o,platform:process.platform,version:G,installKind:g,...typeof S=="function"?{updatePolicy:S()}:S?{updatePolicy:S}:{},providers:qn(),...c?{agents:c}:{}})}),X.on("message",c=>{let r;try{r=JSON.parse(c)}catch{return}if(r.ch==="ctl"&&r.type==="hello_ok"){Y=!0,Oe=Bn,Re=null,y.log(`[plane-link] connected to plane as ${n}`);try{v?.()}catch{}if(typeof r.hashKey=="string"&&r.hashKey)try{w?.(r.hashKey)}catch{}r.minNodeVersion&&G&&ke(G,r.minNodeVersion)&&y.error(`[plane-link] this node is bostrat-node ${G}; the plane asks for \u2265${r.minNodeVersion} \u2014 update with: ${Fe(g)}`);try{R?.(typeof r.updatePolicy=="string"?r.updatePolicy:null)}catch{}let i=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;if(i&&G&&ke(G,i)&&!Dt.has(i)){Dt.add(i),y.log(`[plane-link] bostrat-node ${i} is available (this node runs ${G}) \u2014 ${Fe(g)}`);try{_?.({current:G,latest:i,min:r.minNodeVersion??null,installKind:g,required:!!(r.minNodeVersion&&ke(G,r.minNodeVersion))})}catch(h){y.error(`[plane-link] update notice failed: ${h?.message||h}`)}}let d=r.ingest==="http";E=j==="ws"?"ws":j==="http"||d?"http":"ws",j==="http"&&!d&&y.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),E==="http"&&y.log("[plane-link] spine rides the HTTPS ingest door"),q=!1,pe=0,H=se,ee&&clearInterval(ee),ee=setInterval(()=>{N({v:I,ch:"ctl",type:"ping"}),Ht(),mr().catch(()=>{}),lt(),oe.length&&!C&&ut()},tt),ee.unref?.(),wr(),yr().catch(h=>y.error("[plane-link] backfill failed:",h?.message||h));return}if(r.ch==="ctl"&&r.type==="hello_refused"){let i=typeof r.minNodeVersion=="string"?r.minNodeVersion:null,d=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;y.error(`[plane-link] plane REFUSED this node: bostrat-node ${G??"?"} is below its minimum ${i??"?"} \u2014 ${r.fix||Fe(g)}`),Oe=Un,Re=0;try{A?.({current:G,min:i,latest:d,fix:r.fix||Fe(g),installKind:g})}catch(h){y.error(`[plane-link] refusal handler failed: ${h?.message||h}`)}return}if(r.ch==="ctl"&&r.type==="update_policy"){try{R?.(typeof r.mode=="string"?r.mode:null)}catch{}return}if(r.ch==="ctl"&&r.type==="usage_caps"){Cn(r.caps??{},{source:"plane",updatedAt:r.updatedAt??Date.now()}).then(i=>y.log(`[plane-link] spend caps ${Object.keys(i.caps).length?`updated (${Object.keys(i.caps).join(", ")})`:"cleared"} from plane`)).catch(i=>y.error("[plane-link] spend-caps push rejected:",i?.message||i));return}if(r.ch==="ctl"&&r.type==="transferred"&&Array.isArray(r.tracks)){Promise.resolve().then(()=>u?.(r.tracks)).catch(i=>y.error("[plane-link] transfer notice failed:",i?.message||i));return}if(r.ch==="events"&&r.type==="ack"&&Array.isArray(r.ids)){ct(r.ids);return}if(r.ch==="events"&&r.type==="nack"&&Array.isArray(r.ids)){Bt(r.ids,r.reason,r.permanent===!0,r.retryAfterMs??null);return}if(r.ch==="control"&&r.type==="http_open"){gr(r).catch(i=>N({v:I,ch:"control",type:"http_end",reqId:r.reqId,error:i?.message||"tunnel error"}));return}if(r.ch==="control"&&r.type==="http_cancel"){Me.get(r.reqId)?.abort();return}if(r.ch==="attach"&&r.type==="open"){let i=new At(cr+r.path,Array.isArray(r.protocols)?r.protocols:[],r.host?{headers:{host:r.host}}:void 0);ue.set(r.streamId,i),de.set(r.streamId,[]),i.on("open",()=>{let h=de.get(r.streamId)||[];de.delete(r.streamId);for(let{buf:m,bin:b}of h)i.send(m,{binary:b})}),i.on("message",(h,m)=>{let b=m?h:Buffer.from(String(h));N({v:I,ch:"attach",type:"data",streamId:r.streamId,data:b.toString("base64"),...m?{bin:!0}:{}})});let d=()=>{de.delete(r.streamId),ue.delete(r.streamId)&&N({v:I,ch:"attach",type:"close",streamId:r.streamId})};i.on("close",d),i.on("error",d);return}if(r.ch==="attach"&&r.type==="data"){let i=ue.get(r.streamId);if(!i)return;let d=Buffer.from(r.data,"base64"),h=r.bin===!0,m=de.get(r.streamId);m?m.push({buf:d,bin:h}):i.send(d,{binary:h});return}if(r.ch==="attach"&&r.type==="close"){let i=ue.get(r.streamId);ue.delete(r.streamId),de.delete(r.streamId),i?.close();return}});let a=()=>{Y&&y.log("[plane-link] disconnected from plane"),Y=!1,ee&&(clearInterval(ee),ee=null),te&&(clearInterval(te),te=null),$.clear(),ne={},oe=[],C&&(clearTimeout(C),C=null),ge.clear();for(let i of ue.values())i.close();ue.clear(),de.clear();for(let i of Me.values())i.abort();if(Me.clear(),st||Te)return;Re==null&&(Re=Date.now());let c=Date.now()-Re<Ao,r=Math.max(c?$o+Math.random()*xo:Oe,Ee-Date.now());Te=setTimeout(()=>{Te=null,qt()},r),Te.unref?.(),c||(Oe=Math.min(Oe*2,Un))};X.on("close",a),X.on("error",c=>{let r=/Unexpected server response: (\d+)/.exec(c?.message||"")?.[1];(r==="401"||r==="403")&&Date.now()-Ue>=Wn&&(Ue=Date.now(),y.error(`[plane-link] plane refused this node's credentials (HTTP ${r}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`)),a()})}return je.on("event",zt),lr().then(qt),{stop:()=>{st=!0,je.off("event",zt),Te&&clearTimeout(Te),_e&&clearTimeout(_e),ee&&clearInterval(ee),te&&clearInterval(te),C&&clearTimeout(C),N({v:I,ch:"ctl",type:"bye",reason:"shutdown"}),X?.close()},status:()=>({connected:Y,nodeId:n,cursor:{...fe},inflight:$.size,...Kt()}),_tick:()=>{Ht(),lt()}}}var G,Ln,I,Bn,Un,Ao,$o,xo,se,Eo,Oo,Ro,Yn,No,Io,Hn,Mo,Kn,Po,$t,Do,Wn,xt=k(()=>{qe();Fn();ht();G=(()=>{try{return ko(import.meta.url)("../package.json").version||null}catch{return null}})(),Ln=process.env.BOSTRAT_STATE_DIR||V.join(process.env.HOME||Xe.tmpdir(),".bostrat");I=1,Bn=1e3,Un=3e4,Ao=6e4,$o=1500,xo=500,se=100,Eo=2e3,Oo=25e3,Ro=6e4,Yn=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},No=Yn(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Io=3e4,Hn=10*6e4,Mo=400,Kn=250,Po=Yn(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),$t=4,Do=6e4,Wn=6e4});import{execFile as Co}from"node:child_process";import{promisify as Fo}from"node:util";function Vn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var ic,ac,cc,Jn=k(()=>{gt();ic=Fo(Co),ac=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,cc=Promise.resolve()});var tr={};dt(tr,{ACTIONABLE_KINDS:()=>et,SELF_UPDATE_DIR:()=>Et,createAutoUpdater:()=>Xo,inFlight:()=>Rt,readStatus:()=>Ot,selfUpdatePlan:()=>Qn,settleSelfUpdate:()=>Jo,startSelfUpdate:()=>er,underService:()=>Zn,updatePolicy:()=>zo});import Xn from"node:fs";import ie from"node:fs/promises";import Lo from"node:os";import M from"node:path";import{spawn as Bo}from"node:child_process";import{createRequire as Uo}from"node:module";function zo({kind:e=Ae(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:et.has(e)?e==="git-checkout"||Zn(t)?"auto":"prompt":"off"}function Zn(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Qn({kind:e,to:t,from:n=Ze,statusFile:o=Qe,logFile:s=M.join(Et,"last.log"),port:l=Number(process.env.PORT)||3362,npmPrefix:u=null,serviceName:p=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:T=typeof process.getuid=="function"?process.getuid():0,liveDir:w=process.env.BOSTRAT_LIVE_CHECKOUT||M.resolve(M.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:f=Date.now()}={}){if(!et.has(e))throw new Error(`self-update: install kind "${e}" is not actionable here`);if(!/^\d+\.\d+\.\d+$/.test(String(t)))throw new Error(`self-update: bad target version "${t}"`);if(n&&!/^\d+\.\d+\.\d+$/.test(String(n)))throw new Error(`self-update: bad current version "${n}"`);let _=(D,B="")=>`write_status ${F(D)} ${B}`,R=process.platform==="darwin"?`launchctl kickstart -k gui/${T}/${p}`:`systemctl --user restart ${F(p)}`,A=`
|
|
115
|
+
`),T(0)}var Un,Mo,Bt,lt,qn=S(()=>{Un="wss://plane.bostrat.ai/v1/node",Mo=No(import.meta.url)("../package.json").version,Bt=`ghcr.io/globocodes/bostrat-node:${Mo}`;lt=(e,{stdin:t,exec:n}={})=>new Promise((o,s)=>{if(n)return n(e,{stdin:t}).then(o,s);let l=Ro("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(u,p,T)=>u?s(Object.assign(u,{stdout:p,stderr:T})):o({stdout:p,stderr:T}));t!=null&&l.stdin?.end(t)})});function Gn(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!Co.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let o=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(o))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return o}function Fo(e){let t={};for(let[n,o]of Object.entries(e)){if(!Array.isArray(o)||o.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=o.map(s=>({...s,fromMs:Gn(s.from,"from",n),toMs:Gn(s.to,"to",n)}))}return t}var jo,Co,ic,ac,Vn=S(()=>{jo={"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"GA rates; verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-08-17",note:"$2/$10 is the standard price (intro pricing made permanent; the 2026-09-01 $3/$15 increase was cancelled) \u2014 verified 2026-08-17 against platform.claude.com/docs/en/about-claude/pricing."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-03, re-verified 2026-08-17 (developers.openai.com pricing); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-08-24",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-terra":[{from:null,to:"2026-08-16",input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:2,output:12,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:"2026-08-16",input:1,output:6,cacheWrite:1.25,cacheRead:.1,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:.2,output:1.2,cacheWrite:.25,cacheRead:.02,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}]},Co=/^\d{4}-\d{2}-\d{2}$/;ic=Fo(jo),ac=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var Jn=S(()=>{Vn()});import Xn from"node:fs/promises";import er from"node:path";import Lo from"node:os";function nr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function rr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function or(e){let t=new Date(nr(e));return t.setDate(t.getDate()+7),t.getTime()}function sr(e){let t=new Date(rr(e));return t.setMonth(t.getMonth()+1),t.getTime()}function Wo(e=Date.now()){for(let[t,n]of Object.entries(Ho)){let o=n.startOf(e);if(o!==ut[t]){ut[t]=o;for(let s of Ut.values())s[t]=0;for(let s of Zn)s.includes(`:${t}:`)&&!s.endsWith(`:${o}`)&&Zn.delete(s)}}}function zo(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 l of["weeklyUsd","monthlyUsd"]){let u=o?.[l];if(u==null||u==="")continue;let p=Number(u);if(!Number.isFinite(p)||p<=0)throw new Error(`${n}.${l} must be a positive number or null`);s[l]=p}Object.keys(s).length&&(t[n]=s)}return t}async function ir(e,{source:t="local",updatedAt:n=Date.now()}={}){$e={caps:zo(e),updatedAt:n,source:t};try{await Xn.mkdir(tr,{recursive:!0}),await Xn.writeFile(Bo(),JSON.stringify($e,null,2))}catch{}return Yo()}function Yo(e=Date.now()){Wo(e);let t=new Set([...Ut.keys(),...Object.keys($e?.caps||{})]),n={};for(let o of t){let s=Ut.get(o);n[o]={weeklyUsd:Qn(s?.weekly||0),monthlyUsd:Qn(s?.monthly||0)}}return{caps:$e?.caps||{},configured:!!$e,seeded:Ko,updatedAt:$e?.updatedAt??null,spent:n,windows:{weekly:{start:ut.weekly,resetsAt:or(e)},monthly:{start:ut.monthly,resetsAt:sr(e)}},warnPct:Uo}}var tr,Bo,Uo,Ho,$e,Ko,ut,Ut,Zn,Qn,ar=S(()=>{it();Jn();tr=process.env.BOSTRAT_STATE_DIR||er.join(process.env.HOME||Lo.tmpdir(),".bostrat"),Bo=()=>er.join(tr,"usage-caps.json"),Uo=.8;Ho={weekly:{startOf:nr,nextStart:or,capKey:"weeklyUsd"},monthly:{startOf:rr,nextStart:sr,capKey:"monthlyUsd"}},$e=null,Ko=!1,ut={weekly:0,monthly:0},Ut=new Map,Zn=new Set;Qn=e=>Math.round(e*1e4)/1e4});var wr={};At(wr,{REMOVED_MARKER:()=>Yt,detectInstallKind:()=>Oe,detectProviderAuth:()=>hr,maskToken:()=>zt,readRemovedMarker:()=>pr,startPlaneLink:()=>is,updateCommandFor:()=>Ye,versionLt:()=>Ee});import xe from"node:fs";import ze from"node:fs/promises";import qo from"node:http";import F from"node:path";import dt from"node:os";import{createRequire as Go}from"node:module";import Ht from"ws";function zt(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function pr(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=F.resolve(F.dirname(new URL(import.meta.url).pathname),".."),exists:n=xe.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(F.join(t,"..",".git"))?"git-checkout":"dev"}function Ee(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 l=(n[s]||0)-(o[s]||0);if(l)return l<0}return!1}function Ye(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 hr({home:e=process.env.HOME||dt.homedir(),env:t=process.env}={}){let n=o=>{try{return xe.statSync(o),!0}catch{return!1}};return{claude:n(F.join(e,".claude",".credentials.json")),codex:n(F.join(t.CODEX_HOME||F.join(e,".codex"),"auth.json"))}}function is({url:e,token:t,nodeId:n=dt.hostname(),name:o=dt.hostname(),listTracks:s,detectAgents:l=null,onTracksTransferred:u=null,sampleMetrics:p=null,deliverySample:T=null,onHashKey:y=null,metricsMs:f=ss,onUpdateAvailable:_=null,onUpdatePolicy:I=null,onHelloRefused:A=null,updatePolicy:v=null,installKind:g=Oe(),selfUrl:j=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:U=null,removedMarkerFile:P=Yt,onRemoved:H=null,onDegraded:k=null,onRecovered:Y=null,onConnected:Te=null,ingestMode:_e=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:qe=ts,unackedRetryMs:Ge=es,pingMs:Or=Qo,maxInflightEvents:Rr=rs,httpTimeoutMs:Ve=os,stallBackoffMinMs:Qt=ns,fetchImpl:en=globalThis.fetch,log:m=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=Le(e);let Nr=j.replace(/^http/,"ws"),tn=new Set,le=new Map,ue=new Map,mt=F.join(Wt,"plane-link","cursor.json"),wt=F.join(Wt,"plane-link","dead-letter.ndjson"),nn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),de={},ne={},$=new Map,Je=null,re=null,Q=0,Ie=0,rn=0,on=Promise.resolve(),E="ws",be=0,q=!1,fe=0,yt=!1,K=ie,Se=new Set,oe=[],C=null,X=null,G=!1,gt=!1,Me=cr,Pe=null,ve=null,ke=null,ee=null,te=null,Tt=!1,Xe=0,De=!1,se=pr(P);if(se)if(se.tokenPreview===zt(t))De=!0,Rt({reason:se.reason??"removed",at:se.at??null,nodeId:se.nodeId??n}),m.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),m.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function _t({reason:i="removed",at:c=Date.now(),via:r="ctl"}={}){if(!De){De=!0,Rt({reason:i,at:c,nodeId:n,via:r});try{xe.mkdirSync(F.dirname(P),{recursive:!0}),xe.writeFileSync(P,JSON.stringify({at:c,reason:i,via:r,nodeId:n,tokenPreview:zt(t)},null,2))}catch(a){m.error(`[plane-link] could not write ${P}: ${a?.message||a}`)}m.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{H?.({reason:i,at:c,via:r})}catch{}hn({bye:!1})}}async function Ir(){try{de=JSON.parse(await ze.readFile(mt,"utf8"))}catch{de={}}}function Mr(){Tt=!0,!ke&&(ke=setTimeout(async()=>{if(ke=null,!!Tt){Tt=!1;try{await ze.mkdir(F.dirname(mt),{recursive:!0}),await ze.writeFile(mt,JSON.stringify(de))}catch(i){m.error("[plane-link] cursor flush failed:",i?.message||i)}}},Zo),ke.unref?.())}function O(i){return!X||X.readyState!==Ht.OPEN?!1:(X.send(JSON.stringify(i)),!0)}function je(i){let c=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:c,firstSentAt:d?.firstSentAt??c,retryAt:c+Ge,tries:(d?.tries??0)+1,nacks:d?.nacks??0})}return E==="http"?(Cr(i),!0):O({v:R,ch:"events",type:"append",events:i})}function Pr(i){let c=null;for(let r of $.values())r.trackId===i&&(c==null||r.seq<c)&&(c=r.seq);return c}function bt(i){let c=ne[i];if(c==null)return;let r=Pr(i),a=r==null?c:Math.min(c,r-1);a>(de[i]??0)&&(de[i]=a,Mr())}function Ce(){if(Je=Date.now(),re!=null){let i=Date.now()-re;m.log(`[plane-link] spine sync recovered after ${Math.round(i/1e3)}s degraded (${Q} stall redial(s))`);let c=re;re=null,Q=0,Ie=0,q=!1,fe=0;try{Y?.({since:c,downMs:i})}catch(r){m.error(`[plane-link] onRecovered failed: ${r?.message||r}`)}}}function St(i){if(!Array.isArray(i)||!i.length)return;let c=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),c.add(a.trackId))}for(let r of c)bt(r);Ce()}function sn(i,c){rn++;let r={at:Date.now(),trackId:i.trackId,seq:i.seq,id:i.event?.id??null,type:i.event?.type??null,reason:c,event:i.event??null};m.error(`[plane-link] DEAD-LETTER ${i.trackId} seq ${i.seq} (${r.type??"?"}): plane rejected it permanently (${c}) \u2014 kept in ${wt}`),on=on.then(async()=>{await ze.mkdir(F.dirname(wt),{recursive:!0}),await ze.appendFile(wt,JSON.stringify(r)+`
|
|
116
|
+
`)}).catch(a=>m.error(`[plane-link] dead-letter write failed: ${a?.message||a}`))}function an(i,c,r,a=null){if(!Array.isArray(i)||!i.length)return;let d=new Set,h=Date.now();for(let w of i){let b=$.get(w);b&&(r?($.delete(w),sn(b,c),(ne[b.trackId]??0)<b.seq&&(ne[b.trackId]=b.seq),d.add(b.trackId)):(b.nacks++,b.retryAt=h+Math.max(1e3,Number(a)||Ge)))}for(let w of d)bt(w);Ce()}function cn(i=Date.now()){let c=1/0;for(let r of $.values())r.firstSentAt<c&&(c=r.firstSentAt);return c===1/0?0:i-c}function ln(){if(!G||!$.size)return;let i=Date.now(),c=cn(i);if(c<qe||Je!=null&&i-Je<qe||E==="http"&&q||Ie>i)return;Q++;let r=Math.min(Qt*2**(Q-1),ur);if(re==null){re=i-c,m.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(c/1e3)}s with ${$.size} event(s) in flight (${E} door) \u2014 the plane is not answering appends`);try{k?.({since:re,unacked:$.size,oldestAgeMs:c,mode:E})}catch(a){m.error(`[plane-link] onDegraded failed: ${a?.message||a}`)}}if(E==="http"){q=!0,fe=i+r,m.error(`[plane-link] ingest circuit OPEN (stall #${Q}); probing /v1/ingest/health in ${Math.round(r/1e3)}s`);return}Ie=i+r,m.error(`[plane-link] closing the link and redialing in ${Math.round(r/1e3)}s (stall redial #${Q})`);try{X?.terminate()}catch{}}function vt(){if(!G)return;let i=Date.now();if(E==="http"&&q)return;let c=[...$.values()].filter(a=>a.event&&a.retryAt<=i&&!(E==="http"&&Se.has(a.trackId)));if(!c.length)return;c.sort((a,d)=>a.trackId===d.trackId?a.seq-d.seq:a.trackId<d.trackId?-1:1),m.log(`[plane-link] re-sending ${c.length} unacked event(s) the plane never confirmed`);let r=E==="http"?K:ie;if(E==="http"){let a=new Map;for(let d of c)(a.get(d.trackId)??a.set(d.trackId,[]).get(d.trackId)).push(d);for(let[,d]of a){if(be>=Kt)return;je(d.slice(0,r).map(h=>({trackId:h.trackId,event:h.event})))}return}for(let a=0;a<c.length;a+=r){let d=c.slice(a,a+r).map(h=>({trackId:h.trackId,event:h.event}));if(!je(d))return}}async function Dr(i=null){for(;;){if(!G)return!1;let c=$.size<Rr,r=E!=="http"||be<Kt&&!q&&(!i||!Se.has(i));if(c&&r)return!0;await new Promise(a=>setTimeout(a,100))}}function kt(){if(C=null,!G||!oe.length)return;let i=oe;if(oe=[],E!=="http"){for(let r=0;r<i.length;r+=ie)je(i.slice(r,r+ie));return}let c=new Map;for(let r of i)(c.get(r.trackId)??c.set(r.trackId,[]).get(r.trackId)).push(r);for(let[r,a]of c){if(Se.has(r)||be>=Kt||q){oe.push(...a);continue}for(let d=0;d<a.length;d+=K)je(a.slice(d,d+K))}oe.length&&!C&&(C=setTimeout(kt,dr),C.unref?.())}let jr=i=>{let c=new Map;for(let{trackId:r,event:a}of i)(c.get(r)??c.set(r,[]).get(r)).push(a);return[...c].map(([r,a])=>({trackId:r,events:a}))},pe=(i,c,r,{progress:a})=>{let d=Date.now();for(let{event:h}of i){let w=$.get(h.id);w&&(w.nacks++,w.retryAt=d+Math.max(1e3,r||Ge))}a&&Ce()};async function Cr(i){let c=new Set(i.map(r=>r.trackId));for(let r of c)Se.add(r);be++;try{let r=await en(`${nn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:jr(i)}),signal:AbortSignal.timeout(Ve)}),a=(Number(r.headers.get("retry-after"))||0)*1e3;if(r.status===200){let d=await r.json();K=ie;for(let h of d.results??[]){St(h.acked??[]);let w=(b,D)=>{let W=new Map;for(let x of b??[])(W.get(x.reason)??W.set(x.reason,[]).get(x.reason)).push(x.id);for(let[x,mn]of W)an(mn,x,D,d.retryAfterMs??null)};w(h.rejected,!0),w(h.deferred,!1)}St(d.discarded??[]),Ce();return}if(r.status===429){pe(i,"overloaded",a||5e3,{progress:!0});return}if(r.status===413&&i.length>1){K=Math.max(1,Math.floor(i.length/2)),m.error(`[plane-link] ingest request too large (${i.length} events) \u2014 halving batches to ${K}`),pe(i,"too_large",1e3,{progress:!0});return}if(r.status===413){let d=$.get(i[0].event.id);d&&($.delete(d.event.id),sn(d,"too_large"),(ne[d.trackId]??0)<d.seq&&(ne[d.trackId]=d.seq),bt(d.trackId)),Ce();return}if(r.status===410){_t({reason:"removed",via:"410"}),pe(i,"http_410",6e4,{progress:!1});return}if(r.status===401||r.status===403){let{tripped:d,holdMs:h}=ot();if(d&&m.error(`[plane-link] holding every plane call for ${Math.round(h/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Xe>=fr){Xe=Date.now();let w="";try{w=(await r.json())?.error??""}catch{}m.error(`[plane-link] plane refused ingest (HTTP ${r.status}${w?`: ${w}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}pe(i,`http_${r.status}`,Math.max(6e4,He()),{progress:!1});return}if(r.status===400){m.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`),pe(i,"http_400",6e4,{progress:!1});return}pe(i,`http_${r.status}`,a||5e3,{progress:!1})}catch(r){let a=r?.name==="TimeoutError"||r?.name==="AbortError";a&&i.length>1&&(K=Math.max(1,Math.floor(i.length/2)),m.error(`[plane-link] ingest request of ${i.length} event(s) outlived its ${Ve} ms deadline \u2014 halving batches to ${K}`)),pe(i,a?"timeout":"network",5e3,{progress:!1})}finally{be--;for(let r of c)Se.delete(r)}}async function Fr(){if(E!=="http"||!q||!G||yt)return;let i=Date.now();if(!(fe>i||st(i))){yt=!0;try{let c=await en(`${nn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(Ve)});if(!c.ok)throw new Error(`HTTP ${c.status}`);m.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),q=!1,fe=0,Ie=Date.now()+Ve+Ge+1e3;for(let r of $.values())r.retryAt=Math.min(r.retryAt,Date.now());vt()}catch(c){Q++;let r=Math.min(Qt*2**(Q-1),ur);fe=Date.now()+r,m.error(`[plane-link] ingest door still not answering (${c?.message||c}); next probe in ${Math.round(r/1e3)}s`)}finally{yt=!1}}}function un(){let i=Date.now();return{mode:E,unacked:$.size,oldestUnackedAgeMs:cn(i),lastProgressAt:Je,degradedSince:re,stallRedials:Q,deadLettered:rn,http:E==="http"?{inFlight:be,circuitOpen:q,nextProbeInMs:q?Math.max(0,fe-i):0,batchCap:K}:null}}async function dn(){if(!p)return;let i;try{i=await p()}catch(r){m.error("[plane-link] metrics sample failed:",r?.message||r);return}let c=null;try{c=T?.()??null}catch{}i&&O({v:R,ch:"ctl",type:"metrics",metrics:{...i,planeLink:un(),...c?{delivery:c}:{}}})}function Lr(){p&&(te&&clearInterval(te),dn(),te=setInterval(dn,f),te.unref?.())}async function Br(){let i;try{i=await s()}catch(c){m.error("[plane-link] backfill listTracks failed:",c?.message||c);return}O({v:R,ch:"ctl",type:"tracks",ids:i.filter(c=>!c.transferredTo).map(c=>c.id).filter(c=>typeof c=="string")});for(let c of i){if(!G)return;let r;try{r=await Pt(c)}catch{continue}let a=de[c.id]??0,d=r.filter(w=>w.seq>a&&typeof w.id=="string"),h=E==="http"?K:ie;for(let w=0;w<d.length;w+=h){if(!await Dr(c.id))return;let b=d.slice(w,w+Math.min(h,E==="http"?K:ie)).map(D=>({trackId:c.id,event:D}));if(!je(b))return}}}function fn(i){!G||!i?.trackId||typeof i.id!="string"||(oe.push({trackId:i.trackId,event:i}),C||(C=setTimeout(kt,dr),C.unref?.()))}let Fe=new Map;async function Ur(i){let{reqId:c,method:r,path:a,headers:d={},body:h}=i,w=Object.fromEntries(Object.entries(d).filter(([,D])=>D!=null)),b=new AbortController;Fe.set(c,b);try{if(i.host){await Hr(i,w,b);return}U&&(w["x-bostrat-token"]=U);let D=await fetch(j+a,{method:r,headers:w,body:h?Buffer.from(h,"base64"):void 0,signal:b.signal}),W=Object.fromEntries(D.headers);for(let x of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete W[x];if(W["content-type"]||(W["content-type"]="application/octet-stream"),O({v:R,ch:"control",type:"http_head",reqId:c,status:D.status,headers:W}),D.body){for await(let x of D.body)if(!O({v:R,ch:"control",type:"http_data",reqId:c,data:Buffer.from(x).toString("base64")}))break}O({v:R,ch:"control",type:"http_end",reqId:c,error:null})}finally{Fe.delete(c)}}function Hr(i,c,r){let{reqId:a,method:d,path:h,body:w}=i,b=new URL(j);return new Promise(D=>{let W=qo.request({host:b.hostname,port:b.port,method:d,path:h,headers:{...c,host:i.host},signal:r.signal},x=>{let{connection:mn,"keep-alive":Gs,"transfer-encoding":Vs,upgrade:Js,...Kr}=x.headers;O({v:R,ch:"control",type:"http_head",reqId:a,status:x.statusCode||502,headers:Kr}),x.on("data",Wr=>{O({v:R,ch:"control",type:"http_data",reqId:a,data:Buffer.from(Wr).toString("base64")})||x.destroy()}),x.on("end",()=>{O({v:R,ch:"control",type:"http_end",reqId:a,error:null}),D()}),x.on("error",()=>{O({v:R,ch:"control",type:"http_end",reqId:a,error:"view upstream error"}),D()})});W.on("error",x=>{O({v:R,ch:"control",type:"http_end",reqId:a,error:x?.message||"view request failed"}),D()}),w&&W.write(Buffer.from(w,"base64")),W.end()})}function pn(){if(gt||De)return;X=new Ht(e,{headers:{authorization:`Bearer ${t}`}}),X.on("open",async()=>{let c=null;try{c=await l?.()||null}catch{c=null}O({v:R,ch:"ctl",type:"hello",nodeId:n,name:o,platform:process.platform,version:V,installKind:g,...typeof v=="function"?{updatePolicy:v()}:v?{updatePolicy:v}:{},providers:hr(),...c?{agents:c}:{}})}),X.on("message",c=>{let r;try{r=JSON.parse(c)}catch{return}if(r.ch==="ctl"&&r.type==="hello_ok"){G=!0,Me=cr,Pe=null,kn(),m.log(`[plane-link] connected to plane as ${n}`);try{Te?.()}catch{}if(typeof r.hashKey=="string"&&r.hashKey)try{y?.(r.hashKey)}catch{}r.minNodeVersion&&V&&Ee(V,r.minNodeVersion)&&m.error(`[plane-link] this node is bostrat-node ${V}; the plane asks for \u2265${r.minNodeVersion} \u2014 update with: ${Ye(g)}`);try{I?.(typeof r.updatePolicy=="string"?r.updatePolicy:null)}catch{}let a=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;if(a&&V&&Ee(V,a)&&!tn.has(a)){tn.add(a),m.log(`[plane-link] bostrat-node ${a} is available (this node runs ${V}) \u2014 ${Ye(g)}`);try{_?.({current:V,latest:a,min:r.minNodeVersion??null,installKind:g,required:!!(r.minNodeVersion&&Ee(V,r.minNodeVersion))})}catch(h){m.error(`[plane-link] update notice failed: ${h?.message||h}`)}}let d=r.ingest==="http";E=_e==="ws"?"ws":_e==="http"||d?"http":"ws",_e==="http"&&!d&&m.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),E==="http"&&m.log("[plane-link] spine rides the HTTPS ingest door"),q=!1,fe=0,K=ie,ee&&clearInterval(ee),ee=setInterval(()=>{O({v:R,ch:"ctl",type:"ping"}),ln(),Fr().catch(()=>{}),vt(),oe.length&&!C&&kt()},Or),ee.unref?.(),Lr(),Br().catch(h=>m.error("[plane-link] backfill failed:",h?.message||h));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;m.error(`[plane-link] plane REFUSED this node: bostrat-node ${V??"?"} is below its minimum ${a??"?"} \u2014 ${r.fix||Ye(g)}`),Me=lr,Pe=0;try{A?.({current:V,min:a,latest:d,fix:r.fix||Ye(g),installKind:g})}catch(h){m.error(`[plane-link] refusal handler failed: ${h?.message||h}`)}return}if(r.ch==="ctl"&&r.type==="removed"){O({v:R,ch:"ctl",type:"removed_ack",nodeId:n}),_t({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{I?.(typeof r.mode=="string"?r.mode:null)}catch{}return}if(r.ch==="ctl"&&r.type==="usage_caps"){ir(r.caps??{},{source:"plane",updatedAt:r.updatedAt??Date.now()}).then(a=>m.log(`[plane-link] spend caps ${Object.keys(a.caps).length?`updated (${Object.keys(a.caps).join(", ")})`:"cleared"} from plane`)).catch(a=>m.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=>m.error("[plane-link] transfer notice failed:",a?.message||a));return}if(r.ch==="events"&&r.type==="ack"&&Array.isArray(r.ids)){St(r.ids);return}if(r.ch==="events"&&r.type==="nack"&&Array.isArray(r.ids)){an(r.ids,r.reason,r.permanent===!0,r.retryAfterMs??null);return}if(r.ch==="control"&&r.type==="http_open"){Ur(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"){Fe.get(r.reqId)?.abort();return}if(r.ch==="attach"&&r.type==="open"){let a=new Ht(Nr+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 h=ue.get(r.streamId)||[];ue.delete(r.streamId);for(let{buf:w,bin:b}of h)a.send(w,{binary:b})}),a.on("message",(h,w)=>{let b=w?h:Buffer.from(String(h));O({v:R,ch:"attach",type:"data",streamId:r.streamId,data:b.toString("base64"),...w?{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"),h=r.bin===!0,w=ue.get(r.streamId);w?w.push({buf:d,bin:h}):a.send(d,{binary:h});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=()=>{G&&m.log("[plane-link] disconnected from plane"),G=!1,ee&&(clearInterval(ee),ee=null),te&&(clearInterval(te),te=null),$.clear(),ne={},oe=[],C&&(clearTimeout(C),C=null),Se.clear();for(let a of le.values())a.close();le.clear(),ue.clear();for(let a of Fe.values())a.abort();if(Fe.clear(),gt||ve)return;Pe==null&&(Pe=Date.now());let c=Date.now()-Pe<Vo,r=Math.max(c?Jo+Math.random()*Xo:Me,Ie-Date.now(),He());ve=setTimeout(()=>{ve=null,pn()},r),ve.unref?.(),c||(Me=Math.min(Me*2,lr))};X.on("close",i),X.on("error",c=>{let r=/Unexpected server response: (\d+)/.exec(c?.message||"")?.[1];if(r==="410"){_t({reason:"removed",via:"410"});return}if(r==="401"||r==="403"){let{tripped:a,holdMs:d}=ot();a?m.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()-Xe>=fr&&(Xe=Date.now(),m.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",fn),Ir().then(pn);function hn({bye:i=!0}={}){gt=!0,We.off("event",fn),ve&&clearTimeout(ve),ke&&clearTimeout(ke),ee&&clearInterval(ee),te&&clearInterval(te),C&&clearTimeout(C),i&&O({v:R,ch:"ctl",type:"bye",reason:"shutdown"}),X?.close()}return{stop:()=>hn(),status:()=>({connected:G,nodeId:n,cursor:{...de},inflight:$.size,...un(),auth:An(),dormant:De,removed:Nt()}),_tick:()=>{ln(),vt()}}}var V,Wt,Yt,R,cr,lr,Vo,Jo,Xo,ie,Zo,Qo,es,mr,ts,ns,ur,rs,dr,os,Kt,ss,fr,qt=S(()=>{it();ar();Et();It();V=(()=>{try{return Go(import.meta.url)("../package.json").version||null}catch{return null}})(),Wt=process.env.BOSTRAT_STATE_DIR||F.join(process.env.HOME||dt.tmpdir(),".bostrat"),Yt=F.join(Wt,"plane-link","removed.json");R=1,cr=1e3,lr=3e4,Vo=6e4,Jo=1500,Xo=500,ie=100,Zo=2e3,Qo=25e3,es=6e4,mr=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},ts=mr(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),ns=3e4,ur=10*6e4,rs=400,dr=250,os=mr(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Kt=4,ss=6e4,fr=6e4});import{execFile as as}from"node:child_process";import{promisify as cs}from"node:util";function yr(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Pc,Dc,jc,gr=S(()=>{Dt();Pc=cs(as),Dc=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,jc=Promise.resolve()});var vr={};At(vr,{ACTIONABLE_KINDS:()=>ht,SELF_UPDATE_DIR:()=>Gt,createAutoUpdater:()=>bs,inFlight:()=>Jt,readStatus:()=>Vt,selfUpdatePlan:()=>br,settleSelfUpdate:()=>_s,startSelfUpdate:()=>Sr,underService:()=>_r,updatePolicy:()=>ms});import Tr from"node:fs";import ae from"node:fs/promises";import ls from"node:os";import M from"node:path";import{spawn as us}from"node:child_process";import{createRequire as ds}from"node:module";function ms({kind:e=Oe(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:ht.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 br({kind:e,to:t,from:n=ft,statusFile:o=pt,logFile:s=M.join(Gt,"last.log"),port:l=Number(process.env.PORT)||3362,npmPrefix:u=null,serviceName:p=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:T=typeof process.getuid=="function"?process.getuid():0,liveDir:y=process.env.BOSTRAT_LIVE_CHECKOUT||M.resolve(M.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:f=Date.now()}={}){if(!ht.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 _=(j,U="")=>`write_status ${L(j)} ${U}`,I=process.platform==="darwin"?`launchctl kickstart -k gui/${T}/${p}`:`systemctl --user restart ${L(p)}`,A=`
|
|
117
117
|
health() {
|
|
118
118
|
for i in $(seq 1 45); do
|
|
119
119
|
sleep 1
|
|
120
120
|
if curl -sf -o /dev/null "http://127.0.0.1:${l}/api/health"; then return 0; fi
|
|
121
121
|
done
|
|
122
122
|
return 1
|
|
123
|
-
}`,
|
|
123
|
+
}`,v=`#!/usr/bin/env bash
|
|
124
124
|
# bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
|
|
125
125
|
# ${n??"?"} \u2192 ${t} (${e}). Status: ${o}
|
|
126
126
|
set -u
|
|
127
|
-
FROM=${
|
|
128
|
-
TO=${
|
|
129
|
-
STATUS_FILE=${
|
|
127
|
+
FROM=${L(n??"")}
|
|
128
|
+
TO=${L(t)}
|
|
129
|
+
STATUS_FILE=${L(o)}
|
|
130
130
|
STARTED_AT=${Number(f)}
|
|
131
131
|
write_status() { # <status> [error]
|
|
132
132
|
local err="\${2:-}"
|
|
133
133
|
err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
|
|
134
134
|
printf '{"status":"%s","from":"%s","to":"%s","kind":"%s","startedAt":%s,"updatedAt":%s%s}\\n' \\
|
|
135
|
-
"$1" "$FROM" "$TO" ${
|
|
135
|
+
"$1" "$FROM" "$TO" ${L(e)} "$STARTED_AT" "$(date +%s000)" \\
|
|
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
|
-
`:"",
|
|
139
|
+
`;if(e==="npm-global"){let j=u?M.join(u,"bin","npm"):"npm",U=u?`export PATH=${L(M.join(u,"bin"))}:"$PATH"
|
|
140
|
+
`:"",P=u?` --prefix ${L(u)}`:"",H=k=>`${L(j)} install -g "bostrat-node@${k}" --no-audit --no-fund${P}`;return v+U+`
|
|
141
141
|
${_("updating",'"" ')}
|
|
142
|
-
if ! ${
|
|
142
|
+
if ! ${H("$TO")}; then
|
|
143
143
|
${_("failed",'"npm install failed"')}
|
|
144
144
|
exit 1
|
|
145
145
|
fi
|
|
146
146
|
${_("restarting")}
|
|
147
|
-
if ! ${
|
|
147
|
+
if ! ${I}; then
|
|
148
148
|
${_("failed",'"service restart failed"')}
|
|
149
149
|
exit 1
|
|
150
150
|
fi
|
|
@@ -154,14 +154,14 @@ if health; then
|
|
|
154
154
|
fi
|
|
155
155
|
# \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
|
|
156
156
|
${_("rolling-back",'"agent did not answer on :'+l+' after the update"')}
|
|
157
|
-
if [ -n "$FROM" ] && ${
|
|
157
|
+
if [ -n "$FROM" ] && ${H("$FROM")} && ${I} && health; then
|
|
158
158
|
${_("rolled-back",'"agent did not answer on :'+l+' after the update; rolled back"')}
|
|
159
159
|
exit 1
|
|
160
160
|
fi
|
|
161
161
|
${_("failed",'"agent did not answer after the update AND the rollback"')}
|
|
162
162
|
exit 1
|
|
163
|
-
`}let g=
|
|
164
|
-
LIVE=${
|
|
163
|
+
`}let g=j=>`( cd ${L(y)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${j}" )`;return v+`
|
|
164
|
+
LIVE=${L(y)}
|
|
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
|
|
@@ -178,27 +178,27 @@ if [ -n "$FROM" ] && ${g("$FROM")}; then
|
|
|
178
178
|
fi
|
|
179
179
|
${_("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
|
|
180
180
|
exit 1
|
|
181
|
-
`}async function Ot(e=Qe){try{return JSON.parse(await ie.readFile(e,"utf8"))}catch{return null}}async function er({to:e,from:t=Ze,kind:n=Ae(),reason:o="manual",statusFile:s=Qe,spawnImpl:l=Bo,now:u=Date.now,npmPrefix:p=void 0,log:T=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!et.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!ke(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let w=await Ot(s);if(Rt(w))return{ok:!1,reason:`an update to ${w.to} is already in flight`,status:w};if(w&&w.to===e&&(w.status==="failed"||w.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${w.status} (${w.error||"no detail"}) \u2014 retried when a newer release exists`,status:w};await ie.mkdir(M.dirname(s),{recursive:!0});let f=p!==void 0?p:n==="npm-global"?Vn(await Yo())||M.resolve(M.dirname(process.execPath),".."):null,_=Qn({kind:n,to:e,from:t,statusFile:s,npmPrefix:f,startedAt:u()}),R=M.join(M.dirname(s),`update-${e}.sh`),A=M.join(M.dirname(s),"last.log");await ie.writeFile(R,_,{mode:448}),await ie.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:o,startedAt:u(),updatedAt:u()}));let S=Xn.existsSync("/run/systemd/system")&&await Go("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",R]]:["setsid",["-f","bash","-c",`exec bash ${F(R)} >> ${F(A)} 2>&1`]];try{l(S[0],S[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(g){return await ie.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:o,startedAt:u(),updatedAt:u(),error:`could not spawn updater: ${g?.message||g}`})),{ok:!1,reason:`could not spawn updater: ${g?.message||g}`}}return T.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${o}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:R,statusFile:s}}async function Yo(){try{return await ie.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Go(e){for(let t of String(process.env.PATH||"").split(M.delimiter))try{return await ie.access(M.join(t,e),Xn.constants.X_OK),!0}catch{}return!1}async function Jo({statusFile:e=Qe,current:t=Ze,now:n=Date.now,staleMs:o=Vo}={}){let s=await Ot(e);if(!s)return null;let l=u=>ie.writeFile(e,JSON.stringify(u)).catch(()=>{});if(Rt(s)){if(t&&s.to===t){let u={...s,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await l(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 l(u),u}return null}if(["failed","rolled-back","done"].includes(s.status)&&!s.announced){let u={...s,announced:!0};return await l(u),u}return null}function Xo({isBusy:e,start:t=er,onStuck:n=null,onStarted:o=null,tickMs:s=Wo,stuckMs:l=Ko,now:u=Date.now,setIntervalImpl:p=setInterval,clearIntervalImpl:T=clearInterval,log:w=console}={}){let f=null,_=()=>{f?.timer&&T(f.timer),f=null},R=async()=>{if(!f)return;let A=!0;try{A=await e()!==!1}catch{A=!0}if(A){if(!f.stuckFired&&u()-f.since>=l){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let S=f;_();let g=await t({to:S.to,from:S.from,kind:S.kind,reason:"auto"});w.log?.(`[self-update] stasis reached \u2192 ${g.ok?"started":`not started: ${g.reason}`}`);try{await o?.({...S,result:g})}catch{}};return{arm({to:A,from:S=Ze,kind:g=Ae()}){return f?.to===A?!1:(_(),f={to:A,from:S,kind:g,since:u(),stuckFired:!1,timer:p(R,s)},f.timer.unref?.(),!0)},tick:R,cancel:_,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var Ze,Ho,Et,Qe,Ko,Wo,et,F,qo,Rt,Vo,nr=k(()=>{xt();Jn();Ze=(()=>{try{return Uo(import.meta.url)("../package.json").version||null}catch{return null}})(),Ho=process.env.BOSTRAT_STATE_DIR||M.join(process.env.HOME||Lo.tmpdir(),".bostrat"),Et=M.join(Ho,"self-update"),Qe=M.join(Et,"status.json"),Ko=1440*6e4,Wo=6e4,et=new Set(["npm-global","git-checkout"]);F=e=>`'${String(e).replace(/'/g,"'\\''")}'`;qo=new Set(["updating","restarting","rolling-back"]),Rt=e=>!!(e&&qo.has(e.status));Vo=45*6e4});ht();Tt();import J from"node:fs";import O from"node:path";import xe from"node:os";import{createRequire as Nt}from"node:module";import{execFile as Zo,spawn as Qo}from"node:child_process";import{promisify as es}from"node:util";import ts from"node:readline/promises";import{randomUUID as ns}from"node:crypto";import{fileURLToPath as rs}from"node:url";var rr=(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 l=(n[s]||0)-(o[s]||0);if(l)return l<0}return!1},ae=es(Zo),It=O.dirname(rs(import.meta.url)),we=O.resolve(It,".."),os=O.join(It,"index.js"),ss="wss://plane.bostrat.ai/v1/node",$e=Nt(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}),W=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function is(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?L("node runtime",`${process.version} at ${process.execPath}`):W("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function as(e){let t;try{t=J.statSync(e)}catch{return Z("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?Z("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):L("node.env",`${e} (0600)`)}async function cs(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await ae(t,["-V"],{timeout:5e3});return L("tmux",`${t} (${n.trim()})`)}catch{return W("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function or(e,{required:t=!1}={}){if(await bt(e,{loginShell:!0,failOpen:!1}))return L(e,"resolves on the login-shell PATH");let o="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",s=Ge[e]?`${Ge[e]}${e==="cursor-agent"?" # installs to ~/.local/bin \u2014 ensure your login shell has it on PATH":""}`:`install ${e} so \`$SHELL -lic 'command -v ${e}'\` finds it`;return t?W(e,o,s):Z(e,o,s)}async function ls(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await ae(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return L("gh (GitHub CLI)",n)}catch{return Z("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",Ge.gh)}}async function us(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>or(t)));return e.some(t=>t.level==="pass")||e.push(W("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 ds(){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 bt(t,{failOpen:!1})?L(t,"resolves on the service PATH"):Z(t,`not on the service PATH \u2014 ${n}`,o)))}async function fs(){try{let t=Nt(O.join(we,"src","node-cli.js"))("node-pty");return await new Promise((n,o)=>{let s=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),l=setTimeout(()=>o(new Error("spawn timeout")),5e3);s.onExit(()=>{clearTimeout(l),n()})}),L("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${we} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Nt(O.join(we,"package.json")),o=O.join(O.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 W("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function ps(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(J.existsSync(t))return L("chromium (mocks)",t);let n=process.platform==="darwin"?"brew install --cask chromium (or set BOSTRAT_CHROMIUM_BIN to Chrome.app's inner binary)":"apt install chromium fonts-dejavu-core fonts-liberation (or set BOSTRAT_CHROMIUM_BIN)";return(e.BOSTRAT_INSTALL_KIND==="container"?W:Z)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function hs(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?W("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 ms(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return Z("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,o=Date.now(),s=Pe(e.BOSTRAT_PLANE_URL);return await new Promise(l=>{let u=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),p=w=>{clearTimeout(T);try{u.close()}catch{}l(w)},T=setTimeout(()=>p(W("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-${ns().slice(0,8)}`,ephemeral:!0}))),u.on("message",w=>{try{let f=JSON.parse(w);f.type==="hello_ok"?f.minNodeVersion&&rr($e,f.minNodeVersion)?p(W("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${f.minNodeVersion} \u2014 this node is ${$e}; the real link is refused until it updates`,`bostrat-node self-update --to ${f.latestNodeVersion||f.minNodeVersion}`)):f.latestNodeVersion&&rr($e,f.latestNodeVersion)?p(Z("plane link",`hello_ok in ${Date.now()-o}ms (${s}); bostrat-node ${f.latestNodeVersion} is available (this node: ${$e})`,`bostrat-node self-update --to ${f.latestNodeVersion}`)):p(L("plane link",`hello_ok in ${Date.now()-o}ms (${s})`)):f.type==="error"&&p(W("plane link",`plane said: ${f.code} ${f.message||""}`,"check the token"))}catch{}}),u.on("error",w=>p(W("plane link",`${w?.message||w}`,"check the URL, the token, and the plane's IP gate")))})}function ws(){let e;try{e=JSON.parse(J.readFileSync(O.join(pt,"content-outbox.json"),"utf8"))}catch{return L("content outbox","empty \u2014 every deliverable has reached the plane")}let t=e.ops?.length||0,n=e.parked?.length||0;if(n){let o=e.parked[0];return W("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${o?.op} ${o?.family}/${o?.id}: ${o?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?Z("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):L("content outbox",t?`${t} op(s) in flight`:"drained")}function ys(e){return e.BOSTRAT_STATE_REMOTE?L("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):Z("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}async function sr(e,t={}){let n=[];return n.push(await is()),n.push(as(t.envFile||Se())),n.push(await cs(e)),n.push(...await us()),n.push(await or("git",{required:!0})),n.push(await ls()),n.push(...await ds()),n.push(await fs()),n.push(ps(e)),n.push(hs(e)),n.push(await ms(e,t)),n.push(ws()),n.push(ys(e)),n}function ir(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let l of e)t(`${n[l.level]} ${l.name}: ${l.detail}`),l.fix&&l.level!=="pass"&&t(` fix: ${l.fix}`);let o=e.filter(l=>l.level==="fail").length,s=e.filter(l=>l.level==="warn").length;return t(o?`
|
|
181
|
+
`}async function Vt(e=pt){try{return JSON.parse(await ae.readFile(e,"utf8"))}catch{return null}}async function Sr({to:e,from:t=ft,kind:n=Oe(),reason:o="manual",statusFile:s=pt,spawnImpl:l=us,now:u=Date.now,npmPrefix:p=void 0,log:T=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!ht.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 y=await Vt(s);if(Jt(y))return{ok:!1,reason:`an update to ${y.to} is already in flight`,status:y};if(y&&y.to===e&&(y.status==="failed"||y.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${y.status} (${y.error||"no detail"}) \u2014 retried when a newer release exists`,status:y};await ae.mkdir(M.dirname(s),{recursive:!0});let f=p!==void 0?p:n==="npm-global"?yr(await ys())||M.resolve(M.dirname(process.execPath),".."):null,_=br({kind:n,to:e,from:t,statusFile:s,npmPrefix:f,startedAt:u()}),I=M.join(M.dirname(s),`update-${e}.sh`),A=M.join(M.dirname(s),"last.log");await ae.writeFile(I,_,{mode:448}),await ae.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:o,startedAt:u(),updatedAt:u()}));let v=Tr.existsSync("/run/systemd/system")&&await gs("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",I]]:["setsid",["-f","bash","-c",`exec bash ${L(I)} >> ${L(A)} 2>&1`]];try{l(v[0],v[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(g){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: ${g?.message||g}`})),{ok:!1,reason:`could not spawn updater: ${g?.message||g}`}}return T.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${o}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:I,statusFile:s}}async function ys(){try{return await ae.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function gs(e){for(let t of String(process.env.PATH||"").split(M.delimiter))try{return await ae.access(M.join(t,e),Tr.constants.X_OK),!0}catch{}return!1}async function _s({statusFile:e=pt,current:t=ft,now:n=Date.now,staleMs:o=Ts}={}){let s=await Vt(e);if(!s)return null;let l=u=>ae.writeFile(e,JSON.stringify(u)).catch(()=>{});if(Jt(s)){if(t&&s.to===t){let u={...s,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await l(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 l(u),u}return null}if(["failed","rolled-back","done"].includes(s.status)&&!s.announced){let u={...s,announced:!0};return await l(u),u}return null}function bs({isBusy:e,start:t=Sr,onStuck:n=null,onStarted:o=null,tickMs:s=hs,stuckMs:l=ps,now:u=Date.now,setIntervalImpl:p=setInterval,clearIntervalImpl:T=clearInterval,log:y=console}={}){let f=null,_=()=>{f?.timer&&T(f.timer),f=null},I=async()=>{if(!f)return;let A=!0;try{A=await e()!==!1}catch{A=!0}if(A){if(!f.stuckFired&&u()-f.since>=l){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let v=f;_();let g=await t({to:v.to,from:v.from,kind:v.kind,reason:"auto"});y.log?.(`[self-update] stasis reached \u2192 ${g.ok?"started":`not started: ${g.reason}`}`);try{await o?.({...v,result:g})}catch{}};return{arm({to:A,from:v=ft,kind:g=Oe()}){return f?.to===A?!1:(_(),f={to:A,from:v,kind:g,since:u(),stuckFired:!1,timer:p(I,s)},f.timer.unref?.(),!0)},tick:I,cancel:_,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var ft,fs,Gt,pt,ps,hs,ht,L,ws,Jt,Ts,kr=S(()=>{qt();gr();ft=(()=>{try{return ds(import.meta.url)("../package.json").version||null}catch{return null}})(),fs=process.env.BOSTRAT_STATE_DIR||M.join(process.env.HOME||ls.tmpdir(),".bostrat"),Gt=M.join(fs,"self-update"),pt=M.join(Gt,"status.json"),ps=1440*6e4,hs=6e4,ht=new Set(["npm-global","git-checkout"]);L=e=>`'${String(e).replace(/'/g,"'\\''")}'`;ws=new Set(["updating","restarting","rolling-back"]),Jt=e=>!!(e&&ws.has(e.status));Ts=45*6e4});Et();jt();import J from"node:fs";import N from"node:path";import Ne from"node:os";import{createRequire as Xt}from"node:module";import{execFile as Ss,spawn as vs}from"node:child_process";import{promisify as ks}from"node:util";import As from"node:readline/promises";import{randomUUID as $s}from"node:crypto";import{fileURLToPath as xs}from"node:url";var Ar=(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 l=(n[s]||0)-(o[s]||0);if(l)return l<0}return!1},ce=ks(Ss),Zt=N.dirname(xs(import.meta.url)),ge=N.resolve(Zt,".."),Es=N.join(Zt,"index.js"),Os="wss://plane.bostrat.ai/v1/node",Re=Xt(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}),z=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function Rs(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?B("node runtime",`${process.version} at ${process.execPath}`):z("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Ns(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 Is(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 z("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function $r(e,{required:t=!1}={}){if(await Ft(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=ct[e]?`${ct[e]}${e==="cursor-agent"?" # installs to ~/.local/bin \u2014 ensure your login shell has it on PATH":""}`:`install ${e} so \`$SHELL -lic 'command -v ${e}'\` finds it`;return t?z(e,o,s):Z(e,o,s)}async function Ms(){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",ct.gh)}}async function Ps(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>$r(t)));return e.some(t=>t.level==="pass")||e.push(z("agent CLIs","no agent CLI found at all \u2014 a node with nothing to drive","install at least one of claude / codex / cursor-agent")),e}async function Ds(){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 Ft(t,{failOpen:!1})?B(t,"resolves on the service PATH"):Z(t,`not on the service PATH \u2014 ${n}`,o)))}async function js(){try{let t=Xt(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}),l=setTimeout(()=>o(new Error("spawn timeout")),5e3);s.onExit(()=>{clearTimeout(l),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=Xt(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 z("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function Cs(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"?z:Z)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function Fs(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?z("claude lane","BOSTRAT_CLAUDE_USE_API_KEY=1 but ANTHROPIC_API_KEY is empty","add the key to node.env or set the flag to 0"):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 Ls(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=Le(e.BOSTRAT_PLANE_URL);return await new Promise(l=>{let u=new n(s,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),p=y=>{clearTimeout(T);try{u.close()}catch{}l(y)},T=setTimeout(()=>p(z("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-${$s().slice(0,8)}`,ephemeral:!0}))),u.on("message",y=>{try{let f=JSON.parse(y);f.type==="hello_ok"?f.minNodeVersion&&Ar(Re,f.minNodeVersion)?p(z("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${f.minNodeVersion} \u2014 this node is ${Re}; the real link is refused until it updates`,`bostrat-node self-update --to ${f.latestNodeVersion||f.minNodeVersion}`)):f.latestNodeVersion&&Ar(Re,f.latestNodeVersion)?p(Z("plane link",`hello_ok in ${Date.now()-o}ms (${s}); bostrat-node ${f.latestNodeVersion} is available (this node: ${Re})`,`bostrat-node self-update --to ${f.latestNodeVersion}`)):p(B("plane link",`hello_ok in ${Date.now()-o}ms (${s})`)):f.type==="error"&&p(z("plane link",`plane said: ${f.code} ${f.message||""}`,"check the token"))}catch{}}),u.on("error",y=>p(z("plane link",`${y?.message||y}`,"check the URL, the token, and the plane's IP gate")))})}function Bs(){let e;try{e=JSON.parse(J.readFileSync(N.join(xt,"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 z("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 Us(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")}async function xr(e,t={}){let n=[];return n.push(await Rs()),n.push(Ns(t.envFile||Ae())),n.push(await Is(e)),n.push(...await Ps()),n.push(await $r("git",{required:!0})),n.push(await Ms()),n.push(...await Ds()),n.push(await js()),n.push(Cs(e)),n.push(Fs(e)),n.push(await Ls(e,t)),n.push(Bs()),n.push(Us(e)),n}function Er(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let l of e)t(`${n[l.level]} ${l.name}: ${l.detail}`),l.fix&&l.level!=="pass"&&t(` fix: ${l.fix}`);let o=e.filter(l=>l.level==="fail").length,s=e.filter(l=>l.level==="warn").length;return t(o?`
|
|
182
182
|
FAIL \u2014 ${o} blocking, ${s} warnings`:`
|
|
183
|
-
OK \u2014 0 blocking, ${s} warnings`),o===0}async function
|
|
183
|
+
OK \u2014 0 blocking, ${s} warnings`),o===0}async function Hs({envFile:e=Ae(),input:t=process.stdin,output:n=process.stdout}={}){let o=Qe(e),s=As.createInterface({input:t,output:n}),l=async(H,k)=>(await s.question(k?`${H} [${k}]: `:`${H}: `)).trim()||k||"";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 l("Plane URL",o.BOSTRAT_PLANE_URL||
|
|
187
|
-
`);let T=await l("Node token (minted plane-side; stored 0600)",o.BOSTRAT_PLANE_TOKEN),
|
|
188
|
-
`);let f=await l("Node name",o.BOSTRAT_NODE_NAME||
|
|
186
|
+
`);let u=await l("Plane URL",o.BOSTRAT_PLANE_URL||Os),p=Le(u);p!==u.trim()&&n.write(` \u2192 using ${p}
|
|
187
|
+
`);let T=await l("Node token (minted plane-side; stored 0600)",o.BOSTRAT_PLANE_TOKEN),y=await l("Owner userId (just press Enter \u2014 the plane infers it from your token)",o.BOSTRAT_OWNER||"");y&&!/^user_[A-Za-z0-9]+$/.test(y)&&n.write(` ! that doesn't look like a Clerk userId (user_\u2026) \u2014 leave it empty next time and the plane infers the owner from the token; saved as typed.
|
|
188
|
+
`);let f=await l("Node name",o.BOSTRAT_NODE_NAME||Ne.hostname().split(".")[0]),_=await l("Repos root",o.BOSTRAT_REPOS_ROOT||N.join(Ne.homedir(),"Documents")),I=await l("State remote (per-node private repo; empty = local-only)",o.BOSTRAT_STATE_REMOTE||""),A=(await l("Route NEW claude boxes through a BYO API key? (y/N)",o.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
|
|
195
|
-
`),s.close();let g={...
|
|
194
|
+
`);let v=A?await l("ANTHROPIC_API_KEY (starts sk-ant-)",o.ANTHROPIC_API_KEY):"";A&&v&&!/^sk-ant-/.test(v)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
|
|
195
|
+
`),s.close();let g={...gn(),...o,BOSTRAT_PLANE_URL:p,BOSTRAT_PLANE_TOKEN:T,BOSTRAT_OWNER:y,BOSTRAT_NODE_NAME:f,BOSTRAT_NODE_ID:o.BOSTRAT_NODE_ID||f,BOSTRAT_REPOS_ROOT:_,BOSTRAT_STATE_REMOTE:I,BOSTRAT_CLAUDE_USE_API_KEY:A?"1":"0",ANTHROPIC_API_KEY:A?v:o.ANTHROPIC_API_KEY};yn(e,g,{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
|
|
200
|
+
`);let j={...g,...process.env},U=await xr(j,{envFile:e}),P=Er(U,H=>n.write(H+`
|
|
201
|
+
`));return P&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:P,results:U}}function Ks({envFile:e=Ae()}={}){wn(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=vs(t,[Es],{cwd:ge,stdio:"inherit",env:process.env});for(let o of["SIGINT","SIGTERM"])process.on(o,()=>n.kill(o));return n.on("exit",(o,s)=>process.exit(s?1:o??1)),n}function Ws({agentDir:e=ge,nodeBin:t=process.execPath,envFile:n=Ae(),home:o=Ne.homedir()}={}){let s=N.dirname(t),l=N.join(N.basename(Zt),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
|
|
202
202
|
# ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
|
|
203
203
|
[Unit]
|
|
204
204
|
Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
|
|
@@ -218,7 +218,7 @@ RestartSec=2
|
|
|
218
218
|
|
|
219
219
|
[Install]
|
|
220
220
|
WantedBy=default.target
|
|
221
|
-
`}function
|
|
221
|
+
`}function zs({agentDir:e=ge,nodeBin:t=process.execPath,home:n=Ne.homedir()}={}){let o=N.dirname(t),s=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
|
|
222
222
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
223
223
|
<plist version="1.0">
|
|
224
224
|
<dict>
|
|
@@ -240,7 +240,7 @@ WantedBy=default.target
|
|
|
240
240
|
<key>StandardErrorPath</key><string>${s}/node.err.log</string>
|
|
241
241
|
</dict>
|
|
242
242
|
</plist>
|
|
243
|
-
`}function
|
|
243
|
+
`}function Ys(e=process.platform,t=Ne.homedir()){return e==="darwin"?{kind:"launchd",file:N.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:N.join(t,".config","systemd","user","bostrat-node.service")}}async function qs({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:o=console.log,agentDir:s=ge}={}){let{kind:l,file:u}=Ys(n);if(!e&&s.split(N.sep).includes("_npx"))return o("\u2717 running from the npx cache \u2014 a service must point at a durable install."),o(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){l==="systemd"?(await ce("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),J.rmSync(u,{force:!0}),await ce("systemctl",["--user","daemon-reload"])):(await ce("launchctl",["unload","-w",u]).catch(()=>{}),J.rmSync(u,{force:!0})),o(`removed ${u}`);return}J.mkdirSync(N.dirname(u),{recursive:!0}),l==="systemd"?(J.writeFileSync(u,Ws()),await ce("systemctl",["--user","daemon-reload"]),t&&await ce("systemctl",["--user","enable","--now","bostrat-node.service"]),o(`installed ${u}${t?" (enabled + started)":""}`),o("logs: journalctl --user -u bostrat-node.service -f")):(J.mkdirSync(N.join(Ne.homedir(),"Library","Logs","bostrat"),{recursive:!0}),J.writeFileSync(u,zs()),t&&await ce("launchctl",["load","-w",u]),o(`installed ${u}${t?" (loaded)":""}`),o("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function rl(e=process.argv.slice(2)){let t=e[0],n=Ae();if(t==="--version"||t==="-v"||t==="version")return console.log(Re),0;if(t==="init")return(await Hs({envFile:n})).ok?0:1;if(t==="doctor"){let o={...Qe(n),...process.env};return Er(await xr(o,{envFile:n}))?0:1}if(t==="run"||t==="start")return Ks({envFile:n}),null;if(t==="install-service")return await qs({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:o}=await Promise.resolve().then(()=>(qn(),Yn));return await o({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:o,readStatus:s,updatePolicy:l}=await Promise.resolve().then(()=>(kr(),vr)),{detectInstallKind:u}=await Promise.resolve().then(()=>(qt(),wr)),p=u(),T=e.indexOf("--to"),y=T>=0?String(e[T+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Re,installKind:p,policy:l({kind:p}),status:await s()},null,2)),0;if(!y)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let f=await o({to:y,kind:p,reason:"cli"});return f.ok?(console.log(`\u2713 self-update ${f.from??"?"} \u2192 ${f.to} started (${f.kind}) \u2014 status: ${f.statusFile}; the service restarts when the install completes`),0):(console.error(`\u2717 not started: ${f.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
|
|
244
244
|
|
|
245
245
|
usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
|
|
246
246
|
|
|
@@ -249,4 +249,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
|
|
|
249
249
|
run start the node in the foreground (sources node.env)
|
|
250
250
|
install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
|
|
251
251
|
fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
|
|
252
|
-
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{
|
|
252
|
+
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{Hs as init,qs as installService,zs as launchdPlist,rl as main,Er as printDoctor,Ks as runAgent,xr as runDoctor,Ys as servicePaths,Ws as systemdUnit};
|