bostrat-node 1.7.6 → 1.7.8
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/bin/bostrat-changelog +2 -1
- package/bin/bostrat-loop +3 -3
- package/dist/cli.js +61 -61
- package/dist/index.js +178 -174
- package/package.json +1 -1
package/bin/bostrat-changelog
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import d from"node:fs/promises";var u=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function c(n,e,t){let l=await fetch(`${u}${e}`,{method:n,headers:t?{"content-type":"application/json"}:void 0,body:t?JSON.stringify(t):void 0}),r=await l.json().catch(()=>({}));if(!l.ok)throw new Error(r.error||`HTTP ${l.status}`);return r}function a(n){console.error(`[bostrat-changelog] ${n}`),process.exit(1)}var s=process.argv.slice(2),i=s.shift();if(i==="draft"){let n=null;for(let e=0;e<s.length;e++)s[e]==="--since"&&(n=s[++e]);try{let e=n?`?since=${encodeURIComponent(n)}`:"",{since:t,prs:l,excluded:r=[]}=await c("GET",`/api/changelog/draft${e}`),g=o=>{let h=o.mergedAt?` (merged ${new Date(o.mergedAt).toISOString()})`:"";return`- ${o.repo}#${o.number} \u2014 ${o.title||"(no title recorded)"}${h}${o.url?` ${o.url}`:""}`};if(!l.length){let o=r.length?` (${r.length} merge(s) excluded by the safe-content policy)`:"";console.log(`EMPTY WINDOW \u2014 nothing publishable merged since ${new Date(t).toISOString()}${o}; publish nothing.`),process.exit(0)}console.log(`Merged since ${new Date(t).toISOString()}:`);for(let o of l)console.log(g(o));if(r.length){console.log(`
|
|
3
|
+
EXCLUDED (${r.length}, safe-content policy \u2014 do NOT summarize or look these up):`);for(let o of r)console.log(`- ${o.repo}#${o.number} [${o.excluded}]`)}}catch(e){a(e.message)}}else if(i==="publish"){let n=null,e=null;for(let t=0;t<s.length;t++)s[t]==="--day"?n=s[++t]:s[t].startsWith("--")||(e=s[t]);e||a("usage: bostrat-changelog publish <file.md> [--day YYYY-MM-DD]");try{let t=await d.readFile(e,"utf8").catch(()=>a(`cannot read ${e}`)),{entry:l}=await c("POST","/api/changelog/publish",{md:t,cwd:process.cwd(),...n?{day:n}:{}});console.log(`[bostrat-changelog] published ${l.day}: ${l.bullets.length} bullet(s)${l.title?` under "${l.title}"`:""}`),console.log("The operator sees it in Settings \u2192 Changelog \u2014 re-publishing the same day replaces this entry.")}catch(t){a(t.message)}}else if(i==="retract"){let n=null;for(let e=0;e<s.length;e++)s[e]==="--day"&&(n=s[++e]);n||a("usage: bostrat-changelog retract --day YYYY-MM-DD");try{let{entry:e}=await c("POST","/api/changelog/retract",{day:n,cwd:process.cwd()});console.log(`[bostrat-changelog] retracted ${e.day} \u2014 the day's published entry is removed (re-publish to restore).`)}catch(e){a(e.message)}}else a("usage: bostrat-changelog <draft|publish|retract> \u2026 (draft [--since 24h]; publish <file.md> [--day YYYY-MM-DD]; retract --day YYYY-MM-DD)");
|
package/bin/bostrat-loop
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var d=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;function n(o){console.error(`[bostrat-loop] ${o}`),process.exit(1)}async function h(){let o=await fetch(`${d}/api/loops`),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t.source==="unconfigured"&&n("this node isn't linked to a plane \u2014 loops live in the plane"),t.source==="unreachable"&&n(`plane unreachable (${t.error||"no detail"}) \u2014 try again shortly`),t.loops||[]}var p=o=>o?new Date(o).toISOString().slice(0,16).replace("T"," ")+"Z":"\u2014",u=o=>o.error?`FAILED (${o.error})`:o.outcome==="attention"?`ATTENTION${o.note?` (${o.note})`:""}`:o.outcome==="unreported"?"UNREPORTED (settled with no report \u2014 held for the operator)":o.outcome==="errored"?`ERRORED (the run's provider failed before the agent ran${o.note?`: ${o.note}`:""} \u2014 held for the operator)`:o.outcome==="acted"?`acted${o.note?` (${o.note})`:""}`:o.outcome==="ok"?"ok":"running/unreported",f=o=>{let t=(o.runs||[])[o.runs.length-1];return t?`last ${p(t.firedAt)} \u2014 ${u(t)}`:"never ran"},c=process.argv.slice(2),l=c.shift();if(l==="ls")try{let o=await h();o.length||console.log("no loops defined");for(let t of o){let e=t.enabled?"\u25CF":"\u25CB",
|
|
2
|
+
var d=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;function n(o){console.error(`[bostrat-loop] ${o}`),process.exit(1)}async function h(){let o=await fetch(`${d}/api/loops`),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t.source==="unconfigured"&&n("this node isn't linked to a plane \u2014 loops live in the plane"),t.source==="unreachable"&&n(`plane unreachable (${t.error||"no detail"}) \u2014 try again shortly`),t.loops||[]}var p=o=>o?new Date(o).toISOString().slice(0,16).replace("T"," ")+"Z":"\u2014",u=o=>o.error?`FAILED (${o.error})`:o.outcome==="attention"?`ATTENTION${o.note?` (${o.note})`:""}`:o.outcome==="unreported"?"UNREPORTED (settled with no report \u2014 held for the operator)":o.outcome==="errored"?`ERRORED (the run's provider failed before the agent ran${o.note?`: ${o.note}`:""} \u2014 held for the operator)`:o.outcome==="acted"?`acted${o.note?` (${o.note})`:""}`:o.outcome==="ok"?"ok":"running/unreported",f=o=>{let t=(o.runs||[])[o.runs.length-1];return t?`last ${p(t.firedAt)} \u2014 ${u(t)}`:"never ran"},c=process.argv.slice(2),l=c.shift();if(l==="ls")try{let o=await h();o.length||console.log("no loops defined");for(let t of o){let e=t.enabled?"\u25CF":"\u25CB",r=t.enabled?`next ${p(t.nextFireAt)}`:"disabled";console.log(`${e} ${t.name} [${t.schedule} UTC] ${r} ${f(t)} (loop:${t.id})`)}}catch(o){n(o.message)}else if(l==="show"){let o=c.find(t=>!t.startsWith("--"));o||n("usage: bostrat-loop show <name|id>");try{let e=(await h()).find(s=>s.id===o||s.name===o);e||n(`no loop matching "${o}" \u2014 use \`bostrat-loop ls\``);let r=typeof e.assignment=="object"&&e.assignment?e.assignment.provider||JSON.stringify(e.assignment):e.assignment||"\u2014";console.log(`${e.name} (loop:${e.id})`),console.log(` schedule: ${e.schedule} UTC ${e.enabled?`(next ${p(e.nextFireAt)})`:"(disabled)"}`),console.log(` provider: ${r}${e.repo?` repo: ${e.repo}`:""}`),console.log(` node: ${e.nodeId?`${e.nodeName&&e.nodeName!==e.nodeId?`${e.nodeName} (${e.nodeId})`:e.nodeId}`:"\u2014 (unbound: runs on the plane's default node)"}`),e.trackId&&console.log(` track: ${e.trackId} (the loop's persistent "\u21BB" Track)`),e.expectation&&console.log(` expected: ${e.expectation}`),console.log(` prompt:
|
|
3
3
|
${String(e.prompt||"").split(`
|
|
4
|
-
`).map(
|
|
5
|
-
`)}`);let a=(e.runs||[]).slice(-5);console.log(` recent runs:${a.length?"":" none"}`);for(let
|
|
4
|
+
`).map(s=>` ${s}`).join(`
|
|
5
|
+
`)}`);let a=(e.runs||[]).slice(-5);console.log(` recent runs:${a.length?"":" none"}`);for(let s of a)console.log(` ${p(s.firedAt)} ${u(s)}${s.trackId?` (track ${s.trackId})`:""}`);console.log("Loops are operator-managed (Loops tab) \u2014 to change one, describe the change in chat; `bostrat-loop propose` offers a NEW one."),console.log('On a loop\'s own run Track, end every run with `bostrat-loop report ok|acted|attention "<note>"`.')}catch(t){n(t.message)}}else if(l==="propose"){let o=c.find(e=>!e.startsWith("--")),t=async()=>{let e=[];for await(let r of process.stdin)e.push(r);return Buffer.concat(e).toString("utf8")};try{let e=!o||o==="-"?await t():await(await import("node:fs/promises")).readFile(o,"utf8"),r;try{r=JSON.parse(e)}catch{n("plan must be JSON (a file path, or piped on stdin) \u2014 see the `bostrat-loop` header for the shape")}let a=await fetch(`${d}/api/loops/propose`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({cwd:process.cwd(),plan:r})}),s=await a.json().catch(()=>({}));a.ok||n(s.error||`HTTP ${a.status}`);let i=s.proposal;console.log(`[bostrat-loop] proposed "${i.name}" [${i.schedule} UTC] on ${i.assignment?.provider||"claude"} \u2014 review card posted to the Track chat.`),console.log(` repo: ${i.repo} \xB7 nothing is scheduled until the operator confirms; the card shows your prompt verbatim.`),console.log(" HOLD HERE: end your turn and wait \u2014 do not start or resume other work until the operator answers the card in chat.")}catch(e){n(e.message)}}else if(l==="report"){let o=c[0],t=c[1]||null;["ok","acted","attention"].includes(o)||n('usage: bostrat-loop report <ok|acted|attention> ["<note>"]'),o==="attention"&&!t&&n('an attention report needs a note \u2014 bostrat-loop report attention "<why the operator is needed>"');try{let e=await fetch(`${d}/api/loops/report`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({outcome:o,note:t,cwd:process.cwd()})}),r=await e.json().catch(()=>({}));e.ok||n(r.error||`HTTP ${e.status}`),console.log(`reported "${o}" on loop "${r.loop?.name}"${t?` \u2014 ${t}`:""}`),console.log(o==="attention"?"This Track stays visible on the Tracks page until the operator acknowledges it.":"The settle sweep will archive this Track once the run goes idle.")}catch(e){n(e.message)}}else n("usage: bostrat-loop <ls|show|propose|report> \u2026 (propose posts a review card \u2014 it creates nothing; loops are otherwise operator-managed from the Loops tab)");
|
package/dist/cli.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let a=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!a)continue;let i=a[2].trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),n[a[1]]=i}return n}function
|
|
3
|
-
`).map(o=>o?`# ${o}`:"#"));for(let[o,a]of Object.entries(t))a==null||a===""||r.push(`${o}=${a}`);
|
|
1
|
+
var Tn=Object.defineProperty;var S=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Re=(e,t)=>{for(var n in t)Tn(e,n,{get:t[n],enumerable:!0})};import ye from"node:fs";import Ne from"node:path";import bn from"node:os";function fe(e){let t=String(e||"").trim();if(!t)return"";let n=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`wss://${t}`,r;try{r=new URL(n)}catch{return t}let 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 we(e){let t;try{t=ye.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
|
|
2
|
+
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let a=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!a)continue;let i=a[2].trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),n[a[1]]=i}return n}function rt(e,t=process.env){let n=we(e);for(let[r,o]of Object.entries(n))r in t||(t[r]=o);return n}function ot(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
|
|
3
|
+
`).map(o=>o?`# ${o}`:"#"));for(let[o,a]of Object.entries(t))a==null||a===""||r.push(`${o}=${a}`);ye.mkdirSync(Ne.dirname(e),{recursive:!0}),ye.writeFileSync(e,r.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`,{mode:384}),
|
|
5
|
+
`,{mode:384}),ye.chmodSync(e,384)}function st(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 Ie,re,Pe=S(()=>{Ie=process.env.BOSTRAT_STATE_DIR||Ne.join(process.env.HOME||bn.tmpdir(),".bostrat"),re=()=>Ne.join(Ie,"node.env")});var Me=S(()=>{});var at=S(()=>{Me()});var it=S(()=>{});var ct=S(()=>{});import je from"node:path";import{execFile as Sn}from"node:child_process";import{promisify as xn}from"node:util";var Po,lt,kn,Mo,jo,ut=S(()=>{Po=xn(Sn),lt=process.env.HOME||"/home/globo",kn=je.join(process.env.BOSTRAT_STATE_DIR||je.join(lt,".bostrat"),"repos"),Mo=[...(process.env.BOSTRAT_REPOS_ROOT||je.join(lt,"Documents")).split(","),kn].map(e=>e.trim()).filter(Boolean),jo=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});import dt from"node:path";import vn from"node:os";import{execFile as An}from"node:child_process";import{promisify as On}from"node:util";var Ko,En,Wo,zo,Yo,De=S(()=>{ut();Ko=On(An),En=process.env.BOSTRAT_STATE_DIR||dt.join(process.env.HOME||vn.tmpdir(),".bostrat"),Wo=dt.join(En,"repos"),zo=5*6e4,Yo=10*6e4});var ft=S(()=>{De()});import Rn from"node:fs/promises";import pe from"node:path";import Nn from"node:os";import{EventEmitter as In}from"node:events";function Pn(e){return e?.cwd?pe.join(e.cwd,".bostrat","events"):pe.join(pt,"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"?pe.join(pt,"events"):Pn(e));let o;try{o=await Rn.readFile(Mn(n,r),"utf8")}catch{return[]}let a=[];for(let i of o.split(`
|
|
6
|
+
`))if(i.trim())try{a.push(JSON.parse(i))}catch{}return a}var me,pt,Mn,ge=S(()=>{me=new In;me.setMaxListeners(0);pt=process.env.BOSTRAT_STATE_DIR||pe.join(process.env.HOME||Nn.tmpdir(),".bostrat");Mn=(e,t)=>pe.join(e,`${t}.ndjson`)});import Dn from"node:os";import Cn from"node:path";import{execFile as Fn}from"node:child_process";import{promisify as Bn}from"node:util";var ls,us,ds,fs,ps,ms,mt=S(()=>{ft();ge();ls=Bn(Fn),us=process.env.BOSTRAT_STATE_DIR||Cn.join(process.env.HOME||Dn.tmpdir(),".bostrat"),ds=25*1024,fs=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,ps=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,ms=Promise.resolve()});var ht=S(()=>{});var bs,yt=S(()=>{De();ht();bs=60*6e4});var wt=S(()=>{yt()});import Ln from"node:os";import gt from"node:path";var Un,Is,Ps,Fe=S(()=>{Be();Un=process.env.BOSTRAT_DEBUG_DIR||gt.join(Ln.homedir(),".bostrat","debug"),Is=gt.join(Un,"handoff.jsonl"),Ps=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as Kn}from"node:child_process";import{promisify as Wn}from"node:util";import zn from"node:fs";function _t(e){return`/tmp/tmux-${e}/default`}function qn({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=_t(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function Ue(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Gn(e,{loginShell:t});return r===St?!0:r===Le?!1:n}async function Gn(e,{loginShell:t=!1,timeoutMs:n=Vn}={}){if(!e)return Le;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await Yn(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),St}catch(a){return a?.killed||a?.signal?bt:a?.code===1||a?.code===127?Le:bt}}var Yn,Qs,Tt,ea,ta,na,St,Le,bt,Vn,Te,ra,oa,sa,aa,ia,Be=S(()=>{at();it();ct();mt();wt();Fe();Me();Yn=Wn(Kn),Qs=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";Tt=typeof process.getuid=="function"?process.getuid():0,ea=qn({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return zn.existsSync(_t(Tt))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:Tt}),ta=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",na=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions";St="present",Le="absent",bt="unknown",Vn=5e3;Te={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"},ra=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,oa=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,sa=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,aa=Number(process.env.BOSTRAT_BOX_COLS)||120,ia=Number(process.env.BOSTRAT_BOX_ROWS)||40});var Et={};Re(Et,{NODE_IMAGE:()=>Ke,commandPlan:()=>vt,flyToml:()=>kt,flyWizard:()=>rr,parseFlyFlags:()=>At,stageConfig:()=>Ot});import He from"node:fs";import Q from"node:path";import Jn from"node:os";import Xn from"node:readline/promises";import{execFile as Zn}from"node:child_process";import{createRequire as Qn}from"node:module";import{randomUUID as er}from"node:crypto";function kt({app:e,region:t,nodeName:n=e,planeUrl:r=xt,image:o=Ke}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
|
|
6
7
|
# Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
|
|
7
8
|
# No [http_service] and none should be added: the node dials OUT to the plane;
|
|
8
9
|
# nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
|
|
@@ -42,72 +43,71 @@ swap_size_mb = 1024
|
|
|
42
43
|
# Scale later with: fly scale memory 4096 -a ${e}
|
|
43
44
|
size = "shared-cpu-2x"
|
|
44
45
|
memory = "2gb"
|
|
45
|
-
`}function
|
|
46
|
+
`}function vt({app:e,org:t,region:n,sizeGb:r,token:o,owner:a,dir:i}){let d=[`BOSTRAT_PLANE_TOKEN=${o}`,...a?[`BOSTRAT_OWNER=${a}`]:[]];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>${a?" BOSTRAT_OWNER=\u2026":""} via stdin`,stdin:d.join(`
|
|
46
47
|
`)+`
|
|
47
|
-
`},{argv:["deploy",i,"-c",
|
|
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
|
|
48
|
+
`},{argv:["deploy",i,"-c",Q.join(i,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${i} -c ${Q.join(i,"fly.toml")} -a ${e} --ha=false`}]}function At(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[a,...i]=o.split("=");n[a]?t[n[a]]=i.join("="):a==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function Ot({app:e,dest:t,toml:n}){let r=t||Q.join(Jn.homedir(),".bostrat","fly",e);He.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])He.rmSync(Q.join(r,o),{recursive:!0,force:!0});return He.writeFileSync(Q.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function nr({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await be(["orgs","list","--json"],{exec:n}),a=JSON.parse(o),i=Array.isArray(a)?a.map(d=>d.Slug||d.slug).filter(Boolean):Object.keys(a);if(i.length===1)return t.write(`Org: ${i[0]} (your only org)
|
|
49
|
+
`),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 rr({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:o}={}){let a=At(e),i=Xn.createInterface({input:t,output:n}),d=async(b,A)=>(await i.question(A?`${b} [${A}]: `:`${b}: `)).trim()||A||"",g=b=>(i.close(),b);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
|
|
49
50
|
bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
|
|
50
51
|
|
|
51
|
-
`);try{await
|
|
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"),
|
|
53
|
-
`),
|
|
54
|
-
wrote ${
|
|
52
|
+
`);try{await be(["version"],{exec:r})}catch{return n.write("\u2717 `fly` (flyctl) is not installed or not on PATH.\n install: https://fly.io/docs/flyctl/install/ \u2014 then re-run `bostrat-node fly`\n"),g(1)}try{let{stdout:b}=await be(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${b.trim()}
|
|
53
|
+
`)}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 m=await nr({ask:d,output:n,exec:r,flag:a.org}),l=a.app||await d("App name",`bostrat-node-${er().slice(0,4)}`),T=a.region||await d("Region (see `fly platform regions`)","iad"),x=a.sizeGb||Number(await d("Volume size GB (logins + repos live here)","10"))||10,w=a.name||l,_=a.planeUrl||xt,p=a.token||await d("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!p)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.
|
|
54
|
+
`),g(1);let C=a.owner??await d("Owner userId (shown next to the token; empty = infer from token)",""),I=a.image||Ke,{dir:v}=Ot({app:l,dest:o,toml:kt({app:l,region:T,nodeName:w,planeUrl:_,image:I})});n.write(`
|
|
55
|
+
wrote ${Q.join(v,"fly.toml")} \u2014 deploys the prebuilt node image ${I}
|
|
55
56
|
(claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
|
|
56
57
|
|
|
57
58
|
Plan (your flyctl, your org, your bill):
|
|
58
|
-
`);let
|
|
59
|
+
`);let R=vt({app:l,org:m,region:T,sizeGb:x,token:p,owner:C,dir:v});for(let b of R)n.write(` $ ${b.display}
|
|
59
60
|
`);if(!a.yes&&(await d(`
|
|
60
61
|
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.
|
|
61
|
-
`),
|
|
62
|
-
\u2192 ${
|
|
63
|
-
`);try{let{stdout:
|
|
64
|
-
`).map(
|
|
62
|
+
`),g(1);for(let b of R){n.write(`
|
|
63
|
+
\u2192 ${b.display}
|
|
64
|
+
`);try{let{stdout:A,stderr:z}=await be(b.argv,{stdin:b.stdin,exec:r}),F=`${A||""}${z||""}`.trim();F&&n.write(F.split(`
|
|
65
|
+
`).map(B=>` ${B}`).join(`
|
|
65
66
|
`)+`
|
|
66
|
-
`)}catch(
|
|
67
|
-
`);continue}return n.write(`\u2717 failed: ${
|
|
67
|
+
`)}catch(A){let z=`${A?.stdout||""}${A?.stderr||""}${A?.message||""}`;if(b.tolerate&&b.tolerate.test(z)){n.write(` (already exists \u2014 continuing)
|
|
68
|
+
`);continue}return n.write(`\u2717 failed: ${z.trim().split(`
|
|
68
69
|
`).slice(-4).join(`
|
|
69
70
|
`)}
|
|
70
71
|
fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
|
|
71
|
-
`),
|
|
72
|
+
`),g(1)}}return n.write(`
|
|
72
73
|
\u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
|
|
73
74
|
chat: the node step advances on its own within a minute.
|
|
74
|
-
logs: fly logs -a ${
|
|
75
|
-
redeploy: fly deploy ${
|
|
75
|
+
logs: fly logs -a ${l}
|
|
76
|
+
redeploy: fly deploy ${v} -c ${Q.join(v,"fly.toml")} -a ${l} --ha=false
|
|
76
77
|
Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
|
|
77
78
|
boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
|
|
78
|
-
`),T(0)}var bt,Yn,Fe,we,At=S(()=>{bt="wss://plane.bostrat.ai/v1/node",Yn=Wn(import.meta.url)("../package.json").version,Fe=`ghcr.io/globocodes/bostrat-node:${Yn}`;we=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let a=Kn("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(i,d,T)=>i?o(Object.assign(i,{stdout:d,stderr:T})):r({stdout:d,stderr:T}));t!=null&&a.stdin?.end(t)})});import Vn from"node:fs/promises";import le from"node:path";import Jn from"node:os";import{EventEmitter as Xn}from"node:events";function Zn(e){return e?.cwd?le.join(e.cwd,".bostrat","events"):le.join(Ot,"events")}async function Be(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(Ot,"events"):Zn(e));let o;try{o=await Vn.readFile(Qn(n,r),"utf8")}catch{return[]}let a=[];for(let i of o.split(`
|
|
79
|
-
`))if(i.trim())try{a.push(JSON.parse(i))}catch{}return a}var ue,Ot,Qn,Le=S(()=>{ue=new Xn;ue.setMaxListeners(0);Ot=process.env.BOSTRAT_STATE_DIR||le.join(process.env.HOME||Jn.tmpdir(),".bostrat");Qn=(e,t)=>le.join(e,`${t}.ndjson`)});function Et(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!tr.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 nr(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:Et(o.from,"from",n),toMs:Et(o.to,"to",n)}))}return t}var er,tr,fa,$t=S(()=>{er={"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)."}]},tr=/^\d{4}-\d{2}-\d{2}$/;fa=nr(er)});var Rt=S(()=>{$t()});import Nt from"node:fs/promises";import Mt from"node:path";import rr from"node:os";function Dt(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Ct(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Ft(e){let t=new Date(Dt(e));return t.setDate(t.getDate()+7),t.getTime()}function Bt(e){let t=new Date(Ct(e));return t.setMonth(t.getMonth()+1),t.getTime()}function cr(e=Date.now()){for(let[t,n]of Object.entries(ar)){let r=n.startOf(e);if(r!==ye[t]){ye[t]=r;for(let o of Ue.values())o[t]=0;for(let o of It)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&It.delete(o)}}}function lr(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 a of["weeklyUsd","monthlyUsd"]){let i=r?.[a];if(i==null||i==="")continue;let d=Number(i);if(!Number.isFinite(d)||d<=0)throw new Error(`${n}.${a} must be a positive number or null`);o[a]=d}Object.keys(o).length&&(t[n]=o)}return t}async function Lt(e,{source:t="local",updatedAt:n=Date.now()}={}){re={caps:lr(e),updatedAt:n,source:t};try{await Nt.mkdir(jt,{recursive:!0}),await Nt.writeFile(or(),JSON.stringify(re,null,2))}catch{}return ur()}function ur(e=Date.now()){cr(e);let t=new Set([...Ue.keys(),...Object.keys(re?.caps||{})]),n={};for(let r of t){let o=Ue.get(r);n[r]={weeklyUsd:Pt(o?.weekly||0),monthlyUsd:Pt(o?.monthly||0)}}return{caps:re?.caps||{},configured:!!re,seeded:ir,updatedAt:re?.updatedAt??null,spent:n,windows:{weekly:{start:ye.weekly,resetsAt:Ft(e)},monthly:{start:ye.monthly,resetsAt:Bt(e)}},warnPct:sr}}var jt,or,sr,ar,re,ir,ye,Ue,It,Pt,Ut=S(()=>{Le();Rt();jt=process.env.BOSTRAT_STATE_DIR||Mt.join(process.env.HOME||rr.tmpdir(),".bostrat"),or=()=>Mt.join(jt,"usage-caps.json"),sr=.8;ar={weekly:{startOf:Dt,nextStart:Ft,capKey:"weeklyUsd"},monthly:{startOf:Ct,nextStart:Bt,capKey:"monthlyUsd"}},re=null,ir=!1,ye={weekly:0,monthly:0},Ue=new Map,It=new Set;Pt=e=>Math.round(e*1e4)/1e4});var zt={};Ae(zt,{detectInstallKind:()=>se,detectProviderAuth:()=>Wt,startPlaneLink:()=>xr,updateCommandFor:()=>We,versionLt:()=>oe});import Kt from"node:fs";import He from"node:fs/promises";import dr from"node:http";import q from"node:path";import Te from"node:os";import{createRequire as fr}from"node:module";import Ke from"ws";function se({env:e=process.env,pkgDir:t=q.resolve(q.dirname(new URL(import.meta.url).pathname),".."),exists:n=Kt.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(q.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 a=(n[o]||0)-(r[o]||0);if(a)return a<0}return!1}function We(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 Wt({home:e=process.env.HOME||Te.homedir(),env:t=process.env}={}){let n=r=>{try{return Kt.statSync(r),!0}catch{return!1}};return{claude:n(q.join(e,".claude",".credentials.json")),codex:n(q.join(t.CODEX_HOME||q.join(e,".codex"),"auth.json"))}}function xr({url:e,token:t,nodeId:n=Te.hostname(),name:r=Te.hostname(),listTracks:o,detectAgents:a=null,onTracksTransferred:i=null,sampleMetrics:d=null,metricsMs:T=_r,onUpdateAvailable:p=null,onUpdatePolicy:u=null,updatePolicy:w=null,installKind:x=se(),selfUrl:b=`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 _=b.replace(/^http/,"ws"),M=new Set,k=new Map,A=new Map,F=q.join(pr,"plane-link","cursor.json"),y={},N={},I=new Map,j=null,K=!1,xe=!1,de=Ht,fe=null,ee=null,te=null,W=null,z=null,ke=!1,Xe=0;async function on(){try{y=JSON.parse(await He.readFile(F,"utf8"))}catch{y={}}}function sn(){ke=!0,!te&&(te=setTimeout(async()=>{if(te=null,!!ke){ke=!1;try{await He.mkdir(q.dirname(F),{recursive:!0}),await He.writeFile(F,JSON.stringify(y))}catch(f){m.error("[plane-link] cursor flush failed:",f?.message||f)}}},gr),te.unref?.())}function O(f){return!j||j.readyState!==Ke.OPEN?!1:(j.send(JSON.stringify(f)),!0)}function ve(f){let l=Date.now();for(let{trackId:s,event:c}of f){let h=I.get(c.id);I.set(c.id,{trackId:s,seq:c.seq,event:c,sentAt:l,tries:(h?.tries??0)+1})}return O({v:E,ch:"events",type:"append",events:f})}function an(f){let l=null;for(let s of I.values())s.trackId===f&&(l==null||s.seq<l)&&(l=s.seq);return l}function cn(f){let l=N[f];if(l==null)return;let s=an(f),c=s==null?l:Math.min(l,s-1);c>(y[f]??0)&&(y[f]=c,sn())}function ln(){if(!K)return;let f=Date.now(),l=[...I.values()].filter(s=>s.event&&f-s.sentAt>=br);if(l.length){l.sort((s,c)=>s.trackId===c.trackId?s.seq-c.seq:s.trackId<c.trackId?-1:1),m.log(`[plane-link] re-sending ${l.length} unacked event(s) the plane never confirmed`);for(let s=0;s<l.length;s+=ge){let c=l.slice(s,s+ge).map(h=>({trackId:h.trackId,event:h.event}));if(!ve(c))return}}}async function Ze(){if(!d)return;let f;try{f=await d()}catch(l){m.error("[plane-link] metrics sample failed:",l?.message||l);return}f&&O({v:E,ch:"ctl",type:"metrics",metrics:f})}function un(){d&&(z&&clearInterval(z),Ze(),z=setInterval(Ze,T),z.unref?.())}async function dn(){let f;try{f=await o()}catch(l){m.error("[plane-link] backfill listTracks failed:",l?.message||l);return}O({v:E,ch:"ctl",type:"tracks",ids:f.filter(l=>!l.transferredTo).map(l=>l.id).filter(l=>typeof l=="string")});for(let l of f){if(!K)return;let s;try{s=await Be(l)}catch{continue}let c=y[l.id]??0,h=s.filter(g=>g.seq>c&&typeof g.id=="string");for(let g=0;g<h.length;g+=ge){let R=h.slice(g,g+ge).map(D=>({trackId:l.id,event:D}));if(!ve(R))return}}}function Qe(f){!K||!f?.trackId||typeof f.id!="string"||ve([{trackId:f.trackId,event:f}])}let ie=new Map;async function fn(f){let{reqId:l,method:s,path:c,headers:h={},body:g}=f,R=Object.fromEntries(Object.entries(h).filter(([,U])=>U!=null)),D=new AbortController;ie.set(l,D);try{if(f.host){await pn(f,R,D);return}let U=await fetch(b+c,{method:s,headers:R,body:g?Buffer.from(g,"base64"):void 0,signal:D.signal}),V=Object.fromEntries(U.headers);for(let C of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete V[C];if(V["content-type"]||(V["content-type"]="application/octet-stream"),O({v:E,ch:"control",type:"http_head",reqId:l,status:U.status,headers:V}),U.body){for await(let C of U.body)if(!O({v:E,ch:"control",type:"http_data",reqId:l,data:Buffer.from(C).toString("base64")}))break}O({v:E,ch:"control",type:"http_end",reqId:l,error:null})}finally{ie.delete(l)}}function pn(f,l,s){let{reqId:c,method:h,path:g,body:R}=f,D=new URL(b);return new Promise(U=>{let V=dr.request({host:D.hostname,port:D.port,method:h,path:g,headers:{...l,host:f.host},signal:s.signal},C=>{let{connection:fo,"keep-alive":po,"transfer-encoding":mo,upgrade:ho,...mn}=C.headers;O({v:E,ch:"control",type:"http_head",reqId:c,status:C.statusCode||502,headers:mn}),C.on("data",hn=>{O({v:E,ch:"control",type:"http_data",reqId:c,data:Buffer.from(hn).toString("base64")})||C.destroy()}),C.on("end",()=>{O({v:E,ch:"control",type:"http_end",reqId:c,error:null}),U()}),C.on("error",()=>{O({v:E,ch:"control",type:"http_end",reqId:c,error:"view upstream error"}),U()})});V.on("error",C=>{O({v:E,ch:"control",type:"http_end",reqId:c,error:C?.message||"view request failed"}),U()}),R&&V.write(Buffer.from(R,"base64")),V.end()})}function et(){if(xe)return;j=new Ke(e,{headers:{authorization:`Bearer ${t}`}}),j.on("open",async()=>{let l=null;try{l=await a?.()||null}catch{l=null}O({v:E,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:Y,installKind:x,...typeof w=="function"?{updatePolicy:w()}:w?{updatePolicy:w}:{},providers:Wt(),...l?{agents:l}:{}})}),j.on("message",l=>{let s;try{s=JSON.parse(l)}catch{return}if(s.ch==="ctl"&&s.type==="hello_ok"){K=!0,de=Ht,fe=null,m.log(`[plane-link] connected to plane as ${n}`),s.minNodeVersion&&Y&&oe(Y,s.minNodeVersion)&&m.error(`[plane-link] this node is bostrat-node ${Y}; the plane asks for \u2265${s.minNodeVersion} \u2014 update with: ${We(x)}`);try{u?.(typeof s.updatePolicy=="string"?s.updatePolicy:null)}catch{}let c=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(c&&Y&&oe(Y,c)&&!M.has(c)){M.add(c),m.log(`[plane-link] bostrat-node ${c} is available (this node runs ${Y}) \u2014 ${We(x)}`);try{p?.({current:Y,latest:c,min:s.minNodeVersion??null,installKind:x,required:!!(s.minNodeVersion&&oe(Y,s.minNodeVersion))})}catch(h){m.error(`[plane-link] update notice failed: ${h?.message||h}`)}}W&&clearInterval(W),W=setInterval(()=>{O({v:E,ch:"ctl",type:"ping"}),ln()},Tr),W.unref?.(),un(),dn().catch(h=>m.error("[plane-link] backfill failed:",h?.message||h));return}if(s.ch==="ctl"&&s.type==="update_policy"){try{u?.(typeof s.mode=="string"?s.mode:null)}catch{}return}if(s.ch==="ctl"&&s.type==="usage_caps"){Lt(s.caps??{},{source:"plane",updatedAt:s.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(s.ch==="ctl"&&s.type==="transferred"&&Array.isArray(s.tracks)){Promise.resolve().then(()=>i?.(s.tracks)).catch(c=>m.error("[plane-link] transfer notice failed:",c?.message||c));return}if(s.ch==="events"&&s.type==="ack"&&Array.isArray(s.ids)){let c=new Set;for(let h of s.ids){let g=I.get(h);g&&(I.delete(h),(N[g.trackId]??0)<g.seq&&(N[g.trackId]=g.seq),c.add(g.trackId))}for(let h of c)cn(h);return}if(s.ch==="control"&&s.type==="http_open"){fn(s).catch(c=>O({v:E,ch:"control",type:"http_end",reqId:s.reqId,error:c?.message||"tunnel error"}));return}if(s.ch==="control"&&s.type==="http_cancel"){ie.get(s.reqId)?.abort();return}if(s.ch==="attach"&&s.type==="open"){let c=new Ke(_+s.path,Array.isArray(s.protocols)?s.protocols:[],s.host?{headers:{host:s.host}}:void 0);k.set(s.streamId,c),A.set(s.streamId,[]),c.on("open",()=>{let g=A.get(s.streamId)||[];A.delete(s.streamId);for(let{buf:R,bin:D}of g)c.send(R,{binary:D})}),c.on("message",(g,R)=>{let D=R?g:Buffer.from(String(g));O({v:E,ch:"attach",type:"data",streamId:s.streamId,data:D.toString("base64"),...R?{bin:!0}:{}})});let h=()=>{A.delete(s.streamId),k.delete(s.streamId)&&O({v:E,ch:"attach",type:"close",streamId:s.streamId})};c.on("close",h),c.on("error",h);return}if(s.ch==="attach"&&s.type==="data"){let c=k.get(s.streamId);if(!c)return;let h=Buffer.from(s.data,"base64"),g=s.bin===!0,R=A.get(s.streamId);R?R.push({buf:h,bin:g}):c.send(h,{binary:g});return}if(s.ch==="attach"&&s.type==="close"){let c=k.get(s.streamId);k.delete(s.streamId),A.delete(s.streamId),c?.close();return}});let f=()=>{K&&m.log("[plane-link] disconnected from plane"),K=!1,W&&(clearInterval(W),W=null),z&&(clearInterval(z),z=null),I.clear(),N={};for(let c of k.values())c.close();k.clear(),A.clear();for(let c of ie.values())c.abort();if(ie.clear(),xe||ee)return;fe==null&&(fe=Date.now());let l=Date.now()-fe<hr,s=l?wr+Math.random()*yr:de;ee=setTimeout(()=>{ee=null,et()},s),ee.unref?.(),l||(de=Math.min(de*2,mr))};j.on("close",f),j.on("error",l=>{let s=/Unexpected server response: (\d+)/.exec(l?.message||"")?.[1];(s==="401"||s==="403")&&Date.now()-Xe>=Sr&&(Xe=Date.now(),m.error(`[plane-link] plane refused this node's credentials (HTTP ${s}) \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)`)),f()})}return ue.on("event",Qe),on().then(et),{stop:()=>{xe=!0,ue.off("event",Qe),ee&&clearTimeout(ee),te&&clearTimeout(te),W&&clearInterval(W),z&&clearInterval(z),O({v:E,ch:"ctl",type:"bye",reason:"shutdown"}),j?.close()},status:()=>({connected:K,nodeId:n,cursor:{...y},inflight:I.size})}}var Y,pr,E,Ht,mr,hr,wr,yr,ge,gr,Tr,br,_r,Sr,ze=S(()=>{Le();Ut();$e();Y=(()=>{try{return fr(import.meta.url)("../package.json").version||null}catch{return null}})(),pr=process.env.BOSTRAT_STATE_DIR||q.join(process.env.HOME||Te.tmpdir(),".bostrat");E=1,Ht=1e3,mr=3e4,hr=6e4,wr=1500,yr=500,ge=100,gr=2e3,Tr=25e3,br=6e4,_r=6e4,Sr=6e4});import{execFile as kr}from"node:child_process";import{promisify as vr}from"node:util";function Yt(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Ba,La,Ua,qt=S(()=>{Pe();Ba=vr(kr),La=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Ua=Promise.resolve()});var Zt={};Ae(Zt,{ACTIONABLE_KINDS:()=>Se,SELF_UPDATE_DIR:()=>Ye,createAutoUpdater:()=>Fr,inFlight:()=>Ge,readStatus:()=>qe,selfUpdatePlan:()=>Jt,settleSelfUpdate:()=>Cr,startSelfUpdate:()=>Xt,underService:()=>Vt,updatePolicy:()=>Ir});import Gt from"node:fs";import J from"node:fs/promises";import Ar from"node:os";import $ from"node:path";import{spawn as Or}from"node:child_process";import{createRequire as Er}from"node:module";function Ir({kind:e=se(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:Se.has(e)?e==="git-checkout"||Vt(t)?"auto":"prompt":"off"}function Vt(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Jt({kind:e,to:t,from:n=be,statusFile:r=_e,logFile:o=$.join(Ye,"last.log"),port:a=Number(process.env.PORT)||3362,npmPrefix:i=null,serviceName:d=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:T=typeof process.getuid=="function"?process.getuid():0,liveDir:p=process.env.BOSTRAT_LIVE_CHECKOUT||$.resolve($.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:u=Date.now()}={}){if(!Se.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 w=(M,k="")=>`write_status ${B(M)} ${k}`,x=process.platform==="darwin"?`launchctl kickstart -k gui/${T}/${d}`:`systemctl --user restart ${B(d)}`,b=`
|
|
79
|
+
`),g(0)}var xt,tr,Ke,be,$t=S(()=>{xt="wss://plane.bostrat.ai/v1/node",tr=Qn(import.meta.url)("../package.json").version,Ke=`ghcr.io/globocodes/bostrat-node:${tr}`;be=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let a=Zn("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(i,d,g)=>i?o(Object.assign(i,{stdout:d,stderr:g})):r({stdout:d,stderr:g}));t!=null&&a.stdin?.end(t)})});function Rt(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!sr.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 ar(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:Rt(o.from,"from",n),toMs:Rt(o.to,"to",n)}))}return t}var or,sr,ya,Nt=S(()=>{or={"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)."}]},sr=/^\d{4}-\d{2}-\d{2}$/;ya=ar(or)});var It=S(()=>{Nt()});import Pt from"node:fs/promises";import Dt from"node:path";import ir from"node:os";function Ft(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Bt(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Lt(e){let t=new Date(Ft(e));return t.setDate(t.getDate()+7),t.getTime()}function Ut(e){let t=new Date(Bt(e));return t.setMonth(t.getMonth()+1),t.getTime()}function fr(e=Date.now()){for(let[t,n]of Object.entries(ur)){let r=n.startOf(e);if(r!==_e[t]){_e[t]=r;for(let o of We.values())o[t]=0;for(let o of Mt)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&Mt.delete(o)}}}function pr(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 a of["weeklyUsd","monthlyUsd"]){let i=r?.[a];if(i==null||i==="")continue;let d=Number(i);if(!Number.isFinite(d)||d<=0)throw new Error(`${n}.${a} must be a positive number or null`);o[a]=d}Object.keys(o).length&&(t[n]=o)}return t}async function Ht(e,{source:t="local",updatedAt:n=Date.now()}={}){oe={caps:pr(e),updatedAt:n,source:t};try{await Pt.mkdir(Ct,{recursive:!0}),await Pt.writeFile(cr(),JSON.stringify(oe,null,2))}catch{}return mr()}function mr(e=Date.now()){fr(e);let t=new Set([...We.keys(),...Object.keys(oe?.caps||{})]),n={};for(let r of t){let o=We.get(r);n[r]={weeklyUsd:jt(o?.weekly||0),monthlyUsd:jt(o?.monthly||0)}}return{caps:oe?.caps||{},configured:!!oe,seeded:dr,updatedAt:oe?.updatedAt??null,spent:n,windows:{weekly:{start:_e.weekly,resetsAt:Lt(e)},monthly:{start:_e.monthly,resetsAt:Ut(e)}},warnPct:lr}}var Ct,cr,lr,ur,oe,dr,_e,We,Mt,jt,Kt=S(()=>{ge();It();Ct=process.env.BOSTRAT_STATE_DIR||Dt.join(process.env.HOME||ir.tmpdir(),".bostrat"),cr=()=>Dt.join(Ct,"usage-caps.json"),lr=.8;ur={weekly:{startOf:Ft,nextStart:Lt,capKey:"weeklyUsd"},monthly:{startOf:Bt,nextStart:Ut,capKey:"monthlyUsd"}},oe=null,dr=!1,_e={weekly:0,monthly:0},We=new Map,Mt=new Set;jt=e=>Math.round(e*1e4)/1e4});var Vt={};Re(Vt,{detectInstallKind:()=>ae,detectProviderAuth:()=>qt,startPlaneLink:()=>Ar,updateCommandFor:()=>he,versionLt:()=>se});import Yt from"node:fs";import ze from"node:fs/promises";import hr from"node:http";import V from"node:path";import xe from"node:os";import{createRequire as yr}from"node:module";import Ye from"ws";function ae({env:e=process.env,pkgDir:t=V.resolve(V.dirname(new URL(import.meta.url).pathname),".."),exists:n=Yt.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(V.join(t,"..",".git"))?"git-checkout":"dev"}function se(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 a=(n[o]||0)-(r[o]||0);if(a)return a<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 qt({home:e=process.env.HOME||xe.homedir(),env:t=process.env}={}){let n=r=>{try{return Yt.statSync(r),!0}catch{return!1}};return{claude:n(V.join(e,".claude",".credentials.json")),codex:n(V.join(t.CODEX_HOME||V.join(e,".codex"),"auth.json"))}}function Ar({url:e,token:t,nodeId:n=xe.hostname(),name:r=xe.hostname(),listTracks:o,detectAgents:a=null,onTracksTransferred:i=null,sampleMetrics:d=null,metricsMs:g=kr,onUpdateAvailable:m=null,onUpdatePolicy:l=null,onHelloRefused:T=null,updatePolicy:x=null,installKind:w=ae(),selfUrl:_=`http://127.0.0.1:${process.env.PORT||3362}`,log:p=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=fe(e);let C=_.replace(/^http/,"ws"),I=new Set,v=new Map,R=new Map,b=V.join(wr,"plane-link","cursor.json"),A={},z={},F=new Map,B=null,Z=!1,Oe=!1,le=Wt,ue=null,te=null,ne=null,Y=null,q=null,Ee=!1,Qe=0;async function cn(){try{A=JSON.parse(await ze.readFile(b,"utf8"))}catch{A={}}}function ln(){Ee=!0,!ne&&(ne=setTimeout(async()=>{if(ne=null,!!Ee){Ee=!1;try{await ze.mkdir(V.dirname(b),{recursive:!0}),await ze.writeFile(b,JSON.stringify(A))}catch(f){p.error("[plane-link] cursor flush failed:",f?.message||f)}}},_r),ne.unref?.())}function O(f){return!B||B.readyState!==Ye.OPEN?!1:(B.send(JSON.stringify(f)),!0)}function $e(f){let u=Date.now();for(let{trackId:s,event:c}of f){let h=F.get(c.id);F.set(c.id,{trackId:s,seq:c.seq,event:c,sentAt:u,tries:(h?.tries??0)+1})}return O({v:E,ch:"events",type:"append",events:f})}function un(f){let u=null;for(let s of F.values())s.trackId===f&&(u==null||s.seq<u)&&(u=s.seq);return u}function dn(f){let u=z[f];if(u==null)return;let s=un(f),c=s==null?u:Math.min(u,s-1);c>(A[f]??0)&&(A[f]=c,ln())}function fn(){if(!Z)return;let f=Date.now(),u=[...F.values()].filter(s=>s.event&&f-s.sentAt>=xr);if(u.length){u.sort((s,c)=>s.trackId===c.trackId?s.seq-c.seq:s.trackId<c.trackId?-1:1),p.log(`[plane-link] re-sending ${u.length} unacked event(s) the plane never confirmed`);for(let s=0;s<u.length;s+=Se){let c=u.slice(s,s+Se).map(h=>({trackId:h.trackId,event:h.event}));if(!$e(c))return}}}async function et(){if(!d)return;let f;try{f=await d()}catch(u){p.error("[plane-link] metrics sample failed:",u?.message||u);return}f&&O({v:E,ch:"ctl",type:"metrics",metrics:f})}function pn(){d&&(q&&clearInterval(q),et(),q=setInterval(et,g),q.unref?.())}async function mn(){let f;try{f=await o()}catch(u){p.error("[plane-link] backfill listTracks failed:",u?.message||u);return}O({v:E,ch:"ctl",type:"tracks",ids:f.filter(u=>!u.transferredTo).map(u=>u.id).filter(u=>typeof u=="string")});for(let u of f){if(!Z)return;let s;try{s=await Ce(u)}catch{continue}let c=A[u.id]??0,h=s.filter(y=>y.seq>c&&typeof y.id=="string");for(let y=0;y<h.length;y+=Se){let N=h.slice(y,y+Se).map(M=>({trackId:u.id,event:M}));if(!$e(N))return}}}function tt(f){!Z||!f?.trackId||typeof f.id!="string"||$e([{trackId:f.trackId,event:f}])}let de=new Map;async function hn(f){let{reqId:u,method:s,path:c,headers:h={},body:y}=f,N=Object.fromEntries(Object.entries(h).filter(([,K])=>K!=null)),M=new AbortController;de.set(u,M);try{if(f.host){await yn(f,N,M);return}let K=await fetch(_+c,{method:s,headers:N,body:y?Buffer.from(y,"base64"):void 0,signal:M.signal}),G=Object.fromEntries(K.headers);for(let j of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete G[j];if(G["content-type"]||(G["content-type"]="application/octet-stream"),O({v:E,ch:"control",type:"http_head",reqId:u,status:K.status,headers:G}),K.body){for await(let j of K.body)if(!O({v:E,ch:"control",type:"http_data",reqId:u,data:Buffer.from(j).toString("base64")}))break}O({v:E,ch:"control",type:"http_end",reqId:u,error:null})}finally{de.delete(u)}}function yn(f,u,s){let{reqId:c,method:h,path:y,body:N}=f,M=new URL(_);return new Promise(K=>{let G=hr.request({host:M.hostname,port:M.port,method:h,path:y,headers:{...u,host:f.host},signal:s.signal},j=>{let{connection:ho,"keep-alive":yo,"transfer-encoding":wo,upgrade:go,...wn}=j.headers;O({v:E,ch:"control",type:"http_head",reqId:c,status:j.statusCode||502,headers:wn}),j.on("data",gn=>{O({v:E,ch:"control",type:"http_data",reqId:c,data:Buffer.from(gn).toString("base64")})||j.destroy()}),j.on("end",()=>{O({v:E,ch:"control",type:"http_end",reqId:c,error:null}),K()}),j.on("error",()=>{O({v:E,ch:"control",type:"http_end",reqId:c,error:"view upstream error"}),K()})});G.on("error",j=>{O({v:E,ch:"control",type:"http_end",reqId:c,error:j?.message||"view request failed"}),K()}),N&&G.write(Buffer.from(N,"base64")),G.end()})}function nt(){if(Oe)return;B=new Ye(e,{headers:{authorization:`Bearer ${t}`}}),B.on("open",async()=>{let u=null;try{u=await a?.()||null}catch{u=null}O({v:E,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:L,installKind:w,...typeof x=="function"?{updatePolicy:x()}:x?{updatePolicy:x}:{},providers:qt(),...u?{agents:u}:{}})}),B.on("message",u=>{let s;try{s=JSON.parse(u)}catch{return}if(s.ch==="ctl"&&s.type==="hello_ok"){Z=!0,le=Wt,ue=null,p.log(`[plane-link] connected to plane as ${n}`),s.minNodeVersion&&L&&se(L,s.minNodeVersion)&&p.error(`[plane-link] this node is bostrat-node ${L}; the plane asks for \u2265${s.minNodeVersion} \u2014 update with: ${he(w)}`);try{l?.(typeof s.updatePolicy=="string"?s.updatePolicy:null)}catch{}let c=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(c&&L&&se(L,c)&&!I.has(c)){I.add(c),p.log(`[plane-link] bostrat-node ${c} is available (this node runs ${L}) \u2014 ${he(w)}`);try{m?.({current:L,latest:c,min:s.minNodeVersion??null,installKind:w,required:!!(s.minNodeVersion&&se(L,s.minNodeVersion))})}catch(h){p.error(`[plane-link] update notice failed: ${h?.message||h}`)}}Y&&clearInterval(Y),Y=setInterval(()=>{O({v:E,ch:"ctl",type:"ping"}),fn()},Sr),Y.unref?.(),pn(),mn().catch(h=>p.error("[plane-link] backfill failed:",h?.message||h));return}if(s.ch==="ctl"&&s.type==="hello_refused"){let c=typeof s.minNodeVersion=="string"?s.minNodeVersion:null,h=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;p.error(`[plane-link] plane REFUSED this node: bostrat-node ${L??"?"} is below its minimum ${c??"?"} \u2014 ${s.fix||he(w)}`),le=zt,ue=0;try{T?.({current:L,min:c,latest:h,fix:s.fix||he(w),installKind:w})}catch(y){p.error(`[plane-link] refusal handler failed: ${y?.message||y}`)}return}if(s.ch==="ctl"&&s.type==="update_policy"){try{l?.(typeof s.mode=="string"?s.mode:null)}catch{}return}if(s.ch==="ctl"&&s.type==="usage_caps"){Ht(s.caps??{},{source:"plane",updatedAt:s.updatedAt??Date.now()}).then(c=>p.log(`[plane-link] spend caps ${Object.keys(c.caps).length?`updated (${Object.keys(c.caps).join(", ")})`:"cleared"} from plane`)).catch(c=>p.error("[plane-link] spend-caps push rejected:",c?.message||c));return}if(s.ch==="ctl"&&s.type==="transferred"&&Array.isArray(s.tracks)){Promise.resolve().then(()=>i?.(s.tracks)).catch(c=>p.error("[plane-link] transfer notice failed:",c?.message||c));return}if(s.ch==="events"&&s.type==="ack"&&Array.isArray(s.ids)){let c=new Set;for(let h of s.ids){let y=F.get(h);y&&(F.delete(h),(z[y.trackId]??0)<y.seq&&(z[y.trackId]=y.seq),c.add(y.trackId))}for(let h of c)dn(h);return}if(s.ch==="control"&&s.type==="http_open"){hn(s).catch(c=>O({v:E,ch:"control",type:"http_end",reqId:s.reqId,error:c?.message||"tunnel error"}));return}if(s.ch==="control"&&s.type==="http_cancel"){de.get(s.reqId)?.abort();return}if(s.ch==="attach"&&s.type==="open"){let c=new Ye(C+s.path,Array.isArray(s.protocols)?s.protocols:[],s.host?{headers:{host:s.host}}:void 0);v.set(s.streamId,c),R.set(s.streamId,[]),c.on("open",()=>{let y=R.get(s.streamId)||[];R.delete(s.streamId);for(let{buf:N,bin:M}of y)c.send(N,{binary:M})}),c.on("message",(y,N)=>{let M=N?y:Buffer.from(String(y));O({v:E,ch:"attach",type:"data",streamId:s.streamId,data:M.toString("base64"),...N?{bin:!0}:{}})});let h=()=>{R.delete(s.streamId),v.delete(s.streamId)&&O({v:E,ch:"attach",type:"close",streamId:s.streamId})};c.on("close",h),c.on("error",h);return}if(s.ch==="attach"&&s.type==="data"){let c=v.get(s.streamId);if(!c)return;let h=Buffer.from(s.data,"base64"),y=s.bin===!0,N=R.get(s.streamId);N?N.push({buf:h,bin:y}):c.send(h,{binary:y});return}if(s.ch==="attach"&&s.type==="close"){let c=v.get(s.streamId);v.delete(s.streamId),R.delete(s.streamId),c?.close();return}});let f=()=>{Z&&p.log("[plane-link] disconnected from plane"),Z=!1,Y&&(clearInterval(Y),Y=null),q&&(clearInterval(q),q=null),F.clear(),z={};for(let c of v.values())c.close();v.clear(),R.clear();for(let c of de.values())c.abort();if(de.clear(),Oe||te)return;ue==null&&(ue=Date.now());let u=Date.now()-ue<gr,s=u?Tr+Math.random()*br:le;te=setTimeout(()=>{te=null,nt()},s),te.unref?.(),u||(le=Math.min(le*2,zt))};B.on("close",f),B.on("error",u=>{let s=/Unexpected server response: (\d+)/.exec(u?.message||"")?.[1];(s==="401"||s==="403")&&Date.now()-Qe>=vr&&(Qe=Date.now(),p.error(`[plane-link] plane refused this node's credentials (HTTP ${s}) \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)`)),f()})}return me.on("event",tt),cn().then(nt),{stop:()=>{Oe=!0,me.off("event",tt),te&&clearTimeout(te),ne&&clearTimeout(ne),Y&&clearInterval(Y),q&&clearInterval(q),O({v:E,ch:"ctl",type:"bye",reason:"shutdown"}),B?.close()},status:()=>({connected:Z,nodeId:n,cursor:{...A},inflight:F.size})}}var L,wr,E,Wt,zt,gr,Tr,br,Se,_r,Sr,xr,kr,vr,qe=S(()=>{ge();Kt();Pe();L=(()=>{try{return yr(import.meta.url)("../package.json").version||null}catch{return null}})(),wr=process.env.BOSTRAT_STATE_DIR||V.join(process.env.HOME||xe.tmpdir(),".bostrat");E=1,Wt=1e3,zt=3e4,gr=6e4,Tr=1500,br=500,Se=100,_r=2e3,Sr=25e3,xr=6e4,kr=6e4,vr=6e4});import{execFile as Or}from"node:child_process";import{promisify as Er}from"node:util";function Gt(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Ha,Ka,Wa,Jt=S(()=>{Fe();Ha=Er(Or),Ka=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Wa=Promise.resolve()});var tn={};Re(tn,{ACTIONABLE_KINDS:()=>Ae,SELF_UPDATE_DIR:()=>Ve,createAutoUpdater:()=>Ur,inFlight:()=>Je,readStatus:()=>Ge,selfUpdatePlan:()=>Qt,settleSelfUpdate:()=>Lr,startSelfUpdate:()=>en,underService:()=>Zt,updatePolicy:()=>jr});import Xt from"node:fs";import J from"node:fs/promises";import $r from"node:os";import $ from"node:path";import{spawn as Rr}from"node:child_process";import{createRequire as Nr}from"node:module";function jr({kind:e=ae(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:Ae.has(e)?e==="git-checkout"||Zt(t)?"auto":"prompt":"off"}function Zt(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Qt({kind:e,to:t,from:n=ke,statusFile:r=ve,logFile:o=$.join(Ve,"last.log"),port:a=Number(process.env.PORT)||3362,npmPrefix:i=null,serviceName:d=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:g=typeof process.getuid=="function"?process.getuid():0,liveDir:m=process.env.BOSTRAT_LIVE_CHECKOUT||$.resolve($.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:l=Date.now()}={}){if(!Ae.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=(C,I="")=>`write_status ${U(C)} ${I}`,x=process.platform==="darwin"?`launchctl kickstart -k gui/${g}/${d}`:`systemctl --user restart ${U(d)}`,w=`
|
|
80
80
|
health() {
|
|
81
81
|
for i in $(seq 1 45); do
|
|
82
82
|
sleep 1
|
|
83
|
-
if curl -sf -o /dev/null
|
|
83
|
+
if curl -sf -o /dev/null "http://127.0.0.1:${a}/api/health"; then return 0; fi
|
|
84
84
|
done
|
|
85
85
|
return 1
|
|
86
|
-
}`,
|
|
86
|
+
}`,_=`#!/usr/bin/env bash
|
|
87
87
|
# bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
|
|
88
88
|
# ${n??"?"} \u2192 ${t} (${e}). Status: ${r}
|
|
89
89
|
set -u
|
|
90
|
-
FROM=${
|
|
91
|
-
TO=${
|
|
92
|
-
STATUS_FILE=${
|
|
93
|
-
STARTED_AT=${Number(
|
|
90
|
+
FROM=${U(n??"")}
|
|
91
|
+
TO=${U(t)}
|
|
92
|
+
STATUS_FILE=${U(r)}
|
|
93
|
+
STARTED_AT=${Number(l)}
|
|
94
94
|
write_status() { # <status> [error]
|
|
95
95
|
local err="\${2:-}"
|
|
96
96
|
err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
|
|
97
97
|
printf '{"status":"%s","from":"%s","to":"%s","kind":"%s","startedAt":%s,"updatedAt":%s%s}\\n' \\
|
|
98
|
-
"$1" "$FROM" "$TO" ${
|
|
98
|
+
"$1" "$FROM" "$TO" ${U(e)} "$STARTED_AT" "$(date +%s000)" \\
|
|
99
99
|
"\${err:+,\\"error\\":\\"$err\\"}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
|
|
100
100
|
}
|
|
101
|
-
${
|
|
102
|
-
`;if(e==="npm-global"){let
|
|
103
|
-
${
|
|
104
|
-
if ! ${
|
|
105
|
-
${
|
|
101
|
+
${w}
|
|
102
|
+
`;if(e==="npm-global"){let C=i?$.join(i,"bin","npm"):"npm",I=v=>`${U(C)} install -g "bostrat-node@${v}" --no-audit --no-fund`;return _+`
|
|
103
|
+
${T("updating",'"" ')}
|
|
104
|
+
if ! ${I("$TO")}; then
|
|
105
|
+
${T("failed",'"npm install failed"')}
|
|
106
106
|
exit 1
|
|
107
107
|
fi
|
|
108
|
-
${
|
|
108
|
+
${T("restarting")}
|
|
109
109
|
if ! ${x}; then
|
|
110
|
-
${
|
|
110
|
+
${T("failed",'"service restart failed"')}
|
|
111
111
|
exit 1
|
|
112
112
|
fi
|
|
113
113
|
if health; then
|
|
@@ -115,52 +115,52 @@ if health; then
|
|
|
115
115
|
exit 0
|
|
116
116
|
fi
|
|
117
117
|
# \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
|
|
118
|
-
${
|
|
119
|
-
if [ -n "$FROM" ] && ${
|
|
120
|
-
${
|
|
118
|
+
${T("rolling-back",'"agent did not answer on :'+a+' after the update"')}
|
|
119
|
+
if [ -n "$FROM" ] && ${I("$FROM")} && ${x} && health; then
|
|
120
|
+
${T("rolled-back",'"agent did not answer on :'+a+' after the update; rolled back"')}
|
|
121
121
|
exit 1
|
|
122
122
|
fi
|
|
123
|
-
${
|
|
123
|
+
${T("failed",'"agent did not answer after the update AND the rollback"')}
|
|
124
124
|
exit 1
|
|
125
|
-
`}let
|
|
126
|
-
LIVE=${
|
|
125
|
+
`}let p=C=>`( cd ${U(m)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${C}" )`;return _+`
|
|
126
|
+
LIVE=${U(m)}
|
|
127
127
|
TMP_SCRIPT="$(mktemp)"
|
|
128
128
|
trap 'rm -f "$TMP_SCRIPT"' EXIT
|
|
129
129
|
# "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
|
|
130
130
|
# restart \u2192 health in one call): the agent it restarts settles "done" on boot,
|
|
131
131
|
# and nothing here may write after that boot or the settle would repeat.
|
|
132
|
-
${
|
|
133
|
-
if ${
|
|
132
|
+
${T("restarting")}
|
|
133
|
+
if ${p("$TO")}; then
|
|
134
134
|
exit 0
|
|
135
135
|
fi
|
|
136
|
-
${
|
|
137
|
-
if [ -n "$FROM" ] && ${
|
|
138
|
-
${
|
|
136
|
+
${T("rolling-back",'"deploy-pi.sh v$TO failed"')}
|
|
137
|
+
if [ -n "$FROM" ] && ${p("$FROM")}; then
|
|
138
|
+
${T("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
|
|
139
139
|
exit 1
|
|
140
140
|
fi
|
|
141
|
-
${
|
|
141
|
+
${T("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
|
|
142
142
|
exit 1
|
|
143
|
-
`}async function qe(e=_e){try{return JSON.parse(await J.readFile(e,"utf8"))}catch{return null}}async function Xt({to:e,from:t=be,kind:n=se(),reason:r="manual",statusFile:o=_e,spawnImpl:a=Or,now:i=Date.now,npmPrefix:d=void 0,log:T=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!Se.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 p=await qe(o);if(Ge(p))return{ok:!1,reason:`an update to ${p.to} is already in flight`,status:p};if(p&&p.to===e&&(p.status==="failed"||p.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${p.status} (${p.error||"no detail"}) \u2014 retried when a newer release exists`,status:p};await J.mkdir($.dirname(o),{recursive:!0});let u=d!==void 0?d:n==="npm-global"?Yt(await Mr())||$.resolve($.dirname(process.execPath),".."):null,w=Jt({kind:n,to:e,from:t,statusFile:o,npmPrefix:u,startedAt:i()}),x=$.join($.dirname(o),`update-${e}.sh`),b=$.join($.dirname(o),"last.log");await J.writeFile(x,w,{mode:448}),await J.writeFile(o,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,startedAt:i(),updatedAt:i()}));let m=Gt.existsSync("/run/systemd/system")&&await jr("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",x]]:["setsid",["-f","bash","-c",`exec bash ${B(x)} >> ${B(b)} 2>&1`]];try{a(m[0],m[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(_){return await J.writeFile(o,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,startedAt:i(),updatedAt:i(),error:`could not spawn updater: ${_?.message||_}`})),{ok:!1,reason:`could not spawn updater: ${_?.message||_}`}}return T.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${o}`),{ok:!0,to:e,from:t,kind:n,scriptFile:x,statusFile:o}}async function Mr(){try{return await J.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function jr(e){for(let t of String(process.env.PATH||"").split($.delimiter))try{return await J.access($.join(t,e),Gt.constants.X_OK),!0}catch{}return!1}async function Cr({statusFile:e=_e,current:t=be,now:n=Date.now,staleMs:r=Dr}={}){let o=await qe(e);if(!o)return null;let a=i=>J.writeFile(e,JSON.stringify(i)).catch(()=>{});if(Ge(o)){if(t&&o.to===t){let i={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await a(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 a(i),i}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let i={...o,announced:!0};return await a(i),i}return null}function Fr({isBusy:e,start:t=Xt,onStuck:n=null,onStarted:r=null,tickMs:o=Nr,stuckMs:a=Rr,now:i=Date.now,setIntervalImpl:d=setInterval,clearIntervalImpl:T=clearInterval,log:p=console}={}){let u=null,w=()=>{u?.timer&&T(u.timer),u=null},x=async()=>{if(!u)return;let b=!0;try{b=await e()!==!1}catch{b=!0}if(b){if(!u.stuckFired&&i()-u.since>=a){u.stuckFired=!0;try{await n?.({to:u.to,from:u.from,since:u.since})}catch{}}return}let m=u;w();let _=await t({to:m.to,from:m.from,kind:m.kind,reason:"auto"});p.log?.(`[self-update] stasis reached \u2192 ${_.ok?"started":`not started: ${_.reason}`}`);try{await r?.({...m,result:_})}catch{}};return{arm({to:b,from:m=be,kind:_=se()}){return u?.to===b?!1:(w(),u={to:b,from:m,kind:_,since:i(),stuckFired:!1,timer:d(x,o)},u.timer.unref?.(),!0)},tick:x,cancel:w,get armed(){return u?{to:u.to,from:u.from,kind:u.kind,since:u.since}:null}}}var be,$r,Ye,_e,Rr,Nr,Se,B,Pr,Ge,Dr,Qt=S(()=>{ze();qt();be=(()=>{try{return Er(import.meta.url)("../package.json").version||null}catch{return null}})(),$r=process.env.BOSTRAT_STATE_DIR||$.join(process.env.HOME||Ar.tmpdir(),".bostrat"),Ye=$.join($r,"self-update"),_e=$.join(Ye,"status.json"),Rr=1440*6e4,Nr=6e4,Se=new Set(["npm-global","git-checkout"]);B=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Pr=new Set(["updating","restarting","rolling-back"]),Ge=e=>!!(e&&Pr.has(e.status));Dr=45*6e4});$e();Me();import L from"node:fs";import v from"node:path";import ae from"node:os";import{createRequire as Ve}from"node:module";import{execFile as Br,spawn as Lr}from"node:child_process";import{promisify as Ur}from"node:util";import Hr from"node:readline/promises";import{randomUUID as Kr}from"node:crypto";import{fileURLToPath as Wr}from"node:url";var X=Ur(Br),Je=v.dirname(Wr(import.meta.url)),Q=v.resolve(Je,".."),zr=v.join(Je,"index.js"),Yr="wss://plane.bostrat.ai/v1/node",en=Ve(import.meta.url)("../package.json").version,P=(e,t)=>({name:e,level:"pass",detail:t}),G=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),H=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function qr(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?P("node runtime",`${process.version} at ${process.execPath}`):H("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Gr(e){let t;try{t=L.statSync(e)}catch{return G("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?G("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 Vr(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await X(t,["-V"],{timeout:5e3});return P("tmux",`${t} (${n.trim()})`)}catch{return H("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function tn(e,{required:t=!1}={}){if(await De(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=he[e]?`${he[e]}${e==="cursor-agent"?" # installs to ~/.local/bin \u2014 ensure your login shell has it on PATH":""}`:`install ${e} so \`$SHELL -lic 'command -v ${e}'\` finds it`;return t?H(e,r,o):G(e,r,o)}async function Jr(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await X(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 G("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",he.gh)}}async function Xr(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>tn(t)));return e.some(t=>t.level==="pass")||e.push(H("agent CLIs","no agent CLI found at all \u2014 a node with nothing to drive","install at least one of claude / codex / cursor-agent")),e}async function Zr(){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 De(t,{failOpen:!1})?P(t,"resolves on the service PATH"):G(t,`not on the service PATH \u2014 ${n}`,r)))}async function Qr(){try{let t=Ve(v.join(Q,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let o=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),a=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(a),n()})}),P("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${Q} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Ve(v.join(Q,"package.json")),r=v.join(v.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");L.existsSync(r)&&!(L.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return H("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function eo(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";return L.existsSync(t)?P("chromium (mocks)",t):G("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable`,"install Chromium/Chrome and set BOSTRAT_CHROMIUM_BIN")}function to(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?H("claude lane","BOSTRAT_CLAUDE_USE_API_KEY=1 but ANTHROPIC_API_KEY is empty","add the key to node.env or set the flag to 0"):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 no(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return G("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(a=>{let i=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),d=p=>{clearTimeout(T);try{i.close()}catch{}a(p)},T=setTimeout(()=>d(H("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-${Kr().slice(0,8)}`,ephemeral:!0}))),i.on("message",p=>{try{let u=JSON.parse(p);u.type==="hello_ok"?d(P("plane link",`hello_ok in ${Date.now()-r}ms (${o})`)):u.type==="error"&&d(H("plane link",`plane said: ${u.code} ${u.message||""}`,"check the token"))}catch{}}),i.on("error",p=>d(H("plane link",`${p?.message||p}`,"check the URL, the token, and the plane's IP gate")))})}function ro(){let e;try{e=JSON.parse(L.readFileSync(v.join(Ee,"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 H("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?G("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 oo(e){return e.BOSTRAT_STATE_REMOTE?P("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):G("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 nn(e,t={}){let n=[];return n.push(await qr()),n.push(Gr(t.envFile||ne())),n.push(await Vr(e)),n.push(...await Xr()),n.push(await tn("git",{required:!0})),n.push(await Jr()),n.push(...await Zr()),n.push(await Qr()),n.push(eo(e)),n.push(to(e)),n.push(await no(e,t)),n.push(ro()),n.push(oo(e)),n}function rn(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let a of e)t(`${n[a.level]} ${a.name}: ${a.detail}`),a.fix&&a.level!=="pass"&&t(` fix: ${a.fix}`);let r=e.filter(a=>a.level==="fail").length,o=e.filter(a=>a.level==="warn").length;return t(r?`
|
|
143
|
+
`}async function Ge(e=ve){try{return JSON.parse(await J.readFile(e,"utf8"))}catch{return null}}async function en({to:e,from:t=ke,kind:n=ae(),reason:r="manual",statusFile:o=ve,spawnImpl:a=Rr,now:i=Date.now,npmPrefix:d=void 0,log:g=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!Ae.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!se(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let m=await Ge(o);if(Je(m))return{ok:!1,reason:`an update to ${m.to} is already in flight`,status:m};if(m&&m.to===e&&(m.status==="failed"||m.status==="rolled-back"))return{ok:!1,reason:`update to ${e} already ${m.status} (${m.error||"no detail"}) \u2014 retried when a newer release exists`,status:m};await J.mkdir($.dirname(o),{recursive:!0});let l=d!==void 0?d:n==="npm-global"?Gt(await Cr())||$.resolve($.dirname(process.execPath),".."):null,T=Qt({kind:n,to:e,from:t,statusFile:o,npmPrefix:l,startedAt:i()}),x=$.join($.dirname(o),`update-${e}.sh`),w=$.join($.dirname(o),"last.log");await J.writeFile(x,T,{mode:448}),await J.writeFile(o,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,startedAt:i(),updatedAt:i()}));let _=Xt.existsSync("/run/systemd/system")&&await Fr("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",x]]:["setsid",["-f","bash","-c",`exec bash ${U(x)} >> ${U(w)} 2>&1`]];try{a(_[0],_[1],{detached:!0,stdio:"ignore"}).unref?.()}catch(p){return await J.writeFile(o,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,startedAt:i(),updatedAt:i(),error:`could not spawn updater: ${p?.message||p}`})),{ok:!1,reason:`could not spawn updater: ${p?.message||p}`}}return g.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${o}`),{ok:!0,to:e,from:t,kind:n,scriptFile:x,statusFile:o}}async function Cr(){try{return await J.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Fr(e){for(let t of String(process.env.PATH||"").split($.delimiter))try{return await J.access($.join(t,e),Xt.constants.X_OK),!0}catch{}return!1}async function Lr({statusFile:e=ve,current:t=ke,now:n=Date.now,staleMs:r=Br}={}){let o=await Ge(e);if(!o)return null;let a=i=>J.writeFile(e,JSON.stringify(i)).catch(()=>{});if(Je(o)){if(t&&o.to===t){let i={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await a(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 a(i),i}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let i={...o,announced:!0};return await a(i),i}return null}function Ur({isBusy:e,start:t=en,onStuck:n=null,onStarted:r=null,tickMs:o=Mr,stuckMs:a=Pr,now:i=Date.now,setIntervalImpl:d=setInterval,clearIntervalImpl:g=clearInterval,log:m=console}={}){let l=null,T=()=>{l?.timer&&g(l.timer),l=null},x=async()=>{if(!l)return;let w=!0;try{w=await e()!==!1}catch{w=!0}if(w){if(!l.stuckFired&&i()-l.since>=a){l.stuckFired=!0;try{await n?.({to:l.to,from:l.from,since:l.since})}catch{}}return}let _=l;T();let p=await t({to:_.to,from:_.from,kind:_.kind,reason:"auto"});m.log?.(`[self-update] stasis reached \u2192 ${p.ok?"started":`not started: ${p.reason}`}`);try{await r?.({..._,result:p})}catch{}};return{arm({to:w,from:_=ke,kind:p=ae()}){return l?.to===w?!1:(T(),l={to:w,from:_,kind:p,since:i(),stuckFired:!1,timer:d(x,o)},l.timer.unref?.(),!0)},tick:x,cancel:T,get armed(){return l?{to:l.to,from:l.from,kind:l.kind,since:l.since}:null}}}var ke,Ir,Ve,ve,Pr,Mr,Ae,U,Dr,Je,Br,nn=S(()=>{qe();Jt();ke=(()=>{try{return Nr(import.meta.url)("../package.json").version||null}catch{return null}})(),Ir=process.env.BOSTRAT_STATE_DIR||$.join(process.env.HOME||$r.tmpdir(),".bostrat"),Ve=$.join(Ir,"self-update"),ve=$.join(Ve,"status.json"),Pr=1440*6e4,Mr=6e4,Ae=new Set(["npm-global","git-checkout"]);U=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Dr=new Set(["updating","restarting","rolling-back"]),Je=e=>!!(e&&Dr.has(e.status));Br=45*6e4});Pe();Be();import H from"node:fs";import k from"node:path";import ce from"node:os";import{createRequire as Xe}from"node:module";import{execFile as Hr,spawn as Kr}from"node:child_process";import{promisify as Wr}from"node:util";import zr from"node:readline/promises";import{randomUUID as Yr}from"node:crypto";import{fileURLToPath as qr}from"node:url";var rn=(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 a=(n[o]||0)-(r[o]||0);if(a)return a<0}return!1},X=Wr(Hr),Ze=k.dirname(qr(import.meta.url)),ee=k.resolve(Ze,".."),Vr=k.join(Ze,"index.js"),Gr="wss://plane.bostrat.ai/v1/node",ie=Xe(import.meta.url)("../package.json").version,P=(e,t)=>({name:e,level:"pass",detail:t}),W=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),D=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function Jr(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?P("node runtime",`${process.version} at ${process.execPath}`):D("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Xr(e){let t;try{t=H.statSync(e)}catch{return W("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?W("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 Zr(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await X(t,["-V"],{timeout:5e3});return P("tmux",`${t} (${n.trim()})`)}catch{return D("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function on(e,{required:t=!1}={}){if(await Ue(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=Te[e]?`${Te[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?D(e,r,o):W(e,r,o)}async function Qr(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await X(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 W("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",Te.gh)}}async function eo(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>on(t)));return e.some(t=>t.level==="pass")||e.push(D("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 to(){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 Ue(t,{failOpen:!1})?P(t,"resolves on the service PATH"):W(t,`not on the service PATH \u2014 ${n}`,r)))}async function no(){try{let t=Xe(k.join(ee,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let o=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),a=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(a),n()})}),P("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${ee} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Xe(k.join(ee,"package.json")),r=k.join(k.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");H.existsSync(r)&&!(H.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return D("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function ro(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(H.existsSync(t))return P("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"?D:W)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function oo(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?D("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 so(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return W("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=fe(e.BOSTRAT_PLANE_URL);return await new Promise(a=>{let i=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),d=m=>{clearTimeout(g);try{i.close()}catch{}a(m)},g=setTimeout(()=>d(D("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-${Yr().slice(0,8)}`,ephemeral:!0}))),i.on("message",m=>{try{let l=JSON.parse(m);l.type==="hello_ok"?l.minNodeVersion&&rn(ie,l.minNodeVersion)?d(D("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${l.minNodeVersion} \u2014 this node is ${ie}; the real link is refused until it updates`,`bostrat-node self-update --to ${l.latestNodeVersion||l.minNodeVersion}`)):l.latestNodeVersion&&rn(ie,l.latestNodeVersion)?d(W("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${l.latestNodeVersion} is available (this node: ${ie})`,`bostrat-node self-update --to ${l.latestNodeVersion}`)):d(P("plane link",`hello_ok in ${Date.now()-r}ms (${o})`)):l.type==="error"&&d(D("plane link",`plane said: ${l.code} ${l.message||""}`,"check the token"))}catch{}}),i.on("error",m=>d(D("plane link",`${m?.message||m}`,"check the URL, the token, and the plane's IP gate")))})}function ao(){let e;try{e=JSON.parse(H.readFileSync(k.join(Ie,"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 D("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?W("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 io(e){return e.BOSTRAT_STATE_REMOTE?P("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`):W("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 sn(e,t={}){let n=[];return n.push(await Jr()),n.push(Xr(t.envFile||re())),n.push(await Zr(e)),n.push(...await eo()),n.push(await on("git",{required:!0})),n.push(await Qr()),n.push(...await to()),n.push(await no()),n.push(ro(e)),n.push(oo(e)),n.push(await so(e,t)),n.push(ao()),n.push(io(e)),n}function an(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let a of e)t(`${n[a.level]} ${a.name}: ${a.detail}`),a.fix&&a.level!=="pass"&&t(` fix: ${a.fix}`);let r=e.filter(a=>a.level==="fail").length,o=e.filter(a=>a.level==="warn").length;return t(r?`
|
|
144
144
|
FAIL \u2014 ${r} blocking, ${o} warnings`:`
|
|
145
|
-
OK \u2014 0 blocking, ${o} warnings`),r===0}async function
|
|
145
|
+
OK \u2014 0 blocking, ${o} warnings`),r===0}async function co({envFile:e=re(),input:t=process.stdin,output:n=process.stdout}={}){let r=we(e),o=zr.createInterface({input:t,output:n}),a=async(R,b)=>(await o.question(b?`${R} [${b}]: `:`${R}: `)).trim()||b||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
|
|
146
146
|
you type those inside each box, later (box-auth-policy).
|
|
147
147
|
|
|
148
|
-
`);let i=await a("Plane URL",r.BOSTRAT_PLANE_URL||
|
|
149
|
-
`);let
|
|
150
|
-
`);let
|
|
148
|
+
`);let i=await a("Plane URL",r.BOSTRAT_PLANE_URL||Gr),d=fe(i);d!==i.trim()&&n.write(` \u2192 using ${d}
|
|
149
|
+
`);let g=await a("Node token (minted plane-side; stored 0600)",r.BOSTRAT_PLANE_TOKEN),m=await a("Owner userId (just press Enter \u2014 the plane infers it from your token)",r.BOSTRAT_OWNER||"");m&&!/^user_[A-Za-z0-9]+$/.test(m)&&n.write(` ! that doesn't look like a Clerk userId (user_\u2026) \u2014 leave it empty next time and the plane infers the owner from the token; saved as typed.
|
|
150
|
+
`);let l=await a("Node name",r.BOSTRAT_NODE_NAME||ce.hostname().split(".")[0]),T=await a("Repos root",r.BOSTRAT_REPOS_ROOT||k.join(ce.homedir(),"Documents")),x=await a("State remote (per-node private repo; empty = local-only)",r.BOSTRAT_STATE_REMOTE||""),w=(await a("Route NEW claude boxes through a BYO API key? (y/N)",r.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");w&&n.write(`
|
|
151
151
|
BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
|
|
152
152
|
injected per box, stored 0600 in node.env, never sent to the plane.
|
|
153
153
|
\u2022 create/copy a key: https://console.anthropic.com/settings/keys
|
|
154
154
|
\u2022 set a monthly spend limit while you're there \u2014 the key is live.
|
|
155
155
|
|
|
156
|
-
`);let
|
|
157
|
-
`),o.close();let
|
|
156
|
+
`);let _=w?await a("ANTHROPIC_API_KEY (starts sk-ant-)",r.ANTHROPIC_API_KEY):"";w&&_&&!/^sk-ant-/.test(_)&&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 p={...st(),...r,BOSTRAT_PLANE_URL:d,BOSTRAT_PLANE_TOKEN:g,BOSTRAT_OWNER:m,BOSTRAT_NODE_NAME:l,BOSTRAT_NODE_ID:r.BOSTRAT_NODE_ID||l,BOSTRAT_REPOS_ROOT:T,BOSTRAT_STATE_REMOTE:x,BOSTRAT_CLAUDE_USE_API_KEY:w?"1":"0",ANTHROPIC_API_KEY:w?_:r.ANTHROPIC_API_KEY};ot(e,p,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
|
|
158
158
|
0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
|
|
159
159
|
Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
|
|
160
160
|
wrote ${e}
|
|
161
161
|
|
|
162
|
-
`);let
|
|
163
|
-
`));return
|
|
162
|
+
`);let C={...p,...process.env},I=await sn(C,{envFile:e}),v=an(I,R=>n.write(R+`
|
|
163
|
+
`));return v&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:v,results:I}}function lo({envFile:e=re()}={}){rt(e);let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n=Kr(t,[Vr],{cwd:ee,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 uo({agentDir:e=ee,nodeBin:t=process.execPath,envFile:n=re(),home:r=ce.homedir()}={}){let o=k.dirname(t),a=k.join(k.basename(Ze),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
|
|
164
164
|
# ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
|
|
165
165
|
[Unit]
|
|
166
166
|
Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
|
|
@@ -180,7 +180,7 @@ RestartSec=2
|
|
|
180
180
|
|
|
181
181
|
[Install]
|
|
182
182
|
WantedBy=default.target
|
|
183
|
-
`}function
|
|
183
|
+
`}function fo({agentDir:e=ee,nodeBin:t=process.execPath,home:n=ce.homedir()}={}){let r=k.dirname(t),o=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
|
|
184
184
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
185
185
|
<plist version="1.0">
|
|
186
186
|
<dict>
|
|
@@ -202,7 +202,7 @@ WantedBy=default.target
|
|
|
202
202
|
<key>StandardErrorPath</key><string>${o}/node.err.log</string>
|
|
203
203
|
</dict>
|
|
204
204
|
</plist>
|
|
205
|
-
`}function
|
|
205
|
+
`}function po(e=process.platform,t=ce.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 mo({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=ee}={}){let{kind:a,file:i}=po(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){a==="systemd"?(await X("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),H.rmSync(i,{force:!0}),await X("systemctl",["--user","daemon-reload"])):(await X("launchctl",["unload","-w",i]).catch(()=>{}),H.rmSync(i,{force:!0})),r(`removed ${i}`);return}H.mkdirSync(k.dirname(i),{recursive:!0}),a==="systemd"?(H.writeFileSync(i,uo()),await X("systemctl",["--user","daemon-reload"]),t&&await X("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${i}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(H.mkdirSync(k.join(ce.homedir(),"Library","Logs","bostrat"),{recursive:!0}),H.writeFileSync(i,fo()),t&&await X("launchctl",["load","-w",i]),r(`installed ${i}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function di(e=process.argv.slice(2)){let t=e[0],n=re();if(t==="--version"||t==="-v"||t==="version")return console.log(ie),0;if(t==="init")return(await co({envFile:n})).ok?0:1;if(t==="doctor"){let r={...we(n),...process.env};return an(await sn(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return lo({envFile:n}),null;if(t==="install-service")return await mo({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>($t(),Et));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:a}=await Promise.resolve().then(()=>(nn(),tn)),{detectInstallKind:i}=await Promise.resolve().then(()=>(qe(),Vt)),d=i(),g=e.indexOf("--to"),m=g>=0?String(e[g+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:ie,installKind:d,policy:a({kind:d}),status:await o()},null,2)),0;if(!m)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let l=await r({to:m,kind:d,reason:"cli"});return l.ok?(console.log(`\u2713 self-update ${l.from??"?"} \u2192 ${l.to} started (${l.kind}) \u2014 status: ${l.statusFile}; the service restarts when the install completes`),0):(console.error(`\u2717 not started: ${l.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
|
|
206
206
|
|
|
207
207
|
usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
|
|
208
208
|
|
|
@@ -211,4 +211,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
|
|
|
211
211
|
run start the node in the foreground (sources node.env)
|
|
212
212
|
install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
|
|
213
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{
|
|
214
|
+
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{co as init,mo as installService,fo as launchdPlist,di as main,an as printDoctor,lo as runAgent,sn as runDoctor,po as servicePaths,uo as systemdUnit};
|