bostrat-node 1.7.4 → 1.7.5
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 +107 -41
- package/dist/index.js +219 -155
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var mn=Object.defineProperty;var _=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Ae=(e,t)=>{for(var n in t)mn(e,n,{get:t[n],enumerable:!0})};import pe from"node:fs";import ke from"node:path";import hn from"node:os";function ce(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,r;try{r=new URL(n)}catch{return t}let o={"https:":"wss:","http:":"ws:","wss:":"wss:","ws:":"ws:"}[r.protocol];return o?(r.protocol=o,(r.pathname===""||r.pathname==="/")&&(r.pathname="/v1/node"),r.toString()):t}function fe(e){let t;try{t=pe.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
|
|
2
|
+
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!s)continue;let i=s[2].trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),n[s[1]]=i}return n}function Qe(e,t=process.env){let n=fe(e);for(let[r,o]of Object.entries(n))r in t||(t[r]=o);return n}function et(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
|
|
3
|
+
`).map(o=>o?`# ${o}`:"#"));for(let[o,s]of Object.entries(t))s==null||s===""||r.push(`${o}=${s}`);pe.mkdirSync(ke.dirname(e),{recursive:!0}),pe.writeFileSync(e,r.join(`
|
|
4
|
+
`)+`
|
|
5
|
+
`,{mode:384}),pe.chmodSync(e,384)}function tt(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 Oe,ne,ve=_(()=>{Oe=process.env.BOSTRAT_STATE_DIR||ke.join(process.env.HOME||hn.tmpdir(),".bostrat"),ne=()=>ke.join(Oe,"node.env")});var Ee=_(()=>{});var nt=_(()=>{Ee()});var rt=_(()=>{});var ot=_(()=>{});import $e from"node:path";import{execFile as yn}from"node:child_process";import{promisify as gn}from"node:util";var Eo,st,Tn,$o,Ro,at=_(()=>{Eo=gn(yn),st=process.env.HOME||"/home/globo",Tn=$e.join(process.env.BOSTRAT_STATE_DIR||$e.join(st,".bostrat"),"repos"),$o=[...(process.env.BOSTRAT_REPOS_ROOT||$e.join(st,"Documents")).split(","),Tn].map(e=>e.trim()).filter(Boolean),Ro=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});import it from"node:path";import bn from"node:os";import{execFile as _n}from"node:child_process";import{promisify as Sn}from"node:util";var Fo,xn,Bo,Lo,Uo,Re=_(()=>{at();Fo=Sn(_n),xn=process.env.BOSTRAT_STATE_DIR||it.join(process.env.HOME||bn.tmpdir(),".bostrat"),Bo=it.join(xn,"repos"),Lo=5*6e4,Uo=10*6e4});var ct=_(()=>{Re()});import kn from"node:os";import On from"node:path";import{execFile as vn}from"node:child_process";import{promisify as En}from"node:util";var Zo,Qo,es,lt=_(()=>{ct();Zo=En(vn),Qo=process.env.BOSTRAT_STATE_DIR||On.join(process.env.HOME||kn.tmpdir(),".bostrat"),es=25*1024});var ut=_(()=>{});var as,dt=_(()=>{Re();ut();as=60*6e4});var pt=_(()=>{dt()});import $n from"node:os";import ft from"node:path";var Rn,gs,Ts,Ie=_(()=>{Ne();Rn=process.env.BOSTRAT_DEBUG_DIR||ft.join($n.homedir(),".bostrat","debug"),gs=ft.join(Rn,"handoff.jsonl"),Ts=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as Nn}from"node:child_process";import{promisify as Pn}from"node:util";import Mn from"node:fs";function wt(e){return`/tmp/tmux-${e}/default`}function Dn({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=wt(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function Me(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Fn(e,{loginShell:t});return r===yt?!0:r===Pe?!1:n}async function Fn(e,{loginShell:t=!1,timeoutMs:n=Cn}={}){if(!e)return Pe;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await jn(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),yt}catch(s){return s?.killed||s?.signal?ht:s?.code===1||s?.code===127?Pe:ht}}var jn,Bs,mt,Ls,Us,Hs,yt,Pe,ht,Cn,me,Ks,Ws,zs,Ys,qs,Ne=_(()=>{nt();rt();ot();lt();pt();Ie();Ee();jn=Pn(Nn),Bs=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";mt=typeof process.getuid=="function"?process.getuid():0,Ls=Dn({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return Mn.existsSync(wt(mt))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:mt}),Us=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Hs=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions";yt="present",Pe="absent",ht="unknown",Cn=5e3;me={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"},Ks=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Ws=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,zs=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Ys=Number(process.env.BOSTRAT_BOX_COLS)||120,qs=Number(process.env.BOSTRAT_BOX_ROWS)||40});var xt={};Ae(xt,{NODE_IMAGE:()=>De,commandPlan:()=>bt,flyToml:()=>Tt,flyWizard:()=>Yn,parseFlyFlags:()=>_t,stageConfig:()=>St});import je from"node:fs";import X from"node:path";import Bn from"node:os";import Ln from"node:readline/promises";import{execFile as Un}from"node:child_process";import{createRequire as Hn}from"node:module";import{randomUUID as Kn}from"node:crypto";function Tt({app:e,region:t,nodeName:n=e,planeUrl:r=gt,image:o=De}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
|
|
2
6
|
# Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
|
|
3
7
|
# No [http_service] and none should be added: the node dials OUT to the plane;
|
|
4
8
|
# nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
|
|
@@ -13,7 +17,7 @@ swap_size_mb = 1024
|
|
|
13
17
|
# The published node image (claude + cursor-agent + codex baked in, logged
|
|
14
18
|
# out), pinned to the bostrat-node version that wrote this file. Update with:
|
|
15
19
|
# npm i -g bostrat-node && bostrat-node fly (re-run is safe), or bump the tag.
|
|
16
|
-
image = "${
|
|
20
|
+
image = "${o}"
|
|
17
21
|
|
|
18
22
|
[env]
|
|
19
23
|
PORT = "3362"
|
|
@@ -38,64 +42,125 @@ swap_size_mb = 1024
|
|
|
38
42
|
# Scale later with: fly scale memory 4096 -a ${e}
|
|
39
43
|
size = "shared-cpu-2x"
|
|
40
44
|
memory = "2gb"
|
|
41
|
-
`}function
|
|
45
|
+
`}function bt({app:e,org:t,region:n,sizeGb:r,token:o,owner:s,dir:i}){let d=[`BOSTRAT_PLANE_TOKEN=${o}`,...s?[`BOSTRAT_OWNER=${s}`]:[]];return[{argv:["apps","create",e,"-o",t],display:`fly apps create ${e} -o ${t}`,tolerate:/already|taken|exists/i},{argv:["volumes","create","node_data","-a",e,"-r",n,"-s",String(r),"-y"],display:`fly volumes create node_data -a ${e} -r ${n} -s ${r} -y`,tolerate:/already|exists/i},{argv:["secrets","import","-a",e,"--stage"],display:`fly secrets import -a ${e} --stage # BOSTRAT_PLANE_TOKEN=<redacted>${s?" BOSTRAT_OWNER=\u2026":""} via stdin`,stdin:d.join(`
|
|
42
46
|
`)+`
|
|
43
|
-
`},{argv:["deploy",i,"-c",
|
|
44
|
-
`),i[0];if(i.length>1)return await e(`Fly org (${i.join(" / ")})`,i[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function
|
|
47
|
+
`},{argv:["deploy",i,"-c",X.join(i,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${i} -c ${X.join(i,"fly.toml")} -a ${e} --ha=false`}]}function _t(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--owner":"owner","--image":"image"};for(let r=0;r<e.length;r++){let o=e[r];if(o==="--yes"||o==="-y")t.yes=!0;else if(n[o])t[n[o]]=e[++r]??"";else if(o.startsWith("--")&&o.includes("=")){let[s,...i]=o.split("=");n[s]?t[n[s]]=i.join("="):s==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function St({app:e,dest:t,toml:n}){let r=t||X.join(Bn.homedir(),".bostrat","fly",e);je.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])je.rmSync(X.join(r,o),{recursive:!0,force:!0});return je.writeFileSync(X.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function zn({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await he(["orgs","list","--json"],{exec:n}),s=JSON.parse(o),i=Array.isArray(s)?s.map(d=>d.Slug||d.slug).filter(Boolean):Object.keys(s);if(i.length===1)return t.write(`Org: ${i[0]} (your only org)
|
|
48
|
+
`),i[0];if(i.length>1)return await e(`Fly org (${i.join(" / ")})`,i[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function Yn({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:o}={}){let s=_t(e),i=Ln.createInterface({input:t,output:n}),d=async(w,A)=>(await i.question(A?`${w} [${A}]: `:`${w}: `)).trim()||A||"",b=w=>(i.close(),w);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
|
|
45
49
|
bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
|
|
46
50
|
|
|
47
|
-
`);try{await
|
|
48
|
-
`)}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"),
|
|
49
|
-
`),
|
|
50
|
-
wrote ${
|
|
51
|
+
`);try{await he(["version"],{exec:r})}catch{return n.write("\u2717 `fly` (flyctl) is not installed or not on PATH.\n install: https://fly.io/docs/flyctl/install/ \u2014 then re-run `bostrat-node fly`\n"),b(1)}try{let{stdout:w}=await he(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${w.trim()}
|
|
52
|
+
`)}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"),b(1)}let f=await zn({ask:d,output:n,exec:r,flag:s.org}),u=s.app||await d("App name",`bostrat-node-${Kn().slice(0,4)}`),T=s.region||await d("Region (see `fly platform regions`)","iad"),m=s.sizeGb||Number(await d("Volume size GB (logins + repos live here)","10"))||10,x=s.name||u,S=s.planeUrl||gt,h=s.token||await d("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!h)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.
|
|
53
|
+
`),b(1);let O=s.owner??await d("Owner userId (shown next to the token; empty = infer from token)",""),N=s.image||De,{dir:v}=St({app:u,dest:o,toml:Tt({app:u,region:T,nodeName:x,planeUrl:S,image:N})});n.write(`
|
|
54
|
+
wrote ${X.join(v,"fly.toml")} \u2014 deploys the prebuilt node image ${N}
|
|
51
55
|
(claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
|
|
52
56
|
|
|
53
57
|
Plan (your flyctl, your org, your bill):
|
|
54
|
-
`);let
|
|
55
|
-
`);if(!
|
|
58
|
+
`);let M=bt({app:u,org:f,region:T,sizeGb:m,token:h,owner:O,dir:v});for(let w of M)n.write(` $ ${w.display}
|
|
59
|
+
`);if(!s.yes&&(await d(`
|
|
56
60
|
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.
|
|
57
|
-
`),
|
|
58
|
-
\u2192 ${
|
|
59
|
-
`);try{let{stdout:
|
|
60
|
-
`).map(
|
|
61
|
+
`),b(1);for(let w of M){n.write(`
|
|
62
|
+
\u2192 ${w.display}
|
|
63
|
+
`);try{let{stdout:A,stderr:j}=await he(w.argv,{stdin:w.stdin,exec:r}),Z=`${A||""}${j||""}`.trim();Z&&n.write(Z.split(`
|
|
64
|
+
`).map(Q=>` ${Q}`).join(`
|
|
61
65
|
`)+`
|
|
62
|
-
`)}catch(
|
|
63
|
-
`);continue}return n.write(`\u2717 failed: ${
|
|
66
|
+
`)}catch(A){let j=`${A?.stdout||""}${A?.stderr||""}${A?.message||""}`;if(w.tolerate&&w.tolerate.test(j)){n.write(` (already exists \u2014 continuing)
|
|
67
|
+
`);continue}return n.write(`\u2717 failed: ${j.trim().split(`
|
|
64
68
|
`).slice(-4).join(`
|
|
65
69
|
`)}
|
|
66
70
|
fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
|
|
67
|
-
`),
|
|
71
|
+
`),b(1)}}return n.write(`
|
|
68
72
|
\u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
|
|
69
73
|
chat: the node step advances on its own within a minute.
|
|
70
74
|
logs: fly logs -a ${u}
|
|
71
|
-
redeploy: fly deploy ${
|
|
75
|
+
redeploy: fly deploy ${v} -c ${X.join(v,"fly.toml")} -a ${u} --ha=false
|
|
72
76
|
Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
|
|
73
77
|
boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
|
|
74
|
-
`),
|
|
75
|
-
`)){let s=r.trim();if(!s||s.startsWith("#"))continue;let o=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(s);if(!o)continue;let i=o[2].trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),n[o[1]]=i}return n}function X(e,t=process.env){let n=P(e);for(let[r,s]of Object.entries(n))r in t||(t[r]=s);return n}function V(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
78
|
+
`),b(0)}var gt,Wn,De,he,At=_(()=>{gt="wss://plane.bostrat.ai/v1/node",Wn=Hn(import.meta.url)("../package.json").version,De=`ghcr.io/globocodes/bostrat-node:${Wn}`;he=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let s=Un("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(i,d,b)=>i?o(Object.assign(i,{stdout:d,stderr:b})):r({stdout:d,stderr:b}));t!=null&&s.stdin?.end(t)})});import qn from"node:fs/promises";import le from"node:path";import Gn from"node:os";import{EventEmitter as Vn}from"node:events";function Xn(e){return e?.cwd?le.join(e.cwd,".bostrat","events"):le.join(kt,"events")}async function Ce(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?le.join(kt,"events"):Xn(e));let o;try{o=await qn.readFile(Jn(n,r),"utf8")}catch{return[]}let s=[];for(let i of o.split(`
|
|
79
|
+
`))if(i.trim())try{s.push(JSON.parse(i))}catch{}return s}var ue,kt,Jn,Fe=_(()=>{ue=new Vn;ue.setMaxListeners(0);kt=process.env.BOSTRAT_STATE_DIR||le.join(process.env.HOME||Gn.tmpdir(),".bostrat");Jn=(e,t)=>le.join(e,`${t}.ndjson`)});function Ot(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!Qn.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 er(e){let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||r.length===0)throw new Error(`pricing.js: ${n} must be a non-empty array of rate windows`);t[n]=r.map(o=>({...o,fromMs:Ot(o.from,"from",n),toMs:Ot(o.to,"to",n)}))}return t}var Zn,Qn,ia,vt=_(()=>{Zn={"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,note:"GA rates; verified 2026-08-06 via the claude-api skill."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,note:"verified 2026-08-06 via the claude-api skill."}],"claude-sonnet-5":[{from:null,to:"2026-08-31",input:2,output:10,cacheWrite:4,cacheRead:.2,note:"GA introductory pricing ($2/$10); verified 2026-08-06 via the claude-api skill."},{from:"2026-09-01",to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,note:"standard rates resume after the intro window; verified 2026-08-06."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,note:"verified 2026-08-06 via the claude-api skill."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,note:"verified 2026-08-06 via the claude-api skill."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,note:"verified 2026-08-06 via the claude-api skill; 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,note:"verified 2026-07-03; no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:null,input:5,output:30,cacheWrite:6.25,cacheRead:.5,note:"verified 2026-07-18; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-terra":[{from:null,to:null,input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,note:"verified 2026-07-18; cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:null,input:1,output:6,cacheWrite:1.25,cacheRead:.1,note:"verified 2026-07-18; cacheWrite = 1.25\xD7 input (30-min TTL)."}]},Qn=/^\d{4}-\d{2}-\d{2}$/;ia=er(Zn)});var Et=_(()=>{vt()});import $t from"node:fs/promises";import Nt from"node:path";import tr from"node:os";function Mt(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function jt(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Dt(e){let t=new Date(Mt(e));return t.setDate(t.getDate()+7),t.getTime()}function Ct(e){let t=new Date(jt(e));return t.setMonth(t.getMonth()+1),t.getTime()}function ar(e=Date.now()){for(let[t,n]of Object.entries(or)){let r=n.startOf(e);if(r!==we[t]){we[t]=r;for(let o of Be.values())o[t]=0;for(let o of Rt)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&Rt.delete(o)}}}function ir(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let o={};for(let s of["weeklyUsd","monthlyUsd"]){let i=r?.[s];if(i==null||i==="")continue;let d=Number(i);if(!Number.isFinite(d)||d<=0)throw new Error(`${n}.${s} must be a positive number or null`);o[s]=d}Object.keys(o).length&&(t[n]=o)}return t}async function Ft(e,{source:t="local",updatedAt:n=Date.now()}={}){re={caps:ir(e),updatedAt:n,source:t};try{await $t.mkdir(Pt,{recursive:!0}),await $t.writeFile(nr(),JSON.stringify(re,null,2))}catch{}return cr()}function cr(e=Date.now()){ar(e);let t=new Set([...Be.keys(),...Object.keys(re?.caps||{})]),n={};for(let r of t){let o=Be.get(r);n[r]={weeklyUsd:It(o?.weekly||0),monthlyUsd:It(o?.monthly||0)}}return{caps:re?.caps||{},configured:!!re,seeded:sr,updatedAt:re?.updatedAt??null,spent:n,windows:{weekly:{start:we.weekly,resetsAt:Dt(e)},monthly:{start:we.monthly,resetsAt:Ct(e)}},warnPct:rr}}var Pt,nr,rr,or,re,sr,we,Be,Rt,It,Bt=_(()=>{Fe();Et();Pt=process.env.BOSTRAT_STATE_DIR||Nt.join(process.env.HOME||tr.tmpdir(),".bostrat"),nr=()=>Nt.join(Pt,"usage-caps.json"),rr=.8;or={weekly:{startOf:Mt,nextStart:Dt,capKey:"weeklyUsd"},monthly:{startOf:jt,nextStart:Ct,capKey:"monthlyUsd"}},re=null,sr=!1,we={weekly:0,monthly:0},Be=new Map,Rt=new Set;It=e=>Math.round(e*1e4)/1e4});var Kt={};Ae(Kt,{detectInstallKind:()=>se,detectProviderAuth:()=>Ht,startPlaneLink:()=>_r,updateCommandFor:()=>He,versionLt:()=>oe});import Ut from"node:fs";import Le from"node:fs/promises";import lr from"node:http";import z from"node:path";import ge from"node:os";import{createRequire as ur}from"node:module";import Ue from"ws";function se({env:e=process.env,pkgDir:t=z.resolve(z.dirname(new URL(import.meta.url).pathname),".."),exists:n=Ut.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(z.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 o=0;o<Math.max(n.length,r.length);o++){let s=(n[o]||0)-(r[o]||0);if(s)return s<0}return!1}function He(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 Ht({home:e=process.env.HOME||ge.homedir(),env:t=process.env}={}){let n=r=>{try{return Ut.statSync(r),!0}catch{return!1}};return{claude:n(z.join(e,".claude",".credentials.json")),codex:n(z.join(t.CODEX_HOME||z.join(e,".codex"),"auth.json"))}}function _r({url:e,token:t,nodeId:n=ge.hostname(),name:r=ge.hostname(),listTracks:o,detectAgents:s=null,onTracksTransferred:i=null,sampleMetrics:d=null,metricsMs:b=Tr,onUpdateAvailable:f=null,installKind:u=se(),selfUrl:T=`http://127.0.0.1:${process.env.PORT||3362}`,log:m=console}){if(!e||!t)throw new Error("plane-link: url and token are required");if(typeof o!="function")throw new Error("plane-link: listTracks is required");e=ce(e);let x=T.replace(/^http/,"ws"),S=new Set,h=new Map,O=new Map,N=z.join(dr,"plane-link","cursor.json"),v={},M={},w=new Map,A=null,j=!1,Z=!1,Q=Lt,de=null,ee=null,te=null,H=null,K=null,Se=!1,Ve=0;async function nn(){try{v=JSON.parse(await Le.readFile(N,"utf8"))}catch{v={}}}function rn(){Se=!0,!te&&(te=setTimeout(async()=>{if(te=null,!!Se){Se=!1;try{await Le.mkdir(z.dirname(N),{recursive:!0}),await Le.writeFile(N,JSON.stringify(v))}catch(p){m.error("[plane-link] cursor flush failed:",p?.message||p)}}},wr),te.unref?.())}function E(p){return!A||A.readyState!==Ue.OPEN?!1:(A.send(JSON.stringify(p)),!0)}function xe(p){let l=Date.now();for(let{trackId:a,event:c}of p){let y=w.get(c.id);w.set(c.id,{trackId:a,seq:c.seq,event:c,sentAt:l,tries:(y?.tries??0)+1})}return E({v:$,ch:"events",type:"append",events:p})}function on(p){let l=null;for(let a of w.values())a.trackId===p&&(l==null||a.seq<l)&&(l=a.seq);return l}function sn(p){let l=M[p];if(l==null)return;let a=on(p),c=a==null?l:Math.min(l,a-1);c>(v[p]??0)&&(v[p]=c,rn())}function an(){if(!j)return;let p=Date.now(),l=[...w.values()].filter(a=>a.event&&p-a.sentAt>=gr);if(l.length){l.sort((a,c)=>a.trackId===c.trackId?a.seq-c.seq:a.trackId<c.trackId?-1:1),m.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);for(let a=0;a<l.length;a+=ye){let c=l.slice(a,a+ye).map(y=>({trackId:y.trackId,event:y.event}));if(!xe(c))return}}}async function Xe(){if(!d)return;let p;try{p=await d()}catch(l){m.error("[plane-link] metrics sample failed:",l?.message||l);return}p&&E({v:$,ch:"ctl",type:"metrics",metrics:p})}function cn(){d&&(K&&clearInterval(K),Xe(),K=setInterval(Xe,b),K.unref?.())}async function ln(){let p;try{p=await o()}catch(l){m.error("[plane-link] backfill listTracks failed:",l?.message||l);return}E({v:$,ch:"ctl",type:"tracks",ids:p.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of p){if(!j)return;let a;try{a=await Ce(l)}catch{continue}let c=v[l.id]??0,y=a.filter(g=>g.seq>c&&typeof g.id=="string");for(let g=0;g<y.length;g+=ye){let I=y.slice(g,g+ye).map(D=>({trackId:l.id,event:D}));if(!xe(I))return}}}function Je(p){!j||!p?.trackId||typeof p.id!="string"||xe([{trackId:p.trackId,event:p}])}let ie=new Map;async function un(p){let{reqId:l,method:a,path:c,headers:y={},body:g}=p,I=Object.fromEntries(Object.entries(y).filter(([,L])=>L!=null)),D=new AbortController;ie.set(l,D);try{if(p.host){await dn(p,I,D);return}let L=await fetch(T+c,{method:a,headers:I,body:g?Buffer.from(g,"base64"):void 0,signal:D.signal}),q=Object.fromEntries(L.headers);for(let C of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete q[C];if(q["content-type"]||(q["content-type"]="application/octet-stream"),E({v:$,ch:"control",type:"http_head",reqId:l,status:L.status,headers:q}),L.body){for await(let C of L.body)if(!E({v:$,ch:"control",type:"http_data",reqId:l,data:Buffer.from(C).toString("base64")}))break}E({v:$,ch:"control",type:"http_end",reqId:l,error:null})}finally{ie.delete(l)}}function dn(p,l,a){let{reqId:c,method:y,path:g,body:I}=p,D=new URL(T);return new Promise(L=>{let q=lr.request({host:D.hostname,port:D.port,method:y,path:g,headers:{...l,host:p.host},signal:a.signal},C=>{let{connection:lo,"keep-alive":uo,"transfer-encoding":po,upgrade:fo,...pn}=C.headers;E({v:$,ch:"control",type:"http_head",reqId:c,status:C.statusCode||502,headers:pn}),C.on("data",fn=>{E({v:$,ch:"control",type:"http_data",reqId:c,data:Buffer.from(fn).toString("base64")})||C.destroy()}),C.on("end",()=>{E({v:$,ch:"control",type:"http_end",reqId:c,error:null}),L()}),C.on("error",()=>{E({v:$,ch:"control",type:"http_end",reqId:c,error:"view upstream error"}),L()})});q.on("error",C=>{E({v:$,ch:"control",type:"http_end",reqId:c,error:C?.message||"view request failed"}),L()}),I&&q.write(Buffer.from(I,"base64")),q.end()})}function Ze(){if(Z)return;A=new Ue(e,{headers:{authorization:`Bearer ${t}`}}),A.on("open",async()=>{let l=null;try{l=await s?.()||null}catch{l=null}E({v:$,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:W,installKind:u,providers:Ht(),...l?{agents:l}:{}})}),A.on("message",l=>{let a;try{a=JSON.parse(l)}catch{return}if(a.ch==="ctl"&&a.type==="hello_ok"){j=!0,Q=Lt,de=null,m.log(`[plane-link] connected to plane as ${n}`),a.minNodeVersion&&W&&oe(W,a.minNodeVersion)&&m.error(`[plane-link] this node is bostrat-node ${W}; the plane asks for \u2265${a.minNodeVersion} \u2014 update with: ${He(u)}`);let c=typeof a.latestNodeVersion=="string"?a.latestNodeVersion:null;if(c&&W&&oe(W,c)&&!S.has(c)){S.add(c),m.log(`[plane-link] bostrat-node ${c} is available (this node runs ${W}) \u2014 ${He(u)}`);try{f?.({current:W,latest:c,min:a.minNodeVersion??null,installKind:u,required:!!(a.minNodeVersion&&oe(W,a.minNodeVersion))})}catch(y){m.error(`[plane-link] update notice failed: ${y?.message||y}`)}}H&&clearInterval(H),H=setInterval(()=>{E({v:$,ch:"ctl",type:"ping"}),an()},yr),H.unref?.(),cn(),ln().catch(y=>m.error("[plane-link] backfill failed:",y?.message||y));return}if(a.ch==="ctl"&&a.type==="usage_caps"){Ft(a.caps??{},{source:"plane",updatedAt:a.updatedAt??Date.now()}).then(c=>m.log(`[plane-link] spend caps ${Object.keys(c.caps).length?`updated (${Object.keys(c.caps).join(", ")})`:"cleared"} from plane`)).catch(c=>m.error("[plane-link] spend-caps push rejected:",c?.message||c));return}if(a.ch==="ctl"&&a.type==="transferred"&&Array.isArray(a.tracks)){Promise.resolve().then(()=>i?.(a.tracks)).catch(c=>m.error("[plane-link] transfer notice failed:",c?.message||c));return}if(a.ch==="events"&&a.type==="ack"&&Array.isArray(a.ids)){let c=new Set;for(let y of a.ids){let g=w.get(y);g&&(w.delete(y),(M[g.trackId]??0)<g.seq&&(M[g.trackId]=g.seq),c.add(g.trackId))}for(let y of c)sn(y);return}if(a.ch==="control"&&a.type==="http_open"){un(a).catch(c=>E({v:$,ch:"control",type:"http_end",reqId:a.reqId,error:c?.message||"tunnel error"}));return}if(a.ch==="control"&&a.type==="http_cancel"){ie.get(a.reqId)?.abort();return}if(a.ch==="attach"&&a.type==="open"){let c=new Ue(x+a.path,Array.isArray(a.protocols)?a.protocols:[],a.host?{headers:{host:a.host}}:void 0);h.set(a.streamId,c),O.set(a.streamId,[]),c.on("open",()=>{let g=O.get(a.streamId)||[];O.delete(a.streamId);for(let{buf:I,bin:D}of g)c.send(I,{binary:D})}),c.on("message",(g,I)=>{let D=I?g:Buffer.from(String(g));E({v:$,ch:"attach",type:"data",streamId:a.streamId,data:D.toString("base64"),...I?{bin:!0}:{}})});let y=()=>{O.delete(a.streamId),h.delete(a.streamId)&&E({v:$,ch:"attach",type:"close",streamId:a.streamId})};c.on("close",y),c.on("error",y);return}if(a.ch==="attach"&&a.type==="data"){let c=h.get(a.streamId);if(!c)return;let y=Buffer.from(a.data,"base64"),g=a.bin===!0,I=O.get(a.streamId);I?I.push({buf:y,bin:g}):c.send(y,{binary:g});return}if(a.ch==="attach"&&a.type==="close"){let c=h.get(a.streamId);h.delete(a.streamId),O.delete(a.streamId),c?.close();return}});let p=()=>{j&&m.log("[plane-link] disconnected from plane"),j=!1,H&&(clearInterval(H),H=null),K&&(clearInterval(K),K=null),w.clear(),M={};for(let c of h.values())c.close();h.clear(),O.clear();for(let c of ie.values())c.abort();if(ie.clear(),Z||ee)return;de==null&&(de=Date.now());let l=Date.now()-de<fr,a=l?mr+Math.random()*hr:Q;ee=setTimeout(()=>{ee=null,Ze()},a),ee.unref?.(),l||(Q=Math.min(Q*2,pr))};A.on("close",p),A.on("error",l=>{let a=/Unexpected server response: (\d+)/.exec(l?.message||"")?.[1];(a==="401"||a==="403")&&Date.now()-Ve>=br&&(Ve=Date.now(),m.error(`[plane-link] plane refused this node's credentials (HTTP ${a}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`)),p()})}return ue.on("event",Je),nn().then(Ze),{stop:()=>{Z=!0,ue.off("event",Je),ee&&clearTimeout(ee),te&&clearTimeout(te),H&&clearInterval(H),K&&clearInterval(K),E({v:$,ch:"ctl",type:"bye",reason:"shutdown"}),A?.close()},status:()=>({connected:j,nodeId:n,cursor:{...v},inflight:w.size})}}var W,dr,$,Lt,pr,fr,mr,hr,ye,wr,yr,gr,Tr,br,Ke=_(()=>{Fe();Bt();ve();W=(()=>{try{return ur(import.meta.url)("../package.json").version||null}catch{return null}})(),dr=process.env.BOSTRAT_STATE_DIR||z.join(process.env.HOME||ge.tmpdir(),".bostrat");$=1,Lt=1e3,pr=3e4,fr=6e4,mr=1500,hr=500,ye=100,wr=2e3,yr=25e3,gr=6e4,Tr=6e4,br=6e4});import{execFile as Sr}from"node:child_process";import{promisify as xr}from"node:util";function Wt(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Ma,ja,Da,zt=_(()=>{Ie();Ma=xr(Sr),ja=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Da=Promise.resolve()});var Xt={};Ae(Xt,{ACTIONABLE_KINDS:()=>_e,SELF_UPDATE_DIR:()=>We,createAutoUpdater:()=>Dr,inFlight:()=>Ye,readStatus:()=>ze,selfUpdatePlan:()=>Gt,settleSelfUpdate:()=>jr,startSelfUpdate:()=>Vt,underService:()=>qt,updatePolicy:()=>Rr});import Yt from"node:fs";import G from"node:fs/promises";import Ar from"node:os";import R from"node:path";import{spawn as kr}from"node:child_process";import{createRequire as Or}from"node:module";function Rr({kind:e=se(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:_e.has(e)?e==="git-checkout"||qt(t)?"auto":"prompt":"off"}function qt(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Gt({kind:e,to:t,from:n=Te,statusFile:r=be,logFile:o=R.join(We,"last.log"),port:s=Number(process.env.PORT)||3362,npmPrefix:i=null,serviceName:d=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:b=typeof process.getuid=="function"?process.getuid():0,liveDir:f=process.env.BOSTRAT_LIVE_CHECKOUT||R.resolve(R.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:u=Date.now()}={}){if(!_e.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 T=(O,N="")=>`write_status ${F(O)} ${N}`,m=process.platform==="darwin"?`launchctl kickstart -k gui/${b}/${d}`:`systemctl --user restart ${F(d)}`,x=`
|
|
80
|
+
health() {
|
|
81
|
+
for i in $(seq 1 45); do
|
|
82
|
+
sleep 1
|
|
83
|
+
if curl -sf -o /dev/null -I "http://127.0.0.1:${s}/"; then return 0; fi
|
|
84
|
+
done
|
|
85
|
+
return 1
|
|
86
|
+
}`,S=`#!/usr/bin/env bash
|
|
87
|
+
# bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
|
|
88
|
+
# ${n??"?"} \u2192 ${t} (${e}). Status: ${r}
|
|
89
|
+
set -u
|
|
90
|
+
FROM=${F(n??"")}
|
|
91
|
+
TO=${F(t)}
|
|
92
|
+
STATUS_FILE=${F(r)}
|
|
93
|
+
STARTED_AT=${Number(u)}
|
|
94
|
+
write_status() { # <status> [error]
|
|
95
|
+
local err="\${2:-}"
|
|
96
|
+
err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
|
|
97
|
+
printf '{"status":"%s","from":"%s","to":"%s","kind":"%s","startedAt":%s,"updatedAt":%s%s}\\n' \\
|
|
98
|
+
"$1" "$FROM" "$TO" ${F(e)} "$STARTED_AT" "$(date +%s000)" \\
|
|
99
|
+
"\${err:+,\\"error\\":\\"$err\\"}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
|
|
100
|
+
}
|
|
101
|
+
${x}
|
|
102
|
+
`;if(e==="npm-global"){let O=i?R.join(i,"bin","npm"):"npm",N=v=>`${F(O)} install -g "bostrat-node@${v}" --no-audit --no-fund`;return S+`
|
|
103
|
+
${T("updating",'"" ')}
|
|
104
|
+
if ! ${N("$TO")}; then
|
|
105
|
+
${T("failed",'"npm install failed"')}
|
|
106
|
+
exit 1
|
|
107
|
+
fi
|
|
108
|
+
${T("restarting")}
|
|
109
|
+
if ! ${m}; then
|
|
110
|
+
${T("failed",'"service restart failed"')}
|
|
111
|
+
exit 1
|
|
112
|
+
fi
|
|
113
|
+
if health; then
|
|
114
|
+
# the restarted agent settles "done" once it hellos on the new version
|
|
115
|
+
exit 0
|
|
116
|
+
fi
|
|
117
|
+
# \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
|
|
118
|
+
${T("rolling-back",'"agent did not answer on :'+s+' after the update"')}
|
|
119
|
+
if [ -n "$FROM" ] && ${N("$FROM")} && ${m} && health; then
|
|
120
|
+
${T("rolled-back",'"agent did not answer on :'+s+' after the update; rolled back"')}
|
|
121
|
+
exit 1
|
|
122
|
+
fi
|
|
123
|
+
${T("failed",'"agent did not answer after the update AND the rollback"')}
|
|
124
|
+
exit 1
|
|
125
|
+
`}let h=O=>`( cd ${F(f)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${O}" )`;return S+`
|
|
126
|
+
LIVE=${F(f)}
|
|
127
|
+
TMP_SCRIPT="$(mktemp)"
|
|
128
|
+
trap 'rm -f "$TMP_SCRIPT"' EXIT
|
|
129
|
+
# "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
|
|
130
|
+
# restart \u2192 health in one call): the agent it restarts settles "done" on boot,
|
|
131
|
+
# and nothing here may write after that boot or the settle would repeat.
|
|
132
|
+
${T("restarting")}
|
|
133
|
+
if ${h("$TO")}; then
|
|
134
|
+
exit 0
|
|
135
|
+
fi
|
|
136
|
+
${T("rolling-back",'"deploy-pi.sh v$TO failed"')}
|
|
137
|
+
if [ -n "$FROM" ] && ${h("$FROM")}; then
|
|
138
|
+
${T("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
|
|
139
|
+
exit 1
|
|
140
|
+
fi
|
|
141
|
+
${T("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
|
|
142
|
+
exit 1
|
|
143
|
+
`}async function ze(e=be){try{return JSON.parse(await G.readFile(e,"utf8"))}catch{return null}}async function Vt({to:e,from:t=Te,kind:n=se(),reason:r="manual",statusFile:o=be,spawnImpl:s=kr,now:i=Date.now,npmPrefix:d=void 0,log:b=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!_e.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 ze(o);if(Ye(f))return{ok:!1,reason:`an update to ${f.to} is already in flight`,status:f};if(f&&f.to===e&&(f.status==="failed"||f.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${f.status} (${f.error||"no detail"}) \u2014 retried when a newer release exists`,status:f};await G.mkdir(R.dirname(o),{recursive:!0});let u=d!==void 0?d:n==="npm-global"?Wt(await Nr())||R.resolve(R.dirname(process.execPath),".."):null,T=Gt({kind:n,to:e,from:t,statusFile:o,npmPrefix:u,startedAt:i()}),m=R.join(R.dirname(o),`update-${e}.sh`),x=R.join(R.dirname(o),"last.log");await G.writeFile(m,T,{mode:448}),await G.writeFile(o,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,startedAt:i(),updatedAt:i()}));let S=Yt.existsSync("/run/systemd/system")&&await Pr("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",m]]:["setsid",["-f","bash","-c",`exec bash ${F(m)} >> ${F(x)} 2>&1`]];try{s(S[0],S[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(h){return await G.writeFile(o,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,startedAt:i(),updatedAt:i(),error:`could not spawn updater: ${h?.message||h}`})),{ok:!1,reason:`could not spawn updater: ${h?.message||h}`}}return b.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${o}`),{ok:!0,to:e,from:t,kind:n,scriptFile:m,statusFile:o}}async function Nr(){try{return await G.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Pr(e){for(let t of String(process.env.PATH||"").split(R.delimiter))try{return await G.access(R.join(t,e),Yt.constants.X_OK),!0}catch{}return!1}async function jr({statusFile:e=be,current:t=Te,now:n=Date.now,staleMs:r=Mr}={}){let o=await ze(e);if(!o)return null;let s=i=>G.writeFile(e,JSON.stringify(i)).catch(()=>{});if(Ye(o)){if(t&&o.to===t){let i={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await s(i),i}if(n()-Number(o.updatedAt||o.startedAt||0)>r){let i={...o,status:"failed",error:`updater went silent while ${o.status} (no status change for ${Math.round(r/6e4)} min)`,updatedAt:n(),finishedAt:n(),announced:!0};return await s(i),i}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let i={...o,announced:!0};return await s(i),i}return null}function Dr({isBusy:e,start:t=Vt,onStuck:n=null,onStarted:r=null,tickMs:o=$r,stuckMs:s=Er,now:i=Date.now,setIntervalImpl:d=setInterval,clearIntervalImpl:b=clearInterval,log:f=console}={}){let u=null,T=()=>{u?.timer&&b(u.timer),u=null},m=async()=>{if(!u)return;let x=!0;try{x=await e()!==!1}catch{x=!0}if(x){if(!u.stuckFired&&i()-u.since>=s){u.stuckFired=!0;try{await n?.({to:u.to,from:u.from,since:u.since})}catch{}}return}let S=u;T();let h=await t({to:S.to,from:S.from,kind:S.kind,reason:"auto"});f.log?.(`[self-update] stasis reached \u2192 ${h.ok?"started":`not started: ${h.reason}`}`);try{await r?.({...S,result:h})}catch{}};return{arm({to:x,from:S=Te,kind:h=se()}){return u?.to===x?!1:(T(),u={to:x,from:S,kind:h,since:i(),stuckFired:!1,timer:d(m,o)},u.timer.unref?.(),!0)},tick:m,cancel:T,get armed(){return u?{to:u.to,from:u.from,kind:u.kind,since:u.since}:null}}}var Te,vr,We,be,Er,$r,_e,F,Ir,Ye,Mr,Jt=_(()=>{Ke();zt();Te=(()=>{try{return Or(import.meta.url)("../package.json").version||null}catch{return null}})(),vr=process.env.BOSTRAT_STATE_DIR||R.join(process.env.HOME||Ar.tmpdir(),".bostrat"),We=R.join(vr,"self-update"),be=R.join(We,"status.json"),Er=1440*6e4,$r=6e4,_e=new Set(["npm-global","git-checkout"]);F=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Ir=new Set(["updating","restarting","rolling-back"]),Ye=e=>!!(e&&Ir.has(e.status));Mr=45*6e4});ve();Ne();import B from"node:fs";import k from"node:path";import ae from"node:os";import{createRequire as qe}from"node:module";import{execFile as Cr,spawn as Fr}from"node:child_process";import{promisify as Br}from"node:util";import Lr from"node:readline/promises";import{randomUUID as Ur}from"node:crypto";import{fileURLToPath as Hr}from"node:url";var V=Br(Cr),Ge=k.dirname(Hr(import.meta.url)),J=k.resolve(Ge,".."),Kr=k.join(Ge,"index.js"),Wr="wss://plane.bostrat.ai/v1/node",Zt=qe(import.meta.url)("../package.json").version,P=(e,t)=>({name:e,level:"pass",detail:t}),Y=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),U=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function zr(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?P("node runtime",`${process.version} at ${process.execPath}`):U("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Yr(e){let t;try{t=B.statSync(e)}catch{return Y("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?Y("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):P("node.env",`${e} (0600)`)}async function qr(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await V(t,["-V"],{timeout:5e3});return P("tmux",`${t} (${n.trim()})`)}catch{return U("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Qt(e,{required:t=!1}={}){if(await Me(e,{loginShell:!0,failOpen:!1}))return P(e,"resolves on the login-shell PATH");let r="not on the login-shell PATH \u2014 boxes for this agent (and handoffs to it) will be refused",o=me[e]?`${me[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?U(e,r,o):Y(e,r,o)}async function Gr(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await V(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return P("gh (GitHub CLI)",n)}catch{return Y("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",me.gh)}}async function Vr(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Qt(t)));return e.some(t=>t.level==="pass")||e.push(U("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 Xr(){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 Me(t,{failOpen:!1})?P(t,"resolves on the service PATH"):Y(t,`not on the service PATH \u2014 ${n}`,r)))}async function Jr(){try{let t=qe(k.join(J,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let o=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),s=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(s),n()})}),P("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${J} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=qe(k.join(J,"package.json")),r=k.join(k.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");B.existsSync(r)&&!(B.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return U("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function Zr(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";return B.existsSync(t)?P("chromium (mocks)",t):Y("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable`,"install Chromium/Chrome and set BOSTRAT_CHROMIUM_BIN")}function Qr(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?U("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"):P("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function eo(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return Y("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),o=ce(e.BOSTRAT_PLANE_URL);return await new Promise(s=>{let i=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),d=f=>{clearTimeout(b);try{i.close()}catch{}s(f)},b=setTimeout(()=>d(U("plane link",`no hello_ok within 5s from ${o}`,"check the URL, the token, and the plane's IP gate")),5e3);i.on("open",()=>i.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${Ur().slice(0,8)}`,ephemeral:!0}))),i.on("message",f=>{try{let u=JSON.parse(f);u.type==="hello_ok"?d(P("plane link",`hello_ok in ${Date.now()-r}ms (${o})`)):u.type==="error"&&d(U("plane link",`plane said: ${u.code} ${u.message||""}`,"check the token"))}catch{}}),i.on("error",f=>d(U("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function to(){let e;try{e=JSON.parse(B.readFileSync(k.join(Oe,"content-outbox.json"),"utf8"))}catch{return P("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 U("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?Y("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"):P("content outbox",t?`${t} op(s) in flight`:"drained")}function no(e){return e.BOSTRAT_STATE_REMOTE?P("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):Y("state remote","unset \u2014 state syncs to a local repo only, no off-box durability","create a per-node private repo and set BOSTRAT_STATE_REMOTE")}async function en(e,t={}){let n=[];return n.push(await zr()),n.push(Yr(t.envFile||ne())),n.push(await qr(e)),n.push(...await Vr()),n.push(await Qt("git",{required:!0})),n.push(await Gr()),n.push(...await Xr()),n.push(await Jr()),n.push(Zr(e)),n.push(Qr(e)),n.push(await eo(e,t)),n.push(to()),n.push(no(e)),n}function tn(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let s of e)t(`${n[s.level]} ${s.name}: ${s.detail}`),s.fix&&s.level!=="pass"&&t(` fix: ${s.fix}`);let r=e.filter(s=>s.level==="fail").length,o=e.filter(s=>s.level==="warn").length;return t(r?`
|
|
144
|
+
FAIL \u2014 ${r} blocking, ${o} warnings`:`
|
|
145
|
+
OK \u2014 0 blocking, ${o} warnings`),r===0}async function ro({envFile:e=ne(),input:t=process.stdin,output:n=process.stdout}={}){let r=fe(e),o=Lr.createInterface({input:t,output:n}),s=async(M,w)=>(await o.question(w?`${M} [${w}]: `:`${M}: `)).trim()||w||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
|
|
81
146
|
you type those inside each box, later (box-auth-policy).
|
|
82
147
|
|
|
83
|
-
`);let i=await
|
|
84
|
-
`);let
|
|
85
|
-
`);let u=await
|
|
148
|
+
`);let i=await s("Plane URL",r.BOSTRAT_PLANE_URL||Wr),d=ce(i);d!==i.trim()&&n.write(` \u2192 using ${d}
|
|
149
|
+
`);let b=await s("Node token (minted plane-side; stored 0600)",r.BOSTRAT_PLANE_TOKEN),f=await s("Owner userId (just press Enter \u2014 the plane infers it from your token)",r.BOSTRAT_OWNER||"");f&&!/^user_[A-Za-z0-9]+$/.test(f)&&n.write(` ! that doesn't look like a Clerk userId (user_\u2026) \u2014 leave it empty next time and the plane infers the owner from the token; saved as typed.
|
|
150
|
+
`);let u=await s("Node name",r.BOSTRAT_NODE_NAME||ae.hostname().split(".")[0]),T=await s("Repos root",r.BOSTRAT_REPOS_ROOT||k.join(ae.homedir(),"Documents")),m=await s("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),x=(await s("Route NEW claude boxes through a BYO API key? (y/N)",r.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");x&&n.write(`
|
|
86
151
|
BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
|
|
87
152
|
injected per box, stored 0600 in node.env, never sent to the plane.
|
|
88
153
|
\u2022 create/copy a key: https://console.anthropic.com/settings/keys
|
|
89
154
|
\u2022 set a monthly spend limit while you're there \u2014 the key is live.
|
|
90
155
|
|
|
91
|
-
`);let
|
|
92
|
-
`),
|
|
156
|
+
`);let S=x?await s("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";x&&S&&!/^sk-ant-/.test(S)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
|
|
157
|
+
`),o.close();let h={...tt(),...r,BOSTRAT_PLANE_URL:d,BOSTRAT_PLANE_TOKEN:b,BOSTRAT_OWNER:f,BOSTRAT_NODE_NAME:u,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||u,BOSTRAT_REPOS_ROOT:T,BOSTRAT_STATE_REMOTE:m,BOSTRAT_CLAUDE_USE_API_KEY:x?"1":"0",ANTHROPIC_API_KEY:x?S:r.ANTHROPIC_API_KEY};et(e,h,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
|
|
93
158
|
0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
|
|
94
159
|
Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
|
|
95
160
|
wrote ${e}
|
|
96
161
|
|
|
97
|
-
`);let
|
|
98
|
-
`));return
|
|
162
|
+
`);let O={...h,...process.env},N=await en(O,{envFile:e}),v=tn(N,M=>n.write(M+`
|
|
163
|
+
`));return v&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:v,results:N}}function oo({envFile:e=ne()}={}){Qe(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=Fr(t,[Kr],{cwd:J,stdio:"inherit",env:process.env});for(let r of["SIGINT","SIGTERM"])process.on(r,()=>n.kill(r));return n.on("exit",(r,o)=>process.exit(o?1:r??1)),n}function so({agentDir:e=J,nodeBin:t=process.execPath,envFile:n=ne(),home:r=ae.homedir()}={}){let o=k.dirname(t),s=k.join(k.basename(Ge),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
|
|
99
164
|
# ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
|
|
100
165
|
[Unit]
|
|
101
166
|
Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
|
|
@@ -105,17 +170,17 @@ After=default.target
|
|
|
105
170
|
Type=simple
|
|
106
171
|
WorkingDirectory=${e}
|
|
107
172
|
# Pinned runtime: node-pty is compiled against exactly this node (SEGV trap).
|
|
108
|
-
ExecStart=${t} --disable-warning=ExperimentalWarning ${
|
|
173
|
+
ExecStart=${t} --disable-warning=ExperimentalWarning ${s}
|
|
109
174
|
EnvironmentFile=${n}
|
|
110
175
|
# systemd's user PATH omits ~/.local/bin (cursor-agent, bostrat-view) and the
|
|
111
176
|
# nvm bin dir \u2014 both are load-bearing for box spawning.
|
|
112
|
-
Environment=PATH=${r}/.local/bin:${
|
|
177
|
+
Environment=PATH=${r}/.local/bin:${o}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
|
113
178
|
Restart=on-failure
|
|
114
179
|
RestartSec=2
|
|
115
180
|
|
|
116
181
|
[Install]
|
|
117
182
|
WantedBy=default.target
|
|
118
|
-
`}function
|
|
183
|
+
`}function ao({agentDir:e=J,nodeBin:t=process.execPath,home:n=ae.homedir()}={}){let r=k.dirname(t),o=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
|
|
119
184
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
120
185
|
<plist version="1.0">
|
|
121
186
|
<dict>
|
|
@@ -133,16 +198,17 @@ WantedBy=default.target
|
|
|
133
198
|
</dict>
|
|
134
199
|
<key>RunAtLoad</key><true/>
|
|
135
200
|
<key>KeepAlive</key><true/>
|
|
136
|
-
<key>StandardOutPath</key><string>${
|
|
137
|
-
<key>StandardErrorPath</key><string>${
|
|
201
|
+
<key>StandardOutPath</key><string>${o}/node.out.log</string>
|
|
202
|
+
<key>StandardErrorPath</key><string>${o}/node.err.log</string>
|
|
138
203
|
</dict>
|
|
139
204
|
</plist>
|
|
140
|
-
`}function
|
|
205
|
+
`}function io(e=process.platform,t=ae.homedir()){return e==="darwin"?{kind:"launchd",file:k.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:k.join(t,".config","systemd","user","bostrat-node.service")}}async function co({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=J}={}){let{kind:s,file:i}=io(n);if(!e&&o.split(k.sep).includes("_npx"))return r("\u2717 running from the npx cache \u2014 a service must point at a durable install."),r(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){s==="systemd"?(await V("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),B.rmSync(i,{force:!0}),await V("systemctl",["--user","daemon-reload"])):(await V("launchctl",["unload","-w",i]).catch(()=>{}),B.rmSync(i,{force:!0})),r(`removed ${i}`);return}B.mkdirSync(k.dirname(i),{recursive:!0}),s==="systemd"?(B.writeFileSync(i,so()),await V("systemctl",["--user","daemon-reload"]),t&&await V("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${i}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(B.mkdirSync(k.join(ae.homedir(),"Library","Logs","bostrat"),{recursive:!0}),B.writeFileSync(i,ao()),t&&await V("launchctl",["load","-w",i]),r(`installed ${i}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function ri(e=process.argv.slice(2)){let t=e[0],n=ne();if(t==="--version"||t==="-v"||t==="version")return console.log(Zt),0;if(t==="init")return(await ro({envFile:n})).ok?0:1;if(t==="doctor"){let r={...fe(n),...process.env};return tn(await en(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return oo({envFile:n}),null;if(t==="install-service")return await co({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(At(),xt));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:s}=await Promise.resolve().then(()=>(Jt(),Xt)),{detectInstallKind:i}=await Promise.resolve().then(()=>(Ke(),Kt)),d=i(),b=e.indexOf("--to"),f=b>=0?String(e[b+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:Zt,installKind:d,policy:s({kind:d}),status:await o()},null,2)),0;if(!f)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 u=await r({to:f,kind:d,reason:"cli"});return u.ok?(console.log(`\u2713 self-update ${u.from??"?"} \u2192 ${u.to} started (${u.kind}) \u2014 status: ${u.statusFile}; the service restarts when the install completes`),0):(console.error(`\u2717 not started: ${u.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
|
|
141
206
|
|
|
142
|
-
usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | --version>
|
|
207
|
+
usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
|
|
143
208
|
|
|
144
209
|
init interactive setup \u2192 writes ${n}, then runs doctor
|
|
145
210
|
doctor check this machine (CLIs, tmux, node-pty, plane reachability)
|
|
146
211
|
run start the node in the foreground (sources node.env)
|
|
147
212
|
install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
|
|
148
|
-
fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
|
|
213
|
+
fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
|
|
214
|
+
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{ro as init,co as installService,ao as launchdPlist,ri as main,tn as printDoctor,oo as runAgent,en as runDoctor,io as servicePaths,so as systemdUnit};
|