bostrat-node 1.12.2 → 1.12.3
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 +65 -65
- package/dist/index.js +214 -214
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)){let i=
|
|
3
|
-
`).map(i=>i?`# ${i}`:"#"));for(let[i,c]of Object.entries(t))c==null||c===""||
|
|
1
|
+
var To=Object.defineProperty;var v=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Pt=(e,t)=>{for(var n in t)To(e,n,{get:t[n],enumerable:!0})};import tt from"node:fs";import Dt from"node:path";import _o from"node:os";function Fe(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,o;try{o=new URL(n)}catch{return t}let i={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[o.protocol];return i?(o.protocol=i,(o.pathname===""||o.pathname==="/")&&(o.pathname="/v1/node"),o.toString()):t}function nt(e){let t;try{t=tt.readFileSync(e,"utf8")}catch{return{}}let n={};for(let o of t.split(`
|
|
2
|
+
`)){let i=o.trim();if(!i||i.startsWith("#"))continue;let c=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(i);if(!c)continue;let d=c[2].trim();(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))&&(d=d.slice(1,-1)),n[c[1]]=d}return n}function Bn(e,t=process.env){let n=nt(e);for(let[o,i]of Object.entries(n))o in t||(t[o]=i);return n}function Ln(e,t,{header:n=""}={}){let o=[];n&&o.push(...n.split(`
|
|
3
|
+
`).map(i=>i?`# ${i}`:"#"));for(let[i,c]of Object.entries(t))c==null||c===""||o.push(`${i}=${c}`);tt.mkdirSync(Dt.dirname(e),{recursive:!0}),tt.writeFileSync(e,o.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`,{mode:384}),tt.chmodSync(e,384)}function
|
|
6
|
-
`))if(d.trim())try{c.push(JSON.parse(
|
|
5
|
+
`,{mode:384}),tt.chmodSync(e,384)}function jn(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 Ct,$e,Bt=v(()=>{Ct=process.env.BOSTRAT_STATE_DIR||Dt.join(process.env.HOME||_o.tmpdir(),".bostrat"),$e=()=>Dt.join(Ct,"node.env")});var we,rt,ot=v(()=>{we="BOSTRAT_HOOK_TOKEN",rt="x-bostrat-hook"});var Fn=v(()=>{ot()});var So,Hi,Un=v(()=>{So="check_for_update_on_startup",Hi=`${So} = false`});import vo from"node:os";import Hn from"node:path";var bo,Yi,qi,Lt=v(()=>{jt();bo=process.env.BOSTRAT_DEBUG_DIR||Hn.join(vo.homedir(),".bostrat","debug"),Yi=Hn.join(bo,"handoff.jsonl"),qi=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as ko}from"node:child_process";import{promisify as $o}from"node:util";function Ft(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var ea,ta,na,ra,Ut=v(()=>{Lt();ea=$o(ko),ta=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,na=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,ra=Promise.resolve()});var Kn=v(()=>{});import Ht from"node:path";import{execFile as xo}from"node:child_process";import{promisify as Eo}from"node:util";var la,Wn,Oo,ua,da,zn=v(()=>{la=Eo(xo),Wn=process.env.HOME||"/home/globo",Oo=Ht.join(process.env.BOSTRAT_STATE_DIR||Ht.join(Wn,".bostrat"),"repos"),ua=[...(process.env.BOSTRAT_REPOS_ROOT||Ht.join(Wn,"Documents")).split(","),Oo].map(e=>e.trim()).filter(Boolean),da=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function at(e=Date.now()){if(ge)return{tripped:!1,holdMs:1/0};if(ye>e)return{tripped:!1,holdMs:ye-e};if((!He||e-He>=st.windowMs)&&(He=e,Ue=0),Ue++,Ue<st.trip)return{tripped:!1,holdMs:0};it++;let t=Math.min(st.minMs*2**(it-1),st.maxMs);return ye=e+t,Ue=0,He=0,{tripped:!0,holdMs:t}}function Vn(){Ue=0,He=0,it=0,ye=0}function Ke(e=Date.now()){return ge?1/0:ye>e?ye-e:0}function ct(e=Date.now()){return Ke(e)>0}function Kt(e={}){ge={at:Date.now(),...e},ye=1/0}function Wt(){return ge}function Yn(e=Date.now()){return{held:ct(e),holdMs:ge?null:Ke(e),holds:it,removed:ge?{...ge}:null}}var Ro,st,Ue,He,it,ye,ge,zt=v(()=>{Ro={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},st={...Ro},Ue=0,He=0,it=0,ye=0,ge=null});import qn from"node:path";import No from"node:os";import{execFile as Io}from"node:child_process";import{promisify as Mo}from"node:util";var Sa,Po,va,ba,Aa,Vt=v(()=>{zn();zt();Sa=Mo(Io),Po=process.env.BOSTRAT_STATE_DIR||qn.join(process.env.HOME||No.tmpdir(),".bostrat"),va=qn.join(Po,"repos"),ba=5*6e4,Aa=10*6e4});var Gn=v(()=>{Vt()});import Co from"node:fs/promises";import We from"node:path";import Bo from"node:os";import{EventEmitter as Lo}from"node:events";function jo(e){return e?.cwd?We.join(e.cwd,".bostrat","events"):We.join(Xn,"events")}async function lt(e,t){let n,o;typeof e=="string"&&t?(n=e,o=t):(o=typeof e=="string"?e:e?.id,n=typeof e=="string"?We.join(Xn,"events"):jo(e));let i;try{i=await Co.readFile(Fo(n,o),"utf8")}catch{return[]}let c=[];for(let d of i.split(`
|
|
6
|
+
`))if(d.trim())try{c.push(JSON.parse(Ho(d)?Ko(d):d))}catch{}return c}var ze,Xn,Fo,Uo,Ho,Ko,ut=v(()=>{ze=new Lo;ze.setMaxListeners(0);Xn=process.env.BOSTRAT_STATE_DIR||We.join(process.env.HOME||Bo.tmpdir(),".bostrat");Fo=(e,t)=>We.join(e,`${t}.ndjson`),Uo=/(?<!\\)((?:\\\\)*)\\u0000/g,Ho=e=>e.includes("\\u0000"),Ko=e=>e.replace(Uo,"$1\\ufffd")});import zo from"node:os";import Vo from"node:path";import{execFile as Yo}from"node:child_process";import{promisify as qo}from"node:util";var Ua,Ha,Ka,Wa,za,Va,Jn=v(()=>{Gn();ut();Ua=qo(Yo),Ha=process.env.BOSTRAT_STATE_DIR||Vo.join(process.env.HOME||zo.tmpdir(),".bostrat"),Ka=25*1024,Wa=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,za=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,Va=Promise.resolve()});var Zn=v(()=>{});var Za,Qn=v(()=>{Vt();Zn();Za=60*6e4});var er=v(()=>{Qn()});import tr from"node:path";import Go from"node:os";var dt,Xo,uc,nr,dc,fc,rr=v(()=>{ot();dt="BOSTRAT_NODE_URL",Xo=process.env.BOSTRAT_STATE_DIR||tr.join(process.env.HOME||Go.tmpdir(),".bostrat"),uc=tr.join(Xo,"git-hooks"),nr=`#!/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
|
+
`,dc=`${nr}
|
|
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 "$${we}" ] && exit 0
|
|
25
|
-
[ -z "$${
|
|
25
|
+
[ -z "$${dt}" ] && exit 0
|
|
26
26
|
[ "$2" = "merge" ] && exit 0
|
|
27
|
-
trailers=$(curl -sS -m 3 -H "${rt}: $${we}" "$${
|
|
27
|
+
trailers=$(curl -sS -m 3 -H "${rt}: $${we}" "$${dt}/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
|
+
`,fc=`${nr}
|
|
34
34
|
# \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
|
|
35
35
|
[ -z "$${we}" ] && exit 0
|
|
36
|
-
[ -z "$${
|
|
36
|
+
[ -z "$${dt}" ] && 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 "$${
|
|
39
|
+
printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${dt}/api/git/committed" \\
|
|
40
40
|
-H 'content-type: application/json' -H "${rt}: $${we}" --data-binary @- >/dev/null 2>&1 || true
|
|
41
41
|
exit 0
|
|
42
|
-
`});import{execFile as
|
|
42
|
+
`});import{execFile as Jo}from"node:child_process";import{promisify as Zo}from"node:util";import ir from"node:fs";import Qo from"node:os";function ar(e){return`/tmp/tmux-${e}/default`}function ts({explicit:e,legacyExists:t,runtimeDir:n,uid:o}){if(e)return e;let i=ar(o);return t?i:n?`${n}/bostrat/tmux-default`:i}async function qt(e,{loginShell:t=!1,failOpen:n=!1}={}){let o=await rs(e,{loginShell:t});return o===cr?!0:o===Yt?!1:n}async function rs(e,{loginShell:t=!1,timeoutMs:n=ns}={}){if(!e)return Yt;let o=t?process.env.SHELL||"/bin/sh":"sh",i=t?"-lic":"-c";try{return await es(o,[i,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),cr}catch(c){return c?.killed||c?.signal?sr:c?.code===1||c?.code===127?Yt:sr}}var es,Lc,or,jc,Fc,Uc,Hc,Kc,cr,Yt,sr,ns,ft,Wc,zc,Vc,Yc,qc,Gc,jt=v(()=>{Fn();Un();Ut();Kn();Jn();er();Lt();ot();rr();es=Zo(Jo),Lc=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";or=typeof process.getuid=="function"?process.getuid():0,jc=ts({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return ir.existsSync(ar(or))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:or}),Fc=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Uc=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Hc=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),Kc=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);cr="present",Yt="absent",sr="unknown",ns=5e3;ft={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"},Wc=(()=>{try{let e=Qo.homedir();if(e&&ir.existsSync(e))return e}catch{}return"/"})(),zc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Vc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Yc=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,qc=Number(process.env.BOSTRAT_BOX_COLS)||120,Gc=Number(process.env.BOSTRAT_BOX_ROWS)||40});var gr={};Pt(gr,{NODE_IMAGE:()=>Xt,commandPlan:()=>mr,flyToml:()=>hr,flyWizard:()=>ys,parseFlyFlags:()=>wr,stageConfig:()=>yr});import Gt from"node:fs";import Te from"node:path";import us from"node:os";import ds from"node:readline/promises";import{execFile as fs}from"node:child_process";import{createRequire as ps}from"node:module";import{randomUUID as hs}from"node:crypto";function hr({app:e,region:t,nodeName:n=e,planeUrl:o=pr,image:i=Xt}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
|
|
43
43
|
# Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
|
|
44
44
|
# No [http_service] and none should be added: the node dials OUT to the plane;
|
|
45
45
|
# nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
|
|
@@ -61,7 +61,7 @@ swap_size_mb = 1024
|
|
|
61
61
|
# $HOME on the volume: your agent logins, repos, and node state survive
|
|
62
62
|
# machine replacement (the "your login stays on your node" promise).
|
|
63
63
|
HOME = "/data/home"
|
|
64
|
-
BOSTRAT_PLANE_URL = "${
|
|
64
|
+
BOSTRAT_PLANE_URL = "${o}"
|
|
65
65
|
BOSTRAT_NODE_ID = "${e}"
|
|
66
66
|
BOSTRAT_NODE_NAME = "${n}"
|
|
67
67
|
BOSTRAT_REPOS_ROOT = "/data/home/repos"
|
|
@@ -79,56 +79,56 @@ 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 mr({app:e,org:t,region:n,sizeGb:o,token:i,dir:c}){let d=[`BOSTRAT_PLANE_TOKEN=${i}`];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> via stdin`,stdin:d.join(`
|
|
83
83
|
`)+`
|
|
84
|
-
`},{argv:["deploy",c,"-c",Te.join(c,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${c} -c ${Te.join(c,"fly.toml")} -a ${e} --ha=false`}]}function
|
|
85
|
-
`),d[0];if(d.length>1)return await e(`Fly org (${d.join(" / ")})`,d[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function
|
|
84
|
+
`},{argv:["deploy",c,"-c",Te.join(c,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${c} -c ${Te.join(c,"fly.toml")} -a ${e} --ha=false`}]}function wr(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--image":"image"};for(let o=0;o<e.length;o++){let i=e[o];if(i==="--yes"||i==="-y")t.yes=!0;else if(n[i])t[n[i]]=e[++o]??"";else if(i.startsWith("--")&&i.includes("=")){let[c,...d]=i.split("=");n[c]?t[n[c]]=d.join("="):c==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function yr({app:e,dest:t,toml:n}){let o=t||Te.join(us.homedir(),".bostrat","fly",e);Gt.mkdirSync(o,{recursive:!0});for(let i of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])Gt.rmSync(Te.join(o,i),{recursive:!0,force:!0});return Gt.writeFileSync(Te.join(o,"fly.toml"),n),{dir:o,manifest:["fly.toml"]}}async function ws({ask:e,output:t,exec:n,flag:o}){if(o)return o;try{let{stdout:i}=await pt(["orgs","list","--json"],{exec:n}),c=JSON.parse(i),d=Array.isArray(c)?c.map(h=>h.Slug||h.slug).filter(Boolean):Object.keys(c);if(d.length===1)return t.write(`Org: ${d[0]} (your only org)
|
|
85
|
+
`),d[0];if(d.length>1)return await e(`Fly org (${d.join(" / ")})`,d[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function ys({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:o,stageDest:i}={}){let c=wr(e),d=ds.createInterface({input:t,output:n}),h=async(b,O)=>(await d.question(O?`${b} [${O}]: `:`${b}: `)).trim()||O||"",g=b=>(d.close(),b);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
|
|
86
86
|
bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
|
|
87
87
|
|
|
88
|
-
`);try{await
|
|
89
|
-
`)}catch{return n.write("\u2717 not signed in to Fly. Run `fly auth login` (or `fly auth signup`) and re-run `bostrat-node fly`.\n"),
|
|
90
|
-
`),
|
|
91
|
-
wrote ${Te.join(
|
|
88
|
+
`);try{await pt(["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"),g(1)}try{let{stdout:b}=await pt(["auth","whoami"],{exec:o});n.write(`\u2713 signed in to Fly as ${b.trim()}
|
|
89
|
+
`)}catch{return n.write("\u2717 not signed in to Fly. Run `fly auth login` (or `fly auth signup`) and re-run `bostrat-node fly`.\n"),g(1)}let N=await ws({ask:h,output:n,exec:o,flag:c.org}),f=c.app||await h("App name",`bostrat-node-${hs().slice(0,4)}`),T=c.region||await h("Region (see `fly platform regions`)","iad"),_=c.sizeGb||Number(await h("Volume size GB (logins + repos live here)","10"))||10,x=c.name||f,E=c.planeUrl||pr,k=c.token||await h("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!k)return n.write(`\u2717 a node token is required \u2014 mint one in the bostrat setup chat (Connect a node \u2192 Fly), then re-run with it.
|
|
90
|
+
`),g(1);let L=c.image||Xt,{dir:S}=yr({app:f,dest:i,toml:hr({app:f,region:T,nodeName:x,planeUrl:E,image:L})});n.write(`
|
|
91
|
+
wrote ${Te.join(S,"fly.toml")} \u2014 deploys the prebuilt node image ${L}
|
|
92
92
|
(claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
|
|
93
93
|
|
|
94
94
|
Plan (your flyctl, your org, your bill):
|
|
95
|
-
`);let
|
|
96
|
-
`);if(!c.yes&&(await
|
|
95
|
+
`);let A=mr({app:f,org:N,region:T,sizeGb:_,token:k,dir:S});for(let b of A)n.write(` $ ${b.display}
|
|
96
|
+
`);if(!c.yes&&(await h(`
|
|
97
97
|
Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u2014 nothing was created. Re-run any time; the staged context is kept.
|
|
98
|
-
`),
|
|
99
|
-
\u2192 ${
|
|
100
|
-
`);try{let{stdout:
|
|
101
|
-
`).map(
|
|
98
|
+
`),g(1);for(let b of A){n.write(`
|
|
99
|
+
\u2192 ${b.display}
|
|
100
|
+
`);try{let{stdout:O,stderr:re}=await pt(b.argv,{stdin:b.stdin,exec:o}),Se=`${O||""}${re||""}`.trim();Se&&n.write(Se.split(`
|
|
101
|
+
`).map(Tt=>` ${Tt}`).join(`
|
|
102
102
|
`)+`
|
|
103
|
-
`)}catch(
|
|
104
|
-
`);continue}return n.write(`\u2717 failed: ${
|
|
103
|
+
`)}catch(O){let re=`${O?.stdout||""}${O?.stderr||""}${O?.message||""}`;if(b.tolerate&&b.tolerate.test(re)){n.write(` (already exists \u2014 continuing)
|
|
104
|
+
`);continue}return n.write(`\u2717 failed: ${re.trim().split(`
|
|
105
105
|
`).slice(-4).join(`
|
|
106
106
|
`)}
|
|
107
107
|
fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
|
|
108
|
-
`),
|
|
108
|
+
`),g(1)}}return n.write(`
|
|
109
109
|
\u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
|
|
110
110
|
chat: the node step advances on its own within a minute.
|
|
111
111
|
logs: fly logs -a ${f}
|
|
112
|
-
redeploy: fly deploy ${
|
|
112
|
+
redeploy: fly deploy ${S} -c ${Te.join(S,"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 lr,ds,qt,ft,mr=v(()=>{lr="wss://plane.bostrat.ai/v1/node",ds=ls(import.meta.url)("../package.json").version,qt=`ghcr.io/globocodes/bostrat-node:${ds}`;ft=(e,{stdin:t,exec:n}={})=>new Promise((r,i)=>{if(n)return n(e,{stdin:t}).then(r,i);let c=cs("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,p,T)=>d?i(Object.assign(d,{stdout:p,stderr:T})):r({stdout:p,stderr:T}));t!=null&&c.stdin?.end(t)})});function wr(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!ms.test(String(e)))throw new Error(`pricing.js: ${n} window ${t} must be YYYY-MM-DD, got ${JSON.stringify(e)}`);let r=Date.parse(`${e}T${t==="from"?"00:00:00.000":"23:59:59.999"}Z`);if(!Number.isFinite(r))throw new Error(`pricing.js: ${n} window ${t} is not a real date: ${e}`);return r}function ws(e){let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||r.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=r.map(i=>({...i,fromMs:wr(i.from,"from",n),toMs:wr(i.to,"to",n)}))}return t}var hs,ms,ol,sl,yr=v(()=>{hs={"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"GA rates; verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-08-17",note:"$2/$10 is the standard price (intro pricing made permanent; the 2026-09-01 $3/$15 increase was cancelled) \u2014 verified 2026-08-17 against platform.claude.com/docs/en/about-claude/pricing."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-fable-5-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-09-07",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-03, re-verified 2026-08-17 (developers.openai.com pricing); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-08-24",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-terra":[{from:null,to:"2026-08-16",input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:2,output:12,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:"2026-08-16",input:1,output:6,cacheWrite:1.25,cacheRead:.1,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:.2,output:1.2,cacheWrite:.25,cacheRead:.02,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-09-07",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed)."}]},ms=/^\d{4}-\d{2}-\d{2}$/;ol=ws(hs),sl=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var gr=v(()=>{yr()});import Tr from"node:fs/promises";import vr from"node:path";import ys from"node:os";function Ar(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function kr(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function $r(e){let t=new Date(Ar(e));return t.setDate(t.getDate()+7),t.getTime()}function xr(e){let t=new Date(kr(e));return t.setMonth(t.getMonth()+1),t.getTime()}function vs(e=Date.now()){for(let[t,n]of Object.entries(_s)){let r=n.startOf(e);if(r!==pt[t]){pt[t]=r;for(let i of Xt.values())i[t]=0;for(let i of _r)i.includes(`:${t}:`)&&!i.endsWith(`:${r}`)&&_r.delete(i)}}}function bs(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let i={};for(let c of["weeklyUsd","monthlyUsd"]){let d=r?.[c];if(d==null||d==="")continue;let p=Number(d);if(!Number.isFinite(p)||p<=0)throw new Error(`${n}.${c} must be a positive number or null`);i[c]=p}Object.keys(i).length&&(t[n]=i)}return t}async function Er(e,{source:t="local",updatedAt:n=Date.now()}={}){xe={caps:bs(e),updatedAt:n,source:t};try{await Tr.mkdir(br,{recursive:!0}),await Tr.writeFile(gs(),JSON.stringify(xe,null,2))}catch{}return As()}function As(e=Date.now()){vs(e);let t=new Set([...Xt.keys(),...Object.keys(xe?.caps||{})]),n={};for(let r of t){let i=Xt.get(r);n[r]={weeklyUsd:Sr(i?.weekly||0),monthlyUsd:Sr(i?.monthly||0)}}return{caps:xe?.caps||{},configured:!!xe,seeded:Ss,updatedAt:xe?.updatedAt??null,spent:n,windows:{weekly:{start:pt.weekly,resetsAt:$r(e)},monthly:{start:pt.monthly,resetsAt:xr(e)}},warnPct:Ts}}var br,gs,Ts,_s,xe,Ss,pt,Xt,_r,Sr,Or=v(()=>{lt();gr();br=process.env.BOSTRAT_STATE_DIR||vr.join(process.env.HOME||ys.tmpdir(),".bostrat"),gs=()=>vr.join(br,"usage-caps.json"),Ts=.8;_s={weekly:{startOf:Ar,nextStart:$r,capKey:"weeklyUsd"},monthly:{startOf:kr,nextStart:xr,capKey:"monthlyUsd"}},xe=null,Ss=!1,pt={weekly:0,monthly:0},Xt=new Map,_r=new Set;Sr=e=>Math.round(e*1e4)/1e4});var Lr={};It(Lr,{REMOVED_MARKER:()=>nn,detectInstallKind:()=>Re,detectProviderAuth:()=>Cr,maskToken:()=>tn,readRemovedMarker:()=>Dr,startPlaneLink:()=>Us,updateCommandFor:()=>Ge,versionLt:()=>Oe});import Ee from"node:fs";import Ye from"node:fs/promises";import ks from"node:http";import L from"node:path";import ht from"node:os";import{createRequire as $s}from"node:module";import Jt from"ws";function tn(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function Dr(e=nn){try{let t=JSON.parse(Ee.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function Re({env:e=process.env,pkgDir:t=L.resolve(L.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ee.existsSync}={}){let r=String(e.BOSTRAT_INSTALL_KIND||"").trim();return["container","npm-global","git-checkout","dev"].includes(r)?r:/\/lib\/node_modules\/bostrat-node(?:\/|$)/.test(t.replace(/\\/g,"/"))?"npm-global":n(L.join(t,"..",".git"))?"git-checkout":"dev"}function Oe(e,t){let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let i=0;i<Math.max(n.length,r.length);i++){let c=(n[i]||0)-(r[i]||0);if(c)return c<0}return!1}function Ge(e){switch(e){case"npm-global":return"npm install -g bostrat-node && restart the bostrat-node service";case"git-checkout":return"scripts/deploy-pi.sh (or The Bakery \u2192 Deploy to Pi \u2192 bostrat)";case"container":return"Links \u2192 Fly \u2192 Update (or the plane's auto-update while the node sleeps)";default:return"update this node's bostrat-node checkout/install"}}function Cr({home:e=process.env.HOME||ht.homedir(),env:t=process.env}={}){let n=r=>{try{return Ee.statSync(r),!0}catch{return!1}};return{claude:n(L.join(e,".claude",".credentials.json")),codex:n(L.join(t.CODEX_HOME||L.join(e,".codex"),"auth.json")),cursor:n(L.join(t.XDG_CONFIG_HOME||L.join(e,".config"),"cursor","auth.json"))}}function Us({url:e,token:t,nodeId:n=ht.hostname(),name:r=ht.hostname(),listTracks:i,detectAgents:c=null,onTracksTransferred:d=null,sampleMetrics:p=null,deliverySample:T=null,onHashKey:O=null,onViewBase:f=null,metricsMs:g=Fs,onUpdateAvailable:_=null,onUpdatePolicy:x=null,onHelloRefused:R=null,updatePolicy:b=null,installKind:N=Re(),selfUrl:A=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:k=null,removedMarkerFile:S=nn,onRemoved:j=null,onDegraded:te=null,onRecovered:Se=null,onRefused:gt=null,onConnected:Xr=null,ingestMode:Tt=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:pn=Ps,unackedRetryMs:qe=Ms,pingMs:hn=Ns,deadLinkMs:_t=Math.round(hn*Is),maxInflightEvents:Jr=Ls,httpTimeoutMs:Xe=js,stallBackoffMinMs:mn=Bs,fetchImpl:wn=globalThis.fetch,log:w=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof i!="function")throw new Error("plane-link: listTracks is required");e=Fe(e);let Zr=A.replace(/^http/,"ws"),yn=new Set,gn=s=>{let l=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(!(!(l&&G&&Oe(G,l))||yn.has(l))){yn.add(l),w.log(`[plane-link] bostrat-node ${l} is available (this node runs ${G}) \u2014 ${Ge(N)}`);try{_?.({current:G,latest:l,min:s.minNodeVersion??null,installKind:N,required:!!(s.minNodeVersion&&Oe(G,s.minNodeVersion))})}catch(a){w.error(`[plane-link] update notice failed: ${a?.message||a}`)}}},le=new Map,ue=new Map,St=L.join(en,"plane-link","cursor.json"),vt=L.join(en,"plane-link","dead-letter.ndjson"),Tn=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),de={},ne={},E=new Map,Je=null,re=null,Z=0,Me=0,_n=0,Ze={},Sn=new Set,vn=Promise.resolve(),I="ws",ve=0,V=!1,fe=0,bt=!1,W=ie,be=new Set,oe=[],H=null,z=null,Y=!1,At=!1,Pe=Rr,De=null,Ae=null,ke=null,Q=null,pe=0,bn=0,ee=null,kt=!1,Qe=0,Ce=!1,se=Dr(S);if(se)if(se.tokenPreview===tn(t))Ce=!0,Ut({reason:se.reason??"removed",at:se.at??null,nodeId:se.nodeId??n}),w.error(`[plane-link] this node was REMOVED from the plane (${se.reason??"removed"}${se.at?` at ${new Date(se.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${S} to force a dial.`);else try{Ee.unlinkSync(S),w.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function $t({reason:s="removed",at:l=Date.now(),via:a="ctl"}={}){if(!Ce){Ce=!0,Ut({reason:s,at:l,nodeId:n,via:a});try{Ee.mkdirSync(L.dirname(S),{recursive:!0}),Ee.writeFileSync(S,JSON.stringify({at:l,reason:s,via:a,nodeId:n,tokenPreview:tn(t)},null,2))}catch(o){w.error(`[plane-link] could not write ${S}: ${o?.message||o}`)}w.error(`[plane-link] the plane REMOVED this node (${s}, via ${a}) \u2014 going dormant: no more dials, ingest or broker calls. Re-provision with a new node token to reconnect; the box and its data are untouched.`);try{j?.({reason:s,at:l,via:a})}catch{}Nn({bye:!1})}}async function Qr(){try{de=JSON.parse(await Ye.readFile(St,"utf8"))}catch{de={}}}function eo(){kt=!0,!ke&&(ke=setTimeout(async()=>{if(ke=null,!!kt){kt=!1;try{await Ye.mkdir(L.dirname(St),{recursive:!0}),await Ye.writeFile(St,JSON.stringify(de))}catch(s){w.error("[plane-link] cursor flush failed:",s?.message||s)}}},Rs),ke.unref?.())}function M(s){return!z||z.readyState!==Jt.OPEN?!1:(z.send(JSON.stringify(s)),!0)}function Be(s){let l=Date.now();for(let{trackId:o,event:u}of s){let y=E.get(u.id);E.set(u.id,{trackId:o,seq:u.seq,event:u,sentAt:l,firstSentAt:y?.firstSentAt??l,retryAt:l+qe,tries:(y?.tries??0)+1,nacks:y?.nacks??0})}let a=s.map(({trackId:o,event:u})=>({trackId:o,event:Cs(u)}));return I==="http"?(io(a),!0):M({v:P,ch:"events",type:"append",events:a})}function to(s){let l=null;for(let a of E.values())a.trackId===s&&(l==null||a.seq<l)&&(l=a.seq);return l}function xt(s){let l=ne[s];if(l==null)return;let a=to(s),o=a==null?l:Math.min(l,a-1);o>(de[s]??0)&&(de[s]=o,eo())}function Le(){if(Je=Date.now(),re!=null){let s=Date.now()-re;w.log(`[plane-link] spine sync recovered after ${Math.round(s/1e3)}s degraded (${Z} stall redial(s))`);let l=re;re=null,Z=0,Me=0,V=!1,fe=0;try{Se?.({since:l,downMs:s})}catch(a){w.error(`[plane-link] onRecovered failed: ${a?.message||a}`)}}}function Et(s){if(!Array.isArray(s)||!s.length)return;let l=new Set;for(let a of s){let o=E.get(a);o&&(E.delete(a),(ne[o.trackId]??0)<o.seq&&(ne[o.trackId]=o.seq),l.add(o.trackId))}for(let a of l)xt(a);Le()}function An(s,l){_n++;let a={at:Date.now(),trackId:s.trackId,seq:s.seq,id:s.event?.id??null,type:s.event?.type??null,reason:l,event:s.event??null};w.error(`[plane-link] DEAD-LETTER ${s.trackId} seq ${s.seq} (${a.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${vt}`),vn=vn.then(async()=>{await Ye.mkdir(L.dirname(vt),{recursive:!0}),await Ye.appendFile(vt,JSON.stringify(a)+`
|
|
116
|
-
`)}).catch(o=>w.error(`[plane-link] dead-letter write failed: ${o?.message||o}`))}function no(s,l){if(Ze[s]=(Ze[s]??0)+1,Sn.has(s))return;Sn.add(s);let a=Ds[s]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";w.error(`[plane-link] REFUSED by the plane (${s}) on track ${l}: events are being dropped, not stored \u2014 ${a}`);try{gt?.({reason:s,trackId:l,count:Ze[s],hint:a})}catch(o){w.error(`[plane-link] onRefused failed: ${o?.message||o}`)}}function Ot(s,l,a,o=null){if(!Array.isArray(s)||!s.length)return;let u=new Set,y=Date.now();for(let m of s){let h=E.get(m);h&&(a?(E.delete(m),An(h,l),String(l).startsWith(Zt)&&no(String(l).slice(Zt.length),h.trackId),(ne[h.trackId]??0)<h.seq&&(ne[h.trackId]=h.seq),u.add(h.trackId)):(h.nacks++,h.retryAt=y+Math.max(1e3,Number(o)||qe)))}for(let m of u)xt(m);Le()}function kn(s=Date.now()){let l=1/0;for(let a of E.values())a.firstSentAt<l&&(l=a.firstSentAt);return l===1/0?0:s-l}function ro(s){if(!_t||!s||s!==z||!pe)return!1;let l=Date.now()-pe;if(l<=_t)return!1;bn++,w.error(`[plane-link] no frame from the plane for ${Math.round(l/1e3)}s \u2014 link is half-open; terminating and redialing`);try{s.terminate()}catch{}return!0}function $n(){if(!Y||!E.size)return;let s=Date.now(),l=kn(s);if(l<pn||Je!=null&&s-Je<pn||I==="http"&&V||Me>s)return;Z++;let a=Math.min(mn*2**(Z-1),Ir);if(re==null){re=s-l,w.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${E.size} event(s) in flight (${I} door) \u2014 the plane is not answering appends`);try{te?.({since:re,unacked:E.size,oldestAgeMs:l,mode:I})}catch(o){w.error(`[plane-link] onDegraded failed: ${o?.message||o}`)}}if(I==="http"){V=!0,fe=s+a,w.error(`[plane-link] ingest circuit OPEN (stall #${Z}); probing /v1/ingest/health in ${Math.round(a/1e3)}s`);return}Me=s+a,w.error(`[plane-link] closing the link and redialing in ${Math.round(a/1e3)}s (stall redial #${Z})`);try{z?.terminate()}catch{}}function Rt(){if(!Y)return;let s=Date.now();if(I==="http"&&V)return;let l=[...E.values()].filter(o=>o.event&&o.retryAt<=s&&!(I==="http"&&be.has(o.trackId)));if(!l.length)return;l.sort((o,u)=>o.trackId===u.trackId?o.seq-u.seq:o.trackId<u.trackId?-1:1),w.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let a=I==="http"?W:ie;if(I==="http"){let o=new Map;for(let u of l)(o.get(u.trackId)??o.set(u.trackId,[]).get(u.trackId)).push(u);for(let[,u]of o){if(ve>=Qt)return;Be(u.slice(0,a).map(y=>({trackId:y.trackId,event:y.event})))}return}for(let o=0;o<l.length;o+=a){let u=l.slice(o,o+a).map(y=>({trackId:y.trackId,event:y.event}));if(!Be(u))return}}async function oo(s=null){for(;;){if(!Y)return!1;let l=E.size<Jr,a=I!=="http"||ve<Qt&&!V&&(!s||!be.has(s));if(l&&a)return!0;await new Promise(o=>setTimeout(o,100))}}function Nt(){if(H=null,!Y||!oe.length)return;let s=oe;if(oe=[],I!=="http"){for(let a=0;a<s.length;a+=ie)Be(s.slice(a,a+ie));return}let l=new Map;for(let a of s)(l.get(a.trackId)??l.set(a.trackId,[]).get(a.trackId)).push(a);for(let[a,o]of l){if(be.has(a)||ve>=Qt||V){oe.push(...o);continue}for(let u=0;u<o.length;u+=W)Be(o.slice(u,u+W))}oe.length&&!H&&(H=setTimeout(Nt,Mr),H.unref?.())}let so=s=>{let l=new Map;for(let{trackId:a,event:o}of s)(l.get(a)??l.set(a,[]).get(a)).push(o);return[...l].map(([a,o])=>({trackId:a,events:o}))},he=(s,l,a,{progress:o})=>{let u=Date.now();for(let{event:y}of s){let m=E.get(y.id);m&&(m.nacks++,m.retryAt=u+Math.max(1e3,a||qe))}o&&Le()};async function io(s){let l=new Set(s.map(a=>a.trackId));for(let a of l)be.add(a);ve++;try{let a=await wn(`${Tn}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:so(s)}),signal:AbortSignal.timeout(Xe)}),o=(Number(a.headers.get("retry-after"))||0)*1e3;if(a.status===200){let u=await a.json();W=ie;for(let h of u.results??[]){Et(h.acked??[]);let $=(J,F)=>{let et=new Map;for(let me of J??[])(et.get(me.reason)??et.set(me.reason,[]).get(me.reason)).push(me.id);for(let[me,In]of et)Ot(In,me,F,u.retryAfterMs??null)};$(h.rejected,!0),$(h.deferred,!1)}let y=new Set,m=new Map;for(let h of Array.isArray(u.refused)?u.refused:[])!h||typeof h.id!="string"||(y.add(h.id),(m.get(h.reason)??m.set(h.reason,[]).get(h.reason)).push(h.id));for(let[h,$]of m)Ot($,`${Zt}${h}`,!0);Et((u.discarded??[]).filter(h=>!y.has(h))),Le();return}if(a.status===429){he(s,"overloaded",o||5e3,{progress:!0});return}if(a.status===413&&s.length>1){W=Math.max(1,Math.floor(s.length/2)),w.error(`[plane-link] ingest request too large (${s.length} events) \u2014 halving batches to ${W}`),he(s,"too_large",1e3,{progress:!0});return}if(a.status===413){let u=E.get(s[0].event.id);u&&(E.delete(u.event.id),An(u,"too_large"),(ne[u.trackId]??0)<u.seq&&(ne[u.trackId]=u.seq),xt(u.trackId)),Le();return}if(a.status===410){$t({reason:"removed",via:"410"}),he(s,"http_410",6e4,{progress:!1});return}if(a.status===401||a.status===403){let{tripped:u,holdMs:y}=at();if(u&&w.error(`[plane-link] holding every plane call for ${Math.round(y/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Qe>=Pr){Qe=Date.now();let m="";try{m=(await a.json())?.error??""}catch{}w.error(`[plane-link] plane refused ingest (HTTP ${a.status}${m?`: ${m}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}he(s,`http_${a.status}`,Math.max(6e4,Ke()),{progress:!1});return}if(a.status===400){w.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${s.length} event(s) for retry; this is a bug, not data`),he(s,"http_400",6e4,{progress:!1});return}he(s,`http_${a.status}`,o||5e3,{progress:!1})}catch(a){let o=a?.name==="TimeoutError"||a?.name==="AbortError";o&&s.length>1&&(W=Math.max(1,Math.floor(s.length/2)),w.error(`[plane-link] ingest request of ${s.length} event(s) outlived its ${Xe} ms deadline \u2014 halving batches to ${W}`)),he(s,o?"timeout":"network",5e3,{progress:!1})}finally{ve--;for(let a of l)be.delete(a)}}async function ao(){if(I!=="http"||!V||!Y||bt)return;let s=Date.now();if(!(fe>s||ct(s))){bt=!0;try{let l=await wn(`${Tn}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(Xe)});if(!l.ok)throw new Error(`HTTP ${l.status}`);w.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),V=!1,fe=0,Me=Date.now()+Xe+qe+1e3;for(let a of E.values())a.retryAt=Math.min(a.retryAt,Date.now());Rt()}catch(l){Z++;let a=Math.min(mn*2**(Z-1),Ir);fe=Date.now()+a,w.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(a/1e3)}s`)}finally{bt=!1}}}function xn(){let s=Date.now();return{mode:I,unacked:E.size,oldestUnackedAgeMs:kn(s),lastProgressAt:Je,degradedSince:re,stallRedials:Z,deadLettered:_n,http:I==="http"?{inFlight:ve,circuitOpen:V,nextProbeInMs:V?Math.max(0,fe-s):0,batchCap:W}:null}}async function En(){if(!p)return;let s;try{s=await p()}catch(a){w.error("[plane-link] metrics sample failed:",a?.message||a);return}let l=null;try{l=T?.()??null}catch{}s&&M({v:P,ch:"ctl",type:"metrics",metrics:{...s,planeLink:xn(),...l?{delivery:l}:{}}})}function co(){p&&(ee&&clearInterval(ee),En(),ee=setInterval(En,g),ee.unref?.())}async function lo(){let s;try{s=await i()}catch(l){w.error("[plane-link] backfill listTracks failed:",l?.message||l);return}M({v:P,ch:"ctl",type:"tracks",ids:s.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of s){if(!Y)return;let a;try{a=await zt(l)}catch{continue}let o=de[l.id]??0,u=a.filter(m=>m.seq>o&&typeof m.id=="string"),y=I==="http"?W:ie;for(let m=0;m<u.length;m+=y){if(!await oo(l.id))return;let h=u.slice(m,m+Math.min(y,I==="http"?W:ie)).map($=>({trackId:l.id,event:$}));if(!Be(h))return}}}function On(s){!Y||!s?.trackId||typeof s.id!="string"||(oe.push({trackId:s.trackId,event:s}),H||(H=setTimeout(Nt,Mr),H.unref?.()))}let je=new Map;async function uo(s){let{reqId:l,method:a,path:o,headers:u={},body:y}=s,m=Object.fromEntries(Object.entries(u).filter(([,$])=>$!=null)),h=new AbortController;je.set(l,h);try{if(s.host){await fo(s,m,h);return}k&&(m["x-bostrat-token"]=k);let $=await fetch(A+o,{method:a,headers:m,body:y?Buffer.from(y,"base64"):void 0,signal:h.signal}),J=Object.fromEntries($.headers);for(let F of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete J[F];if(J["content-type"]||(J["content-type"]="application/octet-stream"),M({v:P,ch:"control",type:"http_head",reqId:l,status:$.status,headers:J}),$.body){for await(let F of $.body)if(!M({v:P,ch:"control",type:"http_data",reqId:l,data:Buffer.from(F).toString("base64")}))break}M({v:P,ch:"control",type:"http_end",reqId:l,error:null})}finally{je.delete(l)}}function fo(s,l,a){let{reqId:o,method:u,path:y,body:m}=s,h=new URL(A);return new Promise($=>{let J=ks.request({host:h.hostname,port:h.port,method:u,path:y,headers:{...l,host:s.host},signal:a.signal},F=>{let{connection:et,"keep-alive":me,"transfer-encoding":In,upgrade:Oi,...po}=F.headers;M({v:P,ch:"control",type:"http_head",reqId:o,status:F.statusCode||502,headers:po}),F.on("data",ho=>{M({v:P,ch:"control",type:"http_data",reqId:o,data:Buffer.from(ho).toString("base64")})||F.destroy()}),F.on("end",()=>{M({v:P,ch:"control",type:"http_end",reqId:o,error:null}),$()}),F.on("error",()=>{M({v:P,ch:"control",type:"http_end",reqId:o,error:"view upstream error"}),$()})});J.on("error",F=>{M({v:P,ch:"control",type:"http_end",reqId:o,error:F?.message||"view request failed"}),$()}),m&&J.write(Buffer.from(m,"base64")),J.end()})}function Rn(){if(At||Ce)return;z=new Jt(e,{headers:{authorization:`Bearer ${t}`}});let s=z;pe=0,s.on("ping",()=>{pe=Date.now()}),s.on("pong",()=>{pe=Date.now()}),z.on("open",async()=>{let a=null;try{a=await c?.()||null}catch{a=null}M({v:P,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:G,installKind:N,...typeof b=="function"?{updatePolicy:b()}:b?{updatePolicy:b}:{},providers:Cr(),...a?{agents:a}:{}})}),z.on("message",a=>{pe=Date.now();let o;try{o=JSON.parse(a)}catch{return}if(o.ch==="ctl"&&o.type==="hello_ok"){Y=!0,Pe=Rr,De=null,Hn(),w.log(`[plane-link] connected to plane as ${n}`);try{Xr?.()}catch{}if(typeof o.hashKey=="string"&&o.hashKey)try{O?.(o.hashKey)}catch{}try{f?.(typeof o.viewBase=="string"&&o.viewBase?o.viewBase:null)}catch{}o.minNodeVersion&&G&&Oe(G,o.minNodeVersion)&&w.error(`[plane-link] this node is bostrat-node ${G}; the plane asks for \u2265${o.minNodeVersion} \u2014 update with: ${Ge(N)}`);try{x?.(typeof o.updatePolicy=="string"?o.updatePolicy:null)}catch{}gn(o);let u=o.ingest==="http";I=Tt==="ws"?"ws":Tt==="http"||u?"http":"ws",Tt==="http"&&!u&&w.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),I==="http"&&w.log("[plane-link] spine rides the HTTPS ingest door"),V=!1,fe=0,W=ie,Q&&clearInterval(Q),pe=Date.now(),Q=setInterval(()=>{ro(s)||(M({v:P,ch:"ctl",type:"ping"}),$n(),ao().catch(()=>{}),Rt(),oe.length&&!H&&Nt())},hn),Q.unref?.(),co(),lo().catch(y=>w.error("[plane-link] backfill failed:",y?.message||y));return}if(o.ch==="ctl"&&o.type==="hello_refused"){let u=typeof o.minNodeVersion=="string"?o.minNodeVersion:null,y=typeof o.latestNodeVersion=="string"?o.latestNodeVersion:null;w.error(`[plane-link] plane REFUSED this node: bostrat-node ${G??"?"} is below its minimum ${u??"?"} \u2014 ${o.fix||Ge(N)}`),Pe=Nr,De=0;try{R?.({current:G,min:u,latest:y,fix:o.fix||Ge(N),installKind:N})}catch(m){w.error(`[plane-link] refusal handler failed: ${m?.message||m}`)}return}if(o.ch==="ctl"&&o.type==="removed"){M({v:P,ch:"ctl",type:"removed_ack",nodeId:n}),$t({reason:typeof o.reason=="string"?o.reason:"removed",at:Number(o.at)||Date.now(),via:"ctl"});return}if(o.ch==="ctl"&&o.type==="update_available"){gn(o);return}if(o.ch==="ctl"&&o.type==="update_policy"){try{x?.(typeof o.mode=="string"?o.mode:null)}catch{}return}if(o.ch==="ctl"&&o.type==="usage_caps"){Er(o.caps??{},{source:"plane",updatedAt:o.updatedAt??Date.now()}).then(u=>w.log(`[plane-link] spend caps ${Object.keys(u.caps).length?`updated (${Object.keys(u.caps).join(", ")})`:"cleared"} from plane`)).catch(u=>w.error("[plane-link] spend-caps push rejected:",u?.message||u));return}if(o.ch==="ctl"&&o.type==="transferred"&&Array.isArray(o.tracks)){Promise.resolve().then(()=>d?.(o.tracks)).catch(u=>w.error("[plane-link] transfer notice failed:",u?.message||u));return}if(o.ch==="events"&&o.type==="ack"&&Array.isArray(o.ids)){Et(o.ids);return}if(o.ch==="events"&&o.type==="nack"&&Array.isArray(o.ids)){Ot(o.ids,o.reason,o.permanent===!0,o.retryAfterMs??null);return}if(o.ch==="control"&&o.type==="http_open"){uo(o).catch(u=>M({v:P,ch:"control",type:"http_end",reqId:o.reqId,error:u?.message||"tunnel error"}));return}if(o.ch==="control"&&o.type==="http_cancel"){je.get(o.reqId)?.abort();return}if(o.ch==="attach"&&o.type==="open"){let u=new Jt(Zr+o.path,Array.isArray(o.protocols)?o.protocols:[],o.host?{headers:{host:o.host}}:void 0);le.set(o.streamId,u),ue.set(o.streamId,[]),u.on("open",()=>{let m=ue.get(o.streamId)||[];ue.delete(o.streamId);for(let{buf:h,bin:$}of m)u.send(h,{binary:$})}),u.on("message",(m,h)=>{let $=h?m:Buffer.from(String(m));M({v:P,ch:"attach",type:"data",streamId:o.streamId,data:$.toString("base64"),...h?{bin:!0}:{}})});let y=()=>{ue.delete(o.streamId),le.delete(o.streamId)&&M({v:P,ch:"attach",type:"close",streamId:o.streamId})};u.on("close",y),u.on("error",y);return}if(o.ch==="attach"&&o.type==="data"){let u=le.get(o.streamId);if(!u)return;let y=Buffer.from(o.data,"base64"),m=o.bin===!0,h=ue.get(o.streamId);h?h.push({buf:y,bin:m}):u.send(y,{binary:m});return}if(o.ch==="attach"&&o.type==="close"){let u=le.get(o.streamId);le.delete(o.streamId),ue.delete(o.streamId),u?.close();return}});let l=()=>{Y&&w.log("[plane-link] disconnected from plane"),Y=!1,Q&&(clearInterval(Q),Q=null),ee&&(clearInterval(ee),ee=null),E.clear(),ne={},oe=[],H&&(clearTimeout(H),H=null),be.clear();for(let u of le.values())u.close();le.clear(),ue.clear();for(let u of je.values())u.abort();if(je.clear(),At||Ae)return;De==null&&(De=Date.now());let a=Date.now()-De<xs,o=Math.max(a?Es+Math.random()*Os:Pe,Me-Date.now(),Ke());Ae=setTimeout(()=>{Ae=null,Rn()},o),Ae.unref?.(),a||(Pe=Math.min(Pe*2,Nr))};z.on("close",l),z.on("error",a=>{let o=/Unexpected server response: (\d+)/.exec(a?.message||"")?.[1];if(o==="410"){$t({reason:"removed",via:"410"});return}if(o==="401"||o==="403"){let{tripped:u,holdMs:y}=at();u?w.error(`[plane-link] holding every plane call for ${Math.round(y/6e4)} min \u2014 three credential refusals in a row (HTTP ${o}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(y/6e4)} min.`):Date.now()-Qe>=Pr&&(Qe=Date.now(),w.error(`[plane-link] plane refused this node's credentials (HTTP ${o}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`))}l()})}ze.on("event",On),Qr().then(Rn);function Nn({bye:s=!0}={}){At=!0,ze.off("event",On),Ae&&clearTimeout(Ae),ke&&clearTimeout(ke),Q&&clearInterval(Q),ee&&clearInterval(ee),H&&clearTimeout(H),s&&M({v:P,ch:"ctl",type:"bye",reason:"shutdown"}),z?.close()}return{stop:()=>Nn(),status:()=>({connected:Y,nodeId:n,cursor:{...de},inflight:E.size,...xn(),auth:Kn(),dormant:Ce,removed:Ht(),deadLinkMs:_t,deadLinkRedials:bn,refused:{...Ze}}),_tick:()=>{$n(),Rt()}}}var G,en,nn,P,Rr,Nr,xs,Es,Os,ie,Rs,Ns,Is,Ms,Br,Ps,Zt,Ds,Cs,Bs,Ir,Ls,Mr,js,Qt,Fs,Pr,rn=v(()=>{lt();Or();Dt();Kt();G=(()=>{try{return $s(import.meta.url)("../package.json").version||null}catch{return null}})(),en=process.env.BOSTRAT_STATE_DIR||L.join(process.env.HOME||ht.tmpdir(),".bostrat"),nn=L.join(en,"plane-link","removed.json");P=1,Rr=1e3,Nr=3e4,xs=6e4,Es=1500,Os=500,ie=100,Rs=2e3,Ns=25e3,Is=2.5,Ms=6e4,Br=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Ps=Br(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Zt="refused:",Ds={forgedUserId:"this node's events carry a userId the plane's token does not own \u2014 remove BOSTRAT_OWNER from node.env and the shell environment, then restart the node (current releases never stamp one)",foreignTrack:"the Track belongs to another user's node \u2014 this node must not append to it",squattedTrack:"the Track id is already claimed by another user \u2014 a local Track collided with theirs",transferredAway:"the Track moved to another node \u2014 this copy is stale; it should be demoted, not resumed",slugHijack:"a View slug belongs to another owner \u2014 pick a different slug"},Cs=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},Bs=3e4,Ir=10*6e4,Ls=400,Mr=250,js=Br(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Qt=4,Fs=6e4,Pr=6e4});var jr=v(()=>{jt()});var Wr={};It(Wr,{ACTIONABLE_KINDS:()=>yt,REGISTRY_RETRY_ATTEMPTS:()=>cn,REGISTRY_WAIT_POLLS:()=>on,REGISTRY_WAIT_STEP_S:()=>sn,SELF_UPDATE_DIR:()=>an,createAutoUpdater:()=>ei,inFlight:()=>un,readStatus:()=>ln,selfUpdatePlan:()=>Hr,settleSelfUpdate:()=>Qs,startSelfUpdate:()=>Kr,underService:()=>Ur,updatePolicy:()=>Gs});import Fr from"node:fs";import ae from"node:fs/promises";import Hs from"node:os";import C from"node:path";import{spawn as Ks}from"node:child_process";import{createRequire as Ws}from"node:module";function Gs({kind:e=Re(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:yt.has(e)?e==="git-checkout"||Ur(t)?"auto":"prompt":"off"}function Ur(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Hr({kind:e,to:t,from:n=mt,statusFile:r=wt,logFile:i=C.join(an,"last.log"),port:c=Number(process.env.PORT)||3362,npmPrefix:d=null,serviceName:p=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:T=typeof process.getuid=="function"?process.getuid():0,liveDir:O=process.env.BOSTRAT_LIVE_CHECKOUT||C.resolve(C.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:f=Date.now(),attempts:g=1}={}){if(!yt.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 _=(A,k="")=>`write_status ${U(A)} ${k}`,x=process.platform==="darwin"?`launchctl kickstart -k gui/${T}/${p}`:`systemctl --user restart ${U(p)}`,R=`
|
|
115
|
+
`),g(0)}var pr,ms,Xt,pt,Tr=v(()=>{pr="wss://plane.bostrat.ai/v1/node",ms=ps(import.meta.url)("../package.json").version,Xt=`ghcr.io/globocodes/bostrat-node:${ms}`;pt=(e,{stdin:t,exec:n}={})=>new Promise((o,i)=>{if(n)return n(e,{stdin:t}).then(o,i);let c=fs("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(d,h,g)=>d?i(Object.assign(d,{stdout:h,stderr:g})):o({stdout:h,stderr:g}));t!=null&&c.stdin?.end(t)})});function _r(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!Ts.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 _s(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(i=>({...i,fromMs:_r(i.from,"from",n),toMs:_r(i.to,"to",n)}))}return t}var gs,Ts,cl,ll,Sr=v(()=>{gs={"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"GA rates; verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-08-17",note:"$2/$10 is the standard price (intro pricing made permanent; the 2026-09-01 $3/$15 increase was cancelled) \u2014 verified 2026-08-17 against platform.claude.com/docs/en/about-claude/pricing."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-fable-5-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-09-07",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-03, re-verified 2026-08-17 (developers.openai.com pricing); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-08-24",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-terra":[{from:null,to:"2026-08-16",input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:2,output:12,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:"2026-08-16",input:1,output:6,cacheWrite:1.25,cacheRead:.1,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:.2,output:1.2,cacheWrite:.25,cacheRead:.02,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-09-07",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed)."}]},Ts=/^\d{4}-\d{2}-\d{2}$/;cl=_s(gs),ll=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var vr=v(()=>{Sr()});import br from"node:fs/promises";import $r from"node:path";import Ss from"node:os";function Er(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Or(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Rr(e){let t=new Date(Er(e));return t.setDate(t.getDate()+7),t.getTime()}function Nr(e){let t=new Date(Or(e));return t.setMonth(t.getMonth()+1),t.getTime()}function $s(e=Date.now()){for(let[t,n]of Object.entries(As)){let o=n.startOf(e);if(o!==ht[t]){ht[t]=o;for(let i of Jt.values())i[t]=0;for(let i of Ar)i.includes(`:${t}:`)&&!i.endsWith(`:${o}`)&&Ar.delete(i)}}}function xs(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 i={};for(let c of["weeklyUsd","monthlyUsd"]){let d=o?.[c];if(d==null||d==="")continue;let h=Number(d);if(!Number.isFinite(h)||h<=0)throw new Error(`${n}.${c} must be a positive number or null`);i[c]=h}Object.keys(i).length&&(t[n]=i)}return t}async function Ir(e,{source:t="local",updatedAt:n=Date.now()}={}){xe={caps:xs(e),updatedAt:n,source:t};try{await br.mkdir(xr,{recursive:!0}),await br.writeFile(vs(),JSON.stringify(xe,null,2))}catch{}return Es()}function Es(e=Date.now()){$s(e);let t=new Set([...Jt.keys(),...Object.keys(xe?.caps||{})]),n={};for(let o of t){let i=Jt.get(o);n[o]={weeklyUsd:kr(i?.weekly||0),monthlyUsd:kr(i?.monthly||0)}}return{caps:xe?.caps||{},configured:!!xe,seeded:ks,updatedAt:xe?.updatedAt??null,spent:n,windows:{weekly:{start:ht.weekly,resetsAt:Rr(e)},monthly:{start:ht.monthly,resetsAt:Nr(e)}},warnPct:bs}}var xr,vs,bs,As,xe,ks,ht,Jt,Ar,kr,Mr=v(()=>{ut();vr();xr=process.env.BOSTRAT_STATE_DIR||$r.join(process.env.HOME||Ss.tmpdir(),".bostrat"),vs=()=>$r.join(xr,"usage-caps.json"),bs=.8;As={weekly:{startOf:Er,nextStart:Rr,capKey:"weeklyUsd"},monthly:{startOf:Or,nextStart:Nr,capKey:"monthlyUsd"}},xe=null,ks=!1,ht={weekly:0,monthly:0},Jt=new Map,Ar=new Set;kr=e=>Math.round(e*1e4)/1e4});var Hr={};Pt(Hr,{REMOVED_MARKER:()=>rn,detectInstallKind:()=>Re,detectProviderAuth:()=>Fr,maskToken:()=>nn,readRemovedMarker:()=>jr,startPlaneLink:()=>zs,updateCommandFor:()=>qe,versionLt:()=>Oe});import Ee from"node:fs";import Ye from"node:fs/promises";import Os from"node:http";import j from"node:path";import mt from"node:os";import{createRequire as Rs}from"node:module";import Zt from"ws";function nn(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function jr(e=rn){try{let t=JSON.parse(Ee.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function Re({env:e=process.env,pkgDir:t=j.resolve(j.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ee.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(j.join(t,"..",".git"))?"git-checkout":"dev"}function Oe(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 i=0;i<Math.max(n.length,o.length);i++){let c=(n[i]||0)-(o[i]||0);if(c)return c<0}return!1}function qe(e){switch(e){case"npm-global":return"npm install -g bostrat-node && restart the bostrat-node service";case"git-checkout":return"scripts/deploy-pi.sh (or The Bakery \u2192 Deploy to Pi \u2192 bostrat)";case"container":return"Links \u2192 Fly \u2192 Update (or the plane's auto-update while the node sleeps)";default:return"update this node's bostrat-node checkout/install"}}function Fr({home:e=process.env.HOME||mt.homedir(),env:t=process.env}={}){let n=o=>{try{return Ee.statSync(o),!0}catch{return!1}};return{claude:n(j.join(e,".claude",".credentials.json")),codex:n(j.join(t.CODEX_HOME||j.join(e,".codex"),"auth.json")),cursor:n(j.join(t.XDG_CONFIG_HOME||j.join(e,".config"),"cursor","auth.json"))}}function zs({url:e,token:t,nodeId:n=mt.hostname(),name:o=mt.hostname(),listTracks:i,detectAgents:c=null,onTracksTransferred:d=null,onTracksMoves:h=null,sampleMetrics:g=null,deliverySample:N=null,onHashKey:f=null,onViewBase:T=null,metricsMs:_=Ws,onUpdateAvailable:x=null,onUpdatePolicy:E=null,onHelloRefused:k=null,updatePolicy:L=null,installKind:S=Re(),selfUrl:A=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:b=null,removedMarkerFile:O=rn,onRemoved:re=null,onDegraded:Se=null,onRecovered:Tt=null,onRefused:eo=null,onConnected:to=null,ingestMode:_t=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:hn=Ls,unackedRetryMs:Ge=Bs,pingMs:mn=Ds,deadLinkMs:St=Math.round(mn*Cs),maxInflightEvents:no=Hs,httpTimeoutMs:Xe=Ks,stallBackoffMinMs:wn=Us,fetchImpl:yn=globalThis.fetch,log:m=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof i!="function")throw new Error("plane-link: listTracks is required");e=Fe(e);let ro=A.replace(/^http/,"ws"),gn=new Set,Tn=s=>{let l=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(!(!(l&&q&&Oe(q,l))||gn.has(l))){gn.add(l),m.log(`[plane-link] bostrat-node ${l} is available (this node runs ${q}) \u2014 ${qe(S)}`);try{x?.({current:q,latest:l,min:s.minNodeVersion??null,installKind:S,required:!!(s.minNodeVersion&&Oe(q,s.minNodeVersion))})}catch(a){m.error(`[plane-link] update notice failed: ${a?.message||a}`)}}},ue=new Map,de=new Map,vt=j.join(tn,"plane-link","cursor.json"),bt=j.join(tn,"plane-link","dead-letter.ndjson"),_n=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),Q={},J={},$=new Map,Je=null,oe=null,ee=0,Me=0,Sn=0,Ze={},vn=new Set,bn=Promise.resolve(),I="ws",ve=0,Y=!1,fe=0,At=!1,W=ae,be=new Set,se=[],H=null,z=null,V=!1,kt=!1,Pe=Pr,De=null,Ae=null,ke=null,te=null,pe=0,An=0,ne=null,$t=!1,Qe=0,Ce=!1,ie=jr(O);if(ie)if(ie.tokenPreview===nn(t))Ce=!0,Kt({reason:ie.reason??"removed",at:ie.at??null,nodeId:ie.nodeId??n}),m.error(`[plane-link] this node was REMOVED from the plane (${ie.reason??"removed"}${ie.at?` at ${new Date(ie.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${O} to force a dial.`);else try{Ee.unlinkSync(O),m.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function xt({reason:s="removed",at:l=Date.now(),via:a="ctl"}={}){if(!Ce){Ce=!0,Kt({reason:s,at:l,nodeId:n,via:a});try{Ee.mkdirSync(j.dirname(O),{recursive:!0}),Ee.writeFileSync(O,JSON.stringify({at:l,reason:s,via:a,nodeId:n,tokenPreview:nn(t)},null,2))}catch(r){m.error(`[plane-link] could not write ${O}: ${r?.message||r}`)}m.error(`[plane-link] the plane REMOVED this node (${s}, via ${a}) \u2014 going dormant: no more dials, ingest or broker calls. Re-provision with a new node token to reconnect; the box and its data are untouched.`);try{re?.({reason:s,at:l,via:a})}catch{}Dn({bye:!1})}}async function oo(){try{Q=JSON.parse(await Ye.readFile(vt,"utf8"))}catch{Q={}}}function kn(){$t=!0,!ke&&(ke=setTimeout(async()=>{if(ke=null,!!$t){$t=!1;try{await Ye.mkdir(j.dirname(vt),{recursive:!0}),await Ye.writeFile(vt,JSON.stringify(Q))}catch(s){m.error("[plane-link] cursor flush failed:",s?.message||s)}}},Ps),ke.unref?.())}function M(s){return!z||z.readyState!==Zt.OPEN?!1:(z.send(JSON.stringify(s)),!0)}function Be(s){let l=Date.now();for(let{trackId:r,event:u}of s){let p=$.get(u.id);$.set(u.id,{trackId:r,seq:u.seq,event:u,sentAt:l,firstSentAt:p?.firstSentAt??l,retryAt:l+Ge,tries:(p?.tries??0)+1,nacks:p?.nacks??0})}let a=s.map(({trackId:r,event:u})=>({trackId:r,event:Fs(u)}));return I==="http"?(uo(a),!0):M({v:P,ch:"events",type:"append",events:a})}function so(s){let l=null;for(let a of $.values())a.trackId===s&&(l==null||a.seq<l)&&(l=a.seq);return l}function Et(s){let l=J[s];if(l==null)return;let a=so(s),r=a==null?l:Math.min(l,a-1);r>(Q[s]??0)&&(Q[s]=r,kn())}function Le(){if(Je=Date.now(),oe!=null){let s=Date.now()-oe;m.log(`[plane-link] spine sync recovered after ${Math.round(s/1e3)}s degraded (${ee} stall redial(s))`);let l=oe;oe=null,ee=0,Me=0,Y=!1,fe=0;try{Tt?.({since:l,downMs:s})}catch(a){m.error(`[plane-link] onRecovered failed: ${a?.message||a}`)}}}function Ot(s){if(!Array.isArray(s)||!s.length)return;let l=new Set;for(let a of s){let r=$.get(a);r&&($.delete(a),(J[r.trackId]??0)<r.seq&&(J[r.trackId]=r.seq),l.add(r.trackId))}for(let a of l)Et(a);Le()}function $n(s,l){Sn++;let a={at:Date.now(),trackId:s.trackId,seq:s.seq,id:s.event?.id??null,type:s.event?.type??null,reason:l,event:s.event??null};m.error(`[plane-link] DEAD-LETTER ${s.trackId} seq ${s.seq} (${a.type??"?"}): plane rejected it permanently (${l}) \u2014 kept in ${bt}`),bn=bn.then(async()=>{await Ye.mkdir(j.dirname(bt),{recursive:!0}),await Ye.appendFile(bt,JSON.stringify(a)+`
|
|
116
|
+
`)}).catch(r=>m.error(`[plane-link] dead-letter write failed: ${r?.message||r}`))}function io(s,l){if(Ze[s]=(Ze[s]??0)+1,vn.has(s))return;vn.add(s);let a=js[s]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";m.error(`[plane-link] REFUSED by the plane (${s}) on track ${l}: events are being dropped, not stored \u2014 ${a}`);try{eo?.({reason:s,trackId:l,count:Ze[s],hint:a})}catch(r){m.error(`[plane-link] onRefused failed: ${r?.message||r}`)}}function Rt(s,l,a,r=null){if(!Array.isArray(s)||!s.length)return;let u=new Set,p=Date.now();for(let y of s){let w=$.get(y);w&&(a?($.delete(y),$n(w,l),String(l).startsWith(Qt)&&io(String(l).slice(Qt.length),w.trackId),(J[w.trackId]??0)<w.seq&&(J[w.trackId]=w.seq),u.add(w.trackId)):(w.nacks++,w.retryAt=p+Math.max(1e3,Number(r)||Ge)))}for(let y of u)Et(y);Le()}function xn(s=Date.now()){let l=1/0;for(let a of $.values())a.firstSentAt<l&&(l=a.firstSentAt);return l===1/0?0:s-l}function ao(s){if(!St||!s||s!==z||!pe)return!1;let l=Date.now()-pe;if(l<=St)return!1;An++,m.error(`[plane-link] no frame from the plane for ${Math.round(l/1e3)}s \u2014 link is half-open; terminating and redialing`);try{s.terminate()}catch{}return!0}function En(){if(!V||!$.size)return;let s=Date.now(),l=xn(s);if(l<hn||Je!=null&&s-Je<hn||I==="http"&&Y||Me>s)return;ee++;let a=Math.min(wn*2**(ee-1),Cr);if(oe==null){oe=s-l,m.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(l/1e3)}s with ${$.size} event(s) in flight (${I} door) \u2014 the plane is not answering appends`);try{Se?.({since:oe,unacked:$.size,oldestAgeMs:l,mode:I})}catch(r){m.error(`[plane-link] onDegraded failed: ${r?.message||r}`)}}if(I==="http"){Y=!0,fe=s+a,m.error(`[plane-link] ingest circuit OPEN (stall #${ee}); probing /v1/ingest/health in ${Math.round(a/1e3)}s`);return}Me=s+a,m.error(`[plane-link] closing the link and redialing in ${Math.round(a/1e3)}s (stall redial #${ee})`);try{z?.terminate()}catch{}}function Nt(){if(!V)return;let s=Date.now();if(I==="http"&&Y)return;let l=[...$.values()].filter(r=>r.event&&r.retryAt<=s&&!(I==="http"&&be.has(r.trackId)));if(!l.length)return;l.sort((r,u)=>r.trackId===u.trackId?r.seq-u.seq:r.trackId<u.trackId?-1:1),m.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);let a=I==="http"?W:ae;if(I==="http"){let r=new Map;for(let u of l)(r.get(u.trackId)??r.set(u.trackId,[]).get(u.trackId)).push(u);for(let[,u]of r){if(ve>=en)return;Be(u.slice(0,a).map(p=>({trackId:p.trackId,event:p.event})))}return}for(let r=0;r<l.length;r+=a){let u=l.slice(r,r+a).map(p=>({trackId:p.trackId,event:p.event}));if(!Be(u))return}}async function co(s=null){for(;;){if(!V)return!1;let l=$.size<no,a=I!=="http"||ve<en&&!Y&&(!s||!be.has(s));if(l&&a)return!0;await new Promise(r=>setTimeout(r,100))}}function It(){if(H=null,!V||!se.length)return;let s=se;if(se=[],I!=="http"){for(let a=0;a<s.length;a+=ae)Be(s.slice(a,a+ae));return}let l=new Map;for(let a of s)(l.get(a.trackId)??l.set(a.trackId,[]).get(a.trackId)).push(a);for(let[a,r]of l){if(be.has(a)||ve>=en||Y){se.push(...r);continue}for(let u=0;u<r.length;u+=W)Be(r.slice(u,u+W))}se.length&&!H&&(H=setTimeout(It,Br),H.unref?.())}let lo=s=>{let l=new Map;for(let{trackId:a,event:r}of s)(l.get(a)??l.set(a,[]).get(a)).push(r);return[...l].map(([a,r])=>({trackId:a,events:r}))},he=(s,l,a,{progress:r})=>{let u=Date.now();for(let{event:p}of s){let y=$.get(p.id);y&&(y.nacks++,y.retryAt=u+Math.max(1e3,a||Ge))}r&&Le()};async function uo(s){let l=new Set(s.map(a=>a.trackId));for(let a of l)be.add(a);ve++;try{let a=await yn(`${_n}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:lo(s)}),signal:AbortSignal.timeout(Xe)}),r=(Number(a.headers.get("retry-after"))||0)*1e3;if(a.status===200){let u=await a.json();W=ae;for(let w of u.results??[]){Ot(w.acked??[]);let R=(Z,F)=>{let et=new Map;for(let me of Z??[])(et.get(me.reason)??et.set(me.reason,[]).get(me.reason)).push(me.id);for(let[me,Cn]of et)Rt(Cn,me,F,u.retryAfterMs??null)};R(w.rejected,!0),R(w.deferred,!1)}let p=new Set,y=new Map;for(let w of Array.isArray(u.refused)?u.refused:[])!w||typeof w.id!="string"||(p.add(w.id),(y.get(w.reason)??y.set(w.reason,[]).get(w.reason)).push(w.id));for(let[w,R]of y)Rt(R,`${Qt}${w}`,!0);Ot((u.discarded??[]).filter(w=>!p.has(w))),Le();return}if(a.status===429){he(s,"overloaded",r||5e3,{progress:!0});return}if(a.status===413&&s.length>1){W=Math.max(1,Math.floor(s.length/2)),m.error(`[plane-link] ingest request too large (${s.length} events) \u2014 halving batches to ${W}`),he(s,"too_large",1e3,{progress:!0});return}if(a.status===413){let u=$.get(s[0].event.id);u&&($.delete(u.event.id),$n(u,"too_large"),(J[u.trackId]??0)<u.seq&&(J[u.trackId]=u.seq),Et(u.trackId)),Le();return}if(a.status===410){xt({reason:"removed",via:"410"}),he(s,"http_410",6e4,{progress:!1});return}if(a.status===401||a.status===403){let{tripped:u,holdMs:p}=at();if(u&&m.error(`[plane-link] holding every plane call for ${Math.round(p/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Qe>=Lr){Qe=Date.now();let y="";try{y=(await a.json())?.error??""}catch{}m.error(`[plane-link] plane refused ingest (HTTP ${a.status}${y?`: ${y}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}he(s,`http_${a.status}`,Math.max(6e4,Ke()),{progress:!1});return}if(a.status===400){m.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${s.length} event(s) for retry; this is a bug, not data`),he(s,"http_400",6e4,{progress:!1});return}he(s,`http_${a.status}`,r||5e3,{progress:!1})}catch(a){let r=a?.name==="TimeoutError"||a?.name==="AbortError";r&&s.length>1&&(W=Math.max(1,Math.floor(s.length/2)),m.error(`[plane-link] ingest request of ${s.length} event(s) outlived its ${Xe} ms deadline \u2014 halving batches to ${W}`)),he(s,r?"timeout":"network",5e3,{progress:!1})}finally{ve--;for(let a of l)be.delete(a)}}async function fo(){if(I!=="http"||!Y||!V||At)return;let s=Date.now();if(!(fe>s||ct(s))){At=!0;try{let l=await yn(`${_n}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(Xe)});if(!l.ok)throw new Error(`HTTP ${l.status}`);m.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),Y=!1,fe=0,Me=Date.now()+Xe+Ge+1e3;for(let a of $.values())a.retryAt=Math.min(a.retryAt,Date.now());Nt()}catch(l){ee++;let a=Math.min(wn*2**(ee-1),Cr);fe=Date.now()+a,m.error(`[plane-link] ingest door still not answering (${l?.message||l}); next probe in ${Math.round(a/1e3)}s`)}finally{At=!1}}}function On(){let s=Date.now();return{mode:I,unacked:$.size,oldestUnackedAgeMs:xn(s),lastProgressAt:Je,degradedSince:oe,stallRedials:ee,deadLettered:Sn,http:I==="http"?{inFlight:ve,circuitOpen:Y,nextProbeInMs:Y?Math.max(0,fe-s):0,batchCap:W}:null}}async function Rn(){if(!g)return;let s;try{s=await g()}catch(a){m.error("[plane-link] metrics sample failed:",a?.message||a);return}let l=null;try{l=N?.()??null}catch{}s&&M({v:P,ch:"ctl",type:"metrics",metrics:{...s,planeLink:On(),...l?{delivery:l}:{}}})}function po(){g&&(ne&&clearInterval(ne),Rn(),ne=setInterval(Rn,_),ne.unref?.())}async function ho(){let s;try{s=await i()}catch(l){m.error("[plane-link] backfill listTracks failed:",l?.message||l);return}M({v:P,ch:"ctl",type:"tracks",ids:s.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of s)if(!V||!await Nn(l))return}async function Nn(s){let l;try{l=await lt(s)}catch{return!0}let a=Q[s.id]??0,r=l.filter(p=>p.seq>a&&typeof p.id=="string"),u=I==="http"?W:ae;for(let p=0;p<r.length;p+=u){if(!await co(s.id))return!1;let y=r.slice(p,p+Math.min(u,I==="http"?W:ae)).map(w=>({trackId:s.id,event:w}));if(!Be(y))return!1}return!0}let Mt=new Map;async function In(s,l){if(Mt.get(s)===l)return!1;Mt.set(s,l);let a=null;try{a=(await i()).find(y=>y?.id===s)??null}catch{return!1}if(!a)return!1;let r;try{r=await lt(a)}catch{return!1}let u=[...r].reverse().find(y=>(y?.type==="track.transferred"||y?.type==="track.recovered")&&y.payload?.toNode===n);if(!u||!Number.isFinite(u.seq))return!1;let p=u.seq-1;return(Q[s]??0)>p&&(Q[s]=p,kn()),(J[s]??0)>p&&(J[s]=p),m.log(`[plane-link] re-sending ${s}'s move-commit (seq ${u.seq}, ${u.type}) \u2014 the plane's move record predates this node's adoption`),V?Nn(a):!1}function Mn(s){!V||!s?.trackId||typeof s.id!="string"||(se.push({trackId:s.trackId,event:s}),H||(H=setTimeout(It,Br),H.unref?.()))}let je=new Map;async function mo(s){let{reqId:l,method:a,path:r,headers:u={},body:p}=s,y=Object.fromEntries(Object.entries(u).filter(([,R])=>R!=null)),w=new AbortController;je.set(l,w);try{if(s.host){await wo(s,y,w);return}b&&(y["x-bostrat-token"]=b);let R=await fetch(A+r,{method:a,headers:y,body:p?Buffer.from(p,"base64"):void 0,signal:w.signal}),Z=Object.fromEntries(R.headers);for(let F of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete Z[F];if(Z["content-type"]||(Z["content-type"]="application/octet-stream"),M({v:P,ch:"control",type:"http_head",reqId:l,status:R.status,headers:Z}),R.body){for await(let F of R.body)if(!M({v:P,ch:"control",type:"http_data",reqId:l,data:Buffer.from(F).toString("base64")}))break}M({v:P,ch:"control",type:"http_end",reqId:l,error:null})}finally{je.delete(l)}}function wo(s,l,a){let{reqId:r,method:u,path:p,body:y}=s,w=new URL(A);return new Promise(R=>{let Z=Os.request({host:w.hostname,port:w.port,method:u,path:p,headers:{...l,host:s.host},signal:a.signal},F=>{let{connection:et,"keep-alive":me,"transfer-encoding":Cn,upgrade:Mi,...yo}=F.headers;M({v:P,ch:"control",type:"http_head",reqId:r,status:F.statusCode||502,headers:yo}),F.on("data",go=>{M({v:P,ch:"control",type:"http_data",reqId:r,data:Buffer.from(go).toString("base64")})||F.destroy()}),F.on("end",()=>{M({v:P,ch:"control",type:"http_end",reqId:r,error:null}),R()}),F.on("error",()=>{M({v:P,ch:"control",type:"http_end",reqId:r,error:"view upstream error"}),R()})});Z.on("error",F=>{M({v:P,ch:"control",type:"http_end",reqId:r,error:F?.message||"view request failed"}),R()}),y&&Z.write(Buffer.from(y,"base64")),Z.end()})}function Pn(){if(kt||Ce)return;z=new Zt(e,{headers:{authorization:`Bearer ${t}`}});let s=z;pe=0,s.on("ping",()=>{pe=Date.now()}),s.on("pong",()=>{pe=Date.now()}),z.on("open",async()=>{let a=null;try{a=await c?.()||null}catch{a=null}M({v:P,ch:"ctl",type:"hello",nodeId:n,name:o,platform:process.platform,version:q,installKind:S,...typeof L=="function"?{updatePolicy:L()}:L?{updatePolicy:L}:{},providers:Fr(),...a?{agents:a}:{}})}),z.on("message",a=>{pe=Date.now();let r;try{r=JSON.parse(a)}catch{return}if(r.ch==="ctl"&&r.type==="hello_ok"){Mt.clear(),V=!0,Pe=Pr,De=null,Vn(),m.log(`[plane-link] connected to plane as ${n}`);try{to?.()}catch{}if(typeof r.hashKey=="string"&&r.hashKey)try{f?.(r.hashKey)}catch{}try{T?.(typeof r.viewBase=="string"&&r.viewBase?r.viewBase:null)}catch{}r.minNodeVersion&&q&&Oe(q,r.minNodeVersion)&&m.error(`[plane-link] this node is bostrat-node ${q}; the plane asks for \u2265${r.minNodeVersion} \u2014 update with: ${qe(S)}`);try{E?.(typeof r.updatePolicy=="string"?r.updatePolicy:null)}catch{}Tn(r);let u=r.ingest==="http";I=_t==="ws"?"ws":_t==="http"||u?"http":"ws",_t==="http"&&!u&&m.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),I==="http"&&m.log("[plane-link] spine rides the HTTPS ingest door"),Y=!1,fe=0,W=ae,te&&clearInterval(te),pe=Date.now(),te=setInterval(()=>{ao(s)||(M({v:P,ch:"ctl",type:"ping"}),En(),fo().catch(()=>{}),Nt(),se.length&&!H&&It())},mn),te.unref?.(),po(),ho().catch(p=>m.error("[plane-link] backfill failed:",p?.message||p));return}if(r.ch==="ctl"&&r.type==="hello_refused"){let u=typeof r.minNodeVersion=="string"?r.minNodeVersion:null,p=typeof r.latestNodeVersion=="string"?r.latestNodeVersion:null;m.error(`[plane-link] plane REFUSED this node: bostrat-node ${q??"?"} is below its minimum ${u??"?"} \u2014 ${r.fix||qe(S)}`),Pe=Dr,De=0;try{k?.({current:q,min:u,latest:p,fix:r.fix||qe(S),installKind:S})}catch(y){m.error(`[plane-link] refusal handler failed: ${y?.message||y}`)}return}if(r.ch==="ctl"&&r.type==="removed"){M({v:P,ch:"ctl",type:"removed_ack",nodeId:n}),xt({reason:typeof r.reason=="string"?r.reason:"removed",at:Number(r.at)||Date.now(),via:"ctl"});return}if(r.ch==="ctl"&&r.type==="update_available"){Tn(r);return}if(r.ch==="ctl"&&r.type==="update_policy"){try{E?.(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(u=>m.log(`[plane-link] spend caps ${Object.keys(u.caps).length?`updated (${Object.keys(u.caps).join(", ")})`:"cleared"} from plane`)).catch(u=>m.error("[plane-link] spend-caps push rejected:",u?.message||u));return}if(r.ch==="ctl"&&r.type==="transferred"&&Array.isArray(r.tracks)){Promise.resolve().then(()=>d?.(r.tracks)).then(async u=>{for(let p of Array.isArray(u)?u:[])p?.stale&&p.id&&await In(p.id,p.since??null)}).catch(u=>m.error("[plane-link] transfer notice failed:",u?.message||u));return}if(r.ch==="ctl"&&r.type==="moves"&&Array.isArray(r.tracks)){Promise.resolve().then(()=>h?.(r.tracks)).then(async u=>{for(let p of Array.isArray(u)?u:[])p?.stale&&p.id&&await In(p.id,p.since??null)}).catch(u=>m.error("[plane-link] move-record reconcile failed:",u?.message||u));return}if(r.ch==="events"&&r.type==="ack"&&Array.isArray(r.ids)){Ot(r.ids);return}if(r.ch==="events"&&r.type==="nack"&&Array.isArray(r.ids)){Rt(r.ids,r.reason,r.permanent===!0,r.retryAfterMs??null);return}if(r.ch==="control"&&r.type==="http_open"){mo(r).catch(u=>M({v:P,ch:"control",type:"http_end",reqId:r.reqId,error:u?.message||"tunnel error"}));return}if(r.ch==="control"&&r.type==="http_cancel"){je.get(r.reqId)?.abort();return}if(r.ch==="attach"&&r.type==="open"){let u=new Zt(ro+r.path,Array.isArray(r.protocols)?r.protocols:[],r.host?{headers:{host:r.host}}:void 0);ue.set(r.streamId,u),de.set(r.streamId,[]),u.on("open",()=>{let y=de.get(r.streamId)||[];de.delete(r.streamId);for(let{buf:w,bin:R}of y)u.send(w,{binary:R})}),u.on("message",(y,w)=>{let R=w?y:Buffer.from(String(y));M({v:P,ch:"attach",type:"data",streamId:r.streamId,data:R.toString("base64"),...w?{bin:!0}:{}})});let p=()=>{de.delete(r.streamId),ue.delete(r.streamId)&&M({v:P,ch:"attach",type:"close",streamId:r.streamId})};u.on("close",p),u.on("error",p);return}if(r.ch==="attach"&&r.type==="data"){let u=ue.get(r.streamId);if(!u)return;let p=Buffer.from(r.data,"base64"),y=r.bin===!0,w=de.get(r.streamId);w?w.push({buf:p,bin:y}):u.send(p,{binary:y});return}if(r.ch==="attach"&&r.type==="close"){let u=ue.get(r.streamId);ue.delete(r.streamId),de.delete(r.streamId),u?.close();return}});let l=()=>{V&&m.log("[plane-link] disconnected from plane"),V=!1,te&&(clearInterval(te),te=null),ne&&(clearInterval(ne),ne=null),$.clear(),J={},se=[],H&&(clearTimeout(H),H=null),be.clear();for(let u of ue.values())u.close();ue.clear(),de.clear();for(let u of je.values())u.abort();if(je.clear(),kt||Ae)return;De==null&&(De=Date.now());let a=Date.now()-De<Ns,r=Math.max(a?Is+Math.random()*Ms:Pe,Me-Date.now(),Ke());Ae=setTimeout(()=>{Ae=null,Pn()},r),Ae.unref?.(),a||(Pe=Math.min(Pe*2,Dr))};z.on("close",l),z.on("error",a=>{let r=/Unexpected server response: (\d+)/.exec(a?.message||"")?.[1];if(r==="410"){xt({reason:"removed",via:"410"});return}if(r==="401"||r==="403"){let{tripped:u,holdMs:p}=at();u?m.error(`[plane-link] holding every plane call for ${Math.round(p/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(p/6e4)} min.`):Date.now()-Qe>=Lr&&(Qe=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)`))}l()})}ze.on("event",Mn),oo().then(Pn);function Dn({bye:s=!0}={}){kt=!0,ze.off("event",Mn),Ae&&clearTimeout(Ae),ke&&clearTimeout(ke),te&&clearInterval(te),ne&&clearInterval(ne),H&&clearTimeout(H),s&&M({v:P,ch:"ctl",type:"bye",reason:"shutdown"}),z?.close()}return{stop:()=>Dn(),status:()=>({connected:V,nodeId:n,cursor:{...Q},inflight:$.size,...On(),auth:Yn(),dormant:Ce,removed:Wt(),deadLinkMs:St,deadLinkRedials:An,refused:{...Ze}}),_tick:()=>{En(),Nt()}}}var q,tn,rn,P,Pr,Dr,Ns,Is,Ms,ae,Ps,Ds,Cs,Bs,Ur,Ls,Qt,js,Fs,Us,Cr,Hs,Br,Ks,en,Ws,Lr,on=v(()=>{ut();Mr();Bt();zt();q=(()=>{try{return Rs(import.meta.url)("../package.json").version||null}catch{return null}})(),tn=process.env.BOSTRAT_STATE_DIR||j.join(process.env.HOME||mt.tmpdir(),".bostrat"),rn=j.join(tn,"plane-link","removed.json");P=1,Pr=1e3,Dr=3e4,Ns=6e4,Is=1500,Ms=500,ae=100,Ps=2e3,Ds=25e3,Cs=2.5,Bs=6e4,Ur=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Ls=Ur(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Qt="refused:",js={forgedUserId:"this node's events carry a userId the plane's token does not own \u2014 remove BOSTRAT_OWNER from node.env and the shell environment, then restart the node (current releases never stamp one)",foreignTrack:"the Track belongs to another user's node \u2014 this node must not append to it",squattedTrack:"the Track id is already claimed by another user \u2014 a local Track collided with theirs",transferredAway:"the Track moved to another node \u2014 this copy is stale; it should be demoted, not resumed",slugHijack:"a View slug belongs to another owner \u2014 pick a different slug"},Fs=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},Us=3e4,Cr=10*6e4,Hs=400,Br=250,Ks=Ur(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),en=4,Ws=6e4,Lr=6e4});var Kr=v(()=>{Ut()});var qr={};Pt(qr,{ACTIONABLE_KINDS:()=>gt,REGISTRY_RETRY_ATTEMPTS:()=>ln,REGISTRY_WAIT_POLLS:()=>sn,REGISTRY_WAIT_STEP_S:()=>an,SELF_UPDATE_DIR:()=>cn,createAutoUpdater:()=>oi,inFlight:()=>dn,readStatus:()=>un,selfUpdatePlan:()=>Vr,settleSelfUpdate:()=>ri,startSelfUpdate:()=>Yr,underService:()=>zr,updatePolicy:()=>Zs});import Wr from"node:fs";import ce from"node:fs/promises";import Vs from"node:os";import C from"node:path";import{spawn as Ys}from"node:child_process";import{createRequire as qs}from"node:module";function Zs({kind:e=Re(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:gt.has(e)?e==="git-checkout"||zr(t)?"auto":"prompt":"off"}function zr(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Vr({kind:e,to:t,from:n=wt,statusFile:o=yt,logFile:i=C.join(cn,"last.log"),port:c=Number(process.env.PORT)||3362,npmPrefix:d=null,serviceName:h=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:g=typeof process.getuid=="function"?process.getuid():0,liveDir:N=process.env.BOSTRAT_LIVE_CHECKOUT||C.resolve(C.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:f=Date.now(),attempts:T=1}={}){if(!gt.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 _=(S,A="")=>`write_status ${U(S)} ${A}`,x=process.platform==="darwin"?`launchctl kickstart -k gui/${g}/${h}`:`systemctl --user restart ${U(h)}`,E=`
|
|
117
117
|
health() {
|
|
118
118
|
for i in $(seq 1 45); do
|
|
119
119
|
sleep 1
|
|
120
120
|
if curl -sf -o /dev/null "http://127.0.0.1:${c}/api/health"; then return 0; fi
|
|
121
121
|
done
|
|
122
122
|
return 1
|
|
123
|
-
}`,
|
|
123
|
+
}`,k=`#!/usr/bin/env bash
|
|
124
124
|
# bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
|
|
125
|
-
# ${n??"?"} \u2192 ${t} (${e}). Status: ${
|
|
125
|
+
# ${n??"?"} \u2192 ${t} (${e}). Status: ${o}
|
|
126
126
|
set -u
|
|
127
127
|
FROM=${U(n??"")}
|
|
128
128
|
TO=${U(t)}
|
|
129
|
-
STATUS_FILE=${U(
|
|
129
|
+
STATUS_FILE=${U(o)}
|
|
130
130
|
STARTED_AT=${Number(f)}
|
|
131
|
-
ATTEMPTS=${Number(
|
|
131
|
+
ATTEMPTS=${Number(T)||1}
|
|
132
132
|
write_status() { # <status> [error] [retryable]
|
|
133
133
|
local err="\${2:-}"
|
|
134
134
|
err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
|
|
@@ -136,22 +136,22 @@ write_status() { # <status> [error] [retryable]
|
|
|
136
136
|
"$1" "$FROM" "$TO" ${U(e)} "$ATTEMPTS" "$STARTED_AT" "$(date +%s000)" \\
|
|
137
137
|
"\${err:+,\\"error\\":\\"$err\\"}" "\${3:+,\\"retryable\\":true}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
|
|
138
138
|
}
|
|
139
|
-
${
|
|
140
|
-
`;if(e==="npm-global"){let
|
|
141
|
-
`:"",
|
|
139
|
+
${E}
|
|
140
|
+
`;if(e==="npm-global"){let S=d?C.join(d,"bin","npm"):"npm",A=d?`export PATH=${U(C.join(d,"bin"))}:"$PATH"
|
|
141
|
+
`:"",b=d?` --prefix ${U(d)}`:"",O=Se=>`${U(S)} install -g "bostrat-node@${Se}" --no-audit --no-fund${b}`,re=`
|
|
142
142
|
wait_for_registry() {
|
|
143
|
-
for i in $(seq 1 ${
|
|
144
|
-
if [ "$(${U(
|
|
145
|
-
sleep ${
|
|
143
|
+
for i in $(seq 1 ${sn}); do
|
|
144
|
+
if [ "$(${U(S)} view "bostrat-node@$TO" version --prefer-online 2>/dev/null)" = "$TO" ]; then return 0; fi
|
|
145
|
+
sleep ${an}
|
|
146
146
|
done
|
|
147
147
|
return 1
|
|
148
|
-
}`;return
|
|
148
|
+
}`;return k+A+re+`
|
|
149
149
|
${_("updating",'"" ')}
|
|
150
150
|
if ! wait_for_registry; then
|
|
151
|
-
${_("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(
|
|
151
|
+
${_("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(sn*an/60)} min, attempt $ATTEMPTS of ${ln})" retryable`)}
|
|
152
152
|
exit 1
|
|
153
153
|
fi
|
|
154
|
-
if ! ${
|
|
154
|
+
if ! ${O("$TO")}; then
|
|
155
155
|
${_("failed",'"npm install failed"')}
|
|
156
156
|
exit 1
|
|
157
157
|
fi
|
|
@@ -166,51 +166,51 @@ if health; then
|
|
|
166
166
|
fi
|
|
167
167
|
# \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
|
|
168
168
|
${_("rolling-back",'"agent did not answer on :'+c+' after the update"')}
|
|
169
|
-
if [ -n "$FROM" ] && ${
|
|
169
|
+
if [ -n "$FROM" ] && ${O("$FROM")} && ${x} && health; then
|
|
170
170
|
${_("rolled-back",'"agent did not answer on :'+c+' after the update; rolled back"')}
|
|
171
171
|
exit 1
|
|
172
172
|
fi
|
|
173
173
|
${_("failed",'"agent did not answer after the update AND the rollback"')}
|
|
174
174
|
exit 1
|
|
175
|
-
`}let
|
|
176
|
-
LIVE=${U(
|
|
175
|
+
`}let L=S=>`( cd ${U(N)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${S}" )`;return k+`
|
|
176
|
+
LIVE=${U(N)}
|
|
177
177
|
TMP_SCRIPT="$(mktemp)"
|
|
178
178
|
trap 'rm -f "$TMP_SCRIPT"' EXIT
|
|
179
179
|
# "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
|
|
180
180
|
# restart \u2192 health in one call): the agent it restarts settles "done" on boot,
|
|
181
181
|
# and nothing here may write after that boot or the settle would repeat.
|
|
182
182
|
${_("restarting")}
|
|
183
|
-
if ${
|
|
183
|
+
if ${L("$TO")}; then
|
|
184
184
|
exit 0
|
|
185
185
|
fi
|
|
186
186
|
${_("rolling-back",'"deploy-pi.sh v$TO failed"')}
|
|
187
|
-
if [ -n "$FROM" ] && ${
|
|
187
|
+
if [ -n "$FROM" ] && ${L("$FROM")}; then
|
|
188
188
|
${_("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
|
|
189
189
|
exit 1
|
|
190
190
|
fi
|
|
191
191
|
${_("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
|
|
192
192
|
exit 1
|
|
193
|
-
`}async function ln(e=wt){try{return JSON.parse(await ae.readFile(e,"utf8"))}catch{return null}}async function Kr({to:e,from:t=mt,kind:n=Re(),reason:r="manual",force:i=!1,statusFile:c=wt,spawnImpl:d=Ks,now:p=Date.now,npmPrefix:T=void 0,log:O=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!yt.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Oe(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let f=await ln(c);if(un(f))return{ok:!1,reason:`an update to ${f.to} is already in flight`,status:f};let g=f?.to===e?Number(f.attempts)||1:0;if(!i&&f&&f.to===e&&(f.status==="failed"||f.status==="rolled-back")&&!(f.status==="failed"&&f.retryable===!0&&g<cn))return{ok:!1,reason:`update to ${e} already ${f.status} (${f.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:f};let _=f?.to===e&&(f.status==="failed"||f.status==="rolled-back")?g+1:1;await ae.mkdir(C.dirname(c),{recursive:!0});let x=T!==void 0?T:n==="npm-global"?Lt(await Xs())||C.resolve(C.dirname(process.execPath),".."):null,R=Hr({kind:n,to:e,from:t,statusFile:c,npmPrefix:x,startedAt:p(),attempts:_}),b=C.join(C.dirname(c),`update-${e}.sh`),N=C.join(C.dirname(c),"last.log");await ae.writeFile(b,R,{mode:448}),await ae.writeFile(c,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:_,startedAt:p(),updatedAt:p()}));let A=Fr.existsSync("/run/systemd/system")&&await Js("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",b]]:["setsid",["-f","bash","-c",`exec bash ${U(b)} >> ${U(N)} 2>&1`]];try{d(A[0],A[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(k){return await ae.writeFile(c,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,startedAt:p(),updatedAt:p(),error:`could not spawn updater: ${k?.message||k}`})),{ok:!1,reason:`could not spawn updater: ${k?.message||k}`}}return O.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${c}`),{ok:!0,to:e,from:t,kind:n,scriptFile:b,statusFile:c}}async function Xs(){try{return await ae.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Js(e){for(let t of String(process.env.PATH||"").split(C.delimiter))try{return await ae.access(C.join(t,e),Fr.constants.X_OK),!0}catch{}return!1}async function Qs({statusFile:e=wt,current:t=mt,now:n=Date.now,staleMs:r=Zs}={}){let i=await ln(e);if(!i)return null;let c=d=>ae.writeFile(e,JSON.stringify(d)).catch(()=>{});if(un(i)){if(t&&i.to===t){let d={...i,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await c(d),d}if(n()-Number(i.updatedAt||i.startedAt||0)>r){let d={...i,status:"failed",error:`updater went silent while ${i.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await c(d),d}return null}if(["failed","rolled-back","done"].includes(i.status)&&!i.announced){let d={...i,announced:!0};return await c(d),d}return null}function ei({isBusy:e,start:t=Kr,onStuck:n=null,onStarted:r=null,tickMs:i=Ys,stuckMs:c=Vs,now:d=Date.now,setIntervalImpl:p=setInterval,clearIntervalImpl:T=clearInterval,log:O=console}={}){let f=null,g=()=>{f?.timer&&T(f.timer),f=null},_=async()=>{if(!f)return;let x=!0;try{x=await e()!==!1}catch{x=!0}if(x){if(!f.stuckFired&&d()-f.since>=c){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let R=f;g();let b=await t({to:R.to,from:R.from,kind:R.kind,reason:"auto"});O.log?.(`[self-update] stasis reached \u2192 ${b.ok?"started":`not started: ${b.reason}`}`);try{await r?.({...R,result:b})}catch{}};return{arm({to:x,from:R=mt,kind:b=Re()}){return f?.to===x?!1:(g(),f={to:x,from:R,kind:b,since:d(),stuckFired:!1,timer:p(_,i)},f.timer.unref?.(),!0)},tick:_,cancel:g,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var mt,zs,an,wt,Vs,Ys,on,sn,cn,yt,U,qs,un,Zs,zr=v(()=>{rn();jr();mt=(()=>{try{return Ws(import.meta.url)("../package.json").version||null}catch{return null}})(),zs=process.env.BOSTRAT_STATE_DIR||C.join(process.env.HOME||Hs.tmpdir(),".bostrat"),an=C.join(zs,"self-update"),wt=C.join(an,"status.json"),Vs=1440*6e4,Ys=6e4,on=60,sn=15,cn=3,yt=new Set(["npm-global","git-checkout"]);U=e=>`'${String(e).replace(/'/g,"'\\''")}'`;qs=new Set(["updating","restarting","rolling-back"]),un=e=>!!(e&&qs.has(e.status));Zs=45*6e4});Dt();Bt();import q from"node:fs";import D from"node:path";import Ie from"node:os";import{createRequire as dn}from"node:module";import{execFile as ti,spawn as ni}from"node:child_process";import{promisify as ri}from"node:util";import oi from"node:readline/promises";import{randomUUID as si}from"node:crypto";import{fileURLToPath as ii}from"node:url";import es from"node:fs";import sr from"node:path";import ts from"node:os";var ns=()=>process.env.BOSTRAT_STATE_DIR||sr.join(process.env.HOME||ts.tmpdir(),".bostrat"),rs=()=>sr.join(ns(),"plane-link","public-host.json");var Ve=null;function os(){if(Ve)return Ve;try{let e=JSON.parse(es.readFileSync(rs(),"utf8"));Ve={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{Ve={viewBase:null}}return Ve}function ss(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),i=r?r[1].toLowerCase():t,c=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return c?{proto:i,host:c}:null}function ir(){return os().viewBase}function ar(e=process.env.BOSTRAT_PUBLIC_HOST){return ss(e,"https")}function cr(e=process.env.BOSTRAT_PLANE_URL){let t=String(e||"").trim();if(!t)return null;let n=/^(wss?|https?):\/\/([^/?#]+)/i.exec(t);return n?`${/^(wss|https)$/i.test(n[1])?"https":"http"}://${n[2]}`:null}var Vr=(e,t)=>{let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let i=0;i<Math.max(n.length,r.length);i++){let c=(n[i]||0)-(r[i]||0);if(c)return c<0}return!1},ce=ri(ti),fn=D.dirname(ii(import.meta.url)),_e=D.resolve(fn,".."),ai=D.join(fn,"index.js"),ci="wss://plane.bostrat.ai/v1/node",Ne=dn(import.meta.url)("../package.json").version,B=(e,t)=>({name:e,level:"pass",detail:t}),X=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),K=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function li(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?B("node runtime",`${process.version} at ${process.execPath}`):K("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function ui(e){return e.BOSTRAT_OWNER?X("owner stamp",`BOSTRAT_OWNER=${String(e.BOSTRAT_OWNER).slice(0,12)}\u2026 is set \u2014 ignored by this release; on older releases it got every event refused (forgedUserId)`,"remove BOSTRAT_OWNER from node.env and any shell rc, then restart the node"):B("owner stamp","none (the plane infers the owner from the token)")}function di(e){let t;try{t=q.statSync(e)}catch{return X("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?X("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 fi(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 K("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Yr(e,{required:t=!1}={}){if(await Yt(e,{loginShell:!0,failOpen:!1}))return B(e,"resolves on the login-shell PATH");let r="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",i=dt[e]?`${dt[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?K(e,r,i):X(e,r,i)}async function pi(){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 X("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",dt.gh)}}async function hi(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Yr(t)));return e.some(t=>t.level==="pass")||e.push(K("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 mi(){let e=[...process.platform==="linux"?[["fuser","stopped views can't free their ports (they leak, and the port can't be reused)","apt install psmisc"]]:[],["pgrep","agent-swap can't detect an idle pane shell \u2014 swaps may misfire","apt install procps"],["npm","codex auto-update and `npm run` views are unavailable","install Node.js with npm on the service PATH"]];return Promise.all(e.map(async([t,n,r])=>await Yt(t,{failOpen:!1})?B(t,"resolves on the service PATH"):X(t,`not on the service PATH \u2014 ${n}`,r)))}async function wi(){try{let t=dn(D.join(_e,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let i=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),c=setTimeout(()=>r(new Error("spawn timeout")),5e3);i.onExit(()=>{clearTimeout(c),n()})}),B("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${_e} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=dn(D.join(_e,"package.json")),r=D.join(D.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");q.existsSync(r)&&!(q.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return K("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function yi(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(q.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"?K:X)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function gi(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?K("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 Ti(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return X("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),i=Fe(e.BOSTRAT_PLANE_URL);return await new Promise(c=>{let d=new n(i,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),p=null,T=f=>{clearTimeout(O);try{d.close()}catch{}c(p?{...f,viewBase:p}:f)},O=setTimeout(()=>T(K("plane link",`no hello_ok within 5s from ${i}`,"check the URL, the token, and the plane's IP gate")),5e3);d.on("open",()=>d.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${si().slice(0,8)}`,ephemeral:!0}))),d.on("message",f=>{try{let g=JSON.parse(f);g.type==="hello_ok"?(typeof g.viewBase=="string"&&g.viewBase&&(p=g.viewBase),g.minNodeVersion&&Vr(Ne,g.minNodeVersion)?T(K("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${g.minNodeVersion} \u2014 this node is ${Ne}; the real link is refused until it updates`,`bostrat-node self-update --to ${g.latestNodeVersion||g.minNodeVersion}`)):g.latestNodeVersion&&Vr(Ne,g.latestNodeVersion)?T(X("plane link",`hello_ok in ${Date.now()-r}ms (${i}); bostrat-node ${g.latestNodeVersion} is available (this node: ${Ne})`,`bostrat-node self-update --to ${g.latestNodeVersion}`)):T(B("plane link",`hello_ok in ${Date.now()-r}ms (${i})`))):g.type==="error"&&T(K("plane link",`plane said: ${g.code} ${g.message||""}`,"check the token"))}catch{}}),d.on("error",f=>T(K("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function _i(){let e;try{e=JSON.parse(q.readFileSync(D.join(Pt,"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 r=e.parked[0];return K("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?X("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 Si(e){return e.BOSTRAT_STATE_REMOTE?B("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):X("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}function vi(e,t){let n=t?.viewBase??null,r=ir(),i=ar(e.BOSTRAT_PUBLIC_HOST),c=(()=>{let d=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(d)return`${d.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let p=cr(e.BOSTRAT_PLANE_URL);return p?`${p}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let d=i&&i.host!==n?`; BOSTRAT_PUBLIC_HOST=${i.host} is set but the plane's value wins`:"";return B("public host",`views https://<slug>.${n}/ (plane hello_ok)${d} \xB7 track links ${c}`)}return r?B("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${c}`):i?B("public host",`views ${i.proto}://<slug>.${i.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${c}`):K("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${c}`,"link a plane that sets PLANE_VIEW_BASE (bostrat-node init), or set BOSTRAT_PUBLIC_HOST in node.env for a plane-less node")}async function Gr(e,t={}){let n=[];n.push(await li()),n.push(di(t.envFile||$e())),n.push(await fi(e)),n.push(...await hi()),n.push(await Yr("git",{required:!0})),n.push(await pi()),n.push(...await mi()),n.push(await wi()),n.push(yi(e)),n.push(gi(e)),n.push(ui(e));let r=await Ti(e,t);return n.push(r),n.push(vi(e,r)),n.push(_i()),n.push(Si(e)),n}function qr(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let c of e)t(`${n[c.level]} ${c.name}: ${c.detail}`),c.fix&&c.level!=="pass"&&t(` fix: ${c.fix}`);let r=e.filter(c=>c.level==="fail").length,i=e.filter(c=>c.level==="warn").length;return t(r?`
|
|
194
|
-
FAIL \u2014 ${
|
|
195
|
-
OK \u2014 0 blocking, ${i} warnings`),
|
|
193
|
+
`}async function un(e=yt){try{return JSON.parse(await ce.readFile(e,"utf8"))}catch{return null}}async function Yr({to:e,from:t=wt,kind:n=Re(),reason:o="manual",force:i=!1,statusFile:c=yt,spawnImpl:d=Ys,now:h=Date.now,npmPrefix:g=void 0,log:N=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!gt.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Oe(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let f=await un(c);if(dn(f))return{ok:!1,reason:`an update to ${f.to} is already in flight`,status:f};let T=f?.to===e?Number(f.attempts)||1:0;if(!i&&f&&f.to===e&&(f.status==="failed"||f.status==="rolled-back")&&!(f.status==="failed"&&f.retryable===!0&&T<ln))return{ok:!1,reason:`update to ${e} already ${f.status} (${f.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:f};let _=f?.to===e&&(f.status==="failed"||f.status==="rolled-back")?T+1:1;await ce.mkdir(C.dirname(c),{recursive:!0});let x=g!==void 0?g:n==="npm-global"?Ft(await ei())||C.resolve(C.dirname(process.execPath),".."):null,E=Vr({kind:n,to:e,from:t,statusFile:c,npmPrefix:x,startedAt:h(),attempts:_}),k=C.join(C.dirname(c),`update-${e}.sh`),L=C.join(C.dirname(c),"last.log");await ce.writeFile(k,E,{mode:448}),await ce.writeFile(c,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:o,attempts:_,startedAt:h(),updatedAt:h()}));let S=Wr.existsSync("/run/systemd/system")&&await ti("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",k]]:["setsid",["-f","bash","-c",`exec bash ${U(k)} >> ${U(L)} 2>&1`]];try{d(S[0],S[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(A){return await ce.writeFile(c,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:o,startedAt:h(),updatedAt:h(),error:`could not spawn updater: ${A?.message||A}`})),{ok:!1,reason:`could not spawn updater: ${A?.message||A}`}}return N.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${o}) started \u2014 status ${c}`),{ok:!0,to:e,from:t,kind:n,scriptFile:k,statusFile:c}}async function ei(){try{return await ce.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function ti(e){for(let t of String(process.env.PATH||"").split(C.delimiter))try{return await ce.access(C.join(t,e),Wr.constants.X_OK),!0}catch{}return!1}async function ri({statusFile:e=yt,current:t=wt,now:n=Date.now,staleMs:o=ni}={}){let i=await un(e);if(!i)return null;let c=d=>ce.writeFile(e,JSON.stringify(d)).catch(()=>{});if(dn(i)){if(t&&i.to===t){let d={...i,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await c(d),d}if(n()-Number(i.updatedAt||i.startedAt||0)>o){let d={...i,status:"failed",error:`updater went silent while ${i.status} (no status change for ${Math.round(o/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await c(d),d}return null}if(["failed","rolled-back","done"].includes(i.status)&&!i.announced){let d={...i,announced:!0};return await c(d),d}return null}function oi({isBusy:e,start:t=Yr,onStuck:n=null,onStarted:o=null,tickMs:i=Js,stuckMs:c=Xs,now:d=Date.now,setIntervalImpl:h=setInterval,clearIntervalImpl:g=clearInterval,log:N=console}={}){let f=null,T=()=>{f?.timer&&g(f.timer),f=null},_=async()=>{if(!f)return;let x=!0;try{x=await e()!==!1}catch{x=!0}if(x){if(!f.stuckFired&&d()-f.since>=c){f.stuckFired=!0;try{await n?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let E=f;T();let k=await t({to:E.to,from:E.from,kind:E.kind,reason:"auto"});N.log?.(`[self-update] stasis reached \u2192 ${k.ok?"started":`not started: ${k.reason}`}`);try{await o?.({...E,result:k})}catch{}};return{arm({to:x,from:E=wt,kind:k=Re()}){return f?.to===x?!1:(T(),f={to:x,from:E,kind:k,since:d(),stuckFired:!1,timer:h(_,i)},f.timer.unref?.(),!0)},tick:_,cancel:T,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var wt,Gs,cn,yt,Xs,Js,sn,an,ln,gt,U,Qs,dn,ni,Gr=v(()=>{on();Kr();wt=(()=>{try{return qs(import.meta.url)("../package.json").version||null}catch{return null}})(),Gs=process.env.BOSTRAT_STATE_DIR||C.join(process.env.HOME||Vs.tmpdir(),".bostrat"),cn=C.join(Gs,"self-update"),yt=C.join(cn,"status.json"),Xs=1440*6e4,Js=6e4,sn=60,an=15,ln=3,gt=new Set(["npm-global","git-checkout"]);U=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Qs=new Set(["updating","restarting","rolling-back"]),dn=e=>!!(e&&Qs.has(e.status));ni=45*6e4});Bt();jt();import G from"node:fs";import D from"node:path";import Ie from"node:os";import{createRequire as fn}from"node:module";import{execFile as si,spawn as ii}from"node:child_process";import{promisify as ai}from"node:util";import ci from"node:readline/promises";import{randomUUID as li}from"node:crypto";import{fileURLToPath as ui}from"node:url";import os from"node:fs";import lr from"node:path";import ss from"node:os";var is=()=>process.env.BOSTRAT_STATE_DIR||lr.join(process.env.HOME||ss.tmpdir(),".bostrat"),as=()=>lr.join(is(),"plane-link","public-host.json");var Ve=null;function cs(){if(Ve)return Ve;try{let e=JSON.parse(os.readFileSync(as(),"utf8"));Ve={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{Ve={viewBase:null}}return Ve}function ls(e,t){let n=String(e||"").trim();if(!n)return null;let o=/^(https?):\/\/(.+?)\/?$/i.exec(n),i=o?o[1].toLowerCase():t,c=(o?o[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return c?{proto:i,host:c}:null}function ur(){return cs().viewBase}function dr(e=process.env.BOSTRAT_PUBLIC_HOST){return ls(e,"https")}function fr(e=process.env.BOSTRAT_PLANE_URL){let t=String(e||"").trim();if(!t)return null;let n=/^(wss?|https?):\/\/([^/?#]+)/i.exec(t);return n?`${/^(wss|https)$/i.test(n[1])?"https":"http"}://${n[2]}`:null}var Xr=(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 i=0;i<Math.max(n.length,o.length);i++){let c=(n[i]||0)-(o[i]||0);if(c)return c<0}return!1},le=ai(si),pn=D.dirname(ui(import.meta.url)),_e=D.resolve(pn,".."),di=D.join(pn,"index.js"),fi="wss://plane.bostrat.ai/v1/node",Ne=fn(import.meta.url)("../package.json").version,B=(e,t)=>({name:e,level:"pass",detail:t}),X=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),K=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function pi(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?B("node runtime",`${process.version} at ${process.execPath}`):K("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function hi(e){return e.BOSTRAT_OWNER?X("owner stamp",`BOSTRAT_OWNER=${String(e.BOSTRAT_OWNER).slice(0,12)}\u2026 is set \u2014 ignored by this release; on older releases it got every event refused (forgedUserId)`,"remove BOSTRAT_OWNER from node.env and any shell rc, then restart the node"):B("owner stamp","none (the plane infers the owner from the token)")}function mi(e){let t;try{t=G.statSync(e)}catch{return X("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?X("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 wi(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await le(t,["-V"],{timeout:5e3});return B("tmux",`${t} (${n.trim()})`)}catch{return K("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Jr(e,{required:t=!1}={}){if(await qt(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",i=ft[e]?`${ft[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?K(e,o,i):X(e,o,i)}async function yi(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await le(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 X("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",ft.gh)}}async function gi(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Jr(t)));return e.some(t=>t.level==="pass")||e.push(K("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 Ti(){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 qt(t,{failOpen:!1})?B(t,"resolves on the service PATH"):X(t,`not on the service PATH \u2014 ${n}`,o)))}async function _i(){try{let t=fn(D.join(_e,"src","node-cli.js"))("node-pty");return await new Promise((n,o)=>{let i=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),c=setTimeout(()=>o(new Error("spawn timeout")),5e3);i.onExit(()=>{clearTimeout(c),n()})}),B("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${_e} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=fn(D.join(_e,"package.json")),o=D.join(D.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");G.existsSync(o)&&!(G.statSync(o).mode&73)&&(t=`chmod +x ${o} # node-pty ships it non-executable`)}catch{}return K("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function Si(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(G.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"?K:X)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function vi(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?K("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 bi(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return X("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(),i=Fe(e.BOSTRAT_PLANE_URL);return await new Promise(c=>{let d=new n(i,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),h=null,g=f=>{clearTimeout(N);try{d.close()}catch{}c(h?{...f,viewBase:h}:f)},N=setTimeout(()=>g(K("plane link",`no hello_ok within 5s from ${i}`,"check the URL, the token, and the plane's IP gate")),5e3);d.on("open",()=>d.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${li().slice(0,8)}`,ephemeral:!0}))),d.on("message",f=>{try{let T=JSON.parse(f);T.type==="hello_ok"?(typeof T.viewBase=="string"&&T.viewBase&&(h=T.viewBase),T.minNodeVersion&&Xr(Ne,T.minNodeVersion)?g(K("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${T.minNodeVersion} \u2014 this node is ${Ne}; the real link is refused until it updates`,`bostrat-node self-update --to ${T.latestNodeVersion||T.minNodeVersion}`)):T.latestNodeVersion&&Xr(Ne,T.latestNodeVersion)?g(X("plane link",`hello_ok in ${Date.now()-o}ms (${i}); bostrat-node ${T.latestNodeVersion} is available (this node: ${Ne})`,`bostrat-node self-update --to ${T.latestNodeVersion}`)):g(B("plane link",`hello_ok in ${Date.now()-o}ms (${i})`))):T.type==="error"&&g(K("plane link",`plane said: ${T.code} ${T.message||""}`,"check the token"))}catch{}}),d.on("error",f=>g(K("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function Ai(){let e;try{e=JSON.parse(G.readFileSync(D.join(Ct,"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 K("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?X("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 ki(e){return e.BOSTRAT_STATE_REMOTE?B("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):X("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}function $i(e,t){let n=t?.viewBase??null,o=ur(),i=dr(e.BOSTRAT_PUBLIC_HOST),c=(()=>{let d=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(d)return`${d.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let h=fr(e.BOSTRAT_PLANE_URL);return h?`${h}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let d=i&&i.host!==n?`; BOSTRAT_PUBLIC_HOST=${i.host} is set but the plane's value wins`:"";return B("public host",`views https://<slug>.${n}/ (plane hello_ok)${d} \xB7 track links ${c}`)}return o?B("public host",`views https://<slug>.${o}/ (persisted from the last hello) \xB7 track links ${c}`):i?B("public host",`views ${i.proto}://<slug>.${i.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${c}`):K("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${c}`,"link a plane that sets PLANE_VIEW_BASE (bostrat-node init), or set BOSTRAT_PUBLIC_HOST in node.env for a plane-less node")}async function Zr(e,t={}){let n=[];n.push(await pi()),n.push(mi(t.envFile||$e())),n.push(await wi(e)),n.push(...await gi()),n.push(await Jr("git",{required:!0})),n.push(await yi()),n.push(...await Ti()),n.push(await _i()),n.push(Si(e)),n.push(vi(e)),n.push(hi(e));let o=await bi(e,t);return n.push(o),n.push($i(e,o)),n.push(Ai()),n.push(ki(e)),n}function Qr(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let c of e)t(`${n[c.level]} ${c.name}: ${c.detail}`),c.fix&&c.level!=="pass"&&t(` fix: ${c.fix}`);let o=e.filter(c=>c.level==="fail").length,i=e.filter(c=>c.level==="warn").length;return t(o?`
|
|
194
|
+
FAIL \u2014 ${o} blocking, ${i} warnings`:`
|
|
195
|
+
OK \u2014 0 blocking, ${i} warnings`),o===0}async function xi({envFile:e=$e(),input:t=process.stdin,output:n=process.stdout}={}){let o=nt(e),i=ci.createInterface({input:t,output:n}),c=async(A,b)=>(await i.question(b?`${A} [${b}]: `:`${A}: `)).trim()||b||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
|
|
196
196
|
you type those inside each box, later (box-auth-policy).
|
|
197
197
|
|
|
198
|
-
`);let d=await c("Plane URL",
|
|
199
|
-
`);let
|
|
200
|
-
`);let
|
|
198
|
+
`);let d=await c("Plane URL",o.BOSTRAT_PLANE_URL||fi),h=Fe(d);h!==d.trim()&&n.write(` \u2192 using ${h}
|
|
199
|
+
`);let g=await c("Node token (minted plane-side; stored 0600)",o.BOSTRAT_PLANE_TOKEN);o.BOSTRAT_OWNER&&n.write(` \u2192 dropping BOSTRAT_OWNER from node.env \u2014 the plane infers the owner from the token; a stale id here got every event refused.
|
|
200
|
+
`);let N=await c("Node name",o.BOSTRAT_NODE_NAME||Ie.hostname().split(".")[0]),f=await c("Repos root",o.BOSTRAT_REPOS_ROOT||D.join(Ie.homedir(),"Documents")),T=await c("State remote (per-node private repo; empty = local-only)",o.BOSTRAT_STATE_REMOTE||""),_=(await c("Route NEW claude boxes through a BYO API key? (y/N)",o.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");_&&n.write(`
|
|
201
201
|
BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
|
|
202
202
|
injected per box, stored 0600 in node.env, never sent to the plane.
|
|
203
203
|
\u2022 create/copy a key: https://console.anthropic.com/settings/keys
|
|
204
204
|
\u2022 set a monthly spend limit while you're there \u2014 the key is live.
|
|
205
205
|
|
|
206
|
-
`);let x=_?await c("ANTHROPIC_API_KEY (starts sk-ant-)",
|
|
207
|
-
`),i.close();let
|
|
206
|
+
`);let x=_?await c("ANTHROPIC_API_KEY (starts sk-ant-)",o.ANTHROPIC_API_KEY):"";_&&x&&!/^sk-ant-/.test(x)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
|
|
207
|
+
`),i.close();let E={...jn(),...o,BOSTRAT_PLANE_URL:h,BOSTRAT_PLANE_TOKEN:g,BOSTRAT_NODE_NAME:N,BOSTRAT_NODE_ID:o.BOSTRAT_NODE_ID||N,BOSTRAT_REPOS_ROOT:f,BOSTRAT_STATE_REMOTE:T,BOSTRAT_CLAUDE_USE_API_KEY:_?"1":"0",ANTHROPIC_API_KEY:_?x:o.ANTHROPIC_API_KEY};delete E.BOSTRAT_OWNER,Ln(e,E,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
|
|
208
208
|
0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
|
|
209
209
|
Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
|
|
210
210
|
wrote ${e}
|
|
211
211
|
|
|
212
|
-
`);let
|
|
213
|
-
`));return
|
|
212
|
+
`);let k={...E,...process.env},L=await Zr(k,{envFile:e}),S=Qr(L,A=>n.write(A+`
|
|
213
|
+
`));return S&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:S,results:L}}function Ei({envFile:e=$e()}={}){Bn(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=ii(t,[di],{cwd:_e,stdio:"inherit",env:process.env});for(let o of["SIGINT","SIGTERM"])process.on(o,()=>n.kill(o));return n.on("exit",(o,i)=>process.exit(i?1:o??1)),n}function Oi({agentDir:e=_e,nodeBin:t=process.execPath,envFile:n=$e(),home:o=Ie.homedir()}={}){let i=D.dirname(t),c=D.join(D.basename(pn),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
|
|
214
214
|
# ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
|
|
215
215
|
[Unit]
|
|
216
216
|
Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
|
|
@@ -224,13 +224,13 @@ ExecStart=${t} --disable-warning=ExperimentalWarning ${c}
|
|
|
224
224
|
EnvironmentFile=${n}
|
|
225
225
|
# systemd's user PATH omits ~/.local/bin (cursor-agent, bostrat-view) and the
|
|
226
226
|
# nvm bin dir \u2014 both are load-bearing for box spawning.
|
|
227
|
-
Environment=PATH=${
|
|
227
|
+
Environment=PATH=${o}/.local/bin:${i}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
|
228
228
|
Restart=on-failure
|
|
229
229
|
RestartSec=2
|
|
230
230
|
|
|
231
231
|
[Install]
|
|
232
232
|
WantedBy=default.target
|
|
233
|
-
`}function
|
|
233
|
+
`}function Ri({agentDir:e=_e,nodeBin:t=process.execPath,home:n=Ie.homedir()}={}){let o=D.dirname(t),i=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
|
|
234
234
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
235
235
|
<plist version="1.0">
|
|
236
236
|
<dict>
|
|
@@ -244,7 +244,7 @@ WantedBy=default.target
|
|
|
244
244
|
<key>WorkingDirectory</key><string>${e}</string>
|
|
245
245
|
<key>EnvironmentVariables</key>
|
|
246
246
|
<dict>
|
|
247
|
-
<key>PATH</key><string>${n}/.local/bin:${
|
|
247
|
+
<key>PATH</key><string>${n}/.local/bin:${o}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
|
|
248
248
|
</dict>
|
|
249
249
|
<key>RunAtLoad</key><true/>
|
|
250
250
|
<key>KeepAlive</key><true/>
|
|
@@ -252,7 +252,7 @@ WantedBy=default.target
|
|
|
252
252
|
<key>StandardErrorPath</key><string>${i}/node.err.log</string>
|
|
253
253
|
</dict>
|
|
254
254
|
</plist>
|
|
255
|
-
`}function
|
|
255
|
+
`}function Ni(e=process.platform,t=Ie.homedir()){return e==="darwin"?{kind:"launchd",file:D.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:D.join(t,".config","systemd","user","bostrat-node.service")}}async function Ii({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:o=console.log,agentDir:i=_e}={}){let{kind:c,file:d}=Ni(n);if(!e&&i.split(D.sep).includes("_npx"))return o("\u2717 running from the npx cache \u2014 a service must point at a durable install."),o(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){c==="systemd"?(await le("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),G.rmSync(d,{force:!0}),await le("systemctl",["--user","daemon-reload"])):(await le("launchctl",["unload","-w",d]).catch(()=>{}),G.rmSync(d,{force:!0})),o(`removed ${d}`);return}G.mkdirSync(D.dirname(d),{recursive:!0}),c==="systemd"?(G.writeFileSync(d,Oi()),await le("systemctl",["--user","daemon-reload"]),t&&await le("systemctl",["--user","enable","--now","bostrat-node.service"]),o(`installed ${d}${t?" (enabled + started)":""}`),o("logs: journalctl --user -u bostrat-node.service -f")):(G.mkdirSync(D.join(Ie.homedir(),"Library","Logs","bostrat"),{recursive:!0}),G.writeFileSync(d,Ri()),t&&await le("launchctl",["load","-w",d]),o(`installed ${d}${t?" (loaded)":""}`),o("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function iu(e=process.argv.slice(2)){let t=e[0],n=$e();if(t==="--version"||t==="-v"||t==="version")return console.log(Ne),0;if(t==="init")return(await xi({envFile:n})).ok?0:1;if(t==="doctor"){let o={...nt(n),...process.env};return Qr(await Zr(o,{envFile:n}))?0:1}if(t==="run"||t==="start")return Ei({envFile:n}),null;if(t==="install-service")return await Ii({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:o}=await Promise.resolve().then(()=>(Tr(),gr));return await o({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:o,readStatus:i,updatePolicy:c}=await Promise.resolve().then(()=>(Gr(),qr)),{detectInstallKind:d}=await Promise.resolve().then(()=>(on(),Hr)),h=d(),g=e.indexOf("--to"),N=g>=0?String(e[g+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Ne,installKind:h,policy:c({kind:h}),status:await i()},null,2)),0;if(!N)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:N,kind:h,reason:"cli",force:!0});return f.ok?(console.log(`\u2713 self-update ${f.from??"?"} \u2192 ${f.to} started (${f.kind}) \u2014 status: ${f.statusFile}; the 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)
|
|
256
256
|
|
|
257
257
|
usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
|
|
258
258
|
|
|
@@ -261,4 +261,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
|
|
|
261
261
|
run start the node in the foreground (sources node.env)
|
|
262
262
|
install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
|
|
263
263
|
fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
|
|
264
|
-
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{
|
|
264
|
+
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{xi as init,Ii as installService,Ri as launchdPlist,iu as main,Qr as printDoctor,Ei as runAgent,Zr as runDoctor,Ni as servicePaths,Oi as systemdUnit};
|