bostrat-node 1.7.11 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/bostrat-loop +3 -3
- package/dist/cli.js +5 -5
- package/dist/index.js +196 -181
- package/package.json +1 -1
package/bin/bostrat-loop
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var h=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 $(){let o=await fetch(`${h}/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 u=o=>o?new Date(o).toISOString().slice(0,16).replace("T"," ")+"Z":"\u2014",w=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",y=o=>{let t=(o.runs||[])[o.runs.length-1];return t?`last ${u(t.firedAt)} \u2014 ${w(t)}`:"never ran"},p=process.argv.slice(2),c=p.shift();if(c==="ls")try{let o=await $();o.length||console.log("no loops defined");for(let t of o){let e=t.enabled?"\u25CF":"\u25CB",r=t.enabled?`next ${u(t.nextFireAt)}`:"disabled";console.log(`${e} ${t.name} [${t.schedule} UTC] ${r} ${y(t)} (loop:${t.id})`)}}catch(o){n(o.message)}else if(c==="show"){let o=p.find(t=>!t.startsWith("--"));o||n("usage: bostrat-loop show <name|id>");try{let e=(await $()).find(a=>a.id===o||a.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 ${u(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
|
|
4
|
+
`).map(a=>` ${a}`).join(`
|
|
5
|
+
`)}`);let i=(e.runs||[]).slice(-5);console.log(` recent runs:${i.length?"":" none"}`);for(let a of i)console.log(` ${u(a.firedAt)} ${w(a)}${a.trackId?` (track ${a.trackId})`:""}`);console.log("Loops are operator-managed (Loops tab). `bostrat-loop propose-update <loop> <patch.json>` / `propose-delete <loop> --reason \u2026` post a review card; `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(c==="propose"){let o=p.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 i=await fetch(`${h}/api/loops/propose`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({cwd:process.cwd(),plan:r})}),a=await i.json().catch(()=>({}));i.ok||n(a.error||`HTTP ${i.status}`);let s=a.proposal;console.log(`[bostrat-loop] proposed "${s.name}" [${s.schedule} UTC] on ${s.assignment?.provider||"claude"} \u2014 review card posted to the Track chat.`),console.log(` repo: ${s.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(c==="propose-update"||c==="propose-delete"){let o=p.indexOf("--reason"),t=p.find(s=>s.startsWith("--reason=")),e=t?t.slice(9):o>=0?p[o+1]??null:null,r=p.filter((s,l)=>!s.startsWith("--")&&!(o>=0&&l===o+1)),i=r[0];i||n(`usage: bostrat-loop ${c} <loop-id|name> ${c==="propose-update"?"[patch.json | -]":'--reason "<why>"'}`);let a=async()=>{let s=[];for await(let l of process.stdin)s.push(l);return Buffer.concat(s).toString("utf8")};try{let s={cwd:process.cwd(),loop:i};if(c==="propose-update"){let f=r[1],m=!f||f==="-"?await a():await(await import("node:fs/promises")).readFile(f,"utf8");try{s.patch=JSON.parse(m)}catch{n("patch must be JSON (a file path, or piped on stdin) naming only the fields to change \u2014 see the `bostrat-loop` header")}}else s.reason=e,s.reason||n('a delete proposal needs a reason: bostrat-loop propose-delete <loop> --reason "<why this loop should go>"');let l=await fetch(`${h}/api/loops/${c}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)}),g=await l.json().catch(()=>({}));l.ok||n(g.error||`HTTP ${l.status}`);let d=g.proposal;c==="propose-update"?(console.log(`[bostrat-loop] proposed changes to "${d.name}" (${d.changed.join(", ")}) \u2014 review card posted to the Track chat.`),console.log(" The card shows the change as a diff; nothing is applied until the operator taps Apply under their own session.")):(console.log(`[bostrat-loop] proposed deleting "${d.name}" \u2014 review card posted to the Track chat (Delete / Pause / Keep).`),console.log(" Nothing is removed until the operator taps; the loop's run Track and history stay either way.")),d.selfEdit&&console.log(" Note: this Track IS the loop's own run Track \u2014 the card flags the proposal as a self-edit."),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(s){n(s.message)}}else if(c==="report"){let o=p[0],t=p[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(`${h}/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|propose-update|propose-delete|report> \u2026 (the propose-* commands post a review card \u2014 they change nothing; loops are otherwise operator-managed from the Loops tab)");
|
package/dist/cli.js
CHANGED
|
@@ -2,8 +2,8 @@ var Tn=Object.defineProperty;var S=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(
|
|
|
2
2
|
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let i=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!i)continue;let a=i[2].trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n[i[1]]=a}return n}function rt(e,t=process.env){let n=ye(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
3
|
`).map(o=>o?`# ${o}`:"#"));for(let[o,i]of Object.entries(t))i==null||i===""||r.push(`${o}=${i}`);we.mkdirSync(Ne.dirname(e),{recursive:!0}),we.writeFileSync(e,r.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`,{mode:384}),we.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 it=S(()=>{Me()});var at=S(()=>{});var ct=S(()=>{});import De from"node:path";import{execFile as Sn}from"node:child_process";import{promisify as vn}from"node:util";var Po,lt,An,Mo,Do,ut=S(()=>{Po=vn(Sn),lt=process.env.HOME||"/home/globo",An=De.join(process.env.BOSTRAT_STATE_DIR||De.join(lt,".bostrat"),"repos"),Mo=[...(process.env.BOSTRAT_REPOS_ROOT||De.join(lt,"Documents")).split(","),An].map(e=>e.trim()).filter(Boolean),Do=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});import dt from"node:path";import xn from"node:os";import{execFile as kn}from"node:child_process";import{promisify as On}from"node:util";var Ko,
|
|
6
|
-
`))if(a.trim())try{i.push(JSON.parse(a))}catch{}return i}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 jn 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||jn.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,wt=S(()=>{je();ht();bs=60*6e4});var yt=S(()=>{wt()});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(i){return i?.killed||i?.signal?bt:i?.code===1||i?.code===127?Le:bt}}var Yn,Qs,Tt,ei,ti,ni,St,Le,bt,Vn,Te,ri,oi,si,ii,ai,Be=S(()=>{it();at();ct();mt();yt();Fe();Me();Yn=Wn(Kn),Qs=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";Tt=typeof process.getuid=="function"?process.getuid():0,ei=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}),ti=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",ni=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"},ri=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,oi=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,si=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,ii=Number(process.env.BOSTRAT_BOX_COLS)||120,ai=Number(process.env.BOSTRAT_BOX_ROWS)||40});var
|
|
5
|
+
`,{mode:384}),we.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 it=S(()=>{Me()});var at=S(()=>{});var ct=S(()=>{});import De from"node:path";import{execFile as Sn}from"node:child_process";import{promisify as vn}from"node:util";var Po,lt,An,Mo,Do,ut=S(()=>{Po=vn(Sn),lt=process.env.HOME||"/home/globo",An=De.join(process.env.BOSTRAT_STATE_DIR||De.join(lt,".bostrat"),"repos"),Mo=[...(process.env.BOSTRAT_REPOS_ROOT||De.join(lt,"Documents")).split(","),An].map(e=>e.trim()).filter(Boolean),Do=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});import dt from"node:path";import xn from"node:os";import{execFile as kn}from"node:child_process";import{promisify as On}from"node:util";var Ko,$n,Wo,zo,Yo,je=S(()=>{ut();Ko=On(kn),$n=process.env.BOSTRAT_STATE_DIR||dt.join(process.env.HOME||xn.tmpdir(),".bostrat"),Wo=dt.join($n,"repos"),zo=5*6e4,Yo=10*6e4});var ft=S(()=>{je()});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 i=[];for(let a of o.split(`
|
|
6
|
+
`))if(a.trim())try{i.push(JSON.parse(a))}catch{}return i}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 jn 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||jn.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,wt=S(()=>{je();ht();bs=60*6e4});var yt=S(()=>{wt()});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(i){return i?.killed||i?.signal?bt:i?.code===1||i?.code===127?Le:bt}}var Yn,Qs,Tt,ei,ti,ni,St,Le,bt,Vn,Te,ri,oi,si,ii,ai,Be=S(()=>{it();at();ct();mt();yt();Fe();Me();Yn=Wn(Kn),Qs=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";Tt=typeof process.getuid=="function"?process.getuid():0,ei=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}),ti=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",ni=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"},ri=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,oi=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,si=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,ii=Number(process.env.BOSTRAT_BOX_COLS)||120,ai=Number(process.env.BOSTRAT_BOX_ROWS)||40});var $t={};Re($t,{NODE_IMAGE:()=>Ke,commandPlan:()=>xt,flyToml:()=>At,flyWizard:()=>rr,parseFlyFlags:()=>kt,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 At({app:e,region:t,nodeName:n=e,planeUrl:r=vt,image:o=Ke}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
|
|
7
7
|
# Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
|
|
8
8
|
# No [http_service] and none should be added: the node dials OUT to the plane;
|
|
9
9
|
# nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
|
|
@@ -76,7 +76,7 @@ Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u201
|
|
|
76
76
|
redeploy: fly deploy ${k} -c ${Q.join(k,"fly.toml")} -a ${l} --ha=false
|
|
77
77
|
Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
|
|
78
78
|
boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
|
|
79
|
-
`),T(0)}var vt,tr,Ke,be,$t=S(()=>{vt="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 i=Zn("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(a,d,T)=>a?o(Object.assign(a,{stdout:d,stderr:T})):r({stdout:d,stderr:T}));t!=null&&i.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 ir(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,wi,yi,Nt=S(()=>{or={"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,verifiedAt:"2026-08-17",note:"GA rates; verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-08-17",note:"$2/$10 is the standard price (intro pricing made permanent; the 2026-09-01 $3/$15 increase was cancelled) \u2014 verified 2026-08-17 against platform.claude.com/docs/en/about-claude/pricing."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-03, re-verified 2026-08-17 (developers.openai.com pricing); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:null,input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-terra":[{from:null,to:"2026-08-16",input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:2,output:12,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:"2026-08-16",input:1,output:6,cacheWrite:1.25,cacheRead:.1,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:.2,output:1.2,cacheWrite:.25,cacheRead:.02,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}]},sr=/^\d{4}-\d{2}-\d{2}$/;wi=ir(or),yi=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var It=S(()=>{Nt()});import Pt from"node:fs/promises";import jt from"node:path";import ar 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 i of["weeklyUsd","monthlyUsd"]){let a=r?.[i];if(a==null||a==="")continue;let d=Number(a);if(!Number.isFinite(d)||d<=0)throw new Error(`${n}.${i} must be a positive number or null`);o[i]=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:Dt(o?.weekly||0),monthlyUsd:Dt(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,Dt,Kt=S(()=>{ge();It();Ct=process.env.BOSTRAT_STATE_DIR||jt.join(process.env.HOME||ar.tmpdir(),".bostrat"),cr=()=>jt.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;Dt=e=>Math.round(e*1e4)/1e4});var Vt={};Re(Vt,{detectInstallKind:()=>ie,detectProviderAuth:()=>qt,startPlaneLink:()=>kr,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 ve from"node:os";import{createRequire as wr}from"node:module";import Ye from"ws";function ie({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 i=(n[o]||0)-(r[o]||0);if(i)return i<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||ve.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 kr({url:e,token:t,nodeId:n=ve.hostname(),name:r=ve.hostname(),listTracks:o,detectAgents:i=null,onTracksTransferred:a=null,sampleMetrics:d=null,metricsMs:T=Ar,onUpdateAvailable:m=null,onUpdatePolicy:l=null,onHelloRefused:b=null,updatePolicy:v=null,installKind:y=ie(),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 F=_.replace(/^http/,"ws"),M=new Set,k=new Map,A=new Map,g=V.join(yr,"plane-link","cursor.json"),O={},z={},B=new Map,L=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{O=JSON.parse(await ze.readFile(g,"utf8"))}catch{O={}}}function ln(){Ee=!0,!ne&&(ne=setTimeout(async()=>{if(ne=null,!!Ee){Ee=!1;try{await ze.mkdir(V.dirname(g),{recursive:!0}),await ze.writeFile(g,JSON.stringify(O))}catch(f){p.error("[plane-link] cursor flush failed:",f?.message||f)}}},_r),ne.unref?.())}function E(f){return!L||L.readyState!==Ye.OPEN?!1:(L.send(JSON.stringify(f)),!0)}function $e(f){let u=Date.now();for(let{trackId:s,event:c}of f){let h=B.get(c.id);B.set(c.id,{trackId:s,seq:c.seq,event:c,sentAt:u,tries:(h?.tries??0)+1})}return E({v:$,ch:"events",type:"append",events:f})}function un(f){let u=null;for(let s of B.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>(O[f]??0)&&(O[f]=c,ln())}function fn(){if(!Z)return;let f=Date.now(),u=[...B.values()].filter(s=>s.event&&f-s.sentAt>=vr);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&&E({v:$,ch:"ctl",type:"metrics",metrics:f})}function pn(){d&&(q&&clearInterval(q),et(),q=setInterval(et,T),q.unref?.())}async function mn(){let f;try{f=await o()}catch(u){p.error("[plane-link] backfill listTracks failed:",u?.message||u);return}E({v:$,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=O[u.id]??0,h=s.filter(w=>w.seq>c&&typeof w.id=="string");for(let w=0;w<h.length;w+=Se){let N=h.slice(w,w+Se).map(D=>({trackId:u.id,event:D}));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:w}=f,N=Object.fromEntries(Object.entries(h).filter(([,K])=>K!=null)),D=new AbortController;de.set(u,D);try{if(f.host){await wn(f,N,D);return}let K=await fetch(_+c,{method:s,headers:N,body:w?Buffer.from(w,"base64"):void 0,signal:D.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"),E({v:$,ch:"control",type:"http_head",reqId:u,status:K.status,headers:G}),K.body){for await(let j of K.body)if(!E({v:$,ch:"control",type:"http_data",reqId:u,data:Buffer.from(j).toString("base64")}))break}E({v:$,ch:"control",type:"http_end",reqId:u,error:null})}finally{de.delete(u)}}function wn(f,u,s){let{reqId:c,method:h,path:w,body:N}=f,D=new URL(_);return new Promise(K=>{let G=hr.request({host:D.hostname,port:D.port,method:h,path:w,headers:{...u,host:f.host},signal:s.signal},j=>{let{connection:ho,"keep-alive":wo,"transfer-encoding":yo,upgrade:go,...yn}=j.headers;E({v:$,ch:"control",type:"http_head",reqId:c,status:j.statusCode||502,headers:yn}),j.on("data",gn=>{E({v:$,ch:"control",type:"http_data",reqId:c,data:Buffer.from(gn).toString("base64")})||j.destroy()}),j.on("end",()=>{E({v:$,ch:"control",type:"http_end",reqId:c,error:null}),K()}),j.on("error",()=>{E({v:$,ch:"control",type:"http_end",reqId:c,error:"view upstream error"}),K()})});G.on("error",j=>{E({v:$,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;L=new Ye(e,{headers:{authorization:`Bearer ${t}`}}),L.on("open",async()=>{let u=null;try{u=await i?.()||null}catch{u=null}E({v:$,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:U,installKind:y,...typeof v=="function"?{updatePolicy:v()}:v?{updatePolicy:v}:{},providers:qt(),...u?{agents:u}:{}})}),L.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&&U&&se(U,s.minNodeVersion)&&p.error(`[plane-link] this node is bostrat-node ${U}; the plane asks for \u2265${s.minNodeVersion} \u2014 update with: ${he(y)}`);try{l?.(typeof s.updatePolicy=="string"?s.updatePolicy:null)}catch{}let c=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(c&&U&&se(U,c)&&!M.has(c)){M.add(c),p.log(`[plane-link] bostrat-node ${c} is available (this node runs ${U}) \u2014 ${he(y)}`);try{m?.({current:U,latest:c,min:s.minNodeVersion??null,installKind:y,required:!!(s.minNodeVersion&&se(U,s.minNodeVersion))})}catch(h){p.error(`[plane-link] update notice failed: ${h?.message||h}`)}}Y&&clearInterval(Y),Y=setInterval(()=>{E({v:$,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 ${U??"?"} is below its minimum ${c??"?"} \u2014 ${s.fix||he(y)}`),le=zt,ue=0;try{b?.({current:U,min:c,latest:h,fix:s.fix||he(y),installKind:y})}catch(w){p.error(`[plane-link] refusal handler failed: ${w?.message||w}`)}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(()=>a?.(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 w=B.get(h);w&&(B.delete(h),(z[w.trackId]??0)<w.seq&&(z[w.trackId]=w.seq),c.add(w.trackId))}for(let h of c)dn(h);return}if(s.ch==="control"&&s.type==="http_open"){hn(s).catch(c=>E({v:$,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(F+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 w=A.get(s.streamId)||[];A.delete(s.streamId);for(let{buf:N,bin:D}of w)c.send(N,{binary:D})}),c.on("message",(w,N)=>{let D=N?w:Buffer.from(String(w));E({v:$,ch:"attach",type:"data",streamId:s.streamId,data:D.toString("base64"),...N?{bin:!0}:{}})});let h=()=>{A.delete(s.streamId),k.delete(s.streamId)&&E({v:$,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"),w=s.bin===!0,N=A.get(s.streamId);N?N.push({buf:h,bin:w}):c.send(h,{binary:w});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=()=>{Z&&p.log("[plane-link] disconnected from plane"),Z=!1,Y&&(clearInterval(Y),Y=null),q&&(clearInterval(q),q=null),B.clear(),z={};for(let c of k.values())c.close();k.clear(),A.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))};L.on("close",f),L.on("error",u=>{let s=/Unexpected server response: (\d+)/.exec(u?.message||"")?.[1];(s==="401"||s==="403")&&Date.now()-Qe>=xr&&(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),E({v:$,ch:"ctl",type:"bye",reason:"shutdown"}),L?.close()},status:()=>({connected:Z,nodeId:n,cursor:{...O},inflight:B.size})}}var U,yr,$,Wt,zt,gr,Tr,br,Se,_r,Sr,vr,Ar,xr,qe=S(()=>{ge();Kt();Pe();U=(()=>{try{return wr(import.meta.url)("../package.json").version||null}catch{return null}})(),yr=process.env.BOSTRAT_STATE_DIR||V.join(process.env.HOME||ve.tmpdir(),".bostrat");$=1,Wt=1e3,zt=3e4,gr=6e4,Tr=1500,br=500,Se=100,_r=2e3,Sr=25e3,vr=6e4,Ar=6e4,xr=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 Ki,Wi,zi,Jt=S(()=>{Fe();Ki=Er(Or),Wi=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,zi=Promise.resolve()});var tn={};Re(tn,{ACTIONABLE_KINDS:()=>ke,SELF_UPDATE_DIR:()=>Ve,createAutoUpdater:()=>Ur,inFlight:()=>Je,readStatus:()=>Ge,selfUpdatePlan:()=>Qt,settleSelfUpdate:()=>Lr,startSelfUpdate:()=>en,underService:()=>Zt,updatePolicy:()=>Dr});import Xt from"node:fs";import J from"node:fs/promises";import $r from"node:os";import R from"node:path";import{spawn as Rr}from"node:child_process";import{createRequire as Nr}from"node:module";function Dr({kind:e=ie(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:ke.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=Ae,statusFile:r=xe,logFile:o=R.join(Ve,"last.log"),port:i=Number(process.env.PORT)||3362,npmPrefix:a=null,serviceName:d=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:T=typeof process.getuid=="function"?process.getuid():0,liveDir:m=process.env.BOSTRAT_LIVE_CHECKOUT||R.resolve(R.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:l=Date.now()}={}){if(!ke.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 b=(F,M="")=>`write_status ${I(F)} ${M}`,v=process.platform==="darwin"?`launchctl kickstart -k gui/${T}/${d}`:`systemctl --user restart ${I(d)}`,y=`
|
|
79
|
+
`),T(0)}var vt,tr,Ke,be,Et=S(()=>{vt="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 i=Zn("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(a,d,T)=>a?o(Object.assign(a,{stdout:d,stderr:T})):r({stdout:d,stderr:T}));t!=null&&i.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 ir(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,wi,yi,Nt=S(()=>{or={"claude-opus-5":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"GA rates; verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-opus-4-8":[{from:null,to:null,input:5,output:25,cacheWrite:10,cacheRead:.5,fast:{input:10,output:50,cacheWrite:20,cacheRead:1},verifiedAt:"2026-08-20",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-08-17",note:"$2/$10 is the standard price (intro pricing made permanent; the 2026-09-01 $3/$15 increase was cancelled) \u2014 verified 2026-08-17 against platform.claude.com/docs/en/about-claude/pricing."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-08-17",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-03, re-verified 2026-08-17 (developers.openai.com pricing); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:null,input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-terra":[{from:null,to:"2026-08-16",input:2.5,output:15,cacheWrite:3.125,cacheRead:.25,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:2,output:12,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-5.6-luna":[{from:null,to:"2026-08-16",input:1,output:6,cacheWrite:1.25,cacheRead:.1,verifiedAt:"2026-07-18",note:"as verified 2026-07-18; superseded by the 2026-08-17 sweep (0 corpus rows in this window)."},{from:"2026-08-17",to:null,input:.2,output:1.2,cacheWrite:.25,cacheRead:.02,verifiedAt:"2026-08-17",note:"verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}]},sr=/^\d{4}-\d{2}-\d{2}$/;wi=ir(or),yi=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var It=S(()=>{Nt()});import Pt from"node:fs/promises";import jt from"node:path";import ar 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 i of["weeklyUsd","monthlyUsd"]){let a=r?.[i];if(a==null||a==="")continue;let d=Number(a);if(!Number.isFinite(d)||d<=0)throw new Error(`${n}.${i} must be a positive number or null`);o[i]=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:Dt(o?.weekly||0),monthlyUsd:Dt(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,Dt,Kt=S(()=>{ge();It();Ct=process.env.BOSTRAT_STATE_DIR||jt.join(process.env.HOME||ar.tmpdir(),".bostrat"),cr=()=>jt.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;Dt=e=>Math.round(e*1e4)/1e4});var Vt={};Re(Vt,{detectInstallKind:()=>ie,detectProviderAuth:()=>qt,startPlaneLink:()=>kr,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 ve from"node:os";import{createRequire as wr}from"node:module";import Ye from"ws";function ie({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 i=(n[o]||0)-(r[o]||0);if(i)return i<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||ve.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 kr({url:e,token:t,nodeId:n=ve.hostname(),name:r=ve.hostname(),listTracks:o,detectAgents:i=null,onTracksTransferred:a=null,sampleMetrics:d=null,metricsMs:T=Ar,onUpdateAvailable:m=null,onUpdatePolicy:l=null,onHelloRefused:b=null,updatePolicy:v=null,installKind:y=ie(),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 F=_.replace(/^http/,"ws"),M=new Set,k=new Map,A=new Map,g=V.join(yr,"plane-link","cursor.json"),O={},z={},B=new Map,L=null,Z=!1,Oe=!1,le=Wt,ue=null,te=null,ne=null,Y=null,q=null,$e=!1,Qe=0;async function cn(){try{O=JSON.parse(await ze.readFile(g,"utf8"))}catch{O={}}}function ln(){$e=!0,!ne&&(ne=setTimeout(async()=>{if(ne=null,!!$e){$e=!1;try{await ze.mkdir(V.dirname(g),{recursive:!0}),await ze.writeFile(g,JSON.stringify(O))}catch(f){p.error("[plane-link] cursor flush failed:",f?.message||f)}}},_r),ne.unref?.())}function $(f){return!L||L.readyState!==Ye.OPEN?!1:(L.send(JSON.stringify(f)),!0)}function Ee(f){let u=Date.now();for(let{trackId:s,event:c}of f){let h=B.get(c.id);B.set(c.id,{trackId:s,seq:c.seq,event:c,sentAt:u,tries:(h?.tries??0)+1})}return $({v:E,ch:"events",type:"append",events:f})}function un(f){let u=null;for(let s of B.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>(O[f]??0)&&(O[f]=c,ln())}function fn(){if(!Z)return;let f=Date.now(),u=[...B.values()].filter(s=>s.event&&f-s.sentAt>=vr);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(!Ee(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&&$({v:E,ch:"ctl",type:"metrics",metrics:f})}function pn(){d&&(q&&clearInterval(q),et(),q=setInterval(et,T),q.unref?.())}async function mn(){let f;try{f=await o()}catch(u){p.error("[plane-link] backfill listTracks failed:",u?.message||u);return}$({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=O[u.id]??0,h=s.filter(w=>w.seq>c&&typeof w.id=="string");for(let w=0;w<h.length;w+=Se){let N=h.slice(w,w+Se).map(D=>({trackId:u.id,event:D}));if(!Ee(N))return}}}function tt(f){!Z||!f?.trackId||typeof f.id!="string"||Ee([{trackId:f.trackId,event:f}])}let de=new Map;async function hn(f){let{reqId:u,method:s,path:c,headers:h={},body:w}=f,N=Object.fromEntries(Object.entries(h).filter(([,K])=>K!=null)),D=new AbortController;de.set(u,D);try{if(f.host){await wn(f,N,D);return}let K=await fetch(_+c,{method:s,headers:N,body:w?Buffer.from(w,"base64"):void 0,signal:D.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"),$({v:E,ch:"control",type:"http_head",reqId:u,status:K.status,headers:G}),K.body){for await(let j of K.body)if(!$({v:E,ch:"control",type:"http_data",reqId:u,data:Buffer.from(j).toString("base64")}))break}$({v:E,ch:"control",type:"http_end",reqId:u,error:null})}finally{de.delete(u)}}function wn(f,u,s){let{reqId:c,method:h,path:w,body:N}=f,D=new URL(_);return new Promise(K=>{let G=hr.request({host:D.hostname,port:D.port,method:h,path:w,headers:{...u,host:f.host},signal:s.signal},j=>{let{connection:ho,"keep-alive":wo,"transfer-encoding":yo,upgrade:go,...yn}=j.headers;$({v:E,ch:"control",type:"http_head",reqId:c,status:j.statusCode||502,headers:yn}),j.on("data",gn=>{$({v:E,ch:"control",type:"http_data",reqId:c,data:Buffer.from(gn).toString("base64")})||j.destroy()}),j.on("end",()=>{$({v:E,ch:"control",type:"http_end",reqId:c,error:null}),K()}),j.on("error",()=>{$({v:E,ch:"control",type:"http_end",reqId:c,error:"view upstream error"}),K()})});G.on("error",j=>{$({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;L=new Ye(e,{headers:{authorization:`Bearer ${t}`}}),L.on("open",async()=>{let u=null;try{u=await i?.()||null}catch{u=null}$({v:E,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:U,installKind:y,...typeof v=="function"?{updatePolicy:v()}:v?{updatePolicy:v}:{},providers:qt(),...u?{agents:u}:{}})}),L.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&&U&&se(U,s.minNodeVersion)&&p.error(`[plane-link] this node is bostrat-node ${U}; the plane asks for \u2265${s.minNodeVersion} \u2014 update with: ${he(y)}`);try{l?.(typeof s.updatePolicy=="string"?s.updatePolicy:null)}catch{}let c=typeof s.latestNodeVersion=="string"?s.latestNodeVersion:null;if(c&&U&&se(U,c)&&!M.has(c)){M.add(c),p.log(`[plane-link] bostrat-node ${c} is available (this node runs ${U}) \u2014 ${he(y)}`);try{m?.({current:U,latest:c,min:s.minNodeVersion??null,installKind:y,required:!!(s.minNodeVersion&&se(U,s.minNodeVersion))})}catch(h){p.error(`[plane-link] update notice failed: ${h?.message||h}`)}}Y&&clearInterval(Y),Y=setInterval(()=>{$({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 ${U??"?"} is below its minimum ${c??"?"} \u2014 ${s.fix||he(y)}`),le=zt,ue=0;try{b?.({current:U,min:c,latest:h,fix:s.fix||he(y),installKind:y})}catch(w){p.error(`[plane-link] refusal handler failed: ${w?.message||w}`)}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(()=>a?.(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 w=B.get(h);w&&(B.delete(h),(z[w.trackId]??0)<w.seq&&(z[w.trackId]=w.seq),c.add(w.trackId))}for(let h of c)dn(h);return}if(s.ch==="control"&&s.type==="http_open"){hn(s).catch(c=>$({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(F+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 w=A.get(s.streamId)||[];A.delete(s.streamId);for(let{buf:N,bin:D}of w)c.send(N,{binary:D})}),c.on("message",(w,N)=>{let D=N?w:Buffer.from(String(w));$({v:E,ch:"attach",type:"data",streamId:s.streamId,data:D.toString("base64"),...N?{bin:!0}:{}})});let h=()=>{A.delete(s.streamId),k.delete(s.streamId)&&$({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"),w=s.bin===!0,N=A.get(s.streamId);N?N.push({buf:h,bin:w}):c.send(h,{binary:w});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=()=>{Z&&p.log("[plane-link] disconnected from plane"),Z=!1,Y&&(clearInterval(Y),Y=null),q&&(clearInterval(q),q=null),B.clear(),z={};for(let c of k.values())c.close();k.clear(),A.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))};L.on("close",f),L.on("error",u=>{let s=/Unexpected server response: (\d+)/.exec(u?.message||"")?.[1];(s==="401"||s==="403")&&Date.now()-Qe>=xr&&(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),$({v:E,ch:"ctl",type:"bye",reason:"shutdown"}),L?.close()},status:()=>({connected:Z,nodeId:n,cursor:{...O},inflight:B.size})}}var U,yr,E,Wt,zt,gr,Tr,br,Se,_r,Sr,vr,Ar,xr,qe=S(()=>{ge();Kt();Pe();U=(()=>{try{return wr(import.meta.url)("../package.json").version||null}catch{return null}})(),yr=process.env.BOSTRAT_STATE_DIR||V.join(process.env.HOME||ve.tmpdir(),".bostrat");E=1,Wt=1e3,zt=3e4,gr=6e4,Tr=1500,br=500,Se=100,_r=2e3,Sr=25e3,vr=6e4,Ar=6e4,xr=6e4});import{execFile as Or}from"node:child_process";import{promisify as $r}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 Ki,Wi,zi,Jt=S(()=>{Fe();Ki=$r(Or),Wi=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,zi=Promise.resolve()});var tn={};Re(tn,{ACTIONABLE_KINDS:()=>ke,SELF_UPDATE_DIR:()=>Ve,createAutoUpdater:()=>Ur,inFlight:()=>Je,readStatus:()=>Ge,selfUpdatePlan:()=>Qt,settleSelfUpdate:()=>Lr,startSelfUpdate:()=>en,underService:()=>Zt,updatePolicy:()=>Dr});import Xt from"node:fs";import J from"node:fs/promises";import Er from"node:os";import R from"node:path";import{spawn as Rr}from"node:child_process";import{createRequire as Nr}from"node:module";function Dr({kind:e=ie(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:ke.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=Ae,statusFile:r=xe,logFile:o=R.join(Ve,"last.log"),port:i=Number(process.env.PORT)||3362,npmPrefix:a=null,serviceName:d=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:T=typeof process.getuid=="function"?process.getuid():0,liveDir:m=process.env.BOSTRAT_LIVE_CHECKOUT||R.resolve(R.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:l=Date.now()}={}){if(!ke.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 b=(F,M="")=>`write_status ${I(F)} ${M}`,v=process.platform==="darwin"?`launchctl kickstart -k gui/${T}/${d}`:`systemctl --user restart ${I(d)}`,y=`
|
|
80
80
|
health() {
|
|
81
81
|
for i in $(seq 1 45); do
|
|
82
82
|
sleep 1
|
|
@@ -141,7 +141,7 @@ if [ -n "$FROM" ] && ${p("$FROM")}; then
|
|
|
141
141
|
fi
|
|
142
142
|
${b("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
|
|
143
143
|
exit 1
|
|
144
|
-
`}async function Ge(e=xe){try{return JSON.parse(await J.readFile(e,"utf8"))}catch{return null}}async function en({to:e,from:t=Ae,kind:n=ie(),reason:r="manual",statusFile:o=xe,spawnImpl:i=Rr,now:a=Date.now,npmPrefix:d=void 0,log:T=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!ke.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(R.dirname(o),{recursive:!0});let l=d!==void 0?d:n==="npm-global"?Gt(await Cr())||R.resolve(R.dirname(process.execPath),".."):null,b=Qt({kind:n,to:e,from:t,statusFile:o,npmPrefix:l,startedAt:a()}),v=R.join(R.dirname(o),`update-${e}.sh`),y=R.join(R.dirname(o),"last.log");await J.writeFile(v,b,{mode:448}),await J.writeFile(o,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,startedAt:a(),updatedAt:a()}));let _=Xt.existsSync("/run/systemd/system")&&await Fr("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",v]]:["setsid",["-f","bash","-c",`exec bash ${I(v)} >> ${I(y)} 2>&1`]];try{i(_[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:a(),updatedAt:a(),error:`could not spawn updater: ${p?.message||p}`})),{ok:!1,reason:`could not spawn updater: ${p?.message||p}`}}return T.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${o}`),{ok:!0,to:e,from:t,kind:n,scriptFile:v,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(R.delimiter))try{return await J.access(R.join(t,e),Xt.constants.X_OK),!0}catch{}return!1}async function Lr({statusFile:e=xe,current:t=Ae,now:n=Date.now,staleMs:r=Br}={}){let o=await Ge(e);if(!o)return null;let i=a=>J.writeFile(e,JSON.stringify(a)).catch(()=>{});if(Je(o)){if(t&&o.to===t){let a={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await i(a),a}if(n()-Number(o.updatedAt||o.startedAt||0)>r){let a={...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 i(a),a}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let a={...o,announced:!0};return await i(a),a}return null}function Ur({isBusy:e,start:t=en,onStuck:n=null,onStarted:r=null,tickMs:o=Mr,stuckMs:i=Pr,now:a=Date.now,setIntervalImpl:d=setInterval,clearIntervalImpl:T=clearInterval,log:m=console}={}){let l=null,b=()=>{l?.timer&&T(l.timer),l=null},v=async()=>{if(!l)return;let y=!0;try{y=await e()!==!1}catch{y=!0}if(y){if(!l.stuckFired&&a()-l.since>=i){l.stuckFired=!0;try{await n?.({to:l.to,from:l.from,since:l.since})}catch{}}return}let _=l;b();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:y,from:_=Ae,kind:p=ie()}){return l?.to===y?!1:(b(),l={to:y,from:_,kind:p,since:a(),stuckFired:!1,timer:d(v,o)},l.timer.unref?.(),!0)},tick:v,cancel:b,get armed(){return l?{to:l.to,from:l.from,kind:l.kind,since:l.since}:null}}}var Ae,Ir,Ve,xe,Pr,Mr,ke,I,jr,Je,Br,nn=S(()=>{qe();Jt();Ae=(()=>{try{return Nr(import.meta.url)("../package.json").version||null}catch{return null}})(),Ir=process.env.BOSTRAT_STATE_DIR||R.join(process.env.HOME||$r.tmpdir(),".bostrat"),Ve=R.join(Ir,"self-update"),xe=R.join(Ve,"status.json"),Pr=1440*6e4,Mr=6e4,ke=new Set(["npm-global","git-checkout"]);I=e=>`'${String(e).replace(/'/g,"'\\''")}'`;jr=new Set(["updating","restarting","rolling-back"]),Je=e=>!!(e&&jr.has(e.status));Br=45*6e4});Pe();Be();import H from"node:fs";import x 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 i=(n[o]||0)-(r[o]||0);if(i)return i<0}return!1},X=Wr(Hr),Ze=x.dirname(qr(import.meta.url)),ee=x.resolve(Ze,".."),Vr=x.join(Ze,"index.js"),Gr="wss://plane.bostrat.ai/v1/node",ae=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}),C=(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}`):C("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 C("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?C(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(C("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(x.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}),i=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(i),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(x.join(ee,"package.json")),r=x.join(x.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 C("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"?C: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?C("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(i=>{let a=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),d=m=>{clearTimeout(T);try{a.close()}catch{}i(m)},T=setTimeout(()=>d(C("plane link",`no hello_ok within 5s from ${o}`,"check the URL, the token, and the plane's IP gate")),5e3);a.on("open",()=>a.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${Yr().slice(0,8)}`,ephemeral:!0}))),a.on("message",m=>{try{let l=JSON.parse(m);l.type==="hello_ok"?l.minNodeVersion&&rn(ae,l.minNodeVersion)?d(C("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${l.minNodeVersion} \u2014 this node is ${ae}; the real link is refused until it updates`,`bostrat-node self-update --to ${l.latestNodeVersion||l.minNodeVersion}`)):l.latestNodeVersion&&rn(ae,l.latestNodeVersion)?d(W("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${l.latestNodeVersion} is available (this node: ${ae})`,`bostrat-node self-update --to ${l.latestNodeVersion}`)):d(P("plane link",`hello_ok in ${Date.now()-r}ms (${o})`)):l.type==="error"&&d(C("plane link",`plane said: ${l.code} ${l.message||""}`,"check the token"))}catch{}}),a.on("error",m=>d(C("plane link",`${m?.message||m}`,"check the URL, the token, and the plane's IP gate")))})}function io(){let e;try{e=JSON.parse(H.readFileSync(x.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 C("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 ao(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(io()),n.push(ao(e)),n}function an(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let i of e)t(`${n[i.level]} ${i.name}: ${i.detail}`),i.fix&&i.level!=="pass"&&t(` fix: ${i.fix}`);let r=e.filter(i=>i.level==="fail").length,o=e.filter(i=>i.level==="warn").length;return t(r?`
|
|
144
|
+
`}async function Ge(e=xe){try{return JSON.parse(await J.readFile(e,"utf8"))}catch{return null}}async function en({to:e,from:t=Ae,kind:n=ie(),reason:r="manual",statusFile:o=xe,spawnImpl:i=Rr,now:a=Date.now,npmPrefix:d=void 0,log:T=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!ke.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(R.dirname(o),{recursive:!0});let l=d!==void 0?d:n==="npm-global"?Gt(await Cr())||R.resolve(R.dirname(process.execPath),".."):null,b=Qt({kind:n,to:e,from:t,statusFile:o,npmPrefix:l,startedAt:a()}),v=R.join(R.dirname(o),`update-${e}.sh`),y=R.join(R.dirname(o),"last.log");await J.writeFile(v,b,{mode:448}),await J.writeFile(o,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,startedAt:a(),updatedAt:a()}));let _=Xt.existsSync("/run/systemd/system")&&await Fr("systemd-run")?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",v]]:["setsid",["-f","bash","-c",`exec bash ${I(v)} >> ${I(y)} 2>&1`]];try{i(_[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:a(),updatedAt:a(),error:`could not spawn updater: ${p?.message||p}`})),{ok:!1,reason:`could not spawn updater: ${p?.message||p}`}}return T.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}) started \u2014 status ${o}`),{ok:!0,to:e,from:t,kind:n,scriptFile:v,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(R.delimiter))try{return await J.access(R.join(t,e),Xt.constants.X_OK),!0}catch{}return!1}async function Lr({statusFile:e=xe,current:t=Ae,now:n=Date.now,staleMs:r=Br}={}){let o=await Ge(e);if(!o)return null;let i=a=>J.writeFile(e,JSON.stringify(a)).catch(()=>{});if(Je(o)){if(t&&o.to===t){let a={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await i(a),a}if(n()-Number(o.updatedAt||o.startedAt||0)>r){let a={...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 i(a),a}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let a={...o,announced:!0};return await i(a),a}return null}function Ur({isBusy:e,start:t=en,onStuck:n=null,onStarted:r=null,tickMs:o=Mr,stuckMs:i=Pr,now:a=Date.now,setIntervalImpl:d=setInterval,clearIntervalImpl:T=clearInterval,log:m=console}={}){let l=null,b=()=>{l?.timer&&T(l.timer),l=null},v=async()=>{if(!l)return;let y=!0;try{y=await e()!==!1}catch{y=!0}if(y){if(!l.stuckFired&&a()-l.since>=i){l.stuckFired=!0;try{await n?.({to:l.to,from:l.from,since:l.since})}catch{}}return}let _=l;b();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:y,from:_=Ae,kind:p=ie()}){return l?.to===y?!1:(b(),l={to:y,from:_,kind:p,since:a(),stuckFired:!1,timer:d(v,o)},l.timer.unref?.(),!0)},tick:v,cancel:b,get armed(){return l?{to:l.to,from:l.from,kind:l.kind,since:l.since}:null}}}var Ae,Ir,Ve,xe,Pr,Mr,ke,I,jr,Je,Br,nn=S(()=>{qe();Jt();Ae=(()=>{try{return Nr(import.meta.url)("../package.json").version||null}catch{return null}})(),Ir=process.env.BOSTRAT_STATE_DIR||R.join(process.env.HOME||Er.tmpdir(),".bostrat"),Ve=R.join(Ir,"self-update"),xe=R.join(Ve,"status.json"),Pr=1440*6e4,Mr=6e4,ke=new Set(["npm-global","git-checkout"]);I=e=>`'${String(e).replace(/'/g,"'\\''")}'`;jr=new Set(["updating","restarting","rolling-back"]),Je=e=>!!(e&&jr.has(e.status));Br=45*6e4});Pe();Be();import H from"node:fs";import x 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 i=(n[o]||0)-(r[o]||0);if(i)return i<0}return!1},X=Wr(Hr),Ze=x.dirname(qr(import.meta.url)),ee=x.resolve(Ze,".."),Vr=x.join(Ze,"index.js"),Gr="wss://plane.bostrat.ai/v1/node",ae=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}),C=(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}`):C("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 C("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?C(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(C("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(x.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}),i=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(i),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(x.join(ee,"package.json")),r=x.join(x.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 C("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"?C: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?C("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(i=>{let a=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),d=m=>{clearTimeout(T);try{a.close()}catch{}i(m)},T=setTimeout(()=>d(C("plane link",`no hello_ok within 5s from ${o}`,"check the URL, the token, and the plane's IP gate")),5e3);a.on("open",()=>a.send(JSON.stringify({v:1,ch:"ctl",type:"hello",nodeId:`doctor-${Yr().slice(0,8)}`,ephemeral:!0}))),a.on("message",m=>{try{let l=JSON.parse(m);l.type==="hello_ok"?l.minNodeVersion&&rn(ae,l.minNodeVersion)?d(C("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${l.minNodeVersion} \u2014 this node is ${ae}; the real link is refused until it updates`,`bostrat-node self-update --to ${l.latestNodeVersion||l.minNodeVersion}`)):l.latestNodeVersion&&rn(ae,l.latestNodeVersion)?d(W("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${l.latestNodeVersion} is available (this node: ${ae})`,`bostrat-node self-update --to ${l.latestNodeVersion}`)):d(P("plane link",`hello_ok in ${Date.now()-r}ms (${o})`)):l.type==="error"&&d(C("plane link",`plane said: ${l.code} ${l.message||""}`,"check the token"))}catch{}}),a.on("error",m=>d(C("plane link",`${m?.message||m}`,"check the URL, the token, and the plane's IP gate")))})}function io(){let e;try{e=JSON.parse(H.readFileSync(x.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 C("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 ao(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(io()),n.push(ao(e)),n}function an(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let i of e)t(`${n[i.level]} ${i.name}: ${i.detail}`),i.fix&&i.level!=="pass"&&t(` fix: ${i.fix}`);let r=e.filter(i=>i.level==="fail").length,o=e.filter(i=>i.level==="warn").length;return t(r?`
|
|
145
145
|
FAIL \u2014 ${r} blocking, ${o} warnings`:`
|
|
146
146
|
OK \u2014 0 blocking, ${o} warnings`),r===0}async function co({envFile:e=re(),input:t=process.stdin,output:n=process.stdout}={}){let r=ye(e),o=zr.createInterface({input:t,output:n}),i=async(A,g)=>(await o.question(g?`${A} [${g}]: `:`${A}: `)).trim()||g||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
|
|
147
147
|
you type those inside each box, later (box-auth-policy).
|
|
@@ -203,7 +203,7 @@ WantedBy=default.target
|
|
|
203
203
|
<key>StandardErrorPath</key><string>${o}/node.err.log</string>
|
|
204
204
|
</dict>
|
|
205
205
|
</plist>
|
|
206
|
-
`}function po(e=process.platform,t=ce.homedir()){return e==="darwin"?{kind:"launchd",file:x.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:x.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:i,file:a}=po(n);if(!e&&o.split(x.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){i==="systemd"?(await X("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),H.rmSync(a,{force:!0}),await X("systemctl",["--user","daemon-reload"])):(await X("launchctl",["unload","-w",a]).catch(()=>{}),H.rmSync(a,{force:!0})),r(`removed ${a}`);return}H.mkdirSync(x.dirname(a),{recursive:!0}),i==="systemd"?(H.writeFileSync(a,uo()),await X("systemctl",["--user","daemon-reload"]),t&&await X("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${a}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(H.mkdirSync(x.join(ce.homedir(),"Library","Logs","bostrat"),{recursive:!0}),H.writeFileSync(a,fo()),t&&await X("launchctl",["load","-w",a]),r(`installed ${a}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function fa(e=process.argv.slice(2)){let t=e[0],n=re();if(t==="--version"||t==="-v"||t==="version")return console.log(ae),0;if(t==="init")return(await co({envFile:n})).ok?0:1;if(t==="doctor"){let r={...ye(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(()=>(
|
|
206
|
+
`}function po(e=process.platform,t=ce.homedir()){return e==="darwin"?{kind:"launchd",file:x.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:x.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:i,file:a}=po(n);if(!e&&o.split(x.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){i==="systemd"?(await X("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),H.rmSync(a,{force:!0}),await X("systemctl",["--user","daemon-reload"])):(await X("launchctl",["unload","-w",a]).catch(()=>{}),H.rmSync(a,{force:!0})),r(`removed ${a}`);return}H.mkdirSync(x.dirname(a),{recursive:!0}),i==="systemd"?(H.writeFileSync(a,uo()),await X("systemctl",["--user","daemon-reload"]),t&&await X("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${a}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(H.mkdirSync(x.join(ce.homedir(),"Library","Logs","bostrat"),{recursive:!0}),H.writeFileSync(a,fo()),t&&await X("launchctl",["load","-w",a]),r(`installed ${a}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function fa(e=process.argv.slice(2)){let t=e[0],n=re();if(t==="--version"||t==="-v"||t==="version")return console.log(ae),0;if(t==="init")return(await co({envFile:n})).ok?0:1;if(t==="doctor"){let r={...ye(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(()=>(Et(),$t));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:i}=await Promise.resolve().then(()=>(nn(),tn)),{detectInstallKind:a}=await Promise.resolve().then(()=>(qe(),Vt)),d=a(),T=e.indexOf("--to"),m=T>=0?String(e[T+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:ae,installKind:d,policy:i({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)
|
|
207
207
|
|
|
208
208
|
usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
|
|
209
209
|
|