bostrat-node 1.17.9 → 1.18.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-audit +1 -1
- package/bin/bostrat-track +1 -1
- package/dist/cli.js +178 -148
- package/dist/index.js +318 -317
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,11 +1,22 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)){
|
|
3
|
-
`).map(o=>o?`# ${o}`:"#"));for(let[o,s]of Object.entries(t))s==null||s===""||r.push(`${o}=${s}`);Ut.mkdirSync(Pn.dirname(e),{recursive:!0}),Ut.writeFileSync(e,r.join(`
|
|
1
|
+
var cf=Object.defineProperty;var k=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Z=(e,t)=>{for(var n in t)cf(e,n,{get:t[n],enumerable:!0})};import{createHash as lf}from"node:crypto";function qo(e){return e===null||typeof e!="object"?e===void 0||typeof e=="number"&&!Number.isFinite(e)?"null":JSON.stringify(e):Array.isArray(e)?`[${e.map(n=>qo(n===void 0?null:n)).join(",")}]`:`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${qo(e[n])}`).join(",")}}`}function Vo(e){let t={};for(let n of Object.keys(e))uf.has(n)||(t[n]=e[n]);return lf("sha256").update(qo(t)).digest("hex")}var uf,Ta,xa=k(()=>{uf=new Set(["userId"]);Ta=e=>Number.isFinite(e?.seq)});import dr from"node:fs";import fr from"node:path";import df from"node:os";function wf(e){return typeof e!="string"||!e?"a value is required":e.length<Jo?`a value must be at least ${Jo} characters`:Buffer.byteLength(e,"utf8")>gf?"that value is too large (16 KiB max)":/[\0\r\n]/.test(e)?"a value must be one line":null}function yf(){let e=[];for(let t of Xo.values())for(let[n,{value:r}]of t){let o=`\u2039${n}\u203A`,s=new Set([r]);s.add(encodeURIComponent(r)),s.add(Buffer.from(r,"utf8").toString("base64")),s.add(Buffer.from(r,"utf8").toString("base64url")),s.add(JSON.stringify(r).slice(1,-1));for(let a of s)a&&a.length>=Jo&&e.push({needle:a,mark:o})}e.sort((t,n)=>n.needle.length-t.needle.length),kn=e}function Aa(e){return fr.join($a(),e)}function Ea(){if(ka)return;ka=!0,Xo.clear();let e=[];try{e=dr.readdirSync($a(),{withFileTypes:!0})}catch{e=[]}for(let t of e){if(!t.isDirectory()||!mf.test(t.name))continue;let n=new Map,r=[];try{r=dr.readdirSync(Aa(t.name),{withFileTypes:!0})}catch{continue}for(let o of r)if(!(!o.isFile()||!hf.test(o.name)))try{let s=fr.join(Aa(t.name),o.name),a=dr.readFileSync(s,"utf8");if(wf(a))continue;n.set(o.name,{value:a,addedAt:dr.statSync(s).mtimeMs})}catch{}n.size&&Xo.set(t.name,n)}yf()}function va(){return Ea(),kn.length>0}function hr(e){if(typeof e!="string"||!e||(Ea(),!kn.length))return e;let t=e;for(let{needle:n,mark:r}of kn)t.includes(n)&&(t=t.split(n).join(r));return t}function pr(e,t=new WeakSet){if(typeof e=="string")return hr(e);if(!e||typeof e!="object"||!kn.length||t.has(e))return e;if(t.add(e),Array.isArray(e)){let o=!1,s=e.map(a=>{let i=pr(a,t);return i!==a&&(o=!0),i});return o?s:e}if(Buffer.isBuffer(e)||e instanceof Date)return e;let n=!1,r={};for(let o of Object.keys(e)){let s=pr(e[o],t);s!==e[o]&&(n=!0),r[o]=s}return n?r:e}var pf,ff,$a,hf,mf,gf,Jo,Xo,kn,ka,mr=k(()=>{pf=()=>process.env.BOSTRAT_STATE_DIR||fr.join(process.env.HOME||df.tmpdir(),".bostrat"),ff="secure-inputs",$a=()=>fr.join(pf(),ff),hf=/^[A-Z][A-Z0-9_]{0,63}$/,mf=/^[A-Za-z0-9_-]{1,80}$/,gf=16*1024,Jo=8;Xo=new Map,kn=[],ka=!1});import Zo from"node:fs/promises";import It from"node:path";import Sf from"node:os";import{EventEmitter as bf}from"node:events";import{randomUUID as _f}from"node:crypto";function Oa(e){return e?.cwd?It.join(e.cwd,".bostrat","events"):It.join(Qo,"events")}async function Af(e,t){if(An.has(t))return;let n=await rt(e,t),r=0,o=null;for(let s of n)s.seq>r&&(r=s.seq),Ta(s)&&(o=s);An.set(t,r),wr.set(t,o?Vo(o):null)}function $f(e,t){let r=(gr.get(e)??Promise.resolve()).then(t,t),o=r.then(()=>{},()=>{});return gr.set(e,o),o.then(()=>{gr.get(e)===o&&gr.delete(e)}),r}function Ef(e,t){let n=Array.isArray(e?.epochs)?e.epochs:null;if(!(!n||n.length===0)){if(!Number.isFinite(t))return n.length-1;for(let r=n.length-1;r>=0;r--){let o=n[r].startedAt;if(o==null||o<=t)return r}return 0}}async function Nt(e,t){let n=typeof e=="string"?e:e?.id;if(!n)throw new Error("appendEvent: a track (or trackId) is required");if(!t||!Tf.has(t.type))throw new Error(`appendEvent: unknown event type "${t?.type}"`);if(t.actor&&!xf.has(t.actor))throw new Error(`appendEvent: bad actor "${t.actor}"`);if(t.source&&!kf.has(t.source))throw new Error(`appendEvent: bad source "${t.source}"`);let r=typeof e=="string"?It.join(Qo,"events"):Oa(e),o=t.epoch;if(o==null&&typeof e=="object"&&t.boxId&&Array.isArray(e?.boxes)){let s=e.boxes.find(a=>a.name===t.boxId);o=Ef(s,Number(t.payload?.ts??t.ts)||Date.now())}return $f(n,async()=>{await Af(r,n);let s=An.get(n)+1;An.set(n,s);let a=wr.get(n)??null,i={id:t.id||_f(),trackId:n,boxId:t.boxId??null,...o!=null?{epoch:o}:{},seq:s,prev:a,ts:t.ts??Date.now(),type:t.type,actor:t.actor??"system",provider:t.provider??null,source:t.source??"orchestrator",payload:t.payload??{},...t.causationId?{causationId:t.causationId}:{},...t.correlationId?{correlationId:t.correlationId}:{}};if(va()){let u=pr(i);u!==i&&Object.assign(i,u)}let c=JSON.stringify(i),l=i;Ia(c)&&(c=Na(c),l=JSON.parse(c)),wr.set(n,Vo(l));try{await Zo.mkdir(r,{recursive:!0}),await Zo.appendFile(Ra(r,n),c+`
|
|
2
|
+
`)}catch(u){throw An.set(n,s-1),wr.set(n,a),u}return nt.emit("event",l),nt.emit(`track:${n}`,l),l})}async function rt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?It.join(Qo,"events"):Oa(e));let o;try{o=await Zo.readFile(Ra(n,r),"utf8")}catch{return[]}return Of(o)}function Of(e){let t=[];for(let n of e.split(`
|
|
3
|
+
`))if(n.trim())try{t.push(JSON.parse(Ia(n)?Na(n):n))}catch{}return t}var Tf,xf,kf,nt,Qo,Ra,An,wr,gr,vf,Ia,Na,Mt=k(()=>{xa();mr();Tf=new Set(["session.ready","session.foreign","turn.user","turn.agent","turn.retracted","peer.message","provider.error","delivery.queued","delivery.settled","turn.steered","turn.interrupted","turn.aborted","tool.started","tool.called","tool.failed","tool.result","prompt.raised","prompt.answered","prompt.dismissed","prompt.autoRejected","box.fullscreen.detected","box.fullscreen.answered","box.stuck.detected","box.stuck.answered","context.usage","context.refresh.offered","context.refresh.answered","handoff.offered","handoff.answered","automation.fired","refresh.flow.changed","cost.recorded","memory.ab.released","memory.seed","memory.harvested","handoff.artifact","code.pushed","code.committed","code.rework","rework.cause.offered","rework.cause.answered","rework.cause.retracted","handoff.started","handoff.step","handoff.done","handoff.failed","node.saturated","node.restarted","subtask.delegated","subtask.merged","job.started","job.stalled","job.stopped","pr.state.changed","pr.offered","pr.offer.answered","pr.exists.offered","pr.exists.answered","pr.update.reported","pr.train.boarded","pr.train.landed","pr.train.ejected","pr.train.rebuilt","box.state.changed","view.state.changed","view.spinup.failed","deps.prepare","deps.setup","secret.added","secret.renamed","secret.removed","secret.used","mock.state.changed","flow.state.changed","runbook.state.changed","ticket.linked","ticket.sync.failed","ticket.move.offered","ticket.move.answered","ticket.state.changed","ticket.commented","ticket.flow.changed","ticket.create.offered","ticket.create.answered","ticket.created","loop.create.offered","loop.create.answered","loop.created","loop.update.offered","loop.update.answered","loop.updated","loop.delete.offered","loop.delete.answered","loop.deleted","loop.paused","replay.spec.offered","replay.spec.answered","replay.run.started","replay.run.nudged","replay.run.capped","replay.run.stopped","replay.run.checked","replay.run.finished","replay.run.stubbed","standing.eval.finished","followup.armed","followup.armed.cancelled","followup.arm.saved","followup.offered","followup.answered","followup.create.offered","followup.create.answered","followup.created","planning.change.offered","planning.change.answered","planning.changed","notify.raised","usage.cap.hit","provider.limit.hit","usage.cap.warning","provider.login.started","provider.connected","track.summary.recorded","track.transferred","track.recovered","track.phase.changed","track.operation.changed","track.obligations.changed","track.interrupted.changed","track.circuit.tagged","blueprint.item.launched","blueprint.item.bound","blueprint.status.offered","blueprint.merge.unlocked","blueprint.gate.met","decision.recorded","estimate.recorded","estimate.closed","changelog.published","track.conflict.predicted","track.conflict.cleared","audit.chain.broken","audit.chain.healed","audit.flagged","audit.exec","audit.procs","harness.shape.seen","stall.detected","error"]),xf=new Set(["user","agent","orchestrator","system","peer"]),kf=new Set(["hook","otel","statusline","transcript","pane","orchestrator","vendor","cli","auditd","proc","plane"]),nt=new bf;nt.setMaxListeners(0);Qo=process.env.BOSTRAT_STATE_DIR||It.join(process.env.HOME||Sf.tmpdir(),".bostrat");Ra=(e,t)=>It.join(e,`${t}.ndjson`),An=new Map,wr=new Map,gr=new Map;vf=/(?<!\\)((?:\\\\)*)\\u0000/g,Ia=e=>e.includes("\\u0000"),Na=e=>e.replace(vf,"$1\\ufffd")});function Ca(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!Rf.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 Pa(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:Ca(o.from,"from",n),toMs:Ca(o.to,"to",n)}))}return t}function Nf(e){if(e==null)return Date.now();if(typeof e=="number")return Number.isFinite(e)?e:null;if(e instanceof Date){let n=e.getTime();return Number.isFinite(n)?n:null}let t=Date.parse(String(e));return Number.isFinite(t)?t:null}function Mf(e){if(!e)return null;let t=String(e).trim();if($n[t])return t;if(Ma[t])return Ma[t];let n=null;for(let r of Object.keys($n))t.startsWith(r)&&(!n||r.length>n.length)&&(n=r);return n}function Cf(e){if(!e||e===$n)return If;let t=ja.get(e);return t||(t=Pa(e),ja.set(e,t)),t}function jf(e,t,n={}){let{table:r,speed:o,promptTier:s}=n,a=Cf(r),i=r&&r!==$n?a[e]?e:null:Mf(e);if(!i)return null;let c=Nf(t);if(c===null)return null;let l=a[i].find(f=>c>=f.fromMs&&c<=f.toMs)||null;if(!l)return null;let u=l;if(!(o==null||o==="standard"))if(o==="fast")u=l.fast?{...l.fast,fromMs:l.fromMs,toMs:l.toMs,verifiedAt:l.verifiedAt,note:l.note,speed:"fast"}:null;else return null;return u?s==null||s==="standard"?u:s==="long"&&u.long?{...u.long,fromMs:l.fromMs,toMs:l.toMs,verifiedAt:l.verifiedAt,note:l.note,...u.speed?{speed:u.speed}:{},promptTier:"long"}:null:null}function es(e,t={},n,r){let o=jf(e,n,r);return o?((t.input||0)*o.input+(t.output||0)*o.output+(t.cacheWrite||0)*o.cacheWrite+(t.cacheRead||0)*o.cacheRead)/1e6:0}var $n,Ma,Rf,If,ja,e_,ts=k(()=>{$n={"claude-opus-5-5":[{from:null,to:null,input:4,output:20,cacheWrite:8,cacheRead:.2,cacheReadX:.05,fast:{input:8,output:40,cacheWrite:16,cacheRead:.4},verifiedAt:"2026-09-28",note:"verified 2026-09-28 against platform.claude.com/docs/en/about-claude/pricing: $4/$20, 1h cache write $8 (2\xD7), cache hits $0.20 (0.05\xD7 \u2014 footnote 2), fast $8/$40; added before any fleet turn was recorded."}],"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-10-05",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; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"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-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"claude-sonnet-5-5":[{from:null,to:"2026-10-11",input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.20 (0.1\xD7 \u2014 footnote 2 then named Opus 5.5 only). Superseded 2026-10-12 when the page moved Sonnet 5.5 hits to 0.05\xD7 (window below)."},{from:"2026-10-12",to:null,input:2,output:10,cacheWrite:4,cacheRead:.1,cacheReadX:.05,verifiedAt:"2026-10-12",note:"verified 2026-10-12 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.10 (0.05\xD7 \u2014 footnote 2 now names Opus 5.5 AND Sonnet 5.5; the prompt-caching multiplier table agrees)."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",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; re-verified 2026-10-05 (live pricing page, footnote 3 still published)."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-haiku-5-5":[{from:null,to:null,input:.1,output:.5,cacheWrite:.2,cacheRead:.01,long:{over:1e5,input:.5,output:2.5,cacheWrite:1,cacheRead:.05},verifiedAt:"2026-10-19",note:"verified 2026-10-19 against platform.claude.com/docs/en/about-claude/pricing: prompts up to 100,000 tokens $0.10/$0.50, 1h cache write $0.20 (2\xD7), cache hits $0.01 (0.1\xD7); prompts over 100,000 tokens (the `long` variant) $0.50/$2.50, 1h cache write $1 (2\xD7), cache hits $0.05 (0.1\xD7); added before any fleet turn was recorded."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-fable-5-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-10-26",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page); re-verified 2026-10-26 (live pricing page, footnote 1 unchanged)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend then; re-verified 2026-10-05 (live pricing page: $10/$50, 1h write $20, hits $1 at 0.1\xD7)."}],"gpt-5.5-pro":[{from:null,to:null,input:30,output:180,cacheWrite:30,cacheRead:30,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $30 in / $180 out, no cached-input or cache-write price published (both priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5-cyber":[{from:null,to:null,input:12.5,output:75,cacheWrite:12.5,cacheRead:1.25,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing, Cyber models table): $12.50 in / $1.25 cached / $75 out, no cache-write price published (priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-10-05",note:"verified 2026-07-03, re-verified 2026-08-17 and 2026-10-05 (developers.openai.com pricing: $5 / $0.50 cached / $30); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-11-09",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL); re-verified 2026-10-12 (live pricing page: $4 / $0.40 cached / $5 cache writes / $20, promo note unchanged); re-verified 2026-11-09 (live pricing page: $4 / $0.40 cached / $5 30m cache writes / $20 unchanged \u2014 the 'at least through November 21, 2026' promotional footnote has been removed from the page with no post-promo price or date published; price standing, not a vendor change)."}],"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-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (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-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-6-astra-law":[{from:null,to:null,input:10,output:50,cacheWrite:10,cacheRead:1,verifiedAt:"2026-11-02",note:"verified 2026-11-02 (developers.openai.com pricing, Legal model configurations table): $10 in / $1 cached / $50 out, promotional 'at least through December 31, 2026', no cache-write price published (priced as plain input); added before any fleet turn was recorded."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-10-26",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed); re-verified 2026-10-26 (live pricing page: $10 / $1 cached / $12.50 30m cache writes / $50, fast $20/$100 \u2014 the page now also lists a 12h cache-write tier at 2.5\xD7 input, not modelled: codex reports no cache-write class)."}],"gpt-6.1-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.10 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.20 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-luna":[{from:null,to:null,input:.1,output:.5,cacheWrite:.125,cacheRead:.01,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $0.10 in / $0.01 cached / $0.125 cache writes (1.25\xD7) / $0.50 out; added before any fleet turn was recorded."}]},Ma={opus:"claude-opus-5-5",opusplan:"claude-opus-5-5",default:"claude-opus-5-5",sonnet:"claude-sonnet-5-5",haiku:"claude-haiku-5-5","claude-haiku-4-5-20251001":"claude-haiku-4-5",fable:"claude-fable-5-1","gpt-5.6":"gpt-5.6-sol"},Rf=/^\d{4}-\d{2}-\d{2}$/;If=Pa($n);ja=new WeakMap;e_=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var Ba=k(()=>{ts()});import La from"node:fs/promises";import Ua from"node:path";import Pf from"node:os";function Wa(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function Ka(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function za(e){let t=new Date(Wa(e));return t.setDate(t.getDate()+7),t.getTime()}function Ga(e){let t=new Date(Ka(e));return t.setMonth(t.getMonth()+1),t.getTime()}function Uf(e=Date.now()){for(let[t,n]of Object.entries(Df)){let r=n.startOf(e);if(r!==yr[t]){yr[t]=r;for(let o of ns.values())o[t]=0;for(let o of Da)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&Da.delete(o)}}}function Hf(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let o={};for(let s of["weeklyUsd","monthlyUsd"]){let a=r?.[s];if(a==null||a==="")continue;let i=Number(a);if(!Number.isFinite(i)||i<=0)throw new Error(`${n}.${s} must be a positive number or null`);o[s]=i}Object.keys(o).length&&(t[n]=o)}return t}async function Ya(e,{source:t="local",updatedAt:n=Date.now()}={}){Ct={caps:Hf(e),updatedAt:n,source:t};try{await La.mkdir(Ha,{recursive:!0}),await La.writeFile(Bf(),JSON.stringify(Ct,null,2))}catch{}return Wf()}function Wf(e=Date.now()){Uf(e);let t=new Set([...ns.keys(),...Object.keys(Ct?.caps||{})]),n={};for(let r of t){let o=ns.get(r);n[r]={weeklyUsd:Fa(o?.weekly||0),monthlyUsd:Fa(o?.monthly||0)}}return{caps:Ct?.caps||{},configured:!!Ct,seeded:Ff,updatedAt:Ct?.updatedAt??null,spent:n,windows:{weekly:{start:yr.weekly,resetsAt:za(e)},monthly:{start:yr.monthly,resetsAt:Ga(e)}},warnPct:Lf}}var Ha,Bf,Lf,Df,Ct,Ff,yr,ns,Da,Fa,qa=k(()=>{Mt();Ba();Ha=process.env.BOSTRAT_STATE_DIR||Ua.join(process.env.HOME||Pf.tmpdir(),".bostrat"),Bf=()=>Ua.join(Ha,"usage-caps.json"),Lf=.8;Df={weekly:{startOf:Wa,nextStart:za,capKey:"weeklyUsd"},monthly:{startOf:Ka,nextStart:Ga,capKey:"monthlyUsd"}},Ct=null,Ff=!1,yr={weekly:0,monthly:0},ns=new Map,Da=new Set;Fa=e=>Math.round(e*1e4)/1e4});var Oe,En,Sr=k(()=>{Oe="BOSTRAT_HOOK_TOKEN",En="x-bostrat-hook"});var Kf,f_,Va=k(()=>{Kf=(e,t)=>{if(e==null||e==="")return t;let n=Number(e);return Number.isFinite(n)&&n>=0?n:t},f_=Kf(process.env.BOSTRAT_HOOK_FOLD_MS,250)});function Jf(e,t=Gf){let n=String(e??""),r=n.split(/\s*(?:;|&&|\|\||\||\n)\s*/).map(o=>o.trim()).filter(Boolean);return Number.isFinite(t)&&n.length>=t&&r.length&&r.pop(),r}function br(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function oc(e){let t=0;for(;t<e.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]);)t++;return{cmd:e[t]??null,rest:e.slice(t+1),at:t}}function tc(e){let t=br(e),n=t.findIndex(l=>l==="git"||l.endsWith("/git"));if(n<0)return null;for(n++;n<t.length&&t[n].startsWith("-");)(t[n]==="-C"||t[n]==="-c")&&n++,n++;if(t[n]!=="push")return null;let r=[],o=[];for(let l=n+1;l<t.length;l++){let u=t[l];u.startsWith("-")?(r.push(u),(u==="-o"||u==="--push-option"||u==="--repo"||u==="--receive-pack"||u==="--exec")&&l++):o.push(u)}let s=r.some(l=>l==="--force"||/^-[a-zA-Z]+$/.test(l)&&l.includes("f"))||o.some(l=>l.startsWith("+")),a=r.some(l=>l.startsWith("--force-with-lease")||l.startsWith("--force-if-includes")),i=o[0]??null,c=o.slice(1).map(l=>l.replace(/^["']|["']$/g,"").replace(/^\+/,"")).map(l=>l.includes(":")?l.slice(l.indexOf(":")+1):l).filter(l=>l&&!l.startsWith("$"));return{force:s,lease:a,remote:i,dsts:c}}function ac(e){let{cmd:t,at:n}=oc(e);if(t==="sudo"){for(n++;n<e.length&&e[n].startsWith("-");)n++;t=e[n]??null}return{cmd:t,at:n}}function cc(e,t){let n=String(e??"").match(t);if(!n)return null;let r=n[1],o=r.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");if(new RegExp(`>{1,2}\\s*["']?[^\\s"']*${o}`).test(e))return"redirect";let s=br(e),{cmd:a}=ac(s);return!a||!s.some(i=>i.includes(r))?null:/^(?:rm|mv|truncate|chmod|chown|tee|install|shred|unlink|ln|mkdir|touch)$/.test(a)?a:a==="sed"&&s.some(i=>/^-[a-zA-Z]*i/.test(i))?"sed -i":a==="cp"&&s[s.length-1].includes(r)?"cp":/^(?:python3?|perl|node|ruby)$/.test(a)&&/open\([^)]*['"][wa]|writeFile|write_text|appendFile|fs\.write/.test(e)?`${a} write`:null}function uh(e){let t=br(e),{cmd:n,at:r}=ac(t);if(!n)return null;let o=t.slice(r+1);if(n==="crontab"||n.endsWith("/crontab")){let a=!1,i=!1;for(let c=0;c<o.length;c++){if(o[c]==="-u"){c++;continue}o[c]==="-l"||/^-(?:h|V|T|-help|-version)$/.test(o[c])?a=!0:i=!0}return i||!a?"crontab":null}if(n==="systemctl"||n.endsWith("/systemctl")){let a=o.find(i=>!i.startsWith("-"));return a&&th.test(a)?`systemctl ${a}`:null}if((n==="loginctl"||n.endsWith("/loginctl"))&&o.includes("enable-linger"))return"loginctl enable-linger";if(n==="at"&&o.length&&/^(?:now|midnight|noon|teatime|today|tomorrow|next|\d|-[fqmvt])/.test(o[0]))return"at";let s=cc(e,ic);return s?`${s} unit/cron path`:null}function dh(e){let t=new Set;for(let n of String(e??"").matchAll(sh))t.add(n[1].toLowerCase());return[...t]}var zf,Gf,Ja,Xa,Za,Qa,ec,y_,Yf,qf,rs,Vf,Re,ss,Xf,Zf,Qf,eh,sc,ic,th,nh,rh,oh,sh,nc,rc,ih,ah,ch,lh,oe,vn,os,lc,S_,b_,uc=k(()=>{Va();zf="BP-AU-R4",Gf=160,Ja=200,Xa=5,Za=8,Qa=5,ec=10*6e4,y_=Object.freeze(["localhost","127.0.0.1","0.0.0.0","github.com","api.github.com","raw.githubusercontent.com","objects.githubusercontent.com","registry.npmjs.org","pypi.org","files.pythonhosted.org"]),Yf=5e3,qf=new Set(["tool.called","tool.failed"]),rs=new Set(["Write","Edit","NotebookEdit"]),Vf=e=>String(e??"").replace(/\s+/g," ").trim(),Re=(e,t=120)=>Vf(e).slice(0,t);ss=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,Xf=new RegExp(`${ss}/\\.ssh(?:/|\\b)`),Zf=new RegExp(`${ss}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),Qf=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,eh=/^\.env\.(?:example|sample|template|dist)$/,sc=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,ic=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${ss}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),th=/^(?:enable|disable|start|stop|restart|try-restart|reload|reload-or-restart|daemon-reload|daemon-reexec|link|mask|unmask|edit|preset|preset-all|set-property|revert|isolate|kill|reset-failed|import-environment|set-environment|add-wants|add-requires)$/,nh=/^\/tmp\/|\/\.bostrat\/tmp\//,rh=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,oh=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,sh=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,nc=e=>Xf.test(e)||Zf.test(e),rc=e=>[...String(e??"").matchAll(Qf)].some(t=>!eh.test(t[1])),ih=e=>sc.test(e),ah=e=>ic.test(e),ch=e=>(e.startsWith("/")||e.startsWith("~"))&&!nh.test(e);lh=e=>cc(e,sc);oe=(e,t,n,r)=>Object.freeze({severity:e,requirement:zf,note:t,measured:n,detect:r}),vn=(e,t)=>{let n=0,r=null;for(let o of e.calls)if(o.head)for(let s of Jf(o.head,e.headCap)){let a=t(s,o);a&&(n++,r??=Re(a))}return n?{count:n,sample:r}:null},os=(e,t)=>{let n=0,r=null;for(let o of e.calls){let s=t(o);s&&(n++,r??=Re(s))}return n?{count:n,sample:r}:null},lc=Object.freeze({"force-push":oe("high","git push --force / -f / +refspec in a command head (--force-with-lease, the Track's own rebase flow, is not one)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 1,080 logs 2026-08\u219210 \xB7 58 --force-with-lease pushes excluded by design \u2192 high",(e,t)=>vn(t,n=>{let r=tc(n);return r&&r.force&&!r.lease?n:null})),"protected-config-write":oe("high","a write to the box's own harness: .claude/settings*.json, a .claude/hooks/ script or the Track's .bostrat/events/ log \u2014 by a file tool, a redirect, rm/mv/tee/sed -i, or a scripted open-for-write (reads are not hits)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 165 reads of those paths (cat, grep, python json.loads) excluded by design \u2192 high",(e,t)=>{let n=0,r=null;for(let s of t.calls)rs.has(s.tool)&&s.path&&ih(s.path)&&(n++,r??=Re(`${s.tool} ${s.path}`));let o=vn(t,s=>{let a=lh(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"persistence-install":oe("medium","a shell segment that installs something the OS runs on its own \u2014 crontab (install / edit / remove; -l is a read), a mutating systemctl verb (enable / start / restart / daemon-reload \u2026; status / show / cat / list / is-* are reads), loginctl enable-linger, at / batch \u2014 or a write (file tool, redirect, cp / mv / tee / ln / sed -i) into a systemd unit or cron directory: how a process outlives its turn by the OS's hand (BP-AU-D6's other half)","2026-10-21 fleet replay \xB7 11 hits / 99,122 hook calls \xB7 10 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-asked service work on the operator's own Pi (systemctl --user restart/stop/start of bostrat-node, tmp-sweep, a samba disable, one `crontab -` install for a backfill) \xB7 the bare `at` word a quoted `|` regex leaves in a segment (4 hits) excluded by design \u2192 medium (rail), the guard's deny when opted in",(e,t)=>{let n=0,r=null;for(let s of t.calls)rs.has(s.tool)&&s.path&&ah(s.path)&&(n++,r??=Re(`${s.tool} ${s.path}`));let o=vn(t,s=>{let a=uh(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"push-outside-track":oe("medium","git push to a protected branch (main/master/develop/release\u2026), to a branch that is not a Track branch, or to a remote other than origin/upstream \u2014 a Track's own code leaves on its track/ branch or the WIP shadow ref","2026-10-21 fleet replay \xB7 7 hits / 98,690 hook calls \xB7 4 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-instructed work on another repo (two dep/ branches, a fork's multiplayer branch, one HEAD:main) \u2192 medium, not a page",(e,t)=>vn(t,n=>{let r=tc(n);return r&&(r.remote&&!/^(?:origin|upstream)$/.test(r.remote)&&!r.remote.startsWith("$")&&!r.remote.startsWith("-")||r.dsts.some(o=>rh.test(o)||!oh.test(o)))?n:null})),"credential-read":oe("medium","a command head or file path naming SSH material (~/.ssh) or a vendor auth file (~/.claude.json, ~/.claude/.credentials.json, ~/.codex/auth.json, ~/.cursor) \u2014 the box-auth policy's denylist shapes; ~/.claude/projects (transcripts) is not one","2026-10-21 fleet replay \xB7 12 hits / 98,690 hook calls \xB7 8 Tracks \xB7 3 in the last 14 d \xB7 every hit an operator-asked inspection on the operator's own node (ssh config for a host alias, stat/keys of ~/.claude.json) \u2192 medium until a 14-day window reads 0",(e,t)=>os(t,n=>n.head&&nc(n.head)?n.head:n.path&&nc(n.path)?`${n.tool} ${n.path}`:null)),"dotenv-read":oe("low","a command head or file path naming a .env file (.env, .env.local, .env.production \u2026; the committed .env.example / .sample / .template are not ones)","2026-10-21 fleet replay \xB7 309 hits / 98,690 hook calls \xB7 44 Tracks \xB7 0 in the last 14 d \xB7 all of them an instructed `source \u2026/almanac/.env` on the operator's other repos \u2192 low (report only)",(e,t)=>os(t,n=>n.head&&rc(n.head)?n.head:n.path&&rc(n.path)?`${n.tool} ${n.path}`:null)),"privileged-command":oe("medium","a shell segment whose command is sudo or docker (after any VAR=value prefix) \u2014 host-level reach from inside a box","2026-10-21 fleet replay \xB7 220 hits (183 events) / 98,690 hook calls \xB7 57 Tracks \xB7 3 in the last 14 d \xB7 sudo = the operator's own journalctl/systemctl asks on the Pi, docker = instructed compose/psql work on the operator's other services \u2192 medium (a hosted node's first hit is the number to watch)",(e,t)=>vn(t,n=>{let{cmd:r}=oc(br(n));return r==="sudo"||r==="docker"?n:null})),"write-outside-workspace":oe("low","a file tool (Write / Edit / NotebookEdit) on an absolute path \u2014 the hook strips the box's workspace prefix, so an absolute path is outside it \u2014 that is not the box's scratch dir (/tmp/\u2026, \u2026/.bostrat/tmp/\u2026)","2026-10-21 fleet replay \xB7 106 hits / 98,690 hook calls \xB7 10 Tracks \xB7 44 in the last 14 d \xB7 the operator's other repos and Agent-tool worktrees under .bostrat/repos on the operator's own node \u2192 low (report only)",(e,t)=>os(t,n=>rs.has(n.tool)&&n.path&&ch(n.path)?`${n.tool} ${n.path}`:null)),"egress-new-host":oe("low","a command head reaching, by URL, a host no box in the fleet has reached before (this projection's lifetime, seeded from the warm tails; KNOWN_HOSTS + PLANE_AUDIT_KNOWN_HOSTS never count) \u2014 a baseline-growth signal, so each host is reported once","2026-10-21 fleet replay \xB7 140 first sightings / 98,690 hook calls \xB7 69 Tracks \xB7 8 in the last 14 d \xB7 198 if the baseline were per Track \xB7 every host a vendor API, a docs site or the operator's own services \u2192 low (report only)",(e,t)=>{let n=0,r=null;for(let o of t.calls)if(o.head)for(let s of dh(o.head))t.state.known.has(s)||t.state.hosts.has(s)||(t.state.hosts.add(s),t.state.hosts.size>Yf&&t.state.hosts.delete(t.state.hosts.values().next().value),n++,r??=Re(`${s} \xB7 ${o.head}`));return n?{count:n,sample:r}:null}),"spend-spike":oe("low",`a cost.recorded turn over ${Za}\xD7 the Track's running median (its last ${Ja} cost events, at least ${Xa} of them) and over $${Qa} \u2014 a turn that cost far more than this Track's turns do`,"2026-10-21 fleet replay \xB7 114 hits / 8,421 cost events \xB7 64 Tracks \xB7 2 in the last 14 d \xB7 every hit a long build turn after short prompts (a $25\u201378 turn on a $0.37 median) \u2014 real spend, no one's attack \u2192 low (report only)",(e,t)=>{if(e.type!=="cost.recorded")return null;let n=t.track.costs,r=Number(e.payload?.usd);if(!Number.isFinite(r)||r<0)return null;let o=null;if(n.length>=Xa&&r>=Qa){let s=[...n].sort((i,c)=>i-c),a=s[Math.floor(s.length/2)];r>Za*a&&(o={count:1,sample:`$${r.toFixed(2)} vs median $${a.toFixed(2)} over ${n.length} turns${e.payload?.model?` \xB7 ${e.payload.model}`:""}`})}return n.push(r),n.length>Ja&&n.shift(),o}),"peer-injected-call":oe("medium",`a tool call within ${ec/6e4} min of a peer.message on the same box with no operator or node-typed turn in between \u2014 the cross-session injection vector (peer-message.js); a peer is never a root (BP-AU-D1)`,"2026-10-21 fleet replay \xB7 0 peer.message events in 288,395 \xB7 the replay cannot bound this rule's rate, so it stays medium (rail) until a window with peer traffic has been measured; the shape itself is BP-AU-D1's stated R4 case",(e,t)=>{if(!t.calls.length)return null;let n=t.track.peer.get(t.boxKey);if(n==null||t.ts-n>ec||t.ts<n)return null;let r=t.calls[0];return{count:t.count,sample:Re(`${Math.round((t.ts-n)/1e3)}s after a peer message \xB7 ${r.tool}${r.head?`: ${r.head}`:r.path?` ${r.path}`:""}`)}}),"foreign-session-call":oe("medium","a hook-recorded tool call from a claude session that is not the box's own (payload.foreignSession, BP-AU-I12): a nested or stray CLI driving the box's hooks \u2014 R3 never roots it, this names it","2026-10-21 fleet replay \xB7 14 hits / 98,744 hook calls \xB7 3 Tracks \xB7 4 in the last 14 d \xB7 all the xscout loop's nested claude prompts, I12's own acceptance case \u2192 medium (rail), not a page",(e,t)=>{if(!t.calls.length||!e.payload?.foreignSession)return null;let n=t.calls[0];return{count:t.count,sample:Re(`session ${String(e.payload.sessionId||"?").slice(0,8)} \xB7 ${n.tool}${n.head?`: ${n.head}`:n.path?` ${n.path}`:""}`)}}),"orphan-process":oe("medium","a process the box left running: detached from the pane's tree (its cgroup or pty still lists it), alive at a turn's close and still alive minutes later with no turn open and no background job recorded \u2014 the node's own census (orphan-watch.js, BP-AU-D6), each process once","2026-10-27 fleet replay \xB7 0 audit.procs events in 304,814 (1,121 logs; the type is new, so the replay cannot bound this rule's rate) \xB7 live Pi census the same day: 10 boxes, 2 detached processes, both found by the cgroup census and neither by the pty one (a claude tool call runs on pipes) \u2014 one planted `nohup sleep &`, one real `flyctl agent run` that a lead's flyctl call had left behind 10 h earlier \u2192 medium (rail), never a page, until a window of live samples has been measured",e=>{if(e.type!=="audit.procs"||e.source!=="proc")return null;let t=e.payload||{},n=Array.isArray(t.orphans)?t.orphans:[],r=n.length+(Number(t.dropped)||0);if(!r)return null;let o=n[0]||{},s=Number.isFinite(o.sinceMs)?` \xB7 alive ${Math.max(1,Math.round(o.sinceMs/6e4))} min`:"";return{count:r,sample:Re(`${o.comm||"process"}${o.cmd?`: ${o.cmd}`:""}${o.via?` [${o.via}]`:""}${s}${r>1?` (+${r-1} more)`:""}`)}}),"unknown-harness-shape":oe("medium","a harness-made user turn of a shape chat-notes.js does not list (harness.shape.seen with known: false, harness-shapes.js): Claude Code wrote a new kind of its own turn into a transcript \u2014 hidden from chat by the generic catch, counted once per shape per node here; the node pages the operator once on first sight, this row is the fleet's record","2026-10-28 fleet replay \xB7 0 harness.shape.seen events in 311,055 (1,132 logs; the type is new, so the replay cannot bound this rule's rate) \xB7 transcript scan the same day: 2,863 claude user turns in 1,539 transcripts over 90 d, 144 of them harness-made (isMeta), 9 distinct shapes, 4 of which had rendered in chat as operator messages (<system-reminder><tools-used-before-summary> on 2 Tracks under 2.1.312, a usage-limit-reset notice, a safety-classifier notice) \u2192 medium (rail finding + security row), never a page from the plane: the once-per-shape page is the node's, so a release that adds one shape pages once, not per Track per hour",e=>{if(e.type!=="harness.shape.seen"||e.source!=="transcript")return null;let t=e.payload||{};if(t.known!==!1||!t.key)return null;let n=`${t.provider||"cli"}${t.cliVersion?` ${t.cliVersion}`:""}`;return{count:1,sample:Re(`${t.key} \xB7 ${n}${t.head?` \xB7 ${t.head}`:""}`)}})}),S_=Object.freeze(Object.keys(lc)),b_=new Set([...qf,"cost.recorded","peer.message","turn.user","audit.procs","harness.shape.seen"])});function hh(e){let t=String(e??"").trim().toLowerCase();if(ph.has(t))return{enabled:!1,rules:[],unknown:[]};if(fh.has(t))return{enabled:!0,rules:[...is],unknown:[]};let n=[],r=[];for(let o of t.split(",")){let s=o.trim();s&&(is.includes(s)?n.includes(s)||n.push(s):r.push(s))}return{enabled:n.length>0,rules:n,unknown:r}}function dc(e){return e?.enabled?`on \xB7 denies ${e.rules.length===is.length?"the high set: ":""}${e.rules.join(", ")}${e.unknown.length?` \xB7 ignoring unknown ${e.unknown.join(", ")}`:""} \xB7 fail-open (an unanswered hook allows)`:"off (BOSTRAT_AUDIT_GUARD unset \u2014 PreToolUse records, never denies)"}var is,ph,fh,as,cs=k(()=>{uc();is=Object.freeze(["force-push","protected-config-write","credential-read","persistence-install"]),ph=new Set(["","off","0","false","no","none"]),fh=new Set(["on","1","true","yes","all"]);as=(e=process.env)=>hh(e.BOSTRAT_AUDIT_GUARD)});import jt from"node:fs";import pc from"node:fs/promises";import Tr from"node:os";import se from"node:path";import{execFile as fc}from"node:child_process";import{promisify as mh}from"node:util";function gc(e){try{return jt.readFileSync(e,"utf8").split(`
|
|
4
|
+
`).filter(t=>t&&!t.startsWith("#")).map(t=>t.split(":"))}catch{return[]}}function wc(e,t=process.env){let r=gc(t.BOSTRAT_PASSWD_FILE||"/etc/passwd").find(o=>o[0]===String(e)||o[2]===String(e));return r?{name:r[0],uid:Number(r[2]),gid:Number(r[3]),home:r[5]||null,shell:r[6]||null}:null}function yc(e,t=process.env){let n=gc(t.BOSTRAT_GROUP_FILE||"/etc/group"),r=new Set;for(let o of n)Number(o[2])===e.gid&&r.add(o[0]),(o[3]||"").split(",").includes(e.name)&&r.add(o[0]);return[...r].sort()}function On(e=process.env){let t=String(e[ps]||"").trim();if(yh.has(t.toLowerCase()))return null;let n=`${t}|${e.BOSTRAT_PASSWD_FILE||""}|${e.BOSTRAT_GROUP_FILE||""}|${e.BOSTRAT_BOX_HOME_VIEW||""}`;if(ls?.key===n)return ls.value;let r;if(!wh.test(t))r={name:t,error:`${ps}="${t}" is not a valid user name`};else{let o=wc(t,e),s=_r();if(!o)r={name:t,error:`user "${t}" does not exist \u2014 run scripts/pi/box-user-setup.sh (or the image's useradd)`};else if(o.uid===0)r={name:t,error:`user "${t}" is root`};else if(o.uid===s)r={name:t,error:`user "${t}" is the node's own uid`};else if(!o.home||o.home==="/"||o.home==="/nonexistent")r={name:t,error:`user "${t}" has no home directory`};else{let a=yc(o,e),i=a.filter(c=>hc.includes(c));r=i.length?{name:t,error:`user "${t}" is in ${i.join(", ")} \u2014 a box user must hold no route to root`}:{...o,groups:a,nodeUid:s,rootNode:s===0}}}return ls={key:n,value:r},r}function Bt(e=process.env){let t=On(e);return t&&!t.error?t.home:Tr.homedir()}function Pt(e=process.env){let t=On(e);return!t||t.error||t.rootNode?Bt(e):e.BOSTRAT_BOX_HOME_VIEW||se.join(mc(e),"box-home")}function Sh(e,t=process.env){let n=On(t);return!n||n.error?e:n.rootNode?["setpriv",`--reuid=${n.uid}`,`--regid=${n.gid}`,"--init-groups","--","env",`HOME=${n.home}`,`USER=${n.name}`,`LOGNAME=${n.name}`,...e]:["sudo","-n","-H","-u",n.name,"--",...e]}async function us(e,{env:t=process.env,input:n=null,timeout:r=15e3}={}){let[o,...s]=Sh(e,t);return n==null?fs(o,s,{timeout:r}):new Promise((a,i)=>{fc(o,s,{timeout:r},(l,u,f)=>l?i(l):a({stdout:u,stderr:f})).stdin.end(n)})}function bh(e){return e.BOSTRAT_SETFACL_BIN?e.BOSTRAT_SETFACL_BIN:(ds===void 0&&(ds=["/usr/bin/setfacl","/bin/setfacl"].find(t=>jt.existsSync(t))||null),ds)}function _h(e=process.env){let t=Tr.homedir(),n=mc(e);return[se.join(t,".ssh"),se.join(t,".claude.json"),se.join(t,".claude",".credentials.json"),se.join(t,".codex","auth.json"),se.join(t,".config","gh","hosts.yml"),se.join(t,".cursor","cli-config.json"),se.join(n,"node.env"),se.join(n,"api-token"),se.join(n,"plane-link"),se.join(n,"secure-inputs")]}async function Sc({env:e=process.env,probe:t=!0}={}){let n=On(e),r=await kh(e);if(!n){let s=wc(_r(),e)||{name:Tr.userInfo().username,uid:_r(),gid:-1},a=s.uid===0?["root"]:yc(s,e).filter(l=>hc.includes(l)),i=s.uid!==0&&t?await xh():!1,c=[...a,...i&&!a.includes("sudo")?["sudo (sudoers)"]:[]];return{level:c.length?"root-capable":"node-uid",user:s.name,routes:c,problems:[],auditd:r}}if(n.error)return{level:"misconfigured",user:n.name,error:n.error,problems:[n.error],auditd:r};let o=[];if(t){try{let{stdout:c}=await us(["id","-u"],{env:e,timeout:5e3});Number(c.trim())!==n.uid&&o.push(`switching to ${n.name} landed as uid ${c.trim()}`)}catch(c){o.push(`the node cannot switch to ${n.name} (${n.rootNode?"setpriv":"sudo -n -u"} failed: ${Th(c)})`)}if(!o.length){await us(["sudo","-n","true"],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&o.push(`${n.name} can sudo`);let c=[];for(let l of _h(e))jt.existsSync(l)&&await us(["test","-r",l],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&c.push(l);c.length&&o.push(`${n.name} can read ${c.join(", ")}`)}bh(e)||o.push("setfacl is missing (apt install acl)");let s=Pt(e);s!==n.home&&!jt.existsSync(se.join(s,".claude"))&&o.push(`the read-only mirror of ${n.home} is not mounted at ${s} \u2014 the node cannot read box transcripts`);let a=se.join(n.home,".claude","settings.json"),i=await pc.stat(a).catch(()=>null);i&&i.uid===n.uid&&o.push(`${a} is owned by ${n.name} \u2014 the box can rewrite its own hooks`)}return{level:"uid",user:n.name,uid:n.uid,home:n.home,view:Pt(e),problems:o,auditd:r}}async function xh(){try{return await fs("sudo",["-n","true"],{timeout:3e3}),!0}catch{return!1}}async function kh(e=process.env,{ask:t=!0}={}){let n=e.BOSTRAT_AUDIT_LOG||"/var/log/audit/audit.log",r=!1;try{await pc.access(n,jt.constants.R_OK),r=!0}catch{}let o=e.BOSTRAT_AUDIT_RULES_FILE||"/etc/audit/rules.d/bostrat-box.rules",s=jt.existsSync(o),a=null;if(t&&s){let i=_r()===0?["auditctl",["-l"]]:["sudo",["-n","auditctl","-l"]];try{let{stdout:c}=await fs(i[0],i[1],{timeout:5e3});a=c.includes(`key=${gh}`)}catch{a=null}}else s||(a=!1);return{log:n,readable:r,configured:s,rule:a,rulesFile:o}}function bc(e){let t=e.auditd||{},n=t.rule===!0&&t.readable?"auditd execve logging on":t.rule===!0?"auditd rule loaded, but the node cannot read the log":t.configured&&t.rule===null?`auditd rule configured (not verifiable without root)${t.readable?"":", log unreadable"}`:t.configured?"auditd rule configured but NOT loaded":"no auditd";if(e.level==="uid"){let r=e.problems.length?` \u2014 ${e.problems.length} problem(s): ${e.problems.join("; ")}`:"";return`boxes run as ${e.user} (uid ${e.uid}, no route to root), event log + hook settings read-only to them; ${n}${r}`}return e.level==="misconfigured"?`${ps} is set but unusable \u2014 boxes are REFUSED: ${e.error}`:e.level==="root-capable"?`boxes run as ${e.user} (${e.routes.join(", ")}) \u2014 root-capable: an agent can defeat node-side evidence; ${n}`:`boxes run as the node's uid (${e.user}) \u2014 no route to root, but they can rewrite the node's event log and hooks; ${n}`}var fs,ps,gh,hc,wh,yh,mc,_r,ls,Rn,ds,Th,Ie=k(()=>{fs=mh(fc),ps="BOSTRAT_BOX_USER",gh="bostrat-box",hc=Object.freeze(["root","sudo","wheel","admin","docker","lxd","libvirt","disk"]),wh=/^[a-z_][a-z0-9_-]{0,31}$/,yh=new Set(["","off","0","false","no","none"]),mc=e=>e.BOSTRAT_STATE_DIR||se.join(e.HOME||Tr.homedir(),".bostrat");_r=()=>typeof process.getuid=="function"?process.getuid():0,ls=null;Rn=(e=process.env)=>{let t=On(e);return!!(t&&!t.error)};Th=e=>String(e?.stderr||e?.message||e).trim().split(`
|
|
5
|
+
`)[0].slice(0,160)});import xr from"node:fs/promises";import Ah from"node:path";async function De(e,t,{mode:n}={}){await xr.mkdir(Ah.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${++$h}.tmp`;try{await xr.writeFile(r,JSON.stringify(t,null,2)+`
|
|
6
|
+
`,n!=null?{mode:n}:void 0),await xr.rename(r,e)}catch(o){throw await xr.unlink(r).catch(()=>{}),o}}var $h,ot=k(()=>{$h=0});import Oh from"node:os";import hs from"node:path";function Tc(){return Rn()?hs.join(Bt(),".claude.json"):process.env.CLAUDE_CONFIG_DIR?hs.join(process.env.CLAUDE_CONFIG_DIR,".claude.json"):hs.join(Oh.homedir(),".claude.json")}var ms=k(()=>{Sr();cs();Ie();ot()});import Rh from"node:os";import gs from"node:path";function xc(){if(Rn())return gs.join(Bt(),".codex","config.toml");let e=process.env.CODEX_HOME||gs.join(Rh.homedir(),".codex");return gs.join(e,"config.toml")}var Ih,q_,ws=k(()=>{Ie();Ih="check_for_update_on_startup",q_=`${Ih} = false`});var Mc={};Z(Mc,{_resetMcpBrokerForTests:()=>Hh,brokerReadiness:()=>Er,brokerValues:()=>ks,cancelLogin:()=>In,discoverAuthorizationServer:()=>vc,discoverProtectedResource:()=>Ec,finishLogin:()=>Ic,initMcpBroker:()=>Uh,logout:()=>Fh,mcpTokensFile:()=>$r,onMcpBrokerChange:()=>kc,pendingLogins:()=>As,refreshDue:()=>_s,refreshToken:()=>Nc,startLogin:()=>Dh});import st from"node:fs/promises";import Nh from"node:http";import Mh from"node:os";import Ts from"node:path";import ys from"node:crypto";function kc(e){return kr.add(e),()=>kr.delete(e)}async function Ft(){if(!bs){bs=!0;try{let e=$r();(await st.stat(e)).mode&63&&await st.chmod(e,384).catch(()=>{});let n=JSON.parse(await st.readFile(e,"utf8"));z={tokens:Object.fromEntries(Object.entries(n?.tokens||{}).filter(([r,o])=>xs.test(r)&&o&&typeof o=="object")),clients:n?.clients&&typeof n.clients=="object"?n.clients:{}}}catch{z={tokens:{},clients:{}}}}}async function Dt(){let e=$r();await st.mkdir(Ts.dirname(e),{recursive:!0,mode:448});let t=`${e}.bostrat-${process.pid}.tmp`;await st.writeFile(t,JSON.stringify(z,null,2),{mode:384}),await st.rename(t,e)}function ks(){return Object.fromEntries(Object.entries(z.tokens).filter(([,e])=>Ac(e)).map(([e,t])=>[e,t.access]))}function Er(){let e={};for(let[t,n]of Object.entries(z.tokens)){let r=Ac(n)?"set":n.needsLogin?"needs-login":n.refresh?"refreshing":"needs-login";e[t]={state:r,source:"broker",...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.obtainedAt?{obtainedAt:n.obtainedAt}:{},refreshable:!!n.refresh,...n.lastError?{error:String(n.lastError).slice(0,200)}:{}}}for(let[t,n]of Ne)e[t]||(e[t]={state:"login-pending",source:"broker",startedAt:n.startedAt,redirectUri:n.redirectUri});return e}async function $c(e){let t=await Nn(e,{headers:{accept:"application/json"},signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new Error(`${e} answered ${t.status}`);return t.json()}async function Ec(e){let t=null,n=null;try{let s=(await Nn(e,{method:"POST",headers:{"content-type":"application/json",accept:"application/json, text/event-stream"},body:"{}",signal:AbortSignal.timeout(15e3)})).headers.get("www-authenticate")||"",a=/resource_metadata="([^"]+)"/i.exec(s);a&&(t=a[1]);let i=/\bscope="([^"]+)"/i.exec(s);i&&(n=i[1])}catch{}let r=t?[t,...Ar(e,"oauth-protected-resource")]:Ar(e,"oauth-protected-resource");for(let o of r)try{let s=await $c(o),a=Array.isArray(s.authorization_servers)?s.authorization_servers[0]:null;if(a)return{authorizationServer:String(a),resource:typeof s.resource=="string"?s.resource:e,scope:n||(Array.isArray(s.scopes_supported)?s.scopes_supported.join(" "):null)}}catch{}return{authorizationServer:new URL(e).origin,resource:e,scope:n}}async function vc(e){for(let n of[...Ar(e,"oauth-authorization-server"),...Ar(e,"openid-configuration")])try{let r=await $c(n);if(r.authorization_endpoint&&r.token_endpoint)return{issuer:String(r.issuer||e),authorizationEndpoint:String(r.authorization_endpoint),tokenEndpoint:String(r.token_endpoint),registrationEndpoint:r.registration_endpoint?String(r.registration_endpoint):null,pkce:Array.isArray(r.code_challenge_methods_supported)?r.code_challenge_methods_supported.includes("S256"):!0}}catch{}let t=String(e).replace(/\/+$/,"");return{issuer:t,authorizationEndpoint:`${t}/authorize`,tokenEndpoint:`${t}/token`,registrationEndpoint:`${t}/register`,pkce:!0}}async function Lh(e,t){if(!e.registrationEndpoint)throw new Error(`${e.issuer} offers no dynamic client registration \u2014 pass --client-id with a client registered there`);let n=await Nn(e.registrationEndpoint,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({client_name:Bh,redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new Error(`client registration at ${e.registrationEndpoint} answered ${n.status}`);let r=await n.json();if(!r.client_id)throw new Error("client registration answered without a client_id");return{clientId:String(r.client_id),clientSecret:r.client_secret?String(r.client_secret):null}}function Oc(e=0){return new Promise(t=>{let n=Nh.createServer();n.on("error",()=>t(e?Oc(0):null)),n.listen(e,"127.0.0.1",()=>t(n))})}async function Dh({name:e,url:t,scope:n=null,clientId:r=null,clientSecret:o=null}={},{port:s=0}={}){if(await Ft(),!xs.test(String(e||"")))throw new Error("name must be an env var name");if(!/^https?:\/\//.test(String(t||"")))throw new Error("url must be an http(s) MCP endpoint");Ne.has(e)&&In(e);let a=await Ec(t),i=await vc(a.authorizationServer),c=z.clients[i.issuer],l=c?.redirectUri?Number(new URL(c.redirectUri).port):0,u=await Oc(s||l),f=u?`http://127.0.0.1:${u.address().port}/callback`:null;if(!f)throw new Error("could not open a loopback callback port");let p=r?{clientId:r,clientSecret:o}:null;if(!p&&c?.clientId&&c.redirectUri===f&&(p={clientId:c.clientId,clientSecret:c.clientSecret??null}),!p){try{p=await Lh(i,f)}catch(A){throw u.close(),A}z.clients[i.issuer]={...p,redirectUri:f,registeredAt:Date.now()},await Dt()}let g=Ss(ys.randomBytes(48)),S=Ss(ys.createHash("sha256").update(g).digest()),x=Ss(ys.randomBytes(24)),_=n||a.scope||null,R=new URL(i.authorizationEndpoint);R.searchParams.set("response_type","code"),R.searchParams.set("client_id",p.clientId),R.searchParams.set("redirect_uri",f),R.searchParams.set("code_challenge",S),R.searchParams.set("code_challenge_method","S256"),R.searchParams.set("state",x),R.searchParams.set("resource",a.resource),_&&R.searchParams.set("scope",_);let M={name:e,url:t,verifier:g,state:x,redirectUri:f,server:u,md:i,client:p,resource:a.resource,scope:_,startedAt:Date.now(),done:null};return M.timer=setTimeout(()=>In(e,"login timed out \u2014 start it again"),jh),M.timer.unref?.(),u.on("request",(A,$)=>{let I=new URL(A.url,"http://127.0.0.1");if(I.pathname!=="/callback")return $.statusCode=404,$.end("not found");Ic(e,I.search).then(()=>{$.setHeader("content-type","text/plain"),$.end(`Bostrat: ${e} is signed in on this node. You can close this tab.`)},E=>{$.statusCode=400,$.setHeader("content-type","text/plain"),$.end(`Bostrat: login failed \u2014 ${E?.message||E}`)})}),Ne.set(e,M),it(),{name:e,authorizeUrl:R.toString(),redirectUri:f,resource:a.resource,issuer:i.issuer,scope:_}}function In(e,t="cancelled"){let n=Ne.get(e);return n?(clearTimeout(n.timer),n.server.close(),Ne.delete(e),n.done?.(new Error(t)),it(),!0):!1}async function Rc(e,t,n){let r=new URLSearchParams(t),o={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};n.clientSecret?o.authorization=`Basic ${Buffer.from(`${n.clientId}:${n.clientSecret}`).toString("base64")}`:r.set("client_id",n.clientId);let s=await Nn(e,{method:"POST",headers:o,body:r,signal:AbortSignal.timeout(2e4)}),a={};try{a=await s.json()}catch{}if(!s.ok||!a.access_token){let i=new Error(a.error_description||a.error||`token endpoint answered ${s.status}`);throw i.code=a.error||`http_${s.status}`,i}return a}async function Ic(e,t){await Ft();let n=Ne.get(e);if(!n)throw new Error(`no login in progress for ${e} \u2014 run \`bostrat-mcp login\` first`);let r=String(t||"").trim(),o=null;if(/^https?:\/\//.test(r)||r.startsWith("?")){let i=new URL(r.startsWith("?")?`http://127.0.0.1/callback${r}`:r);if(i.searchParams.get("error"))throw new Error(`the server refused: ${i.searchParams.get("error_description")||i.searchParams.get("error")}`);r=i.searchParams.get("code")||"",o=i.searchParams.get("state")}if(!r)throw new Error("no authorization code in that \u2014 paste the full URL the browser landed on");if(o!=null&&o!==n.state)throw new Error("that redirect belongs to a different login attempt \u2014 start again");let s=await Rc(n.md.tokenEndpoint,{grant_type:"authorization_code",code:r,redirect_uri:n.redirectUri,code_verifier:n.verifier,resource:n.resource},n.client),a=Date.now();return z.tokens[e]={access:String(s.access_token),refresh:s.refresh_token?String(s.refresh_token):null,expiresAt:Number(s.expires_in)>0?a+Number(s.expires_in)*1e3:null,tokenEndpoint:n.md.tokenEndpoint,issuer:n.md.issuer,clientId:n.client.clientId,clientSecret:n.client.clientSecret??null,resource:n.resource,scope:s.scope?String(s.scope):n.scope,url:n.url,obtainedAt:a,needsLogin:!1,lastError:null},await Dt(),clearTimeout(n.timer),n.server.close(),Ne.delete(e),it(),{name:e,expiresAt:z.tokens[e].expiresAt,refreshable:!!z.tokens[e].refresh}}async function Fh(e){return await Ft(),In(e),z.tokens[e]?(delete z.tokens[e],await Dt(),it(),!0):!1}async function Nc(e){await Ft();let t=z.tokens[e];if(!t?.refresh)return!1;try{let n=await Rc(t.tokenEndpoint,{grant_type:"refresh_token",refresh_token:t.refresh,resource:t.resource,...t.scope?{scope:t.scope}:{}},{clientId:t.clientId,clientSecret:t.clientSecret}),r=Date.now();return z.tokens[e]={...t,access:String(n.access_token),refresh:n.refresh_token?String(n.refresh_token):t.refresh,expiresAt:Number(n.expires_in)>0?r+Number(n.expires_in)*1e3:null,obtainedAt:r,needsLogin:!1,lastError:null},await Dt(),it(),!0}catch(n){let r=n?.code==="invalid_grant"||n?.code==="invalid_client"||/^http_4/.test(n?.code||"");return z.tokens[e]={...t,lastError:n?.message||String(n),...r?{needsLogin:!0,access:null,refresh:null}:{}},await Dt(),r&&it(),!1}}async function _s({aheadMs:e=Ph}={}){await Ft();let t=Object.entries(z.tokens).filter(([,r])=>r.refresh&&!r.needsLogin&&r.expiresAt!=null&&r.expiresAt-e<=Date.now());for(let[r]of t)await Nc(r);let n=!1;for(let[r,o]of Object.entries(z.tokens))!o.refresh&&!o.needsLogin&&o.expiresAt!=null&&o.expiresAt<=Date.now()&&(z.tokens[r]={...o,needsLogin:!0,lastError:"token expired and the server issued no refresh token \u2014 log in again"},n=!0);return n&&(await Dt(),it()),t.map(([r])=>r)}async function Uh({refreshEveryMs:e=6e4}={}){return await Ft(),e>0&&!Lt&&(Lt=setInterval(()=>{_s().catch(()=>{})},e),Lt.unref?.()),await _s().catch(()=>{}),Er()}function Hh({fetch:e=null}={}){for(let t of[...Ne.keys()])In(t);z={tokens:{},clients:{}},bs=!1,kr.clear(),Lt&&clearInterval(Lt),Lt=null,Nn=e||((...t)=>globalThis.fetch(...t))}var Ch,$r,xs,jh,Ph,Bh,z,bs,Ne,kr,Lt,Nn,it,Ac,As,Ar,Ss,$s=k(()=>{q();Ch=()=>process.env.BOSTRAT_STATE_DIR||Ts.join(process.env.HOME||Mh.tmpdir(),".bostrat"),$r=()=>Ts.join(Ch(),"mcp-tokens.json"),xs=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/,jh=10*6e4,Ph=5*6e4,Bh="bostrat-node",z={tokens:{},clients:{}},bs=!1,Ne=new Map,kr=new Set,Lt=null,Nn=(...e)=>globalThis.fetch(...e);it=()=>{for(let e of kr)try{e()}catch{}};Ac=e=>typeof e?.access=="string"&&e.access&&!e.needsLogin&&(e.expiresAt==null||e.expiresAt>Date.now());As=()=>[...Ne.keys()];Ar=(e,t)=>{let n=new URL(e),r=n.pathname.replace(/\/+$/,"");return[`${n.origin}/.well-known/${t}${r}`,`${n.origin}/.well-known/${t}`].filter((o,s,a)=>a.indexOf(o)===s)};Ss=e=>e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");j("mcp-oauth",async()=>{let e=null;try{e=JSON.parse(await st.readFile($r(),"utf8"))}catch{return null}let t=Object.entries(e?.tokens||{}).filter(([n,r])=>xs.test(n)&&r?.tokenEndpoint);return t.length?{class:"integration",mode:"timer",host:t.map(([,n])=>n.tokenEndpoint),armedBy:[`mcp-tokens.json: ${t.map(([n])=>n).join(", ")} (bostrat-mcp login)`],purpose:"OAuth token refresh for managed MCP servers"}:null})});import Wh from"node:fs";import Fe from"node:fs/promises";import Dc from"node:os";import Ht from"node:path";function Uc(e){return Os.add(e),()=>Os.delete(e)}function vr(){return{entries:structuredClone(vs),at:Date.now()}}function Vh(e,t,n){if(e.transport==="http"){let o=Object.fromEntries(Object.entries(e.headers||{}).map(([s,a])=>[s,Ut(a,t)]));return{...n==="claude"?{type:"http"}:{},url:Ut(e.url,t),...Object.keys(o).length?{headers:o}:{}}}let r=Object.fromEntries((e.env||[]).map(o=>[o,t[o]]));return{...n==="claude"?{type:"stdio"}:{},command:e.command,args:(e.args||[]).map(o=>Ut(o,t)),...Object.keys(r).length?{env:r}:{}}}function Jh(e,t){let n=[`[mcp_servers.${e.name}]`];if(e.transport==="http"){n.push(`url = ${Mn(Ut(e.url,t))}`);let r=Object.fromEntries(Object.entries(e.headers||{}).map(([o,s])=>[o,Ut(s,t)]));Object.keys(r).length&&n.push(`http_headers = ${jc(r)}`)}else{n.push(`command = ${Mn(e.command)}`),n.push(`args = [${(e.args||[]).map(o=>Mn(Ut(o,t))).join(", ")}]`);let r=Object.fromEntries((e.env||[]).map(o=>[o,t[o]]));Object.keys(r).length&&n.push(`env = ${jc(r)}`)}return n.join(`
|
|
4
7
|
`)+`
|
|
5
|
-
`,{mode:384}),Ut.chmodSync(e,384)}function fo(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 Ht,Fe,Ta,xa,co,Bd,Gt=R(()=>{Ht=process.env.BOSTRAT_STATE_DIR||Pn.join(process.env.HOME||_a.tmpdir(),".bostrat"),Fe=()=>Pn.join(Ht,"node.env"),Ta="local",xa=new Set(["1","true","on","yes"]);co=null;Bd=Object.freeze({loops:"Loops are off in local mode: this plane runs no scheduler.",push:"Phone notifications are off in local mode: this plane sends nothing to ntfy or web push.",share:"Share links are off in local mode: views are reachable on this machine only."})});var jd,zt=R(()=>{jd=16*1024});var pe,ft,Vt=R(()=>{pe="BOSTRAT_HOOK_TOKEN",ft="x-bostrat-hook"});var $a,Ud,ho=R(()=>{$a=(e,t)=>{if(e==null||e==="")return t;let n=Number(e);return Number.isFinite(n)&&n>=0?n:t},Ud=$a(process.env.BOSTRAT_HOOK_FOLD_MS,250)});function Ra(e,t=va){let n=String(e??""),r=n.split(/\s*(?:;|&&|\|\||\||\n)\s*/).map(o=>o.trim()).filter(Boolean);return Number.isFinite(t)&&n.length>=t&&r.length&&r.pop(),r}function qt(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function xo(e){let t=0;for(;t<e.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]);)t++;return{cmd:e[t]??null,rest:e.slice(t+1),at:t}}function So(e){let t=qt(e),n=t.findIndex(m=>m==="git"||m.endsWith("/git"));if(n<0)return null;for(n++;n<t.length&&t[n].startsWith("-");)(t[n]==="-C"||t[n]==="-c")&&n++,n++;if(t[n]!=="push")return null;let r=[],o=[];for(let m=n+1;m<t.length;m++){let d=t[m];d.startsWith("-")?(r.push(d),(d==="-o"||d==="--push-option"||d==="--repo"||d==="--receive-pack"||d==="--exec")&&m++):o.push(d)}let s=r.some(m=>m==="--force"||/^-[a-zA-Z]+$/.test(m)&&m.includes("f"))||o.some(m=>m.startsWith("+")),a=r.some(m=>m.startsWith("--force-with-lease")||m.startsWith("--force-if-includes")),l=o[0]??null,h=o.slice(1).map(m=>m.replace(/^["']|["']$/g,"").replace(/^\+/,"")).map(m=>m.includes(":")?m.slice(m.indexOf(":")+1):m).filter(m=>m&&!m.startsWith("$"));return{force:s,lease:a,remote:l,dsts:h}}function vo(e){let{cmd:t,at:n}=xo(e);if(t==="sudo"){for(n++;n<e.length&&e[n].startsWith("-");)n++;t=e[n]??null}return{cmd:t,at:n}}function ko(e,t){let n=String(e??"").match(t);if(!n)return null;let r=n[1],o=r.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");if(new RegExp(`>{1,2}\\s*["']?[^\\s"']*${o}`).test(e))return"redirect";let s=qt(e),{cmd:a}=vo(s);return!a||!s.some(l=>l.includes(r))?null:/^(?:rm|mv|truncate|chmod|chown|tee|install|shred|unlink|ln|mkdir|touch)$/.test(a)?a:a==="sed"&&s.some(l=>/^-[a-zA-Z]*i/.test(l))?"sed -i":a==="cp"&&s[s.length-1].includes(r)?"cp":/^(?:python3?|perl|node|ruby)$/.test(a)&&/open\([^)]*['"][wa]|writeFile|write_text|appendFile|fs\.write/.test(e)?`${a} write`:null}function Ka(e){let t=qt(e),{cmd:n,at:r}=vo(t);if(!n)return null;let o=t.slice(r+1);if(n==="crontab"||n.endsWith("/crontab")){let a=!1,l=!1;for(let h=0;h<o.length;h++){if(o[h]==="-u"){h++;continue}o[h]==="-l"||/^-(?:h|V|T|-help|-version)$/.test(o[h])?a=!0:l=!0}return l||!a?"crontab":null}if(n==="systemctl"||n.endsWith("/systemctl")){let a=o.find(l=>!l.startsWith("-"));return a&&Ca.test(a)?`systemctl ${a}`:null}if((n==="loginctl"||n.endsWith("/loginctl"))&&o.includes("enable-linger"))return"loginctl enable-linger";if(n==="at"&&o.length&&/^(?:now|midnight|noon|teatime|today|tomorrow|next|\d|-[fqmvt])/.test(o[0]))return"at";let s=ko(e,Ao);return s?`${s} unit/cron path`:null}function Ga(e){let t=new Set;for(let n of String(e??"").matchAll(La))t.add(n[1].toLowerCase());return[...t]}var Aa,va,mo,go,wo,yo,bo,zd,ka,Ea,Bn,Oa,fe,jn,Na,Ma,Ia,Pa,$o,Ao,Ca,Ba,Da,ja,La,_o,To,Fa,Ua,Ha,Wa,Y,ht,Dn,Eo,Vd,qd,Oo=R(()=>{ho();Aa="BP-AU-R4",va=160,mo=200,go=5,wo=8,yo=5,bo=10*6e4,zd=Object.freeze(["localhost","127.0.0.1","0.0.0.0","github.com","api.github.com","raw.githubusercontent.com","objects.githubusercontent.com","registry.npmjs.org","pypi.org","files.pythonhosted.org"]),ka=5e3,Ea=new Set(["tool.called","tool.failed"]),Bn=new Set(["Write","Edit","NotebookEdit"]),Oa=e=>String(e??"").replace(/\s+/g," ").trim(),fe=(e,t=120)=>Oa(e).slice(0,t);jn=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,Na=new RegExp(`${jn}/\\.ssh(?:/|\\b)`),Ma=new RegExp(`${jn}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),Ia=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,Pa=/^\.env\.(?:example|sample|template|dist)$/,$o=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,Ao=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${jn}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),Ca=/^(?:enable|disable|start|stop|restart|try-restart|reload|reload-or-restart|daemon-reload|daemon-reexec|link|mask|unmask|edit|preset|preset-all|set-property|revert|isolate|kill|reset-failed|import-environment|set-environment|add-wants|add-requires)$/,Ba=/^\/tmp\/|\/\.bostrat\/tmp\//,Da=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,ja=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,La=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,_o=e=>Na.test(e)||Ma.test(e),To=e=>[...String(e??"").matchAll(Ia)].some(t=>!Pa.test(t[1])),Fa=e=>$o.test(e),Ua=e=>Ao.test(e),Ha=e=>(e.startsWith("/")||e.startsWith("~"))&&!Ba.test(e);Wa=e=>ko(e,$o);Y=(e,t,n,r)=>Object.freeze({severity:e,requirement:Aa,note:t,measured:n,detect:r}),ht=(e,t)=>{let n=0,r=null;for(let o of e.calls)if(o.head)for(let s of Ra(o.head,e.headCap)){let a=t(s,o);a&&(n++,r??=fe(a))}return n?{count:n,sample:r}:null},Dn=(e,t)=>{let n=0,r=null;for(let o of e.calls){let s=t(o);s&&(n++,r??=fe(s))}return n?{count:n,sample:r}:null},Eo=Object.freeze({"force-push":Y("high","git push --force / -f / +refspec in a command head (--force-with-lease, the Track's own rebase flow, is not one)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 1,080 logs 2026-08\u219210 \xB7 58 --force-with-lease pushes excluded by design \u2192 high",(e,t)=>ht(t,n=>{let r=So(n);return r&&r.force&&!r.lease?n:null})),"protected-config-write":Y("high","a write to the box's own harness: .claude/settings*.json, a .claude/hooks/ script or the Track's .bostrat/events/ log \u2014 by a file tool, a redirect, rm/mv/tee/sed -i, or a scripted open-for-write (reads are not hits)","2026-10-21 fleet replay \xB7 0 hits / 98,690 hook calls \xB7 165 reads of those paths (cat, grep, python json.loads) excluded by design \u2192 high",(e,t)=>{let n=0,r=null;for(let s of t.calls)Bn.has(s.tool)&&s.path&&Fa(s.path)&&(n++,r??=fe(`${s.tool} ${s.path}`));let o=ht(t,s=>{let a=Wa(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"persistence-install":Y("medium","a shell segment that installs something the OS runs on its own \u2014 crontab (install / edit / remove; -l is a read), a mutating systemctl verb (enable / start / restart / daemon-reload \u2026; status / show / cat / list / is-* are reads), loginctl enable-linger, at / batch \u2014 or a write (file tool, redirect, cp / mv / tee / ln / sed -i) into a systemd unit or cron directory: how a process outlives its turn by the OS's hand (BP-AU-D6's other half)","2026-10-21 fleet replay \xB7 11 hits / 99,122 hook calls \xB7 10 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-asked service work on the operator's own Pi (systemctl --user restart/stop/start of bostrat-node, tmp-sweep, a samba disable, one `crontab -` install for a backfill) \xB7 the bare `at` word a quoted `|` regex leaves in a segment (4 hits) excluded by design \u2192 medium (rail), the guard's deny when opted in",(e,t)=>{let n=0,r=null;for(let s of t.calls)Bn.has(s.tool)&&s.path&&Ua(s.path)&&(n++,r??=fe(`${s.tool} ${s.path}`));let o=ht(t,s=>{let a=Ka(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"push-outside-track":Y("medium","git push to a protected branch (main/master/develop/release\u2026), to a branch that is not a Track branch, or to a remote other than origin/upstream \u2014 a Track's own code leaves on its track/ branch or the WIP shadow ref","2026-10-21 fleet replay \xB7 7 hits / 98,690 hook calls \xB7 4 Tracks \xB7 0 in the last 14 d \xB7 every hit operator-instructed work on another repo (two dep/ branches, a fork's multiplayer branch, one HEAD:main) \u2192 medium, not a page",(e,t)=>ht(t,n=>{let r=So(n);return r&&(r.remote&&!/^(?:origin|upstream)$/.test(r.remote)&&!r.remote.startsWith("$")&&!r.remote.startsWith("-")||r.dsts.some(o=>Da.test(o)||!ja.test(o)))?n:null})),"credential-read":Y("medium","a command head or file path naming SSH material (~/.ssh) or a vendor auth file (~/.claude.json, ~/.claude/.credentials.json, ~/.codex/auth.json, ~/.cursor) \u2014 the box-auth policy's denylist shapes; ~/.claude/projects (transcripts) is not one","2026-10-21 fleet replay \xB7 12 hits / 98,690 hook calls \xB7 8 Tracks \xB7 3 in the last 14 d \xB7 every hit an operator-asked inspection on the operator's own node (ssh config for a host alias, stat/keys of ~/.claude.json) \u2192 medium until a 14-day window reads 0",(e,t)=>Dn(t,n=>n.head&&_o(n.head)?n.head:n.path&&_o(n.path)?`${n.tool} ${n.path}`:null)),"dotenv-read":Y("low","a command head or file path naming a .env file (.env, .env.local, .env.production \u2026; the committed .env.example / .sample / .template are not ones)","2026-10-21 fleet replay \xB7 309 hits / 98,690 hook calls \xB7 44 Tracks \xB7 0 in the last 14 d \xB7 all of them an instructed `source \u2026/almanac/.env` on the operator's other repos \u2192 low (report only)",(e,t)=>Dn(t,n=>n.head&&To(n.head)?n.head:n.path&&To(n.path)?`${n.tool} ${n.path}`:null)),"privileged-command":Y("medium","a shell segment whose command is sudo or docker (after any VAR=value prefix) \u2014 host-level reach from inside a box","2026-10-21 fleet replay \xB7 220 hits (183 events) / 98,690 hook calls \xB7 57 Tracks \xB7 3 in the last 14 d \xB7 sudo = the operator's own journalctl/systemctl asks on the Pi, docker = instructed compose/psql work on the operator's other services \u2192 medium (a hosted node's first hit is the number to watch)",(e,t)=>ht(t,n=>{let{cmd:r}=xo(qt(n));return r==="sudo"||r==="docker"?n:null})),"write-outside-workspace":Y("low","a file tool (Write / Edit / NotebookEdit) on an absolute path \u2014 the hook strips the box's workspace prefix, so an absolute path is outside it \u2014 that is not the box's scratch dir (/tmp/\u2026, \u2026/.bostrat/tmp/\u2026)","2026-10-21 fleet replay \xB7 106 hits / 98,690 hook calls \xB7 10 Tracks \xB7 44 in the last 14 d \xB7 the operator's other repos and Agent-tool worktrees under .bostrat/repos on the operator's own node \u2192 low (report only)",(e,t)=>Dn(t,n=>Bn.has(n.tool)&&n.path&&Ha(n.path)?`${n.tool} ${n.path}`:null)),"egress-new-host":Y("low","a command head reaching, by URL, a host no box in the fleet has reached before (this projection's lifetime, seeded from the warm tails; KNOWN_HOSTS + PLANE_AUDIT_KNOWN_HOSTS never count) \u2014 a baseline-growth signal, so each host is reported once","2026-10-21 fleet replay \xB7 140 first sightings / 98,690 hook calls \xB7 69 Tracks \xB7 8 in the last 14 d \xB7 198 if the baseline were per Track \xB7 every host a vendor API, a docs site or the operator's own services \u2192 low (report only)",(e,t)=>{let n=0,r=null;for(let o of t.calls)if(o.head)for(let s of Ga(o.head))t.state.known.has(s)||t.state.hosts.has(s)||(t.state.hosts.add(s),t.state.hosts.size>ka&&t.state.hosts.delete(t.state.hosts.values().next().value),n++,r??=fe(`${s} \xB7 ${o.head}`));return n?{count:n,sample:r}:null}),"spend-spike":Y("low",`a cost.recorded turn over ${wo}\xD7 the Track's running median (its last ${mo} cost events, at least ${go} of them) and over $${yo} \u2014 a turn that cost far more than this Track's turns do`,"2026-10-21 fleet replay \xB7 114 hits / 8,421 cost events \xB7 64 Tracks \xB7 2 in the last 14 d \xB7 every hit a long build turn after short prompts (a $25\u201378 turn on a $0.37 median) \u2014 real spend, no one's attack \u2192 low (report only)",(e,t)=>{if(e.type!=="cost.recorded")return null;let n=t.track.costs,r=Number(e.payload?.usd);if(!Number.isFinite(r)||r<0)return null;let o=null;if(n.length>=go&&r>=yo){let s=[...n].sort((l,h)=>l-h),a=s[Math.floor(s.length/2)];r>wo*a&&(o={count:1,sample:`$${r.toFixed(2)} vs median $${a.toFixed(2)} over ${n.length} turns${e.payload?.model?` \xB7 ${e.payload.model}`:""}`})}return n.push(r),n.length>mo&&n.shift(),o}),"peer-injected-call":Y("medium",`a tool call within ${bo/6e4} min of a peer.message on the same box with no operator or node-typed turn in between \u2014 the cross-session injection vector (peer-message.js); a peer is never a root (BP-AU-D1)`,"2026-10-21 fleet replay \xB7 0 peer.message events in 288,395 \xB7 the replay cannot bound this rule's rate, so it stays medium (rail) until a window with peer traffic has been measured; the shape itself is BP-AU-D1's stated R4 case",(e,t)=>{if(!t.calls.length)return null;let n=t.track.peer.get(t.boxKey);if(n==null||t.ts-n>bo||t.ts<n)return null;let r=t.calls[0];return{count:t.count,sample:fe(`${Math.round((t.ts-n)/1e3)}s after a peer message \xB7 ${r.tool}${r.head?`: ${r.head}`:r.path?` ${r.path}`:""}`)}}),"foreign-session-call":Y("medium","a hook-recorded tool call from a claude session that is not the box's own (payload.foreignSession, BP-AU-I12): a nested or stray CLI driving the box's hooks \u2014 R3 never roots it, this names it","2026-10-21 fleet replay \xB7 14 hits / 98,744 hook calls \xB7 3 Tracks \xB7 4 in the last 14 d \xB7 all the xscout loop's nested claude prompts, I12's own acceptance case \u2192 medium (rail), not a page",(e,t)=>{if(!t.calls.length||!e.payload?.foreignSession)return null;let n=t.calls[0];return{count:t.count,sample:fe(`session ${String(e.payload.sessionId||"?").slice(0,8)} \xB7 ${n.tool}${n.head?`: ${n.head}`:n.path?` ${n.path}`:""}`)}}),"orphan-process":Y("medium","a process the box left running: detached from the pane's tree (its cgroup or pty still lists it), alive at a turn's close and still alive minutes later with no turn open and no background job recorded \u2014 the node's own census (orphan-watch.js, BP-AU-D6), each process once","2026-10-27 fleet replay \xB7 0 audit.procs events in 304,814 (1,121 logs; the type is new, so the replay cannot bound this rule's rate) \xB7 live Pi census the same day: 10 boxes, 2 detached processes, both found by the cgroup census and neither by the pty one (a claude tool call runs on pipes) \u2014 one planted `nohup sleep &`, one real `flyctl agent run` that a lead's flyctl call had left behind 10 h earlier \u2192 medium (rail), never a page, until a window of live samples has been measured",e=>{if(e.type!=="audit.procs"||e.source!=="proc")return null;let t=e.payload||{},n=Array.isArray(t.orphans)?t.orphans:[],r=n.length+(Number(t.dropped)||0);if(!r)return null;let o=n[0]||{},s=Number.isFinite(o.sinceMs)?` \xB7 alive ${Math.max(1,Math.round(o.sinceMs/6e4))} min`:"";return{count:r,sample:fe(`${o.comm||"process"}${o.cmd?`: ${o.cmd}`:""}${o.via?` [${o.via}]`:""}${s}${r>1?` (+${r-1} more)`:""}`)}}),"unknown-harness-shape":Y("medium","a harness-made user turn of a shape chat-notes.js does not list (harness.shape.seen with known: false, harness-shapes.js): Claude Code wrote a new kind of its own turn into a transcript \u2014 hidden from chat by the generic catch, counted once per shape per node here; the node pages the operator once on first sight, this row is the fleet's record","2026-10-28 fleet replay \xB7 0 harness.shape.seen events in 311,055 (1,132 logs; the type is new, so the replay cannot bound this rule's rate) \xB7 transcript scan the same day: 2,863 claude user turns in 1,539 transcripts over 90 d, 144 of them harness-made (isMeta), 9 distinct shapes, 4 of which had rendered in chat as operator messages (<system-reminder><tools-used-before-summary> on 2 Tracks under 2.1.312, a usage-limit-reset notice, a safety-classifier notice) \u2192 medium (rail finding + security row), never a page from the plane: the once-per-shape page is the node's, so a release that adds one shape pages once, not per Track per hour",e=>{if(e.type!=="harness.shape.seen"||e.source!=="transcript")return null;let t=e.payload||{};if(t.known!==!1||!t.key)return null;let n=`${t.provider||"cli"}${t.cliVersion?` ${t.cliVersion}`:""}`;return{count:1,sample:fe(`${t.key} \xB7 ${n}${t.head?` \xB7 ${t.head}`:""}`)}})}),Vd=Object.freeze(Object.keys(Eo)),qd=new Set([...Ea,"cost.recorded","peer.message","turn.user","audit.procs","harness.shape.seen"])});function qa(e){let t=String(e??"").trim().toLowerCase();if(za.has(t))return{enabled:!1,rules:[],unknown:[]};if(Va.has(t))return{enabled:!0,rules:[...Ln],unknown:[]};let n=[],r=[];for(let o of t.split(",")){let s=o.trim();s&&(Ln.includes(s)?n.includes(s)||n.push(s):r.push(s))}return{enabled:n.length>0,rules:n,unknown:r}}function Ro(e){return e?.enabled?`on \xB7 denies ${e.rules.length===Ln.length?"the high set: ":""}${e.rules.join(", ")}${e.unknown.length?` \xB7 ignoring unknown ${e.unknown.join(", ")}`:""} \xB7 fail-open (an unanswered hook allows)`:"off (BOSTRAT_AUDIT_GUARD unset \u2014 PreToolUse records, never denies)"}var Ln,za,Va,Fn,Un=R(()=>{Oo();Ln=Object.freeze(["force-push","protected-config-write","credential-read","persistence-install"]),za=new Set(["","off","0","false","no","none"]),Va=new Set(["on","1","true","yes","all"]);Fn=(e=process.env)=>qa(e.BOSTRAT_AUDIT_GUARD)});import Ue from"node:fs";import Mo from"node:fs/promises";import Xt from"node:os";import X from"node:path";import{execFile as Io}from"node:child_process";import{promisify as Ya}from"node:util";function Bo(e){try{return Ue.readFileSync(e,"utf8").split(`
|
|
6
|
-
`
|
|
7
|
-
|
|
8
|
-
|
|
8
|
+
|
|
9
|
+
`}function Hc(e){let t=[],n=`(?:[A-Za-z0-9_-]+|"[^"
|
|
10
|
+
]*"|'[^'
|
|
11
|
+
]*')`,r=new RegExp(`^[ \\t]*\\[\\[?[ \\t]*${n}(?:[ \\t]*\\.[ \\t]*${n})*[ \\t]*\\]\\]?[ \\t]*(?:#.*)?$`,"gm"),o=0,s;for(;s=r.exec(e);)s.index===0&&o===0||(t.push(e.slice(o,s.index)),o=s.index);return t.push(e.slice(o)),t}function Wc(e){let t=/^[ \t]*\[\s*mcp_servers\s*\.\s*(?:"([^"]+)"|([A-Za-z0-9_-]+))\s*[\].]/.exec(e);return t?t[1]??t[2]:null}function Pc(e){return new Set(Hc(String(e||"")).map(Wc).filter(Boolean))}function Xh(e,t,n){let r=String(e||""),o=new Set,s="";for(let a of Hc(r)){let i=Wc(a);if(i&&t.has(i)){o.has(i)||(s+=t.get(i),o.add(i));continue}i&&n.has(i)||(s+=a)}for(let[a,i]of t)o.has(a)||(s&&!s.endsWith(`
|
|
12
|
+
`)&&(s+=`
|
|
13
|
+
`),s&&!s.endsWith(`
|
|
14
|
+
|
|
15
|
+
`)&&(s+=`
|
|
16
|
+
`),s+=i);return s}async function Zh(e){try{return await Fe.readFile(e,"utf8")}catch(t){if(t?.code==="ENOENT")return null;throw t}}async function Rs(e,t){await Fe.mkdir(Ht.dirname(e),{recursive:!0});let n=`${e}.bostrat-${process.pid}.tmp`,r=384;try{r=(await Fe.stat(e)).mode&511}catch{}await Fe.writeFile(n,t,{mode:r}),await Fe.rename(n,e)}async function Qh(e,t,n,r){let o={},s=e==="claude"?Tc():e==="codex"?xc():Gh(),a=_=>{for(let R of t.keys())o[R]=_};if(e!=="claude"&&!Wh.existsSync(Ht.dirname(s)))return a("cli-absent"),{managed:[],states:o};let i;try{i=await Zh(s)}catch{return a("error"),{managed:n,states:o}}let c=new Set(n);if(e==="codex"){let _=Pc(i??""),R=new Map;for(let[E,L]of t)_.has(E)&&!c.has(E)?o[E]="conflict":R.set(E,Jh(L,r));let M=new Set([...c].filter(E=>!t.has(E))),A=Xh(i??"",R,M);try{A!==(i??"")&&await Rs(s,A)}catch{for(let E of R.keys())o[E]="error";return{managed:n,states:o}}for(let E of R.keys())o[E]="applied";let $=Pc(i??""),I=new Set([...R.keys()].filter(E=>A!==(i??"")&&(!$.has(E)||!(i??"").includes(R.get(E)))));return{managed:[...R.keys()].sort(),states:o,wrote:I}}let l={};if(i!=null&&i.trim()){try{l=JSON.parse(i)}catch{return a("error"),{managed:n,states:o}}if(!l||typeof l!="object"||Array.isArray(l))return a("error"),{managed:n,states:o}}let u=l.mcpServers&&typeof l.mcpServers=="object"?{...l.mcpServers}:{},f=[];for(let[_,R]of t){if(Object.hasOwn(u,_)&&!c.has(_)){o[_]="conflict";continue}u[_]=Vh(R,r,e),f.push(_)}for(let _ of c)t.has(_)||delete u[_];let p={...l,mcpServers:u};!Object.keys(u).length&&!l.mcpServers&&delete p.mcpServers;let g=JSON.stringify(l.mcpServers??{})!==JSON.stringify(u);try{g&&await Rs(s,JSON.stringify(p,null,2))}catch{for(let _ of f)o[_]="error";return{managed:n,states:o}}for(let _ of f)o[_]="applied";let S=l.mcpServers&&typeof l.mcpServers=="object"?l.mcpServers:{},x=new Set(f.filter(_=>JSON.stringify(S[_]??null)!==JSON.stringify(u[_])));return{managed:f.sort(),states:o,wrote:x}}async function em(){let e=zh(),t={};try{(await Fe.stat(e)).mode&63&&await Fe.chmod(e,384).catch(()=>{});let a=JSON.parse(await Fe.readFile(e,"utf8"));t=Object.fromEntries(Object.entries(a||{}).filter(([,i])=>typeof i=="string"&&i!==""))}catch{t={}}let r={...ks(),...t},o={};for(let s of Object.keys(r))o[s]=s in t?"file":"broker";return{values:r,sources:o}}function tm(e){if(e?.transport!=="http")return null;for(let[t,n]of Object.entries(e.headers||{})){if(!/^authorization$/i.test(t))continue;let r=/\$\{([A-Za-z_][A-Za-z0-9_]{0,63})\}/.exec(String(n));if(r)return r[1]}return null}function nm(e,t,n,r,o){let s={},a=tm(e);for(let i of e.env||[])if(t[i]!=null){let c=n[i]==="broker"?r[i]:null;s[i]={state:"set",source:n[i],...c?.expiresAt?{expiresAt:c.expiresAt}:{},...c?{refreshable:!!c.refreshable}:{}}}else o.includes(i)?s[i]={state:"login-pending",source:"broker"}:r[i]?s[i]={state:"needs-login",source:"broker",...r[i].error?{error:r[i].error}:{}}:e.auth==="oauth"&&i===a?s[i]={state:"needs-login",source:"broker"}:s[i]={state:"missing"};return s}function Kc(e){return(Array.isArray(e)?e:[]).filter(t=>t&&Yh.test(t.name)&&(t.transport==="http"?typeof t.url=="string":typeof t.command=="string")).map(t=>t.auth==="oauth"?t:(({auth:n,...r})=>r)(t))}async function Bc(){let{values:e,sources:t}=await em(),n=Er(),r=As(),o=Kc(Me.entries),s={};for(let u of o){let f=nm(u,e,t,n,r),p=Object.entries(f).filter(([,g])=>g.state!=="set").map(([g])=>g);s[u.name]={rev:Number(u.updatedAt)||0,clis:{},since:{},missingEnv:p,env:f,...u.auth==="oauth"?{auth:"oauth"}:{}}}let a={...Me.managed},i={...Me.since||{}},c=Date.now();for(let u of Es){let f=new Map(o.filter(S=>(S.clis||Es).includes(u)&&!s[S.name].missingEnv.length).map(S=>[S.name,S])),p=await Qh(u,f,Me.managed?.[u]??[],e);a[u]=p.managed;let g={...i[u]||{}};for(let[S,x]of Object.entries(p.states)){s[S].clis[u]=x;let _=s[S].rev;x==="applied"?((!g[S]||g[S].rev!==_)&&(g[S]={rev:_,at:p.wrote?.has(S)?c:Math.max(_,g[S]?.at??0)||c}),s[S].since[u]=g[S].at):delete g[S]}for(let S of Object.keys(g))f.has(S)||delete g[S];i[u]=g}for(let u of o){if(!s[u.name].missingEnv.length)continue;let p=Object.values(s[u.name].env).map(g=>g.state).includes("missing")?"missing-secret":"needs-login";for(let g of u.clis||Es)s[u.name].clis[g]=p}Me={...Me,managed:a,since:i},await rm();let l=JSON.stringify(s)!==JSON.stringify(vs);if(vs=s,l)for(let u of Os)try{u(vr())}catch{}return vr()}async function rm(){let e=JSON.stringify(Me,null,2);if(e!==Lc)try{await Rs(Kh(),e),Lc=e}catch(t){console.error("[mcp-config] cache write failed:",t?.message||t)}}function om(){let e=Cc.then(Bc,Bc);return Cc=e.catch(()=>{}),e}function zc(e,{updatedAt:t=Date.now()}={}){return Me={...Me,entries:Kc(e),updatedAt:t},om()}var Fc,Kh,zh,Gh,Es,Yh,qh,Me,vs,Cc,Os,Ut,Mn,jc,Lc,Gc=k(()=>{ms();ws();$s();Fc=()=>process.env.BOSTRAT_STATE_DIR||Ht.join(process.env.HOME||Dc.tmpdir(),".bostrat"),Kh=()=>Ht.join(Fc(),"mcp-config.json"),zh=()=>Ht.join(Fc(),"mcp-env.json"),Gh=()=>Ht.join(Dc.homedir(),".cursor","mcp.json"),Es=["claude","codex","cursor"],Yh=/^[a-z0-9][a-z0-9_-]{0,47}$/,qh=/\$\{([A-Za-z_][A-Za-z0-9_]{0,63})\}/g,Me={entries:[],updatedAt:null,managed:{claude:[],codex:[],cursor:[]},since:{}},vs={},Cc=Promise.resolve(),Os=new Set;Ut=(e,t)=>String(e).replace(qh,(n,r)=>t[r]??"");Mn=e=>JSON.stringify(String(e)),jc=e=>`{ ${Object.entries(e).map(([t,n])=>`${Mn(t)} = ${Mn(n)}`).join(", ")} }`;Lc=null});import Yc from"node:fs/promises";import Jc from"node:path";import sm from"node:os";function am(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("refresh-flow patch must be an object");let t={};for(let[n,r]of Object.entries(e)){if(!(n in Is))throw new Error(`unknown refresh-flow field "${n}" \u2014 fields: ${Zc.join(", ")}`);if(r===null||r===""||r===void 0){t[n]=null;continue}switch(n){case"contextFull":case"limitHit":if(typeof r!="string"||!qc.includes(r))throw new Error(`${n} must be one of ${qc.join(", ")}`);t[n]=r;break;case"contextFullPct":{let o=Number(r);if(!Number.isFinite(o)||o<1||o>100)throw new Error("contextFullPct must be a number from 1 to 100");t[n]=Math.round(o);break}case"contextFullTokens":{let o=Number(r);if(!Number.isFinite(o)||o<=0)throw new Error("contextFullTokens must be a positive number of tokens or null");t[n]=Math.round(o);break}case"fallback":{if(typeof r!="object"||Array.isArray(r))throw new Error("fallback must be an object of provider \u2192 [providers]");let o={};for(let[s,a]of Object.entries(r)){if(!Vc.test(s))throw new Error(`bad provider key "${s}" in fallback`);if(!Array.isArray(a)||a.some(c=>typeof c!="string"||!Vc.test(c)))throw new Error(`fallback.${s} must be a list of provider keys`);let i=[...new Set(a.filter(c=>c!==s))];i.length&&(o[s]=i)}t[n]=Object.keys(o).length?o:null;break}default:throw new Error(`unknown refresh-flow field "${n}"`)}}return t}function cm(e){let t={...Is};for(let n of Zc){let r=e?.[n];r!=null&&(t[n]=r)}return t}function um(){return cm(Wt?.flow)}function Qc(){return{flow:um(),configured:!!Wt,source:Wt?.source??null,updatedAt:Wt?.updatedAt??null}}async function dm(){try{await Yc.mkdir(Xc,{recursive:!0}),await Yc.writeFile(im(),JSON.stringify(Wt,null,2))}catch{}}function el(e=null){for(let t of lm)try{t(Qc(),e)}catch{}}function tl(e){el({rejected:String(e||"rejected by the plane")})}async function nl(e,{source:t="plane",updatedAt:n=Date.now()}={}){return Wt={flow:am(e||{}),updatedAt:n,source:t},await dm(),el(),Qc()}var Xc,im,qc,Is,Zc,Vc,Wt,lm,rl=k(()=>{Xc=process.env.BOSTRAT_STATE_DIR||Jc.join(process.env.HOME||sm.tmpdir(),".bostrat"),im=()=>Jc.join(Xc,"refresh-flow.json"),qc=["prompt","auto","off"],Is=Object.freeze({contextFull:"prompt",contextFullPct:75,contextFullTokens:null,limitHit:"prompt",fallback:null}),Zc=Object.keys(Is),Vc=/^[a-z][a-z0-9-]{0,31}$/;Wt=null,lm=new Set});function Ir(e=Date.now()){if(ct)return{tripped:!1,holdMs:1/0};if(at>e)return{tripped:!1,holdMs:at-e};if((!jn||e-jn>=Or.windowMs)&&(jn=e,Cn=0),Cn++,Cn<Or.trip)return{tripped:!1,holdMs:0};Rr++;let t=Math.min(Or.minMs*2**(Rr-1),Or.maxMs);return at=e+t,Cn=0,jn=0,{tripped:!0,holdMs:t}}function ol(){Cn=0,jn=0,Rr=0,at=0}function Pn(e=Date.now()){return ct?1/0:at>e?at-e:0}function Nr(e=Date.now()){return Pn(e)>0}function Ns(e={}){ct={at:Date.now(),...e},at=1/0}function Ms(){return ct}function sl(e=Date.now()){return{held:Nr(e),holdMs:ct?null:Pn(e),holds:Rr,removed:ct?{...ct}:null}}var pm,Or,Cn,jn,Rr,at,ct,Cs=k(()=>{pm={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},Or={...pm},Cn=0,jn=0,Rr=0,at=0,ct=null});var Hs={};Z(Hs,{REMOVED_MARKER:()=>Fs,detectInstallKind:()=>Gt,detectProviderAuth:()=>pl,maskToken:()=>Ds,readRemovedMarker:()=>dl,startPlaneLink:()=>Rm,updateCommandFor:()=>Ln,versionLt:()=>zt});import Kt from"node:fs";import Bn from"node:fs/promises";import fm from"node:http";import ee from"node:path";import Cr from"node:os";import{createRequire as hm}from"node:module";import js from"ws";function Ds(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function dl(e=Fs){try{let t=JSON.parse(Kt.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function Gt({env:e=process.env,pkgDir:t=ee.resolve(ee.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(ee.join(t,"..",".git"))?"git-checkout":"dev"}function zt(e,t){let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let o=0;o<Math.max(n.length,r.length);o++){let s=(n[o]||0)-(r[o]||0);if(s)return s<0}return!1}function Ln(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 pl({home:e=process.env.HOME||Cr.homedir(),env:t=process.env}={}){let n=r=>{try{return Kt.statSync(r),!0}catch{return!1}};return{claude:n(ee.join(e,".claude",".credentials.json")),codex:n(ee.join(t.CODEX_HOME||ee.join(e,".codex"),"auth.json")),cursor:n(ee.join(t.XDG_CONFIG_HOME||ee.join(e,".config"),"cursor","auth.json"))}}function Rm({url:e,token:t,nodeId:n=Cr.hostname(),name:r=Cr.hostname(),listTracks:o,detectAgents:s=null,onTracksTransferred:a=null,onTracksMoves:i=null,sampleMetrics:c=null,deliverySample:l=null,onHashKey:u=null,onViewBase:f=null,onMode:p=null,metricsMs:g=Om,onUpdateAvailable:S=null,onUpdatePolicy:x=null,onConflictProbe:_=null,restart:R=null,onRestarted:M=null,onHelloRefused:A=null,updatePolicy:$=null,installKind:I=Gt(),selfUrl:E=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:L=null,removedMarkerFile:fe=Fs,onRemoved:hn=null,onDegraded:kt=null,onRecovered:Co=null,onRefused:tr=null,onConnected:nr=null,ingestMode:At=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:mn=Tm,unackedRetryMs:Ve=_m,pingMs:B=Sm,deadLinkMs:Te=Math.round(B*bm),maxInflightEvents:gn=$m,httpTimeoutMs:he=Em,fanoutActive:rr=null,fanoutBatchCap:Qi=vm,stallBackoffMinMs:ea=Am,fetchImpl:ta=globalThis.fetch,log:v=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=lt(e);let zp=E.replace(/^http/,"ws"),na=new Set,ra=h=>{let w=typeof h.latestNodeVersion=="string"?h.latestNodeVersion:null;if(!(!(w&&ye&&zt(ye,w))||na.has(w))){na.add(w),v.log(`[plane-link] bostrat-node ${w} is available (this node runs ${ye}) \u2014 ${Ln(I)}`);try{S?.({current:ye,latest:w,min:h.minNodeVersion??null,installKind:I,required:!!(h.minNodeVersion&&zt(ye,h.minNodeVersion))})}catch(y){v.error(`[plane-link] update notice failed: ${y?.message||y}`)}}},Je=new Map,Xe=new Map,jo=ee.join(Ls,"plane-link","cursor.json"),Po=ee.join(Ls,"plane-link","dead-letter.ndjson"),oa=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),Ae={},me={},D=new Map,or=null,Pe=null,$e=0,wn=0,sa=0,sr={},ia=new Set,aa=Promise.resolve(),J="ws",$t=0,ge=!1,Ze=0,Bo=!1,Be=Mr,yn=new Set,we=[],X=null,ae=null,ce=!1,Et=!1,ir=!1,Lo=!1,Sn=il,bn=null,Do=R&&typeof R=="object"?R:null,vt=null,Ot=null,Ee=null,Qe=0,ca=0,ve=null,Fo=!1,ar=0,_n=!1,Le=dl(fe);if(Le)if(Le.tokenPreview===Ds(t))_n=!0,Ns({reason:Le.reason??"removed",at:Le.at??null,nodeId:Le.nodeId??n}),v.error(`[plane-link] this node was REMOVED from the plane (${Le.reason??"removed"}${Le.at?` at ${new Date(Le.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${fe} to force a dial.`);else try{Kt.unlinkSync(fe),v.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function Uo({reason:h="removed",at:w=Date.now(),via:y="ctl"}={}){if(!_n){_n=!0,Ns({reason:h,at:w,nodeId:n,via:y});try{Kt.mkdirSync(ee.dirname(fe),{recursive:!0}),Kt.writeFileSync(fe,JSON.stringify({at:w,reason:h,via:y,nodeId:n,tokenPreview:Ds(t)},null,2))}catch(d){v.error(`[plane-link] could not write ${fe}: ${d?.message||d}`)}v.error(`[plane-link] the plane REMOVED this node (${h}, via ${y}) \u2014 going dormant: no more dials, ingest or broker calls. Re-provision with a new node token to reconnect; the box and its data are untouched.`);try{hn?.({reason:h,at:w,via:y})}catch{}ba({bye:!1})}}async function Gp(){try{Ae=JSON.parse(await Bn.readFile(jo,"utf8"))}catch{Ae={}}}function la(){Fo=!0,!Ot&&(Ot=setTimeout(async()=>{if(Ot=null,!!Fo){Fo=!1;try{await Bn.mkdir(ee.dirname(jo),{recursive:!0}),await Bn.writeFile(jo,JSON.stringify(Ae))}catch(h){v.error("[plane-link] cursor flush failed:",h?.message||h)}}},ym),Ot.unref?.())}function Ho(){try{return!!rr?.()}catch{return!1}}function Wo(){let h=J==="http"?Be:Mr;return Ho()?Math.min(h,Qi):h}function U(h){return!ae||ae.readyState!==js.OPEN?!1:(ae.send(JSON.stringify(h)),!0)}let Yp=Uc(h=>U({v:H,ch:"ctl",type:"mcp_status",mcp:h}));function Rt(h){let w=Date.now();for(let{trackId:d,event:m}of h){let T=D.get(m.id);D.set(m.id,{trackId:d,seq:m.seq,event:m,sentAt:w,firstSentAt:T?.firstSentAt??w,retryAt:w+Ve,tries:(T?.tries??0)+1,nacks:T?.nacks??0})}let y=h.map(({trackId:d,event:m})=>({trackId:d,event:km(m)}));return J==="http"?(Qp(y),!0):U({v:H,ch:"events",type:"append",events:y})}function ua(h,w=Date.now()){if(yn.has(h))return!0;for(let y of D.values())if(y.trackId===h&&w-y.firstSentAt<mn)return!0;return!1}function qp(h){let w=null;for(let y of D.values())y.trackId===h&&(w==null||y.seq<w)&&(w=y.seq);return w}function cr(h){if(ir)return;let w=me[h];if(w==null)return;let y=qp(h),d=y==null?w:Math.min(w,y-1);d>(Ae[h]??0)&&(Ae[h]=d,la())}function Tn(){if(or=Date.now(),Pe!=null){let h=Date.now()-Pe;v.log(`[plane-link] spine sync recovered after ${Math.round(h/1e3)}s degraded (${$e} stall redial(s))`);let w=Pe;Pe=null,$e=0,wn=0,ge=!1,Ze=0;try{Co?.({since:w,downMs:h})}catch(y){v.error(`[plane-link] onRecovered failed: ${y?.message||y}`)}}}function Ko(h){if(!Array.isArray(h)||!h.length)return;let w=new Set;for(let y of h){let d=D.get(y);d&&(D.delete(y),(me[d.trackId]??0)<d.seq&&(me[d.trackId]=d.seq),w.add(d.trackId))}for(let y of w)cr(y);Tn()}function da(h,w){sa++;let y={at:Date.now(),trackId:h.trackId,seq:h.seq,id:h.event?.id??null,type:h.event?.type??null,reason:w,event:h.event??null};v.error(`[plane-link] DEAD-LETTER ${h.trackId} seq ${h.seq} (${y.type??"?"}): plane rejected it permanently (${w}) \u2014 kept in ${Po}`),aa=aa.then(async()=>{await Bn.mkdir(ee.dirname(Po),{recursive:!0}),await Bn.appendFile(Po,JSON.stringify(y)+`
|
|
17
|
+
`)}).catch(d=>v.error(`[plane-link] dead-letter write failed: ${d?.message||d}`))}function Vp(h,w){if(sr[h]=(sr[h]??0)+1,ia.has(h))return;ia.add(h);let y=xm[h]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";v.error(`[plane-link] REFUSED by the plane (${h}) on track ${w}: events are being dropped, not stored \u2014 ${y}`);try{tr?.({reason:h,trackId:w,count:sr[h],hint:y})}catch(d){v.error(`[plane-link] onRefused failed: ${d?.message||d}`)}}function zo(h,w,y,d=null){if(!Array.isArray(h)||!h.length)return;let m=new Set,T=Date.now();for(let N of h){let C=D.get(N);C&&(y?(D.delete(N),da(C,w),String(w).startsWith(Ps)&&Vp(String(w).slice(Ps.length),C.trackId),(me[C.trackId]??0)<C.seq&&(me[C.trackId]=C.seq),m.add(C.trackId)):(C.nacks++,C.retryAt=T+Math.max(1e3,Number(d)||Ve)))}for(let N of m)cr(N);Tn()}function pa(h=Date.now()){let w=1/0;for(let y of D.values())y.firstSentAt<w&&(w=y.firstSentAt);return w===1/0?0:h-w}function Jp(h){if(!Te||!h||h!==ae||!Qe)return!1;let w=Date.now()-Qe;if(w<=Te)return!1;ca++,v.error(`[plane-link] no frame from the plane for ${Math.round(w/1e3)}s \u2014 link is half-open; terminating and redialing`);try{h.terminate()}catch{}return!0}function fa(){if(!ce||!D.size)return;let h=Date.now(),w=pa(h);if(w<mn||or!=null&&h-or<mn||J==="http"&&ge||wn>h)return;$e++;let y=Math.min(ea*2**($e-1),cl);if(Pe==null){Pe=h-w,v.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(w/1e3)}s with ${D.size} event(s) in flight (${J} door) \u2014 the plane is not answering appends`);try{kt?.({since:Pe,unacked:D.size,oldestAgeMs:w,mode:J})}catch(d){v.error(`[plane-link] onDegraded failed: ${d?.message||d}`)}}if(J==="http"){ge=!0,Ze=h+y,v.error(`[plane-link] ingest circuit OPEN (stall #${$e}); probing /v1/ingest/health in ${Math.round(y/1e3)}s`);return}wn=h+y,v.error(`[plane-link] closing the link and redialing in ${Math.round(y/1e3)}s (stall redial #${$e})`);try{ae?.terminate()}catch{}}function Go(){if(!ce)return;let h=Date.now();if(J==="http"&&ge)return;let w=[...D.values()].filter(d=>d.event&&d.retryAt<=h&&!(J==="http"&&yn.has(d.trackId)));if(!w.length)return;w.sort((d,m)=>d.trackId===m.trackId?d.seq-m.seq:d.trackId<m.trackId?-1:1),v.log(`[plane-link] re-sending ${w.length} unacked event(s) the plane never confirmed`);let y=Wo();if(J==="http"){let d=new Map;for(let m of w)(d.get(m.trackId)??d.set(m.trackId,[]).get(m.trackId)).push(m);for(let[,m]of d){if($t>=Bs)return;Rt(m.slice(0,y).map(T=>({trackId:T.trackId,event:T.event})))}return}for(let d=0;d<w.length;d+=y){let m=w.slice(d,d+y).map(T=>({trackId:T.trackId,event:T.event}));if(!Rt(m))return}}async function Xp(h=null){for(;;){if(!ce)return!1;let w=D.size<gn,y=J!=="http"||$t<Bs&&!ge&&(!h||!ua(h));if(w&&y)return!0;await new Promise(d=>setTimeout(d,100))}}function lr(){if(X=null,!ce||!we.length)return;let h=we;we=[];let w=Wo();if(J!=="http"){for(let m=0;m<h.length;m+=w)Rt(h.slice(m,m+w));return}let y=Ho(),d=new Map;for(let m of h)(d.get(m.trackId)??d.set(m.trackId,[]).get(m.trackId)).push(m);for(let[m,T]of d){if(ua(m)||$t>=Bs||ge){we.push(...T);continue}if(y){Rt(T.slice(0,w)),we.push(...T.slice(w));continue}for(let N=0;N<T.length;N+=w)Rt(T.slice(N,N+w))}we.length&&!X&&(X=setTimeout(lr,ll),X.unref?.())}let Zp=h=>{let w=new Map;for(let{trackId:y,event:d}of h)(w.get(y)??w.set(y,[]).get(y)).push(d);return[...w].map(([y,d])=>({trackId:y,events:d}))},et=(h,w,y,{progress:d})=>{let m=Date.now();for(let{event:T}of h){let N=D.get(T.id);N&&(N.nacks++,N.retryAt=m+Math.max(1e3,y||Ve))}d&&Tn()};async function Qp(h){let w=new Set(h.map(y=>y.trackId));for(let y of w)yn.add(y);$t++;try{let y=await ta(`${oa}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:Zp(h)}),signal:AbortSignal.timeout(he)}),d=(Number(y.headers.get("retry-after"))||0)*1e3;if(y.status===200){let m=await y.json();Be=Mr;for(let C of m.results??[]){Ko(C.acked??[]);let K=(xe,re)=>{let ur=new Map;for(let tt of xe??[])(ur.get(tt.reason)??ur.set(tt.reason,[]).get(tt.reason)).push(tt.id);for(let[tt,_a]of ur)zo(_a,tt,re,m.retryAfterMs??null)};K(C.rejected,!0),K(C.deferred,!1)}let T=new Set,N=new Map;for(let C of Array.isArray(m.refused)?m.refused:[])!C||typeof C.id!="string"||(T.add(C.id),(N.get(C.reason)??N.set(C.reason,[]).get(C.reason)).push(C.id));for(let[C,K]of N)zo(K,`${Ps}${C}`,!0);Ko((m.discarded??[]).filter(C=>!T.has(C))),Tn();return}if(y.status===429){et(h,"overloaded",d||5e3,{progress:!0});return}if(y.status===413&&h.length>1){Be=Math.max(1,Math.floor(h.length/2)),v.error(`[plane-link] ingest request too large (${h.length} events) \u2014 halving batches to ${Be}`),et(h,"too_large",1e3,{progress:!0});return}if(y.status===413){let m=D.get(h[0].event.id);m&&(D.delete(m.event.id),da(m,"too_large"),(me[m.trackId]??0)<m.seq&&(me[m.trackId]=m.seq),cr(m.trackId)),Tn();return}if(y.status===410){Uo({reason:"removed",via:"410"}),et(h,"http_410",6e4,{progress:!1});return}if(y.status===401||y.status===403){let{tripped:m,holdMs:T}=Ir();if(m&&v.error(`[plane-link] holding every plane call for ${Math.round(T/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-ar>=ul){ar=Date.now();let N="";try{N=(await y.json())?.error??""}catch{}v.error(`[plane-link] plane refused ingest (HTTP ${y.status}${N?`: ${N}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}et(h,`http_${y.status}`,Math.max(6e4,Pn()),{progress:!1});return}if(y.status===400){v.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${h.length} event(s) for retry; this is a bug, not data`),et(h,"http_400",6e4,{progress:!1});return}et(h,`http_${y.status}`,d||5e3,{progress:!1})}catch(y){let d=y?.name==="TimeoutError"||y?.name==="AbortError";d&&h.length>1&&(Be=Math.max(1,Math.floor(h.length/2)),v.error(`[plane-link] ingest request of ${h.length} event(s) outlived its ${he} ms deadline \u2014 halving batches to ${Be}`)),et(h,d?"timeout":"network",5e3,{progress:!1})}finally{$t--;for(let y of w)yn.delete(y);we.length&&!X&&(X=setTimeout(lr,0),X.unref?.())}}async function ef(){if(J!=="http"||!ge||!ce||Bo)return;let h=Date.now();if(!(Ze>h||Nr(h))){Bo=!0;try{let w=await ta(`${oa}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(he)});if(!w.ok)throw new Error(`HTTP ${w.status}`);v.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),ge=!1,Ze=0,wn=Date.now()+he+Ve+1e3;for(let y of D.values())y.retryAt=Math.min(y.retryAt,Date.now());Go()}catch(w){$e++;let y=Math.min(ea*2**($e-1),cl);Ze=Date.now()+y,v.error(`[plane-link] ingest door still not answering (${w?.message||w}); next probe in ${Math.round(y/1e3)}s`)}finally{Bo=!1}}}function ha(){let h=Date.now();return{mode:J,unacked:D.size,oldestUnackedAgeMs:pa(h),lastProgressAt:or,degradedSince:Pe,stallRedials:$e,deadLettered:sa,fanoutCap:Ho()?Qi:null,http:J==="http"?{inFlight:$t,circuitOpen:ge,nextProbeInMs:ge?Math.max(0,Ze-h):0,batchCap:Be,heldLive:we.length}:null}}async function ma(){if(!c)return;let h;try{h=await c()}catch(y){v.error("[plane-link] metrics sample failed:",y?.message||y);return}let w=null;try{w=l?.()??null}catch{}h&&U({v:H,ch:"ctl",type:"metrics",metrics:{...h,planeLink:ha(),...w?{delivery:w}:{}}})}function tf(){c&&(ve&&clearInterval(ve),ma(),ve=setInterval(ma,g),ve.unref?.())}async function nf(){let h;try{h=await o()}catch(w){v.error("[plane-link] backfill listTracks failed:",w?.message||w);return}U({v:H,ch:"ctl",type:"tracks",ids:h.filter(w=>!w.transferredTo).map(w=>w.id).filter(w=>typeof w=="string")});for(let w of h)if(!ce||!await ga(w))return;ir=!1;for(let w of Object.keys(me))cr(w)}async function ga(h){let w;try{w=await rt(h)}catch{return!0}let y=Ae[h.id]??0,d=w.filter(m=>m.seq>y&&typeof m.id=="string");for(let m=0;m<d.length;){if(!await Xp(h.id))return!1;let T=d.slice(m,m+Wo()).map(N=>({trackId:h.id,event:N}));if(!Rt(T))return!1;m+=T.length}return!0}let Yo=new Map;async function wa(h,w){if(Yo.get(h)===w)return!1;Yo.set(h,w);let y=null;try{y=(await o()).find(N=>N?.id===h)??null}catch{return!1}if(!y)return!1;let d;try{d=await rt(y)}catch{return!1}let m=[...d].reverse().find(N=>(N?.type==="track.transferred"||N?.type==="track.recovered")&&N.payload?.toNode===n);if(!m||!Number.isFinite(m.seq))return!1;let T=m.seq-1;return(Ae[h]??0)>T&&(Ae[h]=T,la()),(me[h]??0)>T&&(me[h]=T),v.log(`[plane-link] re-sending ${h}'s move-commit (seq ${m.seq}, ${m.type}) \u2014 the plane's move record predates this node's adoption`),ce?ga(y):!1}function ya(h){!ce||!h?.trackId||typeof h.id!="string"||(we.push({trackId:h.trackId,event:h}),X||(X=setTimeout(lr,ll),X.unref?.()))}let xn=new Map;async function rf(h){let{reqId:w,method:y,path:d,headers:m={},body:T}=h,N=Object.fromEntries(Object.entries(m).filter(([,K])=>K!=null)),C=new AbortController;xn.set(w,C);try{if(h.host){await of(h,N,C);return}L&&(N["x-bostrat-token"]=L);let K=await fetch(E+d,{method:y,headers:N,body:T?Buffer.from(T,"base64"):void 0,signal:C.signal}),xe=Object.fromEntries(K.headers);for(let re of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete xe[re];if(xe["content-type"]||(xe["content-type"]="application/octet-stream"),U({v:H,ch:"control",type:"http_head",reqId:w,status:K.status,headers:xe}),K.body){for await(let re of K.body)if(!U({v:H,ch:"control",type:"http_data",reqId:w,data:Buffer.from(re).toString("base64")}))break}U({v:H,ch:"control",type:"http_end",reqId:w,error:null})}finally{xn.delete(w)}}function of(h,w,y){let{reqId:d,method:m,path:T,body:N}=h,C=new URL(E);return new Promise(K=>{let xe=fm.request({host:C.hostname,port:C.port,method:m,path:T,headers:{...w,host:h.host},signal:y.signal},re=>{let{connection:ur,"keep-alive":tt,"transfer-encoding":_a,upgrade:Lb,...sf}=re.headers;U({v:H,ch:"control",type:"http_head",reqId:d,status:re.statusCode||502,headers:sf}),re.on("data",af=>{U({v:H,ch:"control",type:"http_data",reqId:d,data:Buffer.from(af).toString("base64")})||re.destroy()}),re.on("end",()=>{U({v:H,ch:"control",type:"http_end",reqId:d,error:null}),K()}),re.on("error",()=>{U({v:H,ch:"control",type:"http_end",reqId:d,error:"view upstream error"}),K()})});xe.on("error",re=>{U({v:H,ch:"control",type:"http_end",reqId:d,error:re?.message||"view request failed"}),K()}),N&&xe.write(Buffer.from(N,"base64")),xe.end()})}function Sa(){if(Lo||_n)return;ae=new js(e,{headers:{authorization:`Bearer ${t}`}});let h=ae;Qe=0,h.on("ping",()=>{Qe=Date.now()}),h.on("pong",()=>{Qe=Date.now()}),ae.on("open",async()=>{let y=null;try{y=await s?.()||null}catch{y=null}U({v:H,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:ye,installKind:I,...typeof $=="function"?{updatePolicy:$()}:$?{updatePolicy:$}:{},providers:pl(),...y?{agents:y}:{},mcp:vr(),...Do?{restart:Do}:{}})}),ae.on("message",y=>{Qe=Date.now();let d;try{d=JSON.parse(y)}catch{return}if(d.ch==="ctl"&&d.type==="warming"){Et||v.log("[plane-link] plane is warming \u2014 hello held until it is ready"),Et=!0;return}if(d.ch==="ctl"&&d.type==="hello_ok"){Yo.clear(),Et&&v.log("[plane-link] plane is ready \u2014 held hello answered"),Et=!1,ce=!0,Sn=il,bn=null,Do=null,ol(),v.log(`[plane-link] connected to plane as ${n}`);try{nr?.()}catch{}if(typeof d.hashKey=="string"&&d.hashKey)try{u?.(d.hashKey)}catch{}try{f?.(typeof d.viewBase=="string"&&d.viewBase?d.viewBase:null)}catch{}try{p?.(d.mode==="local"?"local":"default")}catch{}d.minNodeVersion&&ye&&zt(ye,d.minNodeVersion)&&v.error(`[plane-link] this node is bostrat-node ${ye}; the plane asks for \u2265${d.minNodeVersion} \u2014 update with: ${Ln(I)}`);try{x?.(typeof d.updatePolicy=="string"?d.updatePolicy:null)}catch{}ra(d);let m=d.ingest==="http";J=At==="ws"?"ws":At==="http"||m?"http":"ws",At==="http"&&!m&&v.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),J==="http"&&v.log("[plane-link] spine rides the HTTPS ingest door"),ge=!1,Ze=0,Be=Mr,Ee&&clearInterval(Ee),Qe=Date.now(),Ee=setInterval(()=>{Jp(h)||(U({v:H,ch:"ctl",type:"ping"}),fa(),ef().catch(()=>{}),Go(),we.length&&!X&&lr())},B),Ee.unref?.(),tf(),ir=!0,nf().catch(T=>v.error("[plane-link] backfill failed:",T?.message||T));return}if(d.ch==="ctl"&&d.type==="hello_refused"){let m=typeof d.minNodeVersion=="string"?d.minNodeVersion:null,T=typeof d.latestNodeVersion=="string"?d.latestNodeVersion:null;v.error(`[plane-link] plane REFUSED this node: bostrat-node ${ye??"?"} is below its minimum ${m??"?"} \u2014 ${d.fix||Ln(I)}`),Sn=al,bn=0;try{A?.({current:ye,min:m,latest:T,fix:d.fix||Ln(I),installKind:I})}catch(N){v.error(`[plane-link] refusal handler failed: ${N?.message||N}`)}return}if(d.ch==="ctl"&&d.type==="removed"){U({v:H,ch:"ctl",type:"removed_ack",nodeId:n}),Uo({reason:typeof d.reason=="string"?d.reason:"removed",at:Number(d.at)||Date.now(),via:"ctl"});return}if(d.ch==="ctl"&&d.type==="update_available"){ra(d);return}if(d.ch==="ctl"&&d.type==="update_policy"){try{x?.(typeof d.mode=="string"?d.mode:null)}catch{}return}if(d.ch==="ctl"&&d.type==="conflict_probe"&&Array.isArray(d.trackIds)){try{_?.(d.trackIds.filter(m=>typeof m=="string"&&m).slice(0,200))}catch{}return}if(d.ch==="ctl"&&d.type==="restarted"){Promise.resolve().then(()=>M?.({kind:d.kind,at:d.at,reason:d.reason})).catch(m=>v.error("[plane-link] restart notice failed:",m?.message||m));return}if(d.ch==="ctl"&&d.type==="usage_caps"){Ya(d.caps??{},{source:"plane",updatedAt:d.updatedAt??Date.now()}).then(m=>v.log(`[plane-link] spend caps ${Object.keys(m.caps).length?`updated (${Object.keys(m.caps).join(", ")})`:"cleared"} from plane`)).catch(m=>v.error("[plane-link] spend-caps push rejected:",m?.message||m));return}if(d.ch==="ctl"&&d.type==="mcp_config"){zc(d.entries??[],{updatedAt:d.updatedAt??Date.now()}).then(m=>v.log(`[plane-link] mcp config applied: ${Object.keys(m.entries).length} entr${Object.keys(m.entries).length===1?"y":"ies"}`)).catch(m=>v.error("[plane-link] mcp config apply failed:",m?.message||m));return}if(d.ch==="ctl"&&d.type==="refresh_flow"){nl(d.flow??{},{source:"plane",updatedAt:d.updatedAt??Date.now()}).then(m=>v.log(`[plane-link] refresh flow from plane: contextFull=${m.flow.contextFull} rung=${m.flow.contextFullTokens?`${m.flow.contextFullTokens} tokens`:`${m.flow.contextFullPct}%`}`)).catch(m=>v.error("[plane-link] refresh-flow push rejected:",m?.message||m));return}if(d.ch==="ctl"&&d.type==="refresh_flow_rejected"){tl(typeof d.error=="string"?d.error:"rejected by the plane");return}if(d.ch==="ctl"&&d.type==="transferred"&&Array.isArray(d.tracks)){Promise.resolve().then(()=>a?.(d.tracks)).then(async m=>{for(let T of Array.isArray(m)?m:[])T?.stale&&T.id&&await wa(T.id,T.since??null)}).catch(m=>v.error("[plane-link] transfer notice failed:",m?.message||m));return}if(d.ch==="ctl"&&d.type==="moves"&&Array.isArray(d.tracks)){Promise.resolve().then(()=>i?.(d.tracks)).then(async m=>{for(let T of Array.isArray(m)?m:[])T?.stale&&T.id&&await wa(T.id,T.since??null)}).catch(m=>v.error("[plane-link] move-record reconcile failed:",m?.message||m));return}if(d.ch==="events"&&d.type==="ack"&&Array.isArray(d.ids)){Ko(d.ids);return}if(d.ch==="events"&&d.type==="nack"&&Array.isArray(d.ids)){zo(d.ids,d.reason,d.permanent===!0,d.retryAfterMs??null);return}if(d.ch==="control"&&d.type==="http_open"){rf(d).catch(m=>U({v:H,ch:"control",type:"http_end",reqId:d.reqId,error:m?.message||"tunnel error"}));return}if(d.ch==="control"&&d.type==="http_cancel"){xn.get(d.reqId)?.abort();return}if(d.ch==="attach"&&d.type==="open"){let m=new js(zp+d.path,Array.isArray(d.protocols)?d.protocols:[],d.host?{headers:{host:d.host}}:void 0);Je.set(d.streamId,m),Xe.set(d.streamId,[]),m.on("open",()=>{let N=Xe.get(d.streamId)||[];Xe.delete(d.streamId);for(let{buf:C,bin:K}of N)m.send(C,{binary:K})}),m.on("message",(N,C)=>{let K=C?N:Buffer.from(String(N));U({v:H,ch:"attach",type:"data",streamId:d.streamId,data:K.toString("base64"),...C?{bin:!0}:{}})});let T=()=>{Xe.delete(d.streamId),Je.delete(d.streamId)&&U({v:H,ch:"attach",type:"close",streamId:d.streamId})};m.on("close",T),m.on("error",T);return}if(d.ch==="attach"&&d.type==="data"){let m=Je.get(d.streamId);if(!m)return;let T=Buffer.from(d.data,"base64"),N=d.bin===!0,C=Xe.get(d.streamId);C?C.push({buf:T,bin:N}):m.send(T,{binary:N});return}if(d.ch==="attach"&&d.type==="close"){let m=Je.get(d.streamId);Je.delete(d.streamId),Xe.delete(d.streamId),m?.close();return}});let w=()=>{ce&&v.log("[plane-link] disconnected from plane"),ce=!1,Et=!1,Ee&&(clearInterval(Ee),Ee=null),ve&&(clearInterval(ve),ve=null),D.clear(),me={},we=[],X&&(clearTimeout(X),X=null),yn.clear();for(let m of Je.values())m.close();Je.clear(),Xe.clear();for(let m of xn.values())m.abort();if(xn.clear(),Lo||vt)return;bn==null&&(bn=Date.now());let y=Date.now()-bn<mm,d=Math.max(y?gm+Math.random()*wm:Sn,wn-Date.now(),Pn());vt=setTimeout(()=>{vt=null,Sa()},d),vt.unref?.(),y||(Sn=Math.min(Sn*2,al))};ae.on("close",w),ae.on("error",y=>{let d=/Unexpected server response: (\d+)/.exec(y?.message||"")?.[1];if(d==="410"){Uo({reason:"removed",via:"410"});return}if(d==="401"||d==="403"){let{tripped:m,holdMs:T}=Ir();m?v.error(`[plane-link] holding every plane call for ${Math.round(T/6e4)} min \u2014 three credential refusals in a row (HTTP ${d}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(T/6e4)} min.`):Date.now()-ar>=ul&&(ar=Date.now(),v.error(`[plane-link] plane refused this node's credentials (HTTP ${d}) \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)`))}w()})}nt.on("event",ya),Gp().then(Sa);function ba({bye:h=!0}={}){Lo=!0,nt.off("event",ya),Yp(),vt&&clearTimeout(vt),Ot&&clearTimeout(Ot),Ee&&clearInterval(Ee),ve&&clearInterval(ve),X&&clearTimeout(X),h&&U({v:H,ch:"ctl",type:"bye",reason:"shutdown"}),ae?.close()}return{stop:()=>ba(),setRefreshFlow:h=>U({v:H,ch:"ctl",type:"refresh_flow_set",patch:h}),status:()=>({connected:ce,warming:Et,nodeId:n,cursor:{...Ae},backfillHeld:ir,inflight:D.size,...ha(),auth:sl(),dormant:_n,removed:Ms(),deadLinkMs:Te,deadLinkRedials:ca,refused:{...sr}}),_tick:()=>{fa(),Go()}}}var ye,Ls,Fs,H,il,al,mm,gm,wm,Mr,ym,Sm,bm,_m,Us,Tm,Ps,xm,km,Am,cl,$m,ll,Em,Bs,vm,Om,ul,jr=k(()=>{Mt();qa();Gc();rl();Ue();Cs();q();ye=(()=>{try{return hm(import.meta.url)("../package.json").version||null}catch{return null}})(),Ls=process.env.BOSTRAT_STATE_DIR||ee.join(process.env.HOME||Cr.tmpdir(),".bostrat"),Fs=ee.join(Ls,"plane-link","removed.json");H=1,il=1e3,al=3e4,mm=6e4,gm=1500,wm=500,Mr=100,ym=2e3,Sm=25e3,bm=2.5,_m=6e4,Us=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Tm=Us(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),Ps="refused:",xm={forgedUserId:"this node's events carry a userId the plane's token does not own \u2014 remove BOSTRAT_OWNER from node.env and the shell environment, then restart the node (current releases never stamp one)",foreignTrack:"the Track belongs to another user's node \u2014 this node must not append to it",squattedTrack:"the Track id is already claimed by another user \u2014 a local Track collided with theirs",transferredAway:"the Track moved to another node \u2014 this copy is stale; it should be demoted, not resumed",slugHijack:"a View slug belongs to another owner \u2014 pick a different slug"},km=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},Am=3e4,cl=10*6e4,$m=400,ll=250,Em=Us(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),Bs=4,vm=Math.max(1,Math.round(Us(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),Om=6e4,ul=6e4;j("plane",({env:e})=>e.BOSTRAT_PLANE_URL?{class:"plane",mode:"timer",host:lt(e.BOSTRAT_PLANE_URL),armedBy:["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"],purpose:"the coordination plane: the link, event ingest, content and brokered tokens"}:null)});var wl={};Z(wl,{__resetReposForTest:()=>Fm,forgeHosts:()=>gl,listRepos:()=>Ks,localRepoPathForSlug:()=>Dm,parseRepoSlug:()=>ml,repoSlug:()=>Br});import Ws from"node:fs/promises";import He from"node:path";import{execFile as Im}from"node:child_process";import{promisify as Nm}from"node:util";async function Bm(e){try{return(await Ws.stat(He.join(e,".git"))).isDirectory()?"repo":"worktree"}catch{return null}}async function Lm(e){let t=i=>Ws.readFile(He.join(e,".git",i),"utf8").then(c=>c.trim()).catch(()=>null),r=(await t("refs/remotes/origin/HEAD"))?.match(/^ref:\s*refs\/remotes\/origin\/(.+)/);if(r)return r[1].trim();let o;for(let i of["main","master"])if(await t(`refs/heads/${i}`)||(o??=await t("packed-refs")||"",new RegExp(`^[0-9a-f]{40} refs/heads/${i}$`,"m").test(o)))return i;let a=(await t("HEAD"))?.match(/^ref:\s*refs\/heads\/(.+)/);return a?a[1].trim():null}async function Ks(){let e=new Map;async function t(o,s){if(e.has(o))return;let a=await Bm(o);if(a==="worktree")return;if(a==="repo"){e.set(o,{path:o,name:He.basename(o),branch:await Lm(o)});return}if(s>=jm)return;let i;try{i=await Ws.readdir(o,{withFileTypes:!0})}catch{return}for(let c of i)!c.isDirectory()||c.name.startsWith(".")||Pm.has(c.name)||await t(He.join(o,c.name),s+1)}for(let o of Cm)await t(He.resolve(o),0);let n=new Set,r=[];for(let o of e.values()){let s=await Br(o.path),a=s?.toLowerCase();if(a){if(n.has(a))continue;n.add(a),o.slug=s}r.push(o)}return r.sort((o,s)=>o.name.localeCompare(s.name))}function ml(e){let t=String(e||"").trim().match(/github\.com[:/]+([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i);return t?`${t[1]}/${t[2]}`:null}async function Br(e){if(!e)return null;if(Pr.has(e))return Pr.get(e);let t=null;try{let{stdout:n}=await fl("git",["-C",e,"config","--get","remote.origin.url"],{timeout:5e3});t=ml(n)}catch{t=null}return Pr.set(e,t),t}async function Dm(e){let t=String(e||"").toLowerCase();if(!t)return null;for(let n of await Ks())if((await Br(n.path))?.toLowerCase()===t)return n.path;return null}function Fm(){Pr.clear()}async function gl(){let e=new Map;for(let t of await Ks()){let n="";try{({stdout:n}=await fl("git",["-C",t.path,"config","--get","remote.origin.url"],{timeout:5e3}))}catch{continue}let r=Gs(n);r&&!/^[./~]/.test(n.trim())&&e.set(r,(e.get(r)||0)+1)}return e}var fl,hl,Mm,Cm,jm,Pm,Pr,zs=k(()=>{q();fl=Nm(Im),hl=process.env.HOME||"/home/globo",Mm=He.join(process.env.BOSTRAT_STATE_DIR||He.join(hl,".bostrat"),"repos"),Cm=[...(process.env.BOSTRAT_REPOS_ROOT||He.join(hl,"Documents")).split(","),Mm].map(e=>e.trim()).filter(Boolean),jm=Number(process.env.BOSTRAT_REPOS_DEPTH)||3,Pm=new Set(["node_modules",".git",".cache","dist","build",".next","vendor","__pycache__","venv",".venv","target"]);Pr=new Map;j("forge",async()=>{let e=await gl();return e.size?{class:"forge",mode:"timer",host:[...e.keys()].flatMap(n=>n==="github.com"?[n,"api.github.com"]:[n]),armedBy:[`the origin remote of ${[...e.values()].reduce((n,r)=>n+r,0)} repo(s) under this node's roots`],purpose:"git and gh: fetch, the WIP push, pull requests"}:null})});import yl from"node:path";import Um from"node:os";import{fileURLToPath as Hm}from"node:url";import{execFile as Wm}from"node:child_process";import{promisify as Km}from"node:util";function Lr(e=process.env){let t=e.BOSTRAT_PLANE_URL||"";if(!t)return null;try{let n=new URL(t);return n.protocol=n.protocol==="ws:"?"http:":"https:",n.origin}catch{return null}}async function Sl(e,{env:t=process.env}={}){let n=(...r)=>zm("git",["-C",e,...r],{timeout:1e4});await n("config","--replace-all","credential.helper",""),await n("config","--add","credential.helper",`!"${Ym()}" ${qm(t)}`),await n("config","credential.useHttpPath","true")}var zm,Gm,UT,HT,WT,Ym,qm,Dr=k(()=>{zs();Cs();zm=Km(Wm),Gm=process.env.BOSTRAT_STATE_DIR||yl.join(process.env.HOME||Um.tmpdir(),".bostrat"),UT=yl.join(Gm,"repos"),HT=5*6e4,WT=10*6e4;Ym=()=>Hm(new URL("../bin/bostrat-git-credential",import.meta.url)),qm=(e=process.env)=>`http://127.0.0.1:${Number(e.PORT)||3362}`});function bl(e,{at:t=Date.now(),reason:n="node-transfer"}={}){let r=!1;for(let o of e?.boxes||[]){if(!o||typeof o!="object")continue;!Vm.has(o.state)&&o.state!=="stopped"&&(o.state="stopped",r=!0);let s=Array.isArray(o.epochs)?o.epochs:[],a=s[s.length-1];a&&typeof a=="object"&&a.endedAt==null&&(a.endedAt=t,a.endReason==null&&(a.endReason=n),r=!0)}return r}var Vm,_l=k(()=>{Vm=new Set(["merged","conflict","canceled","failed","handed-off"])});var kl={};Z(kl,{CREDENTIAL_DENYLIST:()=>xl,rebuildTracksFromSpine:()=>sg,resetStateSyncMemory:()=>ng,stateSyncMode:()=>Xs,syncDiagnostics:()=>tg,syncStateOnce:()=>og});import ut from"node:fs/promises";import Jm from"node:fs";import F from"node:path";import Xm from"node:os";import{execFile as Zm}from"node:child_process";import{promisify as Qm}from"node:util";function Xs({remote:e=process.env.BOSTRAT_STATE_REMOTE||null,env:t=process.env}={}){let n=String(t.BOSTRAT_STATE_SYNC??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?{enabled:!1,reason:"BOSTRAT_STATE_SYNC=off"}:n==="on"||n==="1"||n==="true"?{enabled:!0,reason:"BOSTRAT_STATE_SYNC=on"}:e?{enabled:!0,reason:"BOSTRAT_STATE_REMOTE is set"}:{enabled:!1,reason:"no BOSTRAT_STATE_REMOTE and BOSTRAT_STATE_SYNC unset"}}function tg(){return{...dt,tracked:Yt.size}}function ng(){Yt.clear(),Vs=0;for(let e of Object.keys(dt))dt[e]=0}async function rg(e){let t=await ut.stat(F.join(e.cwd,".bostrat","events",`${e.id}.ndjson`)).catch(()=>null);return t?.isFile()?`${t.size}:${t.mtimeMs}`:"absent"}async function Js(e,t){let n=await ut.stat(e).catch(()=>null);if(!n?.isFile())return!1;let r=await ut.stat(t).catch(()=>null);return r&&r.size===n.size&&r.mtimeMs>=n.mtimeMs?!1:(await ut.mkdir(F.dirname(t),{recursive:!0}),await ut.copyFile(e,t),!0)}async function Ur(e,t,{skip:n=null}={}){let r=0,o=await ut.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(xl.has(s.name)||n?.has(s.name))continue;let a=F.join(e,s.name);s.isDirectory()?r+=await Ur(a,F.join(t,s.name)):s.isFile()&&(r+=await Js(a,F.join(t,s.name))?1:0)}return r}async function og({stateDir:e=qs,dest:t=process.env.BOSTRAT_SYNC_DIR||`${qs}-sync`,remote:n=process.env.BOSTRAT_STATE_REMOTE||null,tracks:r=null}={}){if(!Xs({remote:n}).enabled)return{staged:0,committed:!1,pushed:!1,skipped:"off"};try{await ut.mkdir(t,{recursive:!0});let o=0;o+=await Js(F.join(e,"tracks.json"),F.join(t,"tracks.json"))?1:0,o+=await Js(F.join(e,"events.jsonl"),F.join(t,"events.jsonl"))?1:0,o+=await Ur(F.join(e,"events"),F.join(t,"events")),o+=await Ur(F.join(e,"memory"),F.join(t,"memory"));let s=new Set(["mocks"]);Vs++,dt.passes++;let a=Tl>0&&Vs%Tl===0;a&&dt.fullPasses++;let i=new Set;for(let p of r||[]){if(!p?.cwd||!p?.id)continue;i.add(p.id);let g=await rg(p);if(!a&&Yt.get(p.id)===g){dt.skipped++;continue}dt.walked++,o+=await Ur(F.join(p.cwd,".bostrat"),F.join(t,"workspaces",p.id,".bostrat"),{skip:s}),Yt.set(p.id,g)}for(let p of Yt.keys())i.has(p)||Yt.delete(p);let c=(...p)=>eg("git",["-C",t,...p]);Jm.existsSync(F.join(t,".git"))||(await c("init","-q"),await c("symbolic-ref","HEAD","refs/heads/main"),await c("config","user.email","agent@bostrat.local"),await c("config","user.name","bostrat state sync")),n&&/^https:\/\/github\.com\//i.test(n)&&(await c("config","--get","credential.useHttpPath").then(()=>!0).catch(()=>!1)||await Sl(t).catch(()=>{}));let l=!1,{stdout:u}=await c("status","--porcelain");u.trim()&&(await c("add","-A"),await c("commit","-q","-m",`state sync ${new Date().toISOString()}`),l=!0);let f=!1;if(n&&(l||Fr))try{await c("push","-q",n,"HEAD:refs/heads/main"),f=!0,Fr&&console.log("[state-sync] push recovered \u2014 off-box copy is current again"),Fr=!1,Ys=null}catch(p){Fr=!0;let g=(p?.stderr||p?.message||String(p)).trim().split(`
|
|
18
|
+
`).slice(-3).join(" | ").slice(0,300);g!==Ys&&(Ys=g,console.warn(`[state-sync] PUSH FAILING (retrying each cycle; off-box copy is STALE): ${g}`))}return{staged:o,committed:l,pushed:f}}catch(o){return{staged:0,committed:!1,pushed:!1,error:o?.message||String(o)}}}function sg(e,{stateDir:t=qs}={}){let n=new Map,r=0;for(let s of String(e||"").split(`
|
|
19
|
+
`)){let a=s.trim();if(!a||a[0]!=="{")continue;let i;try{i=JSON.parse(a)}catch{continue}if(!i.trackId||!i.type)continue;r++;let c=n.get(i.trackId);c||(c={id:i.trackId,name:null,cwd:F.join(t,"workspaces",i.trackId),leadBox:null,boxes:[],events:[],createdAt:i.at??null},n.set(i.trackId,c));let{trackId:l,...u}=i;c.events.push(u);let f=p=>c.boxes.find(g=>g.name===p);switch(i.type){case"opened":i.name&&(c.name=i.name),i.cwd&&(c.cwd=i.cwd),i.workspace&&typeof i.workspace=="object"&&(c.workspace={dir:i.cwd||c.cwd,...i.workspace},Array.isArray(c.workspace.repos)&&(c.workspace.repos=c.workspace.repos.map(p=>p&&typeof p=="object"?{...p,dir:p.dir??(p.name?F.join(i.cwd||c.cwd,p.name):null)}:p))),c.createdAt=i.at??c.createdAt,i.box&&!f(i.box)&&(c.boxes.push({name:i.box,agent:i.agent||null,role:"lead",state:"stopped",cwd:c.cwd}),c.leadBox=i.box);break;case"renamed":typeof i.to=="string"&&i.to&&(c.name=i.to);break;case"retagged":if(i.workspace&&typeof i.workspace=="object"&&c.workspace&&(c.workspace={...c.workspace,...i.workspace},Array.isArray(c.workspace.repos)&&(c.workspace.repos=c.workspace.repos.map(p=>p&&typeof p=="object"?{...p,dir:p.dir??(p.name?F.join(c.cwd,p.name):null)}:p))),i.action==="reshape"){if(c.workspace){let{base:g,baseRef:S,repo:x,..._}=c.workspace;c.workspace={..._,dir:c.cwd,kind:"multi",repos:Array.isArray(_.repos)?_.repos:[]}}let p=f(i.box||c.leadBox);if(p){p.cwd=c.cwd,(!Array.isArray(p.epochs)||p.epochs.length===0)&&(p.epochs=[{agent:i.agent??p.agent??null,sessionId:i.fromSessionId??null,startedAt:null,endedAt:null}]);let g=p.epochs[p.epochs.length-1];g.endedAt==null&&(g.endedAt=i.at??null),g.endReason==null&&(g.endReason="reshape"),p.epochs.push({agent:i.agent??p.agent??null,sessionId:i.toSessionId??null,startedAt:i.at??null,endedAt:null}),i.toSessionId&&(p.sessionId=i.toSessionId)}}break;case"lead-handoff":{if(i.to&&i.from===i.to){let g=f(i.to);if(g){(!Array.isArray(g.epochs)||g.epochs.length===0)&&(g.epochs=[{agent:i.fromAgent??g.agent??null,sessionId:i.fromSessionId??null,startedAt:null,endedAt:null}]);let S=g.epochs[g.epochs.length-1];S.endedAt=i.at??null,i.reason&&(S.endReason=i.reason),g.epochs.push({agent:i.toAgent??null,sessionId:i.toSessionId??null,startedAt:i.at??null,endedAt:null}),g.agent=i.toAgent||g.agent,g.role="lead"}else c.boxes.push({name:i.to,agent:i.toAgent||null,role:"lead",state:"stopped",cwd:c.cwd});c.leadBox=i.to;break}let p=f(i.from);p&&(p.role="handed-off",p.state="handed-off"),i.to&&!f(i.to)&&c.boxes.push({name:i.to,agent:i.toAgent||null,role:"lead",state:"stopped",cwd:c.cwd}),c.leadBox=i.to||c.leadBox;break}case"subtask-delegated":i.to&&!f(i.to)&&c.boxes.push({name:i.to,agent:i.toAgent||null,role:"subtask",state:"stopped",cwd:c.cwd});break;case"subtask-merged":{let p=f(i.box||i.from);p&&(p.state="merged");break}case"archived":c.archivedAt=i.at??Date.now();break;case"unarchived":delete c.archivedAt;break;case"lead-refreshed":{let p=f(i.box);if(!p)break;(!Array.isArray(p.epochs)||p.epochs.length===0)&&(p.epochs=[{agent:i.agent??p.agent??null,sessionId:i.fromSessionId??null,startedAt:null,endedAt:null}]);let g=p.epochs[p.epochs.length-1];g.endedAt==null&&(g.endedAt=i.at??null),g.endReason==null&&i.reason&&(g.endReason=i.reason),p.epochs.push({agent:i.agent??p.agent??null,sessionId:i.toSessionId??null,startedAt:i.at??null,endedAt:null}),i.toSessionId&&(p.sessionId=i.toSessionId);break}case"transferred-out":c.transferredTo=i.toNode??null,c.transferredAt=i.at??null,bl(c,{at:i.at??Date.now(),reason:i.mode==="recover"?"node-offline":"node-transfer"});break;case"transferred-in":{delete c.transferredTo,delete c.transferredAt,i.name&&(c.name=i.name),i.cwd&&(c.cwd=i.cwd),i.workspace&&typeof i.workspace=="object"&&(c.workspace={dir:i.cwd||c.cwd,...i.workspace},Array.isArray(c.workspace.repos)&&(c.workspace.repos=c.workspace.repos.map(p=>p&&typeof p=="object"?{...p,dir:p.dir??(p.name?F.join(i.cwd||c.cwd,p.name):null)}:p))),i.box&&!f(i.box)&&c.boxes.push({name:i.box,agent:i.agent||null,role:"lead",state:"stopped",cwd:c.cwd}),i.box&&(c.leadBox=i.box);break}case"track-deleted":i.name&&!c.name&&(c.name=i.name),c.deleted=!0;break;default:break}}let o=[...n.values()].filter(s=>!s.deleted);for(let s of o)s.name||(s.name=s.id);return{tracks:o,counts:{lines:r,tracks:o.length,deleted:n.size-o.length}}}var eg,qs,Fr,Ys,Yt,Vs,dt,Tl,xl,Al=k(()=>{Dr();_l();q();eg=Qm(Zm),qs=process.env.BOSTRAT_STATE_DIR||F.join(process.env.HOME||Xm.tmpdir(),".bostrat"),Fr=!1,Ys=null;Yt=new Map,Vs=0,dt={passes:0,fullPasses:0,walked:0,skipped:0},Tl=Math.max(0,Number(process.env.BOSTRAT_STATE_SYNC_FULL_EVERY??30)||0);xl=new Set([".claude",".codex",".cursor",".credentials.json","auth.json",".claude.json","api-token","node.env","certs","integrations.json","mcp-env.json","mcp-tokens.json","gcloud","application_default_credentials.json",".gemini","secure-inputs"]);j("state-remote",({env:e})=>{let t=e.BOSTRAT_STATE_REMOTE||"";return!t||/^[./~]/.test(t)||!Xs({remote:t,env:e}).enabled?null:{class:"forge",mode:"timer",host:t,armedBy:["BOSTRAT_STATE_REMOTE"],purpose:"the optional git export of this node's state"}})});var $l=k(()=>{Ie()});import ig from"node:path";var ag,sx,ix,El=k(()=>{Ue();ag=Object.freeze(["memory","withheld"]),sx=new Set([...ag,"released"]),ix=ig.join(".bostrat","memory-arm")});var vl=k(()=>{Dr()});import cg from"node:os";import lg from"node:path";import{execFile as ug}from"node:child_process";import{promisify as dg}from"node:util";var bx,_x,Tx,xx,kx,Ax,Ol=k(()=>{El();vl();Mt();bx=dg(ug),_x=process.env.BOSTRAT_STATE_DIR||lg.join(process.env.HOME||cg.tmpdir(),".bostrat"),Tx=25*1024,xx=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,kx=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,Ax=Promise.resolve()});function Rl(e=process.env){return!!(Lr(e)&&e.BOSTRAT_PLANE_TOKEN)}async function mg(e,t={},n=process.env){let r=new AbortController,o=setTimeout(()=>r.abort(),pg);try{return await fg(`${Lr(n)}${e}`,{...t,signal:r.signal})}finally{clearTimeout(o)}}async function Il({env:e=process.env}={}){if(!Rl(e))return{state:"ready",ok:!0,reason:null,s3:null,source:"node"};try{let t=await mg("/v1/video-state",{headers:hg(e)},e);if(!t.ok)return null;let n=await t.json();return typeof n?.state!="string"?null:{state:n.state,ok:n.state==="ready",reason:typeof n.reason=="string"?n.reason:null,s3:n.s3??null,source:"plane"}}catch{return null}}var pg,Ox,fg,hg,Zs=k(()=>{Dr();ot();pg=1e4,Ox=60*6e4,fg=(...e)=>fetch(...e);hg=(e=process.env)=>({authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN||""}`})});var Nl=k(()=>{Zs()});import Ml from"node:path";import gg from"node:os";var qt,wg,Hx,Qs,Wx,Kx,zx,Cl=k(()=>{Sr();Ie();qt="BOSTRAT_NODE_URL",wg=process.env.BOSTRAT_STATE_DIR||Ml.join(process.env.HOME||gg.tmpdir(),".bostrat"),Hx=Ml.join(wg,"git-hooks"),Qs=`#!/bin/sh
|
|
9
20
|
# bostrat git hook shim (agent/src/git-hooks.js) \u2014 chains to the repo's own hook,
|
|
10
21
|
# then stamps/reports for rework attribution when running inside a bostrat box.
|
|
11
22
|
hook=$(basename "$0")
|
|
@@ -20,172 +31,92 @@ esac
|
|
|
20
31
|
if [ -x "$orig/$hook" ] && [ "$orig/$hook" != "$0" ]; then
|
|
21
32
|
"$orig/$hook" "$@" || exit $?
|
|
22
33
|
fi
|
|
23
|
-
`,
|
|
34
|
+
`,Wx=`${Qs}
|
|
24
35
|
# \u2500\u2500 bostrat: append provenance trailers (Layer 0). Skipped for merge commits
|
|
25
36
|
# (nobody "wrote" a merge) and outside a box (no token / no node url).
|
|
26
|
-
[ -z "$${
|
|
27
|
-
[ -z "$${
|
|
37
|
+
[ -z "$${Oe}" ] && exit 0
|
|
38
|
+
[ -z "$${qt}" ] && exit 0
|
|
28
39
|
[ "$2" = "merge" ] && exit 0
|
|
29
|
-
trailers=$(curl -sS -m 3 -H "${
|
|
40
|
+
trailers=$(curl -sS -m 3 -H "${En}: $${Oe}" "$${qt}/api/git/trailers" 2>/dev/null) || exit 0
|
|
30
41
|
[ -z "$trailers" ] && exit 0
|
|
31
42
|
printf '%s\\n' "$trailers" | while IFS= read -r line; do
|
|
32
43
|
[ -n "$line" ] && git interpret-trailers --in-place --if-exists addIfDifferent --trailer "$line" "$1" >/dev/null 2>&1 || true
|
|
33
44
|
done
|
|
34
45
|
exit 0
|
|
35
|
-
`,
|
|
46
|
+
`,Kx=`${Qs}
|
|
36
47
|
# \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
|
|
37
|
-
[ -z "$${
|
|
38
|
-
[ -z "$${
|
|
48
|
+
[ -z "$${Oe}" ] && exit 0
|
|
49
|
+
[ -z "$${qt}" ] && exit 0
|
|
39
50
|
sha=$(git rev-parse HEAD 2>/dev/null) || exit 0
|
|
40
51
|
cwd=$(git rev-parse --show-toplevel 2>/dev/null)
|
|
41
|
-
printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${
|
|
42
|
-
-H 'content-type: application/json' -H "${
|
|
52
|
+
printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${qt}/api/git/committed" \\
|
|
53
|
+
-H 'content-type: application/json' -H "${En}: $${Oe}" --data-binary @- >/dev/null 2>&1 || true
|
|
43
54
|
exit 0
|
|
44
|
-
`,
|
|
55
|
+
`,zx=`${Qs}
|
|
45
56
|
# \u2500\u2500 bostrat: the tree moved \u2014 let the node re-read this workspace's lockfiles.
|
|
46
|
-
[ -z "$${
|
|
47
|
-
[ -z "$${
|
|
57
|
+
[ -z "$${Oe}" ] && exit 0
|
|
58
|
+
[ -z "$${qt}" ] && exit 0
|
|
48
59
|
[ "$hook" = "post-checkout" ] && [ "$3" != "1" ] && exit 0
|
|
49
|
-
curl -sS -m 3 -X POST "$${
|
|
50
|
-
-H 'content-type: application/json' -H "${
|
|
60
|
+
curl -sS -m 3 -X POST "$${qt}/api/deps/refresh" \\
|
|
61
|
+
-H 'content-type: application/json' -H "${En}: $${Oe}" --data-binary '{}' >/dev/null 2>&1 || true
|
|
51
62
|
exit 0
|
|
52
|
-
`});import
|
|
53
|
-
`)[0]})`}}let r
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
# nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
|
|
57
|
-
app = "${e}"
|
|
58
|
-
primary_region = "${t}"
|
|
59
|
-
# Swap absorbs agent-CLI memory spikes that would otherwise hang the whole
|
|
60
|
-
# guest (the 2026-08-13 hang class); much slower than RAM \u2014 scale memory for
|
|
61
|
-
# sustained multi-session use.
|
|
62
|
-
swap_size_mb = 1024
|
|
63
|
-
|
|
64
|
-
[build]
|
|
65
|
-
# The published node image (claude + cursor-agent + codex baked in, logged
|
|
66
|
-
# out), pinned to the bostrat-node version that wrote this file. Update with:
|
|
67
|
-
# npm i -g bostrat-node && bostrat-node fly (re-run is safe), or bump the tag.
|
|
68
|
-
image = "${o}"
|
|
69
|
-
|
|
70
|
-
[env]
|
|
71
|
-
PORT = "3362"
|
|
72
|
-
# $HOME on the volume: your agent logins, repos, and node state survive
|
|
73
|
-
# machine replacement (the "your login stays on your node" promise).
|
|
74
|
-
HOME = "/data/home"
|
|
75
|
-
BOSTRAT_PLANE_URL = "${r}"
|
|
76
|
-
BOSTRAT_NODE_ID = "${e}"
|
|
77
|
-
BOSTRAT_NODE_NAME = "${n}"
|
|
78
|
-
BOSTRAT_REPOS_ROOT = "/data/home/repos"
|
|
79
|
-
BOSTRAT_TMUX_SOCKET = "/tmp/tmux-0/default"
|
|
80
|
-
# claude refuses --dangerously-skip-permissions as root unless sandboxed;
|
|
81
|
-
# this dedicated Firecracker microVM IS the sandbox.
|
|
82
|
-
IS_SANDBOX = "1"
|
|
83
|
-
|
|
84
|
-
[[mounts]]
|
|
85
|
-
source = "node_data"
|
|
86
|
-
destination = "/data"
|
|
87
|
-
|
|
88
|
-
[[vm]]
|
|
89
|
-
# Agent CLIs are RAM-hungry; 2GB is the floor for one lead box.
|
|
90
|
-
# Scale later with: fly scale memory 4096 -a ${e}
|
|
91
|
-
size = "shared-cpu-2x"
|
|
92
|
-
memory = "2gb"
|
|
93
|
-
`}function Us({app:e,org:t,region:n,sizeGb:r,token:o,dir:s}){let a=[`BOSTRAT_PLANE_TOKEN=${o}`];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> via stdin`,stdin:a.join(`
|
|
94
|
-
`)+`
|
|
95
|
-
`},{argv:["deploy",s,"-c",Ne.join(s,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${s} -c ${Ne.join(s,"fly.toml")} -a ${e} --ha=false`}]}function Hs(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--image":"image"};for(let r=0;r<e.length;r++){let o=e[r];if(o==="--yes"||o==="-y")t.yes=!0;else if(n[o])t[n[o]]=e[++r]??"";else if(o.startsWith("--")&&o.includes("=")){let[s,...a]=o.split("=");n[s]?t[n[s]]=a.join("="):s==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function Ws({app:e,dest:t,toml:n}){let r=t||Ne.join(Al.homedir(),".bostrat","fly",e);hr.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])hr.rmSync(Ne.join(r,o),{recursive:!0,force:!0});return hr.writeFileSync(Ne.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function Nl({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await cn(["orgs","list","--json"],{exec:n}),s=JSON.parse(o),a=Array.isArray(s)?s.map(l=>l.Slug||l.slug).filter(Boolean):Object.keys(s);if(a.length===1)return t.write(`Org: ${a[0]} (your only org)
|
|
96
|
-
`),a[0];if(a.length>1)return await e(`Fly org (${a.join(" / ")})`,a[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function Ml({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:o}={}){let s=Hs(e),a=vl.createInterface({input:t,output:n}),l=async(A,O)=>(await a.question(O?`${A} [${O}]: `:`${A}: `)).trim()||O||"",h=A=>(a.close(),A);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
|
|
97
|
-
bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
|
|
98
|
-
|
|
99
|
-
`);try{await cn(["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"),h(1)}try{let{stdout:A}=await cn(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${A.trim()}
|
|
100
|
-
`)}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"),h(1)}let m=await Nl({ask:l,output:n,exec:r,flag:s.org}),d=s.app||await l("App name",`bostrat-node-${Ol().slice(0,4)}`),S=s.region||await l("Region (see `fly platform regions`)","iad"),y=s.sizeGb||Number(await l("Volume size GB (logins + repos live here)","10"))||10,g=s.name||d,b=s.planeUrl||Ls,M=s.token||await l("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!M)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.
|
|
101
|
-
`),h(1);let T=s.image||mr,{dir:N}=Ws({app:d,dest:o,toml:Fs({app:d,region:S,nodeName:g,planeUrl:b,image:T})});n.write(`
|
|
102
|
-
wrote ${Ne.join(N,"fly.toml")} \u2014 deploys the prebuilt node image ${T}
|
|
103
|
-
(claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
|
|
104
|
-
|
|
105
|
-
Plan (your flyctl, your org, your bill):
|
|
106
|
-
`);let E=Us({app:d,org:m,region:S,sizeGb:y,token:M,dir:N});for(let A of E)n.write(` $ ${A.display}
|
|
107
|
-
`);if(!s.yes&&(await l(`
|
|
108
|
-
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.
|
|
109
|
-
`),h(1);for(let A of E){n.write(`
|
|
110
|
-
\u2192 ${A.display}
|
|
111
|
-
`);try{let{stdout:O,stderr:k}=await cn(A.argv,{stdin:A.stdin,exec:r}),x=`${O||""}${k||""}`.trim();x&&n.write(x.split(`
|
|
112
|
-
`).map(C=>` ${C}`).join(`
|
|
113
|
-
`)+`
|
|
114
|
-
`)}catch(O){let k=`${O?.stdout||""}${O?.stderr||""}${O?.message||""}`;if(A.tolerate&&A.tolerate.test(k)){n.write(` (already exists \u2014 continuing)
|
|
115
|
-
`);continue}return n.write(`\u2717 failed: ${k.trim().split(`
|
|
116
|
-
`).slice(-4).join(`
|
|
63
|
+
`});import Dn from"node:fs/promises";import Hr from"node:os";import Vt from"node:path";import{execFile as yg}from"node:child_process";import{promisify as Sg}from"node:util";function Ll(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function Dl(e=process.env){let t=String(e.BOSTRAT_BOX_CGROUPS??"").trim().toLowerCase();return["1","on","true","yes"].includes(t)?"on":["0","off","false","no"].includes(t)?"off":"auto"}function Ag(e=process.env){let t=Dl(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function Fl(e=Hr.totalmem()){return Math.max(e-_g*Fn,Math.floor(e/2))}function $g(e=Hr.totalmem(),t=process.env){let n=Number(t.BOSTRAT_BOX_MEMORY_MAX_MB);return Number.isFinite(n)&&n>=256?Math.floor(n)*Fn:Math.min(xg*Fn,Fl(e))}function Eg(e=process.env){return Vt.join(Ll(e),Tg)}async function vg(e){return(await Dn.readFile(e,"utf8")).trim()}async function Ul({env:e=process.env,totalBytes:t=Hr.totalmem(),force:n=!1,platform:r=process.platform}={}){if(!n&&!Ag(e))return Jt=Dl(e)==="off"?{available:!1,reason:"disabled (BOSTRAT_BOX_CGROUPS=0)"}:await Og({env:e,totalBytes:t,platform:r}),Jt;let o=Ll(e),s=Eg(e);try{let a;try{a=(await vg(Vt.join(o,"cgroup.controllers"))).split(/\s+/).filter(Boolean)}catch(u){throw new Error(`no cgroup v2 tree at ${o} (${u?.code||u?.message||u})`)}let i=["cpu","memory"].filter(u=>a.includes(u));if(!i.length)throw new Error(`cgroup v2 at ${o} offers neither cpu nor memory (controllers: ${a.join(" ")||"none"})`);await Dn.mkdir(s,{recursive:!0});let c=`+${i.join(" +")}`;for(let u of[Vt.join(o,"cgroup.subtree_control"),Vt.join(s,"cgroup.subtree_control")])try{await Dn.writeFile(u,c)}catch(f){throw new Error(`cannot enable ${c} in ${u} (${f?.code||f?.message||f})`)}let l=Fl(t);i.includes("cpu")&&await Dn.writeFile(Vt.join(s,"cpu.weight"),String(jl)),i.includes("memory")&&await Dn.writeFile(Vt.join(s,"memory.max"),String(l)),Jt={available:!0,backend:"cgroupfs",path:s,controllers:i,cpuWeight:i.includes("cpu")?jl:null,memoryMaxMb:i.includes("memory")?Math.round(l/Fn):null}}catch(a){Jt={available:!1,reason:a?.message||String(a)}}return Jt}async function Og({env:e=process.env,totalBytes:t=Hr.totalmem(),platform:n=process.platform}={}){if(n!=="linux")return{available:!1,reason:`not a Fly/container node, and no systemd on ${n}`};try{await bg(Pl(e),["--user","show","--property=Version","--value"],{timeout:3e3})}catch(o){return{available:!1,reason:`not a Fly/container node, and no systemd user manager to ask (${String(o?.stderr||o?.code||o?.message||o).trim().split(`
|
|
64
|
+
`)[0]})`}}let r=$g(t,e);return{available:!0,backend:"systemd",path:null,controllers:["memory"],cpuWeight:null,memoryMaxMb:Math.round(r/Fn),swapMaxMb:kg,systemctl:Pl(e),procRoot:e.BOSTRAT_PROC_ROOT||"/proc"}}function Hl(e=Jt){let t=`nice ${Bl} floor on every box`;if(!e)return`${t}; cgroup ceiling not probed yet`;if(e.available&&e.backend==="systemd")return`${t}; memory ceiling on each box's tmux-spawn scope, set through the systemd user manager (MemoryMax ${e.memoryMaxMb} MB, MemorySwapMax ${e.swapMaxMb} MB)`;if(e.available){let n=[];return e.cpuWeight!=null&&n.push(`cpu.weight ${e.cpuWeight}`),e.memoryMaxMb!=null&&n.push(`memory.max ${e.memoryMaxMb} MB`),`${t}; cgroup ceiling at ${e.path} (${n.join(", ")})`}return`${t}; cgroup ceiling unavailable \u2014 ${e.reason}`}var bg,Bl,jl,_g,Tg,xg,kg,Fn,Jt,Pl,ei=k(()=>{bg=Sg(yg),Bl=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),jl=50,_g=768,Tg="bostrat-boxes",xg=4096,kg=512,Fn=1024*1024;Jt=null;Pl=(e=process.env)=>e.BOSTRAT_SYSTEMCTL_BIN||"systemctl"});import{execFile as Rg}from"node:child_process";import{promisify as Ig}from"node:util";import zl from"node:fs";import Ng from"node:os";function Yl(e){return`/tmp/tmux-${e}/default`}function Cg({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=Yl(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function ni(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Bg(e,{loginShell:t});return r===ql?!0:r===ti?!1:n}async function Bg(e,{loginShell:t=!1,timeoutMs:n=Pg}={}){if(!e)return ti;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await Gl(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),ql}catch(s){return s?.killed||s?.signal?Kl:s?.code===1||s?.code===127?ti:Kl}}function Lg(...e){return["-S",jg,...e]}function Fg(e){return typeof e=="string"&&Dg.test(e)}async function Vl(e,{lines:t=40}={}){if(!Fg(e))return"";try{let n=Lg("capture-pane","-t",e,"-p");Number.isFinite(t)&&t>0&&n.push("-S",`-${Math.floor(t)}`);let{stdout:r}=await Gl(Mg,n);return String(r||"")}catch{return""}}var Gl,Mg,Wl,jg,Ck,jk,Pk,Bk,ql,ti,Kl,Pg,Wr,Lk,Dg,Dk,Fk,Uk,Hk,Wk,ri=k(()=>{mr();ms();ws();Un();$l();Ol();Nl();oi();Sr();Cl();ei();Ie();Gl=Ig(Rg),Mg=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";Wl=typeof process.getuid=="function"?process.getuid():0,jg=Cg({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return zl.existsSync(Yl(Wl))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:Wl}),Ck=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",jk=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Pk=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),Bk=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);ql="present",ti="absent",Kl="unknown",Pg=5e3;Wr={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"};Lk=(()=>{try{let e=Ng.homedir();if(e&&zl.existsSync(e))return e}catch{}return"/"})(),Dg=/^[A-Za-z0-9_.-]{1,64}$/;Dk=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Fk=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Uk=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Hk=Number(process.env.BOSTRAT_BOX_COLS)||120,Wk=Number(process.env.BOSTRAT_BOX_ROWS)||40});import Kr from"node:fs/promises";import Ug from"node:os";import eu from"node:path";function Wg(e){let t=String(e??"");t=hr(t);for(let n of Hg)t=t.replace(n,"\u2039redacted\u203A");return t}function Ql(){let e=process.env.BOSTRAT_HANDOFF_DEBUG;return e==="1"||e==="true"}async function Kg(e){try{await Kr.mkdir(tu,{recursive:!0}),await Kr.appendFile(zr,`${JSON.stringify(e)}
|
|
65
|
+
`,"utf8");let n=(await Kr.readFile(zr,"utf8")).split(`
|
|
66
|
+
`).filter(Boolean);n.length>Zl&&await Kr.writeFile(zr,`${n.slice(-Zl).join(`
|
|
117
67
|
`)}
|
|
118
|
-
fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
|
|
119
|
-
`),h(1)}}return n.write(`
|
|
120
|
-
\u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
|
|
121
|
-
chat: the node step advances on its own within a minute.
|
|
122
|
-
logs: fly logs -a ${d}
|
|
123
|
-
redeploy: fly deploy ${N} -c ${Ne.join(N,"fly.toml")} -a ${d} --ha=false
|
|
124
|
-
Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
|
|
125
|
-
boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
|
|
126
|
-
`),h(0)}var Ls,Rl,mr,cn,Gs=R(()=>{Ls="wss://plane.bostrat.ai/v1/node",Rl=El(import.meta.url)("../package.json").version,mr=`ghcr.io/globocodes/bostrat-node:${Rl}`;cn=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let s=kl("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(a,l,h)=>a?o(Object.assign(a,{stdout:l,stderr:h})):r({stdout:l,stderr:h}));t!=null&&s.stdin?.end(t)})});function zs(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!Pl.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 Cl(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:zs(o.from,"from",n),toMs:zs(o.to,"to",n)}))}return t}var Il,Pl,Im,Pm,Vs=R(()=>{Il={"claude-opus-5-5":[{from:null,to:null,input:4,output:20,cacheWrite:8,cacheRead:.2,cacheReadX:.05,fast:{input:8,output:40,cacheWrite:16,cacheRead:.4},verifiedAt:"2026-09-28",note:"verified 2026-09-28 against platform.claude.com/docs/en/about-claude/pricing: $4/$20, 1h cache write $8 (2\xD7), cache hits $0.20 (0.05\xD7 \u2014 footnote 2), fast $8/$40; added before any fleet turn was recorded."}],"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-10-05",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; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"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-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); fast-mode variant added 2026-08-20; re-verified 2026-10-05 (live pricing page: $5/$25, 1h write $10, hits $0.50, fast $10/$50)."}],"claude-sonnet-5-5":[{from:null,to:"2026-10-11",input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.20 (0.1\xD7 \u2014 footnote 2 then named Opus 5.5 only). Superseded 2026-10-12 when the page moved Sonnet 5.5 hits to 0.05\xD7 (window below)."},{from:"2026-10-12",to:null,input:2,output:10,cacheWrite:4,cacheRead:.1,cacheReadX:.05,verifiedAt:"2026-10-12",note:"verified 2026-10-12 against platform.claude.com/docs/en/about-claude/pricing: $2/$10, 1h cache write $4 (2\xD7), cache hits $0.10 (0.05\xD7 \u2014 footnote 2 now names Opus 5.5 AND Sonnet 5.5; the prompt-caching multiplier table agrees)."}],"claude-sonnet-5":[{from:null,to:null,input:2,output:10,cacheWrite:4,cacheRead:.2,verifiedAt:"2026-10-05",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; re-verified 2026-10-05 (live pricing page, footnote 3 still published)."}],"claude-sonnet-4-6":[{from:null,to:null,input:3,output:15,cacheWrite:6,cacheRead:.3,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-haiku-5-5":[{from:null,to:null,input:.1,output:.5,cacheWrite:.2,cacheRead:.01,long:{over:1e5,input:.5,output:2.5,cacheWrite:1,cacheRead:.05},verifiedAt:"2026-10-19",note:"verified 2026-10-19 against platform.claude.com/docs/en/about-claude/pricing: prompts up to 100,000 tokens $0.10/$0.50, 1h cache write $0.20 (2\xD7), cache hits $0.01 (0.1\xD7); prompts over 100,000 tokens (the `long` variant) $0.50/$2.50, 1h cache write $1 (2\xD7), cache hits $0.05 (0.1\xD7); added before any fleet turn was recorded."}],"claude-haiku-4-5":[{from:null,to:null,input:1,output:5,cacheWrite:2,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page), re-verified 2026-10-05 (live pricing page)."}],"claude-fable-5-1":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:.25,cacheReadX:.025,verifiedAt:"2026-10-26",note:"verified 2026-09-07 against platform.claude.com/docs/en/about-claude/pricing: $10/$50, 1h cache write $20 (2\xD7), cache hits $0.25 (0.025\xD7 \u2014 the 5.1-only multiplier; footnote 1 on the page); re-verified 2026-10-26 (live pricing page, footnote 1 unchanged)."}],"claude-fable-5":[{from:null,to:null,input:10,output:50,cacheWrite:20,cacheRead:1,verifiedAt:"2026-10-05",note:"verified 2026-08-06 (claude-api skill), re-verified 2026-08-17 (live pricing page); 83% of fleet spend then; re-verified 2026-10-05 (live pricing page: $10/$50, 1h write $20, hits $1 at 0.1\xD7)."}],"gpt-5.5-pro":[{from:null,to:null,input:30,output:180,cacheWrite:30,cacheRead:30,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $30 in / $180 out, no cached-input or cache-write price published (both priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5-cyber":[{from:null,to:null,input:12.5,output:75,cacheWrite:12.5,cacheRead:1.25,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing, Cyber models table): $12.50 in / $1.25 cached / $75 out, no cache-write price published (priced as plain input); added before any fleet turn was recorded."}],"gpt-5.5":[{from:null,to:null,input:5,output:30,cacheWrite:5,cacheRead:.5,verifiedAt:"2026-10-05",note:"verified 2026-07-03, re-verified 2026-08-17 and 2026-10-05 (developers.openai.com pricing: $5 / $0.50 cached / $30); no cache-write premium on 5.5-and-earlier."}],"gpt-5.6-sol":[{from:null,to:"2026-08-23",input:5,output:30,cacheWrite:6.25,cacheRead:.5,verifiedAt:"2026-08-17",note:"verified 2026-07-18, re-verified 2026-08-17 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL). Superseded 2026-08-24 by the vendor's promotional cut (window below)."},{from:"2026-08-24",to:null,input:4,output:20,cacheWrite:5,cacheRead:.4,verifiedAt:"2026-11-09",note:"promotional pricing verified 2026-08-24 (developers.openai.com pricing), 'at least through November 21, 2026'; cacheWrite = 1.25\xD7 input (30-min TTL); re-verified 2026-10-12 (live pricing page: $4 / $0.40 cached / $5 cache writes / $20, promo note unchanged); re-verified 2026-11-09 (live pricing page: $4 / $0.40 cached / $5 30m cache writes / $20 unchanged \u2014 the 'at least through November 21, 2026' promotional footnote has been removed from the page with no post-promo price or date published; price standing, not a vendor change)."}],"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-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (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-10-05",note:"verified 2026-08-17, re-verified 2026-10-05 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input (30-min TTL)."}],"gpt-6-astra-law":[{from:null,to:null,input:10,output:50,cacheWrite:10,cacheRead:1,verifiedAt:"2026-11-02",note:"verified 2026-11-02 (developers.openai.com pricing, Legal model configurations table): $10 in / $1 cached / $50 out, promotional 'at least through December 31, 2026', no cache-write price published (priced as plain input); added before any fleet turn was recorded."}],"gpt-6-astra":[{from:null,to:null,input:10,output:50,cacheWrite:12.5,cacheRead:1,fast:{input:20,output:100,cacheWrite:25,cacheRead:2},verifiedAt:"2026-10-26",note:"verified 2026-09-07 (developers.openai.com pricing); cacheWrite = 1.25\xD7 input; fast tier $20/$100 recorded as the fast variant (codex reports no speed); re-verified 2026-10-26 (live pricing page: $10 / $1 cached / $12.50 30m cache writes / $50, fast $20/$100 \u2014 the page now also lists a 12h cache-write tier at 2.5\xD7 input, not modelled: codex reports no cache-write class)."}],"gpt-6.1-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.1,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.10 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-sol":[{from:null,to:null,input:2,output:10,cacheWrite:2.5,cacheRead:.2,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $2 in / $0.20 cached / $2.50 cache writes (1.25\xD7) / $10 out; added before any fleet turn was recorded."}],"gpt-6-luna":[{from:null,to:null,input:.1,output:.5,cacheWrite:.125,cacheRead:.01,verifiedAt:"2026-10-05",note:"verified 2026-10-05 (developers.openai.com pricing): $0.10 in / $0.01 cached / $0.125 cache writes (1.25\xD7) / $0.50 out; added before any fleet turn was recorded."}]},Pl=/^\d{4}-\d{2}-\d{2}$/;Im=Cl(Il),Pm=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var qs=R(()=>{Vs()});import Ys from"node:fs/promises";import Zs from"node:path";import Bl from"node:os";function ei(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function ti(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function ni(e){let t=new Date(ei(e));return t.setDate(t.getDate()+7),t.getTime()}function ri(e){let t=new Date(ti(e));return t.setMonth(t.getMonth()+1),t.getTime()}function Ul(e=Date.now()){for(let[t,n]of Object.entries(Ll)){let r=n.startOf(e);if(r!==ln[t]){ln[t]=r;for(let o of gr.values())o[t]=0;for(let o of Xs)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&Xs.delete(o)}}}function Hl(e){let t={};for(let[n,r]of Object.entries(e||{})){if(typeof n!="string"||!/^[a-z][a-z0-9-]{0,31}$/.test(n))throw new Error(`bad provider key "${n}"`);let o={};for(let s of["weeklyUsd","monthlyUsd"]){let a=r?.[s];if(a==null||a==="")continue;let l=Number(a);if(!Number.isFinite(l)||l<=0)throw new Error(`${n}.${s} must be a positive number or null`);o[s]=l}Object.keys(o).length&&(t[n]=o)}return t}async function oi(e,{source:t="local",updatedAt:n=Date.now()}={}){Ve={caps:Hl(e),updatedAt:n,source:t};try{await Ys.mkdir(Qs,{recursive:!0}),await Ys.writeFile(Dl(),JSON.stringify(Ve,null,2))}catch{}return Wl()}function Wl(e=Date.now()){Ul(e);let t=new Set([...gr.keys(),...Object.keys(Ve?.caps||{})]),n={};for(let r of t){let o=gr.get(r);n[r]={weeklyUsd:Js(o?.weekly||0),monthlyUsd:Js(o?.monthly||0)}}return{caps:Ve?.caps||{},configured:!!Ve,seeded:Fl,updatedAt:Ve?.updatedAt??null,spent:n,windows:{weekly:{start:ln.weekly,resetsAt:ni(e)},monthly:{start:ln.monthly,resetsAt:ri(e)}},warnPct:jl}}var Qs,Dl,jl,Ll,Ve,Fl,ln,gr,Xs,Js,si=R(()=>{rn();qs();Qs=process.env.BOSTRAT_STATE_DIR||Zs.join(process.env.HOME||Bl.tmpdir(),".bostrat"),Dl=()=>Zs.join(Qs,"usage-caps.json"),jl=.8;Ll={weekly:{startOf:ei,nextStart:ni,capKey:"weeklyUsd"},monthly:{startOf:ti,nextStart:ri,capKey:"monthlyUsd"}},Ve=null,Fl=!1,ln={weekly:0,monthly:0},gr=new Map,Xs=new Set;Js=e=>Math.round(e*1e4)/1e4});function li(){return Object.fromEntries(Object.entries(ii.tokens).filter(([,e])=>ci(e)).map(([e,t])=>[e,t.access]))}function ui(){let e={};for(let[t,n]of Object.entries(ii.tokens)){let r=ci(n)?"set":n.needsLogin?"needs-login":n.refresh?"refreshing":"needs-login";e[t]={state:r,source:"broker",...n.expiresAt?{expiresAt:n.expiresAt}:{},...n.obtainedAt?{obtainedAt:n.obtainedAt}:{},refreshable:!!n.refresh,...n.lastError?{error:String(n.lastError).slice(0,200)}:{}}}for(let[t,n]of ai)e[t]||(e[t]={state:"login-pending",source:"broker",startedAt:n.startedAt,redirectUri:n.redirectUri});return e}var Vm,qm,ii,ai,ci,di,pi=R(()=>{Vm=10*6e4,qm=5*6e4,ii={tokens:{},clients:{}},ai=new Map,ci=e=>typeof e?.access=="string"&&e.access&&!e.needsLogin&&(e.expiresAt==null||e.expiresAt>Date.now());di=()=>[...ai.keys()]});import Kl from"node:fs";import ye from"node:fs/promises";import yi from"node:os";import Ye from"node:path";function Si(e){return br.add(e),()=>br.delete(e)}function un(){return{entries:structuredClone(yr),at:Date.now()}}function Xl(e,t,n){if(e.transport==="http"){let o=Object.fromEntries(Object.entries(e.headers||{}).map(([s,a])=>[s,qe(a,t)]));return{...n==="claude"?{type:"http"}:{},url:qe(e.url,t),...Object.keys(o).length?{headers:o}:{}}}let r=Object.fromEntries((e.env||[]).map(o=>[o,t[o]]));return{...n==="claude"?{type:"stdio"}:{},command:e.command,args:(e.args||[]).map(o=>qe(o,t)),...Object.keys(r).length?{env:r}:{}}}function Jl(e,t){let n=[`[mcp_servers.${e.name}]`];if(e.transport==="http"){n.push(`url = ${kt(qe(e.url,t))}`);let r=Object.fromEntries(Object.entries(e.headers||{}).map(([o,s])=>[o,qe(s,t)]));Object.keys(r).length&&n.push(`http_headers = ${hi(r)}`)}else{n.push(`command = ${kt(e.command)}`),n.push(`args = [${(e.args||[]).map(o=>kt(qe(o,t))).join(", ")}]`);let r=Object.fromEntries((e.env||[]).map(o=>[o,t[o]]));Object.keys(r).length&&n.push(`env = ${hi(r)}`)}return n.join(`
|
|
127
|
-
`)+`
|
|
128
|
-
|
|
129
|
-
`}function _i(e){let t=[],n=`(?:[A-Za-z0-9_-]+|"[^"
|
|
130
|
-
]*"|'[^'
|
|
131
|
-
]*')`,r=new RegExp(`^[ \\t]*\\[\\[?[ \\t]*${n}(?:[ \\t]*\\.[ \\t]*${n})*[ \\t]*\\]\\]?[ \\t]*(?:#.*)?$`,"gm"),o=0,s;for(;s=r.exec(e);)s.index===0&&o===0||(t.push(e.slice(o,s.index)),o=s.index);return t.push(e.slice(o)),t}function Ti(e){let t=/^[ \t]*\[\s*mcp_servers\s*\.\s*(?:"([^"]+)"|([A-Za-z0-9_-]+))\s*[\].]/.exec(e);return t?t[1]??t[2]:null}function mi(e){return new Set(_i(String(e||"")).map(Ti).filter(Boolean))}function Zl(e,t,n){let r=String(e||""),o=new Set,s="";for(let a of _i(r)){let l=Ti(a);if(l&&t.has(l)){o.has(l)||(s+=t.get(l),o.add(l));continue}l&&n.has(l)||(s+=a)}for(let[a,l]of t)o.has(a)||(s&&!s.endsWith(`
|
|
132
|
-
`)&&(s+=`
|
|
133
|
-
`),s&&!s.endsWith(`
|
|
134
|
-
|
|
135
|
-
`)&&(s+=`
|
|
136
|
-
`),s+=l);return s}async function Ql(e){try{return await ye.readFile(e,"utf8")}catch(t){if(t?.code==="ENOENT")return null;throw t}}async function Sr(e,t){await ye.mkdir(Ye.dirname(e),{recursive:!0});let n=`${e}.bostrat-${process.pid}.tmp`,r=384;try{r=(await ye.stat(e)).mode&511}catch{}await ye.writeFile(n,t,{mode:r}),await ye.rename(n,e)}async function eu(e,t,n,r){let o={},s=e==="claude"?Ho():e==="codex"?Wo():Vl(),a=T=>{for(let N of t.keys())o[N]=T};if(e!=="claude"&&!Kl.existsSync(Ye.dirname(s)))return a("cli-absent"),{managed:[],states:o};let l;try{l=await Ql(s)}catch{return a("error"),{managed:n,states:o}}let h=new Set(n);if(e==="codex"){let T=mi(l??""),N=new Map;for(let[x,C]of t)T.has(x)&&!h.has(x)?o[x]="conflict":N.set(x,Jl(C,r));let E=new Set([...h].filter(x=>!t.has(x))),A=Zl(l??"",N,E);try{A!==(l??"")&&await Sr(s,A)}catch{for(let x of N.keys())o[x]="error";return{managed:n,states:o}}for(let x of N.keys())o[x]="applied";let O=mi(l??""),k=new Set([...N.keys()].filter(x=>A!==(l??"")&&(!O.has(x)||!(l??"").includes(N.get(x)))));return{managed:[...N.keys()].sort(),states:o,wrote:k}}let m={};if(l!=null&&l.trim()){try{m=JSON.parse(l)}catch{return a("error"),{managed:n,states:o}}if(!m||typeof m!="object"||Array.isArray(m))return a("error"),{managed:n,states:o}}let d=m.mcpServers&&typeof m.mcpServers=="object"?{...m.mcpServers}:{},S=[];for(let[T,N]of t){if(Object.hasOwn(d,T)&&!h.has(T)){o[T]="conflict";continue}d[T]=Xl(N,r,e),S.push(T)}for(let T of h)t.has(T)||delete d[T];let y={...m,mcpServers:d};!Object.keys(d).length&&!m.mcpServers&&delete y.mcpServers;let g=JSON.stringify(m.mcpServers??{})!==JSON.stringify(d);try{g&&await Sr(s,JSON.stringify(y,null,2))}catch{for(let T of S)o[T]="error";return{managed:n,states:o}}for(let T of S)o[T]="applied";let b=m.mcpServers&&typeof m.mcpServers=="object"?m.mcpServers:{},M=new Set(S.filter(T=>JSON.stringify(b[T]??null)!==JSON.stringify(d[T])));return{managed:S.sort(),states:o,wrote:M}}async function tu(){let e=zl(),t={};try{(await ye.stat(e)).mode&63&&await ye.chmod(e,384).catch(()=>{});let a=JSON.parse(await ye.readFile(e,"utf8"));t=Object.fromEntries(Object.entries(a||{}).filter(([,l])=>typeof l=="string"&&l!==""))}catch{t={}}let r={...li(),...t},o={};for(let s of Object.keys(r))o[s]=s in t?"file":"broker";return{values:r,sources:o}}function nu(e){if(e?.transport!=="http")return null;for(let[t,n]of Object.entries(e.headers||{})){if(!/^authorization$/i.test(t))continue;let r=/\$\{([A-Za-z_][A-Za-z0-9_]{0,63})\}/.exec(String(n));if(r)return r[1]}return null}function ru(e,t,n,r,o){let s={},a=nu(e);for(let l of e.env||[])if(t[l]!=null){let h=n[l]==="broker"?r[l]:null;s[l]={state:"set",source:n[l],...h?.expiresAt?{expiresAt:h.expiresAt}:{},...h?{refreshable:!!h.refreshable}:{}}}else o.includes(l)?s[l]={state:"login-pending",source:"broker"}:r[l]?s[l]={state:"needs-login",source:"broker",...r[l].error?{error:r[l].error}:{}}:e.auth==="oauth"&&l===a?s[l]={state:"needs-login",source:"broker"}:s[l]={state:"missing"};return s}function xi(e){return(Array.isArray(e)?e:[]).filter(t=>t&&ql.test(t.name)&&(t.transport==="http"?typeof t.url=="string":typeof t.command=="string")).map(t=>t.auth==="oauth"?t:(({auth:n,...r})=>r)(t))}async function gi(){let{values:e,sources:t}=await tu(),n=ui(),r=di(),o=xi(he.entries),s={};for(let d of o){let S=ru(d,e,t,n,r),y=Object.entries(S).filter(([,g])=>g.state!=="set").map(([g])=>g);s[d.name]={rev:Number(d.updatedAt)||0,clis:{},since:{},missingEnv:y,env:S,...d.auth==="oauth"?{auth:"oauth"}:{}}}let a={...he.managed},l={...he.since||{}},h=Date.now();for(let d of wr){let S=new Map(o.filter(b=>(b.clis||wr).includes(d)&&!s[b.name].missingEnv.length).map(b=>[b.name,b])),y=await eu(d,S,he.managed?.[d]??[],e);a[d]=y.managed;let g={...l[d]||{}};for(let[b,M]of Object.entries(y.states)){s[b].clis[d]=M;let T=s[b].rev;M==="applied"?((!g[b]||g[b].rev!==T)&&(g[b]={rev:T,at:y.wrote?.has(b)?h:Math.max(T,g[b]?.at??0)||h}),s[b].since[d]=g[b].at):delete g[b]}for(let b of Object.keys(g))S.has(b)||delete g[b];l[d]=g}for(let d of o){if(!s[d.name].missingEnv.length)continue;let y=Object.values(s[d.name].env).map(g=>g.state).includes("missing")?"missing-secret":"needs-login";for(let g of d.clis||wr)s[d.name].clis[g]=y}he={...he,managed:a,since:l},await ou();let m=JSON.stringify(s)!==JSON.stringify(yr);if(yr=s,m)for(let d of br)try{d(un())}catch{}return un()}async function ou(){let e=JSON.stringify(he,null,2);if(e!==wi)try{await Sr(Gl(),e),wi=e}catch(t){console.error("[mcp-config] cache write failed:",t?.message||t)}}function su(){let e=fi.then(gi,gi);return fi=e.catch(()=>{}),e}function $i(e,{updatedAt:t=Date.now()}={}){return he={...he,entries:xi(e),updatedAt:t},su()}var bi,Gl,zl,Vl,wr,ql,Yl,he,yr,fi,br,qe,kt,hi,wi,Ai=R(()=>{Yn();Jn();pi();bi=()=>process.env.BOSTRAT_STATE_DIR||Ye.join(process.env.HOME||yi.tmpdir(),".bostrat"),Gl=()=>Ye.join(bi(),"mcp-config.json"),zl=()=>Ye.join(bi(),"mcp-env.json"),Vl=()=>Ye.join(yi.homedir(),".cursor","mcp.json"),wr=["claude","codex","cursor"],ql=/^[a-z0-9][a-z0-9_-]{0,47}$/,Yl=/\$\{([A-Za-z_][A-Za-z0-9_]{0,63})\}/g,he={entries:[],updatedAt:null,managed:{claude:[],codex:[],cursor:[]},since:{}},yr={},fi=Promise.resolve(),br=new Set;qe=(e,t)=>String(e).replace(Yl,(n,r)=>t[r]??"");kt=e=>JSON.stringify(String(e)),hi=e=>`{ ${Object.entries(e).map(([t,n])=>`${kt(t)} = ${kt(n)}`).join(", ")} }`;wi=null});import vi from"node:fs/promises";import Oi from"node:path";import iu from"node:os";function cu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("refresh-flow patch must be an object");let t={};for(let[n,r]of Object.entries(e)){if(!(n in _r))throw new Error(`unknown refresh-flow field "${n}" \u2014 fields: ${Ni.join(", ")}`);if(r===null||r===""||r===void 0){t[n]=null;continue}switch(n){case"contextFull":case"limitHit":if(typeof r!="string"||!ki.includes(r))throw new Error(`${n} must be one of ${ki.join(", ")}`);t[n]=r;break;case"contextFullPct":{let o=Number(r);if(!Number.isFinite(o)||o<1||o>100)throw new Error("contextFullPct must be a number from 1 to 100");t[n]=Math.round(o);break}case"contextFullTokens":{let o=Number(r);if(!Number.isFinite(o)||o<=0)throw new Error("contextFullTokens must be a positive number of tokens or null");t[n]=Math.round(o);break}case"fallback":{if(typeof r!="object"||Array.isArray(r))throw new Error("fallback must be an object of provider \u2192 [providers]");let o={};for(let[s,a]of Object.entries(r)){if(!Ei.test(s))throw new Error(`bad provider key "${s}" in fallback`);if(!Array.isArray(a)||a.some(h=>typeof h!="string"||!Ei.test(h)))throw new Error(`fallback.${s} must be a list of provider keys`);let l=[...new Set(a.filter(h=>h!==s))];l.length&&(o[s]=l)}t[n]=Object.keys(o).length?o:null;break}default:throw new Error(`unknown refresh-flow field "${n}"`)}}return t}function lu(e){let t={..._r};for(let n of Ni){let r=e?.[n];r!=null&&(t[n]=r)}return t}function du(){return lu(Xe?.flow)}function Mi(){return{flow:du(),configured:!!Xe,source:Xe?.source??null,updatedAt:Xe?.updatedAt??null}}async function pu(){try{await vi.mkdir(Ri,{recursive:!0}),await vi.writeFile(au(),JSON.stringify(Xe,null,2))}catch{}}function Ii(e=null){for(let t of uu)try{t(Mi(),e)}catch{}}function Pi(e){Ii({rejected:String(e||"rejected by the plane")})}async function Ci(e,{source:t="plane",updatedAt:n=Date.now()}={}){return Xe={flow:cu(e||{}),updatedAt:n,source:t},await pu(),Ii(),Mi()}var Ri,au,ki,_r,Ni,Ei,Xe,uu,Bi=R(()=>{Ri=process.env.BOSTRAT_STATE_DIR||Oi.join(process.env.HOME||iu.tmpdir(),".bostrat"),au=()=>Oi.join(Ri,"refresh-flow.json"),ki=["prompt","auto","off"],_r=Object.freeze({contextFull:"prompt",contextFullPct:75,contextFullTokens:null,limitHit:"prompt",fallback:null}),Ni=Object.keys(_r),Ei=/^[a-z][a-z0-9-]{0,31}$/;Xe=null,uu=new Set});var Ki={};In(Ki,{REMOVED_MARKER:()=>kr,detectInstallKind:()=>Qe,detectProviderAuth:()=>Wi,maskToken:()=>vr,readRemovedMarker:()=>Hi,startPlaneLink:()=>Ru,updateCommandFor:()=>Ot,versionLt:()=>Ze});import Je from"node:fs";import Et from"node:fs/promises";import fu from"node:http";import G from"node:path";import pn from"node:os";import{createRequire as hu}from"node:module";import Tr from"ws";function vr(e){return typeof e!="string"||e.length<8?"\u2022\u2022\u2022\u2022":`${e.slice(0,6)}\u2026${e.slice(-4)}`}function Hi(e=kr){try{let t=JSON.parse(Je.readFileSync(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function Qe({env:e=process.env,pkgDir:t=G.resolve(G.dirname(new URL(import.meta.url).pathname),".."),exists:n=Je.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(G.join(t,"..",".git"))?"git-checkout":"dev"}function Ze(e,t){let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let o=0;o<Math.max(n.length,r.length);o++){let s=(n[o]||0)-(r[o]||0);if(s)return s<0}return!1}function Ot(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 Wi({home:e=process.env.HOME||pn.homedir(),env:t=process.env}={}){let n=r=>{try{return Je.statSync(r),!0}catch{return!1}};return{claude:n(G.join(e,".claude",".credentials.json")),codex:n(G.join(t.CODEX_HOME||G.join(e,".codex"),"auth.json")),cursor:n(G.join(t.XDG_CONFIG_HOME||G.join(e,".config"),"cursor","auth.json"))}}function Ru({url:e,token:t,nodeId:n=pn.hostname(),name:r=pn.hostname(),listTracks:o,detectAgents:s=null,onTracksTransferred:a=null,onTracksMoves:l=null,sampleMetrics:h=null,deliverySample:m=null,onHashKey:d=null,onViewBase:S=null,onMode:y=null,metricsMs:g=Ou,onUpdateAvailable:b=null,onUpdatePolicy:M=null,onConflictProbe:T=null,restart:N=null,onRestarted:E=null,onHelloRefused:A=null,updatePolicy:O=null,installKind:k=Qe(),selfUrl:x=`http://127.0.0.1:${process.env.PORT||3362}`,apiToken:C=null,removedMarkerFile:ee=kr,onRemoved:nt=null,onDegraded:Ie=null,onRecovered:bn=null,onRefused:Nt=null,onConnected:Mt=null,ingestMode:Pe=["ws","http","auto"].includes(process.env.BOSTRAT_PLANE_INGEST)?process.env.BOSTRAT_PLANE_INGEST:"auto",deliveryTimeoutMs:rt=Tu,unackedRetryMs:_e=_u,pingMs:P=bu,deadLinkMs:ie=Math.round(P*Su),maxInflightEvents:ot=vu,httpTimeoutMs:te=ku,fanoutActive:It=null,fanoutBatchCap:Lr=Eu,stallBackoffMinMs:Fr=Au,fetchImpl:Ur=globalThis.fetch,log:_=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=pt(e);let oa=x.replace(/^http/,"ws"),Hr=new Set,Wr=c=>{let p=typeof c.latestNodeVersion=="string"?c.latestNodeVersion:null;if(!(!(p&&se&&Ze(se,p))||Hr.has(p))){Hr.add(p),_.log(`[plane-link] bostrat-node ${p} is available (this node runs ${se}) \u2014 ${Ot(k)}`);try{b?.({current:se,latest:p,min:c.minNodeVersion??null,installKind:k,required:!!(c.minNodeVersion&&Ze(se,c.minNodeVersion))})}catch(f){_.error(`[plane-link] update notice failed: ${f?.message||f}`)}}},Te=new Map,xe=new Map,Sn=G.join(Ar,"plane-link","cursor.json"),_n=G.join(Ar,"plane-link","dead-letter.ndjson"),Kr=e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/v1\/node\/?$/,""),ce={},ne={},B=new Map,Pt=null,me=null,le=0,st=0,Gr=0,Ct={},zr=new Set,Vr=Promise.resolve(),W="ws",Ce=0,re=!1,$e=0,Tn=!1,ge=dn,it=new Set,oe=[],K=null,J=null,Z=!1,Be=!1,Bt=!1,xn=!1,at=Di,ct=null,$n=N&&typeof N=="object"?N:null,De=null,je=null,ue=null,Ae=0,qr=0,de=null,An=!1,Dt=0,lt=!1,we=Hi(ee);if(we)if(we.tokenPreview===vr(t))lt=!0,rr({reason:we.reason??"removed",at:we.at??null,nodeId:we.nodeId??n}),_.error(`[plane-link] this node was REMOVED from the plane (${we.reason??"removed"}${we.at?` at ${new Date(we.at).toISOString()}`:""}) \u2014 not dialing. Re-provision it with a new node token, or delete ${ee} to force a dial.`);else try{Je.unlinkSync(ee),_.log("[plane-link] stale removed-marker discarded \u2014 the node token changed")}catch{}function vn({reason:c="removed",at:p=Date.now(),via:f="ctl"}={}){if(!lt){lt=!0,rr({reason:c,at:p,nodeId:n,via:f});try{Je.mkdirSync(G.dirname(ee),{recursive:!0}),Je.writeFileSync(ee,JSON.stringify({at:p,reason:c,via:f,nodeId:n,tokenPreview:vr(t)},null,2))}catch(i){_.error(`[plane-link] could not write ${ee}: ${i?.message||i}`)}_.error(`[plane-link] the plane REMOVED this node (${c}, via ${f}) \u2014 going dormant: no more dials, ingest or broker calls. Re-provision with a new node token to reconnect; the box and its data are untouched.`);try{nt?.({reason:c,at:p,via:f})}catch{}io({bye:!1})}}async function sa(){try{ce=JSON.parse(await Et.readFile(Sn,"utf8"))}catch{ce={}}}function Yr(){An=!0,!je&&(je=setTimeout(async()=>{if(je=null,!!An){An=!1;try{await Et.mkdir(G.dirname(Sn),{recursive:!0}),await Et.writeFile(Sn,JSON.stringify(ce))}catch(c){_.error("[plane-link] cursor flush failed:",c?.message||c)}}},yu),je.unref?.())}function kn(){try{return!!It?.()}catch{return!1}}function En(){let c=W==="http"?ge:dn;return kn()?Math.min(c,Lr):c}function D(c){return!J||J.readyState!==Tr.OPEN?!1:(J.send(JSON.stringify(c)),!0)}let ia=Si(c=>D({v:j,ch:"ctl",type:"mcp_status",mcp:c}));function Le(c){let p=Date.now();for(let{trackId:i,event:u}of c){let w=B.get(u.id);B.set(u.id,{trackId:i,seq:u.seq,event:u,sentAt:p,firstSentAt:w?.firstSentAt??p,retryAt:p+_e,tries:(w?.tries??0)+1,nacks:w?.nacks??0})}let f=c.map(({trackId:i,event:u})=>({trackId:i,event:$u(u)}));return W==="http"?(pa(f),!0):D({v:j,ch:"events",type:"append",events:f})}function Xr(c,p=Date.now()){if(it.has(c))return!0;for(let f of B.values())if(f.trackId===c&&p-f.firstSentAt<rt)return!0;return!1}function aa(c){let p=null;for(let f of B.values())f.trackId===c&&(p==null||f.seq<p)&&(p=f.seq);return p}function jt(c){if(Bt)return;let p=ne[c];if(p==null)return;let f=aa(c),i=f==null?p:Math.min(p,f-1);i>(ce[c]??0)&&(ce[c]=i,Yr())}function ut(){if(Pt=Date.now(),me!=null){let c=Date.now()-me;_.log(`[plane-link] spine sync recovered after ${Math.round(c/1e3)}s degraded (${le} stall redial(s))`);let p=me;me=null,le=0,st=0,re=!1,$e=0;try{bn?.({since:p,downMs:c})}catch(f){_.error(`[plane-link] onRecovered failed: ${f?.message||f}`)}}}function On(c){if(!Array.isArray(c)||!c.length)return;let p=new Set;for(let f of c){let i=B.get(f);i&&(B.delete(f),(ne[i.trackId]??0)<i.seq&&(ne[i.trackId]=i.seq),p.add(i.trackId))}for(let f of p)jt(f);ut()}function Jr(c,p){Gr++;let f={at:Date.now(),trackId:c.trackId,seq:c.seq,id:c.event?.id??null,type:c.event?.type??null,reason:p,event:c.event??null};_.error(`[plane-link] DEAD-LETTER ${c.trackId} seq ${c.seq} (${f.type??"?"}): plane rejected it permanently (${p}) \u2014 kept in ${_n}`),Vr=Vr.then(async()=>{await Et.mkdir(G.dirname(_n),{recursive:!0}),await Et.appendFile(_n,JSON.stringify(f)+`
|
|
137
|
-
`)}).catch(i=>_.error(`[plane-link] dead-letter write failed: ${i?.message||i}`))}function ca(c,p){if(Ct[c]=(Ct[c]??0)+1,zr.has(c))return;zr.add(c);let f=xu[c]??"see the plane's tenancy alarm ring (GET /plane/tenancy/alarms)";_.error(`[plane-link] REFUSED by the plane (${c}) on track ${p}: events are being dropped, not stored \u2014 ${f}`);try{Nt?.({reason:c,trackId:p,count:Ct[c],hint:f})}catch(i){_.error(`[plane-link] onRefused failed: ${i?.message||i}`)}}function Rn(c,p,f,i=null){if(!Array.isArray(c)||!c.length)return;let u=new Set,w=Date.now();for(let $ of c){let v=B.get($);v&&(f?(B.delete($),Jr(v,p),String(p).startsWith(xr)&&ca(String(p).slice(xr.length),v.trackId),(ne[v.trackId]??0)<v.seq&&(ne[v.trackId]=v.seq),u.add(v.trackId)):(v.nacks++,v.retryAt=w+Math.max(1e3,Number(i)||_e)))}for(let $ of u)jt($);ut()}function Zr(c=Date.now()){let p=1/0;for(let f of B.values())f.firstSentAt<p&&(p=f.firstSentAt);return p===1/0?0:c-p}function la(c){if(!ie||!c||c!==J||!Ae)return!1;let p=Date.now()-Ae;if(p<=ie)return!1;qr++,_.error(`[plane-link] no frame from the plane for ${Math.round(p/1e3)}s \u2014 link is half-open; terminating and redialing`);try{c.terminate()}catch{}return!0}function Qr(){if(!Z||!B.size)return;let c=Date.now(),p=Zr(c);if(p<rt||Pt!=null&&c-Pt<rt||W==="http"&&re||st>c)return;le++;let f=Math.min(Fr*2**(le-1),Li);if(me==null){me=c-p,_.error(`[plane-link] DEGRADED: no ack or nack for ${Math.round(p/1e3)}s with ${B.size} event(s) in flight (${W} door) \u2014 the plane is not answering appends`);try{Ie?.({since:me,unacked:B.size,oldestAgeMs:p,mode:W})}catch(i){_.error(`[plane-link] onDegraded failed: ${i?.message||i}`)}}if(W==="http"){re=!0,$e=c+f,_.error(`[plane-link] ingest circuit OPEN (stall #${le}); probing /v1/ingest/health in ${Math.round(f/1e3)}s`);return}st=c+f,_.error(`[plane-link] closing the link and redialing in ${Math.round(f/1e3)}s (stall redial #${le})`);try{J?.terminate()}catch{}}function Nn(){if(!Z)return;let c=Date.now();if(W==="http"&&re)return;let p=[...B.values()].filter(i=>i.event&&i.retryAt<=c&&!(W==="http"&&it.has(i.trackId)));if(!p.length)return;p.sort((i,u)=>i.trackId===u.trackId?i.seq-u.seq:i.trackId<u.trackId?-1:1),_.log(`[plane-link] re-sending ${p.length} unacked event(s) the plane never confirmed`);let f=En();if(W==="http"){let i=new Map;for(let u of p)(i.get(u.trackId)??i.set(u.trackId,[]).get(u.trackId)).push(u);for(let[,u]of i){if(Ce>=$r)return;Le(u.slice(0,f).map(w=>({trackId:w.trackId,event:w.event})))}return}for(let i=0;i<p.length;i+=f){let u=p.slice(i,i+f).map(w=>({trackId:w.trackId,event:w.event}));if(!Le(u))return}}async function ua(c=null){for(;;){if(!Z)return!1;let p=B.size<ot,f=W!=="http"||Ce<$r&&!re&&(!c||!Xr(c));if(p&&f)return!0;await new Promise(i=>setTimeout(i,100))}}function Lt(){if(K=null,!Z||!oe.length)return;let c=oe;oe=[];let p=En();if(W!=="http"){for(let u=0;u<c.length;u+=p)Le(c.slice(u,u+p));return}let f=kn(),i=new Map;for(let u of c)(i.get(u.trackId)??i.set(u.trackId,[]).get(u.trackId)).push(u);for(let[u,w]of i){if(Xr(u)||Ce>=$r||re){oe.push(...w);continue}if(f){Le(w.slice(0,p)),oe.push(...w.slice(p));continue}for(let $=0;$<w.length;$+=p)Le(w.slice($,$+p))}oe.length&&!K&&(K=setTimeout(Lt,Fi),K.unref?.())}let da=c=>{let p=new Map;for(let{trackId:f,event:i}of c)(p.get(f)??p.set(f,[]).get(f)).push(i);return[...p].map(([f,i])=>({trackId:f,events:i}))},ve=(c,p,f,{progress:i})=>{let u=Date.now();for(let{event:w}of c){let $=B.get(w.id);$&&($.nacks++,$.retryAt=u+Math.max(1e3,f||_e))}i&&ut()};async function pa(c){let p=new Set(c.map(f=>f.trackId));for(let f of p)it.add(f);Ce++;try{let f=await Ur(`${Kr}/v1/ingest`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({node:n,batches:da(c)}),signal:AbortSignal.timeout(te)}),i=(Number(f.headers.get("retry-after"))||0)*1e3;if(f.status===200){let u=await f.json();ge=dn;for(let v of u.results??[]){On(v.acked??[]);let F=(ae,q)=>{let Ft=new Map;for(let ke of ae??[])(Ft.get(ke.reason)??Ft.set(ke.reason,[]).get(ke.reason)).push(ke.id);for(let[ke,ao]of Ft)Rn(ao,ke,q,u.retryAfterMs??null)};F(v.rejected,!0),F(v.deferred,!1)}let w=new Set,$=new Map;for(let v of Array.isArray(u.refused)?u.refused:[])!v||typeof v.id!="string"||(w.add(v.id),($.get(v.reason)??$.set(v.reason,[]).get(v.reason)).push(v.id));for(let[v,F]of $)Rn(F,`${xr}${v}`,!0);On((u.discarded??[]).filter(v=>!w.has(v))),ut();return}if(f.status===429){ve(c,"overloaded",i||5e3,{progress:!0});return}if(f.status===413&&c.length>1){ge=Math.max(1,Math.floor(c.length/2)),_.error(`[plane-link] ingest request too large (${c.length} events) \u2014 halving batches to ${ge}`),ve(c,"too_large",1e3,{progress:!0});return}if(f.status===413){let u=B.get(c[0].event.id);u&&(B.delete(u.event.id),Jr(u,"too_large"),(ne[u.trackId]??0)<u.seq&&(ne[u.trackId]=u.seq),jt(u.trackId)),ut();return}if(f.status===410){vn({reason:"removed",via:"410"}),ve(c,"http_410",6e4,{progress:!1});return}if(f.status===401||f.status===403){let{tripped:u,holdMs:w}=Qt();if(u&&_.error(`[plane-link] holding every plane call for ${Math.round(w/6e4)} min \u2014 the ingest door refused this node's token three times in a row`),Date.now()-Dt>=Ui){Dt=Date.now();let $="";try{$=(await f.json())?.error??""}catch{}_.error(`[plane-link] plane refused ingest (HTTP ${f.status}${$?`: ${$}`:""}) \u2014 events are held locally and retried; check this node's token/binding`)}ve(c,`http_${f.status}`,Math.max(6e4,St()),{progress:!1});return}if(f.status===400){_.error(`[plane-link] plane rejected an ingest request as malformed (400) \u2014 holding ${c.length} event(s) for retry; this is a bug, not data`),ve(c,"http_400",6e4,{progress:!1});return}ve(c,`http_${f.status}`,i||5e3,{progress:!1})}catch(f){let i=f?.name==="TimeoutError"||f?.name==="AbortError";i&&c.length>1&&(ge=Math.max(1,Math.floor(c.length/2)),_.error(`[plane-link] ingest request of ${c.length} event(s) outlived its ${te} ms deadline \u2014 halving batches to ${ge}`)),ve(c,i?"timeout":"network",5e3,{progress:!1})}finally{Ce--;for(let f of p)it.delete(f);oe.length&&!K&&(K=setTimeout(Lt,0),K.unref?.())}}async function fa(){if(W!=="http"||!re||!Z||Tn)return;let c=Date.now();if(!($e>c||en(c))){Tn=!0;try{let p=await Ur(`${Kr}/v1/ingest/health`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(te)});if(!p.ok)throw new Error(`HTTP ${p.status}`);_.log("[plane-link] ingest door answering \u2014 closing the circuit and re-sending"),re=!1,$e=0,st=Date.now()+te+_e+1e3;for(let f of B.values())f.retryAt=Math.min(f.retryAt,Date.now());Nn()}catch(p){le++;let f=Math.min(Fr*2**(le-1),Li);$e=Date.now()+f,_.error(`[plane-link] ingest door still not answering (${p?.message||p}); next probe in ${Math.round(f/1e3)}s`)}finally{Tn=!1}}}function eo(){let c=Date.now();return{mode:W,unacked:B.size,oldestUnackedAgeMs:Zr(c),lastProgressAt:Pt,degradedSince:me,stallRedials:le,deadLettered:Gr,fanoutCap:kn()?Lr:null,http:W==="http"?{inFlight:Ce,circuitOpen:re,nextProbeInMs:re?Math.max(0,$e-c):0,batchCap:ge,heldLive:oe.length}:null}}async function to(){if(!h)return;let c;try{c=await h()}catch(f){_.error("[plane-link] metrics sample failed:",f?.message||f);return}let p=null;try{p=m?.()??null}catch{}c&&D({v:j,ch:"ctl",type:"metrics",metrics:{...c,planeLink:eo(),...p?{delivery:p}:{}}})}function ha(){h&&(de&&clearInterval(de),to(),de=setInterval(to,g),de.unref?.())}async function ma(){let c;try{c=await o()}catch(p){_.error("[plane-link] backfill listTracks failed:",p?.message||p);return}D({v:j,ch:"ctl",type:"tracks",ids:c.filter(p=>!p.transferredTo).map(p=>p.id).filter(p=>typeof p=="string")});for(let p of c)if(!Z||!await no(p))return;Bt=!1;for(let p of Object.keys(ne))jt(p)}async function no(c){let p;try{p=await nn(c)}catch{return!0}let f=ce[c.id]??0,i=p.filter(u=>u.seq>f&&typeof u.id=="string");for(let u=0;u<i.length;){if(!await ua(c.id))return!1;let w=i.slice(u,u+En()).map($=>({trackId:c.id,event:$}));if(!Le(w))return!1;u+=w.length}return!0}let Mn=new Map;async function ro(c,p){if(Mn.get(c)===p)return!1;Mn.set(c,p);let f=null;try{f=(await o()).find($=>$?.id===c)??null}catch{return!1}if(!f)return!1;let i;try{i=await nn(f)}catch{return!1}let u=[...i].reverse().find($=>($?.type==="track.transferred"||$?.type==="track.recovered")&&$.payload?.toNode===n);if(!u||!Number.isFinite(u.seq))return!1;let w=u.seq-1;return(ce[c]??0)>w&&(ce[c]=w,Yr()),(ne[c]??0)>w&&(ne[c]=w),_.log(`[plane-link] re-sending ${c}'s move-commit (seq ${u.seq}, ${u.type}) \u2014 the plane's move record predates this node's adoption`),Z?no(f):!1}function oo(c){!Z||!c?.trackId||typeof c.id!="string"||(oe.push({trackId:c.trackId,event:c}),K||(K=setTimeout(Lt,Fi),K.unref?.()))}let dt=new Map;async function ga(c){let{reqId:p,method:f,path:i,headers:u={},body:w}=c,$=Object.fromEntries(Object.entries(u).filter(([,F])=>F!=null)),v=new AbortController;dt.set(p,v);try{if(c.host){await wa(c,$,v);return}C&&($["x-bostrat-token"]=C);let F=await fetch(x+i,{method:f,headers:$,body:w?Buffer.from(w,"base64"):void 0,signal:v.signal}),ae=Object.fromEntries(F.headers);for(let q of["connection","keep-alive","transfer-encoding","upgrade","content-encoding","content-length"])delete ae[q];if(ae["content-type"]||(ae["content-type"]="application/octet-stream"),D({v:j,ch:"control",type:"http_head",reqId:p,status:F.status,headers:ae}),F.body){for await(let q of F.body)if(!D({v:j,ch:"control",type:"http_data",reqId:p,data:Buffer.from(q).toString("base64")}))break}D({v:j,ch:"control",type:"http_end",reqId:p,error:null})}finally{dt.delete(p)}}function wa(c,p,f){let{reqId:i,method:u,path:w,body:$}=c,v=new URL(x);return new Promise(F=>{let ae=fu.request({host:v.hostname,port:v.port,method:u,path:w,headers:{...p,host:c.host},signal:f.signal},q=>{let{connection:Ft,"keep-alive":ke,"transfer-encoding":ao,upgrade:Nd,...ya}=q.headers;D({v:j,ch:"control",type:"http_head",reqId:i,status:q.statusCode||502,headers:ya}),q.on("data",ba=>{D({v:j,ch:"control",type:"http_data",reqId:i,data:Buffer.from(ba).toString("base64")})||q.destroy()}),q.on("end",()=>{D({v:j,ch:"control",type:"http_end",reqId:i,error:null}),F()}),q.on("error",()=>{D({v:j,ch:"control",type:"http_end",reqId:i,error:"view upstream error"}),F()})});ae.on("error",q=>{D({v:j,ch:"control",type:"http_end",reqId:i,error:q?.message||"view request failed"}),F()}),$&&ae.write(Buffer.from($,"base64")),ae.end()})}function so(){if(xn||lt)return;J=new Tr(e,{headers:{authorization:`Bearer ${t}`}});let c=J;Ae=0,c.on("ping",()=>{Ae=Date.now()}),c.on("pong",()=>{Ae=Date.now()}),J.on("open",async()=>{let f=null;try{f=await s?.()||null}catch{f=null}D({v:j,ch:"ctl",type:"hello",nodeId:n,name:r,platform:process.platform,version:se,installKind:k,...typeof O=="function"?{updatePolicy:O()}:O?{updatePolicy:O}:{},providers:Wi(),...f?{agents:f}:{},mcp:un(),...$n?{restart:$n}:{}})}),J.on("message",f=>{Ae=Date.now();let i;try{i=JSON.parse(f)}catch{return}if(i.ch==="ctl"&&i.type==="warming"){Be||_.log("[plane-link] plane is warming \u2014 hello held until it is ready"),Be=!0;return}if(i.ch==="ctl"&&i.type==="hello_ok"){Mn.clear(),Be&&_.log("[plane-link] plane is ready \u2014 held hello answered"),Be=!1,Z=!0,at=Di,ct=null,$n=null,qo(),_.log(`[plane-link] connected to plane as ${n}`);try{Mt?.()}catch{}if(typeof i.hashKey=="string"&&i.hashKey)try{d?.(i.hashKey)}catch{}try{S?.(typeof i.viewBase=="string"&&i.viewBase?i.viewBase:null)}catch{}try{y?.(i.mode==="local"?"local":"default")}catch{}i.minNodeVersion&&se&&Ze(se,i.minNodeVersion)&&_.error(`[plane-link] this node is bostrat-node ${se}; the plane asks for \u2265${i.minNodeVersion} \u2014 update with: ${Ot(k)}`);try{M?.(typeof i.updatePolicy=="string"?i.updatePolicy:null)}catch{}Wr(i);let u=i.ingest==="http";W=Pe==="ws"?"ws":Pe==="http"||u?"http":"ws",Pe==="http"&&!u&&_.error("[plane-link] BOSTRAT_PLANE_INGEST=http but this plane offers no HTTPS ingest door \u2014 events will fail until it does"),W==="http"&&_.log("[plane-link] spine rides the HTTPS ingest door"),re=!1,$e=0,ge=dn,ue&&clearInterval(ue),Ae=Date.now(),ue=setInterval(()=>{la(c)||(D({v:j,ch:"ctl",type:"ping"}),Qr(),fa().catch(()=>{}),Nn(),oe.length&&!K&&Lt())},P),ue.unref?.(),ha(),Bt=!0,ma().catch(w=>_.error("[plane-link] backfill failed:",w?.message||w));return}if(i.ch==="ctl"&&i.type==="hello_refused"){let u=typeof i.minNodeVersion=="string"?i.minNodeVersion:null,w=typeof i.latestNodeVersion=="string"?i.latestNodeVersion:null;_.error(`[plane-link] plane REFUSED this node: bostrat-node ${se??"?"} is below its minimum ${u??"?"} \u2014 ${i.fix||Ot(k)}`),at=ji,ct=0;try{A?.({current:se,min:u,latest:w,fix:i.fix||Ot(k),installKind:k})}catch($){_.error(`[plane-link] refusal handler failed: ${$?.message||$}`)}return}if(i.ch==="ctl"&&i.type==="removed"){D({v:j,ch:"ctl",type:"removed_ack",nodeId:n}),vn({reason:typeof i.reason=="string"?i.reason:"removed",at:Number(i.at)||Date.now(),via:"ctl"});return}if(i.ch==="ctl"&&i.type==="update_available"){Wr(i);return}if(i.ch==="ctl"&&i.type==="update_policy"){try{M?.(typeof i.mode=="string"?i.mode:null)}catch{}return}if(i.ch==="ctl"&&i.type==="conflict_probe"&&Array.isArray(i.trackIds)){try{T?.(i.trackIds.filter(u=>typeof u=="string"&&u).slice(0,200))}catch{}return}if(i.ch==="ctl"&&i.type==="restarted"){Promise.resolve().then(()=>E?.({kind:i.kind,at:i.at,reason:i.reason})).catch(u=>_.error("[plane-link] restart notice failed:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="usage_caps"){oi(i.caps??{},{source:"plane",updatedAt:i.updatedAt??Date.now()}).then(u=>_.log(`[plane-link] spend caps ${Object.keys(u.caps).length?`updated (${Object.keys(u.caps).join(", ")})`:"cleared"} from plane`)).catch(u=>_.error("[plane-link] spend-caps push rejected:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="mcp_config"){$i(i.entries??[],{updatedAt:i.updatedAt??Date.now()}).then(u=>_.log(`[plane-link] mcp config applied: ${Object.keys(u.entries).length} entr${Object.keys(u.entries).length===1?"y":"ies"}`)).catch(u=>_.error("[plane-link] mcp config apply failed:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="refresh_flow"){Ci(i.flow??{},{source:"plane",updatedAt:i.updatedAt??Date.now()}).then(u=>_.log(`[plane-link] refresh flow from plane: contextFull=${u.flow.contextFull} rung=${u.flow.contextFullTokens?`${u.flow.contextFullTokens} tokens`:`${u.flow.contextFullPct}%`}`)).catch(u=>_.error("[plane-link] refresh-flow push rejected:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="refresh_flow_rejected"){Pi(typeof i.error=="string"?i.error:"rejected by the plane");return}if(i.ch==="ctl"&&i.type==="transferred"&&Array.isArray(i.tracks)){Promise.resolve().then(()=>a?.(i.tracks)).then(async u=>{for(let w of Array.isArray(u)?u:[])w?.stale&&w.id&&await ro(w.id,w.since??null)}).catch(u=>_.error("[plane-link] transfer notice failed:",u?.message||u));return}if(i.ch==="ctl"&&i.type==="moves"&&Array.isArray(i.tracks)){Promise.resolve().then(()=>l?.(i.tracks)).then(async u=>{for(let w of Array.isArray(u)?u:[])w?.stale&&w.id&&await ro(w.id,w.since??null)}).catch(u=>_.error("[plane-link] move-record reconcile failed:",u?.message||u));return}if(i.ch==="events"&&i.type==="ack"&&Array.isArray(i.ids)){On(i.ids);return}if(i.ch==="events"&&i.type==="nack"&&Array.isArray(i.ids)){Rn(i.ids,i.reason,i.permanent===!0,i.retryAfterMs??null);return}if(i.ch==="control"&&i.type==="http_open"){ga(i).catch(u=>D({v:j,ch:"control",type:"http_end",reqId:i.reqId,error:u?.message||"tunnel error"}));return}if(i.ch==="control"&&i.type==="http_cancel"){dt.get(i.reqId)?.abort();return}if(i.ch==="attach"&&i.type==="open"){let u=new Tr(oa+i.path,Array.isArray(i.protocols)?i.protocols:[],i.host?{headers:{host:i.host}}:void 0);Te.set(i.streamId,u),xe.set(i.streamId,[]),u.on("open",()=>{let $=xe.get(i.streamId)||[];xe.delete(i.streamId);for(let{buf:v,bin:F}of $)u.send(v,{binary:F})}),u.on("message",($,v)=>{let F=v?$:Buffer.from(String($));D({v:j,ch:"attach",type:"data",streamId:i.streamId,data:F.toString("base64"),...v?{bin:!0}:{}})});let w=()=>{xe.delete(i.streamId),Te.delete(i.streamId)&&D({v:j,ch:"attach",type:"close",streamId:i.streamId})};u.on("close",w),u.on("error",w);return}if(i.ch==="attach"&&i.type==="data"){let u=Te.get(i.streamId);if(!u)return;let w=Buffer.from(i.data,"base64"),$=i.bin===!0,v=xe.get(i.streamId);v?v.push({buf:w,bin:$}):u.send(w,{binary:$});return}if(i.ch==="attach"&&i.type==="close"){let u=Te.get(i.streamId);Te.delete(i.streamId),xe.delete(i.streamId),u?.close();return}});let p=()=>{Z&&_.log("[plane-link] disconnected from plane"),Z=!1,Be=!1,ue&&(clearInterval(ue),ue=null),de&&(clearInterval(de),de=null),B.clear(),ne={},oe=[],K&&(clearTimeout(K),K=null),it.clear();for(let u of Te.values())u.close();Te.clear(),xe.clear();for(let u of dt.values())u.abort();if(dt.clear(),xn||De)return;ct==null&&(ct=Date.now());let f=Date.now()-ct<mu,i=Math.max(f?gu+Math.random()*wu:at,st-Date.now(),St());De=setTimeout(()=>{De=null,so()},i),De.unref?.(),f||(at=Math.min(at*2,ji))};J.on("close",p),J.on("error",f=>{let i=/Unexpected server response: (\d+)/.exec(f?.message||"")?.[1];if(i==="410"){vn({reason:"removed",via:"410"});return}if(i==="401"||i==="403"){let{tripped:u,holdMs:w}=Qt();u?_.error(`[plane-link] holding every plane call for ${Math.round(w/6e4)} min \u2014 three credential refusals in a row (HTTP ${i}) mean the token is revoked or unknown, not that the plane is down; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN. Next dial in ${Math.round(w/6e4)} min.`):Date.now()-Dt>=Ui&&(Dt=Date.now(),_.error(`[plane-link] plane refused this node's credentials (HTTP ${i}) \u2014 the token was revoked or is unknown to the plane; mint a new node token and update this node's BOSTRAT_PLANE_TOKEN (still retrying)`))}p()})}Tt.on("event",oo),sa().then(so);function io({bye:c=!0}={}){xn=!0,Tt.off("event",oo),ia(),De&&clearTimeout(De),je&&clearTimeout(je),ue&&clearInterval(ue),de&&clearInterval(de),K&&clearTimeout(K),c&&D({v:j,ch:"ctl",type:"bye",reason:"shutdown"}),J?.close()}return{stop:()=>io(),setRefreshFlow:c=>D({v:j,ch:"ctl",type:"refresh_flow_set",patch:c}),status:()=>({connected:Z,warming:Be,nodeId:n,cursor:{...ce},backfillHeld:Bt,inflight:B.size,...eo(),auth:Yo(),dormant:lt,removed:or(),deadLinkMs:ie,deadLinkRedials:qr,refused:{...Ct}}),_tick:()=>{Qr(),Nn()}}}var se,Ar,kr,j,Di,ji,mu,gu,wu,dn,yu,bu,Su,_u,Er,Tu,xr,xu,$u,Au,Li,vu,Fi,ku,$r,Eu,Ou,Ui,Or=R(()=>{rn();si();Ai();Bi();Gt();sr();se=(()=>{try{return hu(import.meta.url)("../package.json").version||null}catch{return null}})(),Ar=process.env.BOSTRAT_STATE_DIR||G.join(process.env.HOME||pn.tmpdir(),".bostrat"),kr=G.join(Ar,"plane-link","removed.json");j=1,Di=1e3,ji=3e4,mu=6e4,gu=1500,wu=500,dn=100,yu=2e3,bu=25e3,Su=2.5,_u=6e4,Er=(e,t)=>{let n=Number(e);return Number.isFinite(n)&&n>0?n:t},Tu=Er(process.env.BOSTRAT_PLANE_DELIVERY_TIMEOUT_MS,18e4),xr="refused:",xu={forgedUserId:"this node's events carry a userId the plane's token does not own \u2014 remove BOSTRAT_OWNER from node.env and the shell environment, then restart the node (current releases never stamp one)",foreignTrack:"the Track belongs to another user's node \u2014 this node must not append to it",squattedTrack:"the Track id is already claimed by another user \u2014 a local Track collided with theirs",transferredAway:"the Track moved to another node \u2014 this copy is stale; it should be demoted, not resumed",slugHijack:"a View slug belongs to another owner \u2014 pick a different slug"},$u=e=>{if(!e||e.userId===void 0)return e;let{userId:t,...n}=e;return n},Au=3e4,Li=10*6e4,vu=400,Fi=250,ku=Er(process.env.BOSTRAT_PLANE_INGEST_TIMEOUT_MS,1e4),$r=4,Eu=Math.max(1,Math.round(Er(process.env.BOSTRAT_PLANE_FANOUT_BATCH_CAP,25))),Ou=6e4,Ui=6e4});var Gi=R(()=>{tr()});var Zi={};In(Zi,{ACTIONABLE_KINDS:()=>wn,INSTALL_ATTEMPTS:()=>fn,INSTALL_RETRY_STEP_S:()=>zi,REGISTRY_RETRY_ATTEMPTS:()=>Mr,REGISTRY_WAIT_POLLS:()=>Rr,REGISTRY_WAIT_STEP_S:()=>Nr,RESTART_SIGNAL:()=>qi,SELF_UPDATE_DIR:()=>mn,SUPERVISOR_PID_FILE:()=>Vi,createAutoUpdater:()=>Gu,inFlight:()=>Br,readStatus:()=>Cr,restartCommand:()=>Yi,restartStrategy:()=>Pr,selfUpdatePlan:()=>Xi,settleSelfUpdate:()=>Ku,startSelfUpdate:()=>Ji,underService:()=>Ir,updatePolicy:()=>ju});import Rt from"node:fs";import be from"node:fs/promises";import Nu from"node:os";import U from"node:path";import{spawn as Mu,execFileSync as Iu}from"node:child_process";import{createRequire as Pu}from"node:module";function ju({kind:e=Qe(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:wn.has(e)?e==="git-checkout"||Ir(t)?"auto":"prompt":"off"}function Ir(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function Pr({env:e=process.env,platform:t=process.platform,uid:n=typeof process.getuid=="function"?process.getuid():0,serviceName:r=t==="darwin"?"com.bostrat.node":"bostrat-node.service",pidFile:o=Vi,readFile:s=l=>Rt.readFileSync(l,"utf8"),alive:a=Lu}={}){let l=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(Ir(e))return l;let h=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(h)&&h>0)){try{h=Number(String(s(o)).trim())}catch{h=NaN}Number.isInteger(h)&&h>0&&a(h)||(h=NaN)}return Number.isInteger(h)&&h>0?{mode:"supervisor",pid:h}:l}function Lu(e){try{process.kill(e,0)}catch{return!1}try{let t=Iu("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/bostrat-node|\/cli\.js|node-cli\.js/.test(t)}catch{return!1}}function Yi(e){switch(e?.mode){case"systemd":return`systemctl --user restart ${Q(e.serviceName||"bostrat-node.service")}`;case"launchd":return`launchctl kickstart -k gui/${Number(e.uid)||0}/${e.serviceName||"com.bostrat.node"}`;case"supervisor":return`kill -${qi.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function Xi({kind:e,to:t,from:n=hn,statusFile:r=gn,logFile:o=U.join(mn,"last.log"),port:s=Number(process.env.PORT)||3362,npmPrefix:a=null,serviceName:l=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:h=typeof process.getuid=="function"?process.getuid():0,restart:m=Pr({env:{},platform:process.platform,uid:h,serviceName:l,readFile:()=>{throw new Error("no pidfile")}}),liveDir:d=process.env.BOSTRAT_LIVE_CHECKOUT||U.resolve(U.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:S=Date.now(),attempts:y=1}={}){if(!wn.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 g=(E,A="")=>`write_status ${Q(E)} ${A}`,b=Yi(m),M=`
|
|
68
|
+
`,"utf8")}catch(t){console.warn(`[handoff-debug] failed to write ${zr}: ${t?.message||t}`)}}async function V(e={}){let t=e.paneTail===!0,n={at:new Date().toISOString(),ts:Date.now(),...e};t&&delete n.paneTail;let r=[n.flow||"handoff",n.phase||n.step||"?",n.trackId?`track=${n.trackId}`:"",n.sessionName?`box=${n.sessionName}`:"",n.error?`ERR=${n.error}`:""].filter(Boolean).join(" \xB7 ");if(console.log(`[handoff-debug] ${r}`),n.sessionName&&(t||Ql()))try{n.paneTail=Wg((await Vl(n.sessionName,{lines:t?zg:35})).slice(-Gg))}catch{n.paneTail=null}(t||Ql()||n.error||/^(checkpoint|spawn|hydrate|commit|done|summarize|clear|resume|ready|send|seed|failed|launch|submit-|gate-accept|blocked|timeout|dialog|exit|config-|waiting|quiet|quiescence-|await-)/.test(String(n.phase||n.step||"")))&&await Kg(n)}var Hg,tu,zr,Zl,zg,Gg,oi=k(()=>{ri();mr();Hg=[/[A-Za-z0-9_-]{20,}#[A-Za-z0-9_-]{20,}/g,/\bsk-[A-Za-z0-9_-]{16,}/g,/\bghs_[A-Za-z0-9]{16,}|\bghp_[A-Za-z0-9]{16,}|\bgithub_pat_[A-Za-z0-9_]{20,}/g,/\bFlyV1 [A-Za-z0-9+/=_-]{16,}/g,/\bey[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g];tu=process.env.BOSTRAT_DEBUG_DIR||eu.join(Ug.homedir(),".bostrat","debug"),zr=eu.join(tu,"handoff.jsonl"),Zl=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500;zg=40,Gg=4e3});var di={};Z(di,{CLIS:()=>ft,SWEPT:()=>su,_codexUpdateIdle:()=>fu,_resetCodexUpdateForTest:()=>mu,_setCodexUpdateExecForTest:()=>hu,awaitSpawnGate:()=>si,configureCliCurrency:()=>Zg,discover:()=>du,ensureCliLaunches:()=>Xl,installInFlight:()=>tw,launchErrorHead:()=>zn,nodePrefixFromBin:()=>Kn,releaseSpawnLease:()=>cu,scheduleCodexUpdate:()=>lu,scheduleInstall:()=>Zt,setCodexUpdateNotifier:()=>iu,spawnLease:()=>Jl,startCliCurrency:()=>sw,sweep:()=>pu,updateNow:()=>ow,versionLt:()=>au});import Yg from"node:fs/promises";import{execFile as li}from"node:child_process";import{promisify as ui}from"node:util";function iu(e){qr=typeof e=="function"?e:null}function Zg({holdWhile:e=null}={}){Vr=typeof e=="function"?e:null}function Qg(e){return new Promise(t=>setTimeout(t,e))}function Kn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}function au(e,t){let n=s=>String(s||"").split(/[-+]/)[0].split(".").map(Number),r=n(e),o=n(t);if(!r.length||!o.length||r.some(Number.isNaN)||o.some(Number.isNaN))return!1;for(let s=0;s<Math.max(r.length,o.length);s++){let a=(r[s]||0)-(o[s]||0);if(a)return a<0}return!1}async function Xr(e){let t=(await ke("/bin/sh",["-c",`command -v ${e.bin}`])).stdout.trim();if(!t)throw new Error(`${e.bin} not on PATH`);let n=await Yg.realpath(t).catch(()=>t),r=Kn(n),o=r?{...process.env,PATH:`${r}/bin:${process.env.PATH||""}`}:process.env;return{bin:t,env:o,npmGlobal:!!r}}async function Wn(e,t,{timeout:n=Jr}={}){return(await ke(t,["--version"],{timeout:n})).stdout.trim().replace(e.versionRe,"")||null}async function ew(e,t,n){let r=await ke("npm",["view",e.pkg,"time","--json"],{env:n,timeout:Jr}),o=JSON.parse(String(r.stdout||"{}")),s=Date.parse(o?.[t]||"");return Number.isFinite(s)?s:null}async function si({timeoutMs:e=ou()}={}){if(!Se)return{waited:!1,timedOut:!1};let t=Date.now(),n=null,r=await Promise.race([Se.then(()=>!1,()=>!1),new Promise(o=>{n=setTimeout(()=>o(!0),e)})]);return clearTimeout(n),{waited:!0,waitedMs:Date.now()-t,timedOut:r}}function tw(){return Se!==null}function Jl(e,{ttlMs:t=qg()}={}){let n=String(e||"");return n?(Xt.set(n,Date.now()+t),()=>cu(n)):()=>{}}function cu(e){Xt.delete(String(e||""))}function nw(){let e=Date.now();for(let[t,n]of Xt)n<=e&&Xt.delete(t);return Xt.size}async function rw({timeoutMs:e=Vg()}={}){let t=Date.now()+e;for(;nw()>0||Vr&&await Vr().catch(()=>!1);){if(Date.now()>t)return!1;await Qg(Jg)}return!0}function Zt({cli:e=ft.codex,sessionName:t=null,from:n=null,to:r,reason:o="sweep",repair:s=!1}={}){let a=String(r||"").trim();if(!a)return!1;if(le())return V({flow:"cli-currency",phase:"local-mode-skip",cli:e.name,sessionName:t,from:n,to:a,reason:o}).catch(()=>{}),!1;if(s){let l=Gr.get(a)||0;if(l>=Xg||Se)return!1;Gr.set(a,l+1)}else{if(ai.has(a))return!1;ai.add(a)}let i=pt.then(()=>uu({cli:e,sessionName:t,from:n,to:a,reason:o,repair:s})).catch(()=>{});pt=i;let c=i.then(()=>{Se===c&&(Se=null)});return Se=c,!0}function lu({sessionName:e,from:t,to:n}={}){let r=String(n||"").trim();r&&(V({flow:"cli-currency",phase:"fallback",cli:"codex",sessionName:e,from:t,to:r}).catch(()=>{}),Zt({cli:ft.codex,sessionName:e,from:t,to:r,reason:"chooser"}))}async function uu({cli:e,sessionName:t,from:n,to:r,reason:o,repair:s=!1}){await V({flow:"codex-update",phase:"start",cli:e.name,sessionName:t,from:n,to:r,reason:o,...s?{repair:!0}:{}}).catch(()=>{});let a=null,i=process.env;try{await rw()||await V({flow:"codex-update",phase:"lease-wait-cap",cli:e.name,to:r}).catch(()=>{}),{bin:a,env:i}=await Xr(e);let l=/^\d/.test(r)?`${e.pkg}@${r}`:e.pkg;await ke("npm",["install","-g",l],{env:i,timeout:ii});let u=await ci(e,a);return await V({flow:"codex-update",phase:"done",cli:e.name,sessionName:t,from:n,to:r,version:u,reason:o}).catch(()=>{}),s&&Gr.delete(r),await ru({cli:e.name,sessionName:t,from:n,to:r,version:u,status:"updated",reason:o}),{status:"updated",from:n,to:r,version:u}}catch(c){let l=String(c?.message||c).slice(0,300),u=null;if(a&&n&&/^\d/.test(String(n))&&String(n)!==String(r)){await V({flow:"codex-update",phase:"rollback",cli:e.name,sessionName:t,from:n,to:r,error:l}).catch(()=>{});try{await ke("npm",["install","-g",`${e.pkg}@${n}`],{env:i,timeout:ii}),await ci(e,a),u=!0}catch(f){u=!1,await V({flow:"codex-update",phase:"rollback-failed",cli:e.name,sessionName:t,from:n,to:r,error:String(f?.message||f).slice(0,300)}).catch(()=>{})}}return await V({flow:"codex-update",phase:"failed",cli:e.name,sessionName:t,from:n,to:r,error:l,reason:o,...u!==null?{rolledBack:u}:{}}).catch(()=>{}),await ru({cli:e.name,sessionName:t,from:n,to:r,status:"failed",error:l,reason:o,...u!==null?{rolledBack:u}:{},...s?{repair:!0}:{}}),{status:"failed",from:n,to:r,error:l,...u!==null?{rolledBack:u}:{}}}}async function ci(e,t){let n=null;try{n=await Wn(e,t,{timeout:Hn})}catch(r){throw new Error(`${e.bin} does not launch after the install: ${zn(r)}`)}if(!n)throw new Error(`${e.bin} --version printed no version after the install`);return n}function zn(e){let n=String(e?.stderr||"").split(/\r?\n/).map(o=>o.trim()).filter(Boolean);return(n.find(o=>/^Error\b|Error:/.test(o))||n.find(o=>!/^\s*at\s/.test(o))||null||String(e?.message||e)).slice(0,200)}async function ru(e){if(qr)try{await qr(e)}catch{}}async function du(e="codex",{reason:t="sweep"}={}){let n=ft[e],r={cli:e,installed:null,latest:null,drift:!1,scheduled:!1,broken:!1,held:!1};if(!n)return r;try{let{bin:o,env:s}=await Xr(n),a=null;try{r.installed=await Wn(n,o,{timeout:Hn})}catch(c){a=zn(c),r.broken=!0}let i=await ke("npm",["view",n.pkg,"dist-tags.latest"],{env:s,timeout:Jr});if(r.latest=String(i.stdout||"").trim().split(/\s+/).pop()||null,!/^\d+\.\d+\.\d+/.test(r.latest||""))throw new Error(`registry answered "${r.latest}"`);if(Yr=r.latest,r.drift=!!(r.installed&&au(r.installed,r.latest)),r.broken)return await V({flow:"cli-currency",phase:"broken",cli:e,latest:r.latest,error:a,reason:t}).catch(()=>{}),r.scheduled=Zt({cli:n,from:null,to:r.latest,reason:"repair",repair:!0}),r;if(r.drift&&nu()>0){let c=await ew(n,r.latest,s).catch(()=>null);c!==null&&Date.now()-c<nu()&&(r.held=!0,r.publishedAt=c)}await V({flow:"cli-currency",phase:"discover",cli:e,installed:r.installed,latest:r.latest,drift:r.drift,held:r.held,reason:t}).catch(()=>{}),r.drift&&!r.held&&(r.scheduled=Zt({cli:n,from:r.installed,to:r.latest,reason:t}))}catch(o){await V({flow:"cli-currency",phase:"discover-failed",cli:e,error:String(o?.message||o).slice(0,300),broken:r.broken,reason:t}).catch(()=>{}),r.broken&&(r.scheduled=Zt({cli:n,from:null,to:Yr||"latest",reason:"repair",repair:!0}))}return r}async function Xl(e="codex",{timeoutMs:t=ou()}={}){let n=ft[e];if(!n)return{ok:!0};let r;try{({bin:r}=await Xr(n))}catch{return{ok:!1,missing:!0}}try{return{ok:!0,version:await Wn(n,r,{timeout:Hn})}}catch(o){let s=zn(o);await V({flow:"cli-currency",phase:"broken",cli:e,at:"spawn",error:s}).catch(()=>{});let a=Zt({cli:n,from:null,to:Yr||"latest",reason:"repair",repair:!0}),i=await si({timeoutMs:t}),c=!1;return i.waited&&!i.timedOut&&(c=await Wn(n,r,{timeout:Hn}).then(Boolean,()=>!1)),{ok:c,repaired:c,scheduled:a,error:s,...i}}}async function pu({reason:e="sweep"}={}){let t=[];for(let n of su)t.push(await du(n,{reason:e}));return t}async function ow(e,{to:t=null}={}){let n=ft[e];if(!n)return{ok:!1,cli:e,status:"refused",error:`unknown CLI "${e}" \u2014 one of: ${Object.keys(ft).join(", ")}`};let r=t==null?null:String(t).trim().replace(/^v/,"");if(r!==null&&!/^\d+\.\d+\.\d+(-[\w.]+)?$/.test(r))return{ok:!1,cli:e,status:"refused",error:`bad version "${t}" (want X.Y.Z)`};let o,s,a;try{({bin:o,env:s,npmGlobal:a}=await Xr(n))}catch{return{ok:!1,cli:e,status:"refused",error:`${n.bin} is not on PATH`}}let i=await Wn(n,o,{timeout:Hn}).catch(()=>null);if(!a&&n.selfUpdate){if(r)return{ok:!1,cli:e,status:"refused",from:i,error:`this ${n.bin} is not an npm-global install \u2014 it moves through \`${n.bin} ${n.selfUpdate.join(" ")}\`, which takes the vendor's current release and cannot pin one`};await V({flow:"codex-update",phase:"start",cli:e,from:i,reason:"manual",via:"vendor"}).catch(()=>{});try{await ke(o,n.selfUpdate,{env:s,timeout:ii});let p=await ci(n,o);return await V({flow:"codex-update",phase:"done",cli:e,from:i,version:p,reason:"manual",via:"vendor"}).catch(()=>{}),{ok:!0,cli:e,status:p===i?"current":"updated",from:i,to:p,version:p,via:"vendor"}}catch(p){let g=zn(p);return await V({flow:"codex-update",phase:"failed",cli:e,from:i,error:g,reason:"manual",via:"vendor"}).catch(()=>{}),{ok:!1,cli:e,status:"failed",from:i,error:g,via:"vendor"}}}let c=r;if(!c)try{let p=await ke("npm",["view",n.pkg,"dist-tags.latest"],{env:s,timeout:Jr});if(c=String(p.stdout||"").trim().split(/\s+/).pop()||"",!/^\d+\.\d+\.\d+/.test(c))throw new Error(`registry answered "${c}"`)}catch(p){return{ok:!1,cli:e,status:"failed",from:i,error:`could not read ${n.pkg}'s latest release from the registry: ${String(p?.message||p).slice(0,200)} \u2014 name one with --to X.Y.Z`}}if(i&&i===c)return{ok:!0,cli:e,status:"current",from:i,to:c,version:i,via:"npm"};let l=pt.then(()=>uu({cli:n,sessionName:null,from:i,to:c,reason:"manual",repair:!i}));pt=l.catch(()=>{});let u=pt.then(()=>{Se===u&&(Se=null)});Se=u;let f=await l.catch(p=>({status:"failed",from:i,to:c,error:String(p?.message||p).slice(0,300)}));return{ok:f.status==="updated",cli:e,via:"npm",...f}}function sw({env:e=process.env,initialDelayMs:t=9e4}={}){let n=e.BOSTRAT_CLI_CURRENCY_MS===void 0?216e5:Number(e.BOSTRAT_CLI_CURRENCY_MS);if(!(n>0)||le(e))return null;let r=()=>le(e)?Promise.resolve([]):pu({reason:"sweep"}).catch(()=>{}),o=setTimeout(r,t);o.unref?.();let s=setInterval(r,n);return s.unref?.(),{stop:()=>{clearTimeout(o),clearInterval(s)}}}function fu(){return pt}function hu(e){ke=e||ui(li)}function mu(){ai.clear(),Gr.clear(),Yr=null,pt=Promise.resolve(),Se=null,Xt.clear(),qr=null,Vr=null,ke=ui(li)}var ke,ii,Jr,ou,qg,Vg,Jg,nu,Xg,Hn,ft,su,ai,Gr,Yr,pt,Se,Xt,qr,Vr,Un=k(()=>{oi();Ue();q();ke=ui(li),ii=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Jr=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,ou=()=>Number(process.env.BOSTRAT_CLI_UPDATE_WAIT_MS)||45e3,qg=()=>Number(process.env.BOSTRAT_CLI_SPAWN_LEASE_MS)||9e4,Vg=()=>Number(process.env.BOSTRAT_CLI_LEASE_WAIT_MS)||12e4,Jg=250,nu=()=>process.env.BOSTRAT_CLI_RELEASE_MIN_AGE_MS===void 0?240*6e4:Number(process.env.BOSTRAT_CLI_RELEASE_MIN_AGE_MS)||0,Xg=3,Hn=Number(process.env.BOSTRAT_CLI_PROBE_TIMEOUT_MS)||8e3,ft={codex:{name:"codex",pkg:"@openai/codex",bin:"codex",versionRe:/^codex-cli\s*/},claude:{name:"claude",pkg:"@anthropic-ai/claude-code",bin:"claude",versionRe:/\s*\(Claude Code\)\s*$/,selfUpdate:["update"]}},su=["codex"],ai=new Set,Gr=new Map,Yr=null,pt=Promise.resolve(),Se=null,Xt=new Map,qr=null;Vr=null;j("npm-cli-currency",({env:e,local:t})=>{let n=e.BOSTRAT_CLI_CURRENCY_MS===void 0?216e5:Number(e.BOSTRAT_CLI_CURRENCY_MS),r=!t&&n>0;return{class:"registry",mode:r?"timer":"manual",host:Qt(e),armedBy:[r?"BOSTRAT_CLI_CURRENCY_MS (on unless 0)":"bostrat-node cli-update (by hand)"],purpose:"agent CLI releases"}})});var gu=k(()=>{Un()});var Si={};Z(Si,{ACTIONABLE_KINDS:()=>no,INSTALL_ATTEMPTS:()=>Zr,INSTALL_RETRY_STEP_S:()=>wu,REGISTRY_RETRY_ATTEMPTS:()=>hi,REGISTRY_WAIT_POLLS:()=>pi,REGISTRY_WAIT_STEP_S:()=>fi,RESTART_SIGNAL:()=>Su,SELF_UPDATE_DIR:()=>eo,SUPERVISOR_PID_FILE:()=>yu,createAutoUpdater:()=>Sw,inFlight:()=>yi,readStatus:()=>wi,restartCommand:()=>_u,restartStrategy:()=>gi,selfUpdatePlan:()=>Tu,settleSelfUpdate:()=>yw,startSelfUpdate:()=>xu,underService:()=>mi,updatePolicy:()=>bu});import Gn from"node:fs";import We from"node:fs/promises";import iw from"node:os";import G from"node:path";import{spawn as aw,execFileSync as cw}from"node:child_process";import{createRequire as lw}from"node:module";function bu({kind:e=Gt(),env:t=process.env}={}){let n=String(t.BOSTRAT_UPDATE_POLICY||"").trim();return["auto","prompt","off"].includes(n)?n:no.has(e)?e==="git-checkout"||mi(t)?"auto":"prompt":"off"}function mi(e=process.env){return!!(e.INVOCATION_ID||e.XPC_SERVICE_NAME&&e.XPC_SERVICE_NAME!=="0")}function gi({env:e=process.env,platform:t=process.platform,uid:n=typeof process.getuid=="function"?process.getuid():0,serviceName:r=t==="darwin"?"com.bostrat.node":"bostrat-node.service",pidFile:o=yu,readFile:s=i=>Gn.readFileSync(i,"utf8"),alive:a=fw}={}){let i=t==="darwin"?{mode:"launchd",uid:n,serviceName:r}:{mode:"systemd",serviceName:r};if(mi(e))return i;let c=Number(e.BOSTRAT_RUN_SUPERVISOR_PID);if(!(Number.isInteger(c)&&c>0)){try{c=Number(String(s(o)).trim())}catch{c=NaN}Number.isInteger(c)&&c>0&&a(c)||(c=NaN)}return Number.isInteger(c)&&c>0?{mode:"supervisor",pid:c}:i}function fw(e){try{process.kill(e,0)}catch{return!1}try{let t=cw("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return/bostrat-node|\/cli\.js|node-cli\.js/.test(t)}catch{return!1}}function _u(e){switch(e?.mode){case"systemd":return`systemctl --user restart ${ue(e.serviceName||"bostrat-node.service")}`;case"launchd":return`launchctl kickstart -k gui/${Number(e.uid)||0}/${e.serviceName||"com.bostrat.node"}`;case"supervisor":return`kill -${Su.replace(/^SIG/,"")} ${Number(e.pid)}`;default:throw new Error(`self-update: unknown restart strategy "${e?.mode}"`)}}function Tu({kind:e,to:t,from:n=Qr,statusFile:r=to,logFile:o=G.join(eo,"last.log"),port:s=Number(process.env.PORT)||3362,npmPrefix:a=null,serviceName:i=process.platform==="darwin"?"com.bostrat.node":"bostrat-node.service",uid:c=typeof process.getuid=="function"?process.getuid():0,restart:l=gi({env:{},platform:process.platform,uid:c,serviceName:i,readFile:()=>{throw new Error("no pidfile")}}),liveDir:u=process.env.BOSTRAT_LIVE_CHECKOUT||G.resolve(G.dirname(new URL(import.meta.url).pathname),"..",".."),startedAt:f=Date.now(),attempts:p=1}={}){if(!no.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 g=(M,A="")=>`write_status ${ue(M)} ${A}`,S=_u(l),x=`
|
|
138
69
|
health() {
|
|
139
70
|
for i in $(seq 1 45); do
|
|
140
71
|
sleep 1
|
|
141
72
|
if curl -sf -o /dev/null "http://127.0.0.1:${s}/api/health"; then return 0; fi
|
|
142
73
|
done
|
|
143
74
|
return 1
|
|
144
|
-
}`,
|
|
75
|
+
}`,_=`#!/usr/bin/env bash
|
|
145
76
|
# bostrat-node self-update one-shot \u2014 written by agent/src/self-update.js.
|
|
146
77
|
# ${n??"?"} \u2192 ${t} (${e}). Status: ${r}
|
|
147
78
|
set -u
|
|
148
|
-
FROM=${
|
|
149
|
-
TO=${
|
|
150
|
-
STATUS_FILE=${
|
|
151
|
-
STARTED_AT=${Number(
|
|
152
|
-
ATTEMPTS=${Number(
|
|
79
|
+
FROM=${ue(n??"")}
|
|
80
|
+
TO=${ue(t)}
|
|
81
|
+
STATUS_FILE=${ue(r)}
|
|
82
|
+
STARTED_AT=${Number(f)}
|
|
83
|
+
ATTEMPTS=${Number(p)||1}
|
|
153
84
|
write_status() { # <status> [error] [retryable]
|
|
154
85
|
local err="\${2:-}"
|
|
155
86
|
err="\${err//\\\\/\\\\\\\\}"; err="\${err//\\"/\\\\\\"}"
|
|
156
87
|
printf '{"status":"%s","from":"%s","to":"%s","kind":"%s","attempts":%s,"startedAt":%s,"updatedAt":%s%s%s}\\n' \\
|
|
157
|
-
"$1" "$FROM" "$TO" ${
|
|
88
|
+
"$1" "$FROM" "$TO" ${ue(e)} "$ATTEMPTS" "$STARTED_AT" "$(date +%s000)" \\
|
|
158
89
|
"\${err:+,\\"error\\":\\"$err\\"}" "\${3:+,\\"retryable\\":true}" > "$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
|
|
159
90
|
}
|
|
160
|
-
${
|
|
161
|
-
`;if(e==="npm-global"){let
|
|
162
|
-
`:""
|
|
91
|
+
${x}
|
|
92
|
+
`;if(e==="npm-global"){let M=a?G.join(a,"bin","npm"):"npm",A=a?`export PATH=${ue(G.join(a,"bin"))}:"$PATH"
|
|
93
|
+
`:"",$=a?` --prefix ${ue(a)}`:"",I=fe=>`${ue(M)} install -g "bostrat-node@${fe}" --no-audit --no-fund${$}`,E=`
|
|
163
94
|
install_target() {
|
|
164
|
-
for i in $(seq 1 ${
|
|
165
|
-
if ${
|
|
166
|
-
[ "$i" -lt ${
|
|
95
|
+
for i in $(seq 1 ${Zr}); do
|
|
96
|
+
if ${I("$TO")}; then return 0; fi
|
|
97
|
+
[ "$i" -lt ${Zr} ] && sleep ${wu}
|
|
167
98
|
done
|
|
168
99
|
return 1
|
|
169
|
-
}`,
|
|
100
|
+
}`,L=`
|
|
170
101
|
wait_for_registry() {
|
|
171
|
-
for i in $(seq 1 ${
|
|
172
|
-
if [ "$(${
|
|
173
|
-
sleep ${
|
|
102
|
+
for i in $(seq 1 ${pi}); do
|
|
103
|
+
if [ "$(${ue(M)} view "bostrat-node@$TO" version --prefer-online 2>/dev/null)" = "$TO" ]; then return 0; fi
|
|
104
|
+
sleep ${fi}
|
|
174
105
|
done
|
|
175
106
|
return 1
|
|
176
|
-
}`;return
|
|
107
|
+
}`;return _+A+L+E+`
|
|
177
108
|
${g("updating",'"" ')}
|
|
178
109
|
if ! wait_for_registry; then
|
|
179
|
-
${g("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(
|
|
110
|
+
${g("failed",`"bostrat-node@$TO is not on the npm registry yet (waited ${Math.round(pi*fi/60)} min, attempt $ATTEMPTS of ${hi})" retryable`)}
|
|
180
111
|
exit 1
|
|
181
112
|
fi
|
|
182
113
|
if ! install_target; then
|
|
183
|
-
${g("failed",`"npm install failed (${
|
|
114
|
+
${g("failed",`"npm install failed (${Zr} attempts)"`)}
|
|
184
115
|
exit 1
|
|
185
116
|
fi
|
|
186
117
|
${g("restarting")}
|
|
187
|
-
if ! ${
|
|
188
|
-
${g("failed",`"restart failed (${
|
|
118
|
+
if ! ${S}; then
|
|
119
|
+
${g("failed",`"restart failed (${S.replace(/"/g,"")})"`)}
|
|
189
120
|
exit 1
|
|
190
121
|
fi
|
|
191
122
|
if health; then
|
|
@@ -194,53 +125,148 @@ if health; then
|
|
|
194
125
|
fi
|
|
195
126
|
# \u2500\u2500 rollback: the same primitive with the previous version \u2500\u2500
|
|
196
127
|
${g("rolling-back",'"agent did not answer on :'+s+' after the update"')}
|
|
197
|
-
if [ -n "$FROM" ] && ${
|
|
128
|
+
if [ -n "$FROM" ] && ${I("$FROM")} && ${S} && health; then
|
|
198
129
|
${g("rolled-back",'"agent did not answer on :'+s+' after the update; rolled back"')}
|
|
199
130
|
exit 1
|
|
200
131
|
fi
|
|
201
132
|
${g("failed",'"agent did not answer after the update AND the rollback"')}
|
|
202
133
|
exit 1
|
|
203
|
-
`}let
|
|
204
|
-
LIVE=${
|
|
134
|
+
`}let R=M=>`( cd ${ue(u)} && git fetch -q origin main --tags && git show origin/main:scripts/deploy-pi.sh > "$TMP_SCRIPT" && bash "$TMP_SCRIPT" "v${M}" )`;return _+`
|
|
135
|
+
LIVE=${ue(u)}
|
|
205
136
|
TMP_SCRIPT="$(mktemp)"
|
|
206
137
|
trap 'rm -f "$TMP_SCRIPT"' EXIT
|
|
207
138
|
# "restarting" is written BEFORE deploy-pi.sh runs (it does fetch \u2192 build \u2192
|
|
208
139
|
# restart \u2192 health in one call): the agent it restarts settles "done" on boot,
|
|
209
140
|
# and nothing here may write after that boot or the settle would repeat.
|
|
210
141
|
${g("restarting")}
|
|
211
|
-
if ${
|
|
142
|
+
if ${R("$TO")}; then
|
|
212
143
|
exit 0
|
|
213
144
|
fi
|
|
214
145
|
${g("rolling-back",'"deploy-pi.sh v$TO failed"')}
|
|
215
|
-
if [ -n "$FROM" ] && ${
|
|
146
|
+
if [ -n "$FROM" ] && ${R("$FROM")}; then
|
|
216
147
|
${g("rolled-back",'"deploy-pi.sh v$TO failed; rolled back to v$FROM"')}
|
|
217
148
|
exit 1
|
|
218
149
|
fi
|
|
219
150
|
${g("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
|
|
220
151
|
exit 1
|
|
221
|
-
`}async function Cr(e=gn){try{return JSON.parse(await be.readFile(e,"utf8"))}catch{return null}}async function Ji({to:e,from:t=hn,kind:n=Qe(),reason:r="manual",force:o=!1,statusFile:s=gn,spawnImpl:a=Mu,now:l=Date.now,npmPrefix:h=void 0,log:m=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!wn.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!Ze(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let d=await Cr(s);if(Br(d))return{ok:!1,reason:`an update to ${d.to} is already in flight`,status:d};let S=d?.to===e?Number(d.attempts)||1:0;if(!o&&d&&d.to===e&&(d.status==="failed"||d.status==="rolled-back")&&!(d.status==="failed"&&d.retryable===!0&&S<Mr))return{ok:!1,reason:`update to ${e} already ${d.status} (${d.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:d};let y=d?.to===e&&(d.status==="failed"||d.status==="rolled-back")?S+1:1;await be.mkdir(U.dirname(s),{recursive:!0});let g=h!==void 0?h:n==="npm-global"?er(await Uu())||U.resolve(U.dirname(process.execPath),".."):null,b=Pr(),M=Xi({kind:n,to:e,from:t,statusFile:s,npmPrefix:g,startedAt:l(),attempts:y,restart:b}),T=U.join(U.dirname(s),`update-${e}.sh`),N=U.join(U.dirname(s),"last.log");await be.writeFile(T,M,{mode:448}),await be.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:y,startedAt:l(),updatedAt:l()}));let E=Rt.existsSync("/run/systemd/system")&&await Hu("systemd-run"),A=E?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",T]]:["bash",[T]],O=async x=>{let C=`could not spawn updater: ${x?.message||x}`;return await be.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,attempts:y,startedAt:l(),updatedAt:l(),error:C})).catch(()=>{}),m.error?.(`[self-update] ${C}`),C},k=null;try{E||(k=Rt.openSync(N,"a"));let x=a(A[0],A[1],{detached:!0,stdio:E?"ignore":["ignore",k,k]});x.on?.("error",C=>{O(C)}),x.unref?.()}catch(x){return{ok:!1,reason:await O(x)}}finally{k!==null&&Rt.closeSync(k)}return m.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}, restart via ${b.mode}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:T,statusFile:s}}async function Uu(){try{return await be.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Hu(e){for(let t of String(process.env.PATH||"").split(U.delimiter))try{return await be.access(U.join(t,e),Rt.constants.X_OK),!0}catch{}return!1}async function Ku({statusFile:e=gn,current:t=hn,now:n=Date.now,staleMs:r=Wu}={}){let o=await Cr(e);if(!o)return null;let s=a=>be.writeFile(e,JSON.stringify(a)).catch(()=>{});if(Br(o)){if(t&&o.to===t){let a={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await s(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 s(a),a}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let a={...o,announced:!0};return await s(a),a}return null}function Gu({isBusy:e,start:t=Ji,onStuck:n=null,onStarted:r=null,tickMs:o=Du,stuckMs:s=Bu,now:a=Date.now,setIntervalImpl:l=setInterval,clearIntervalImpl:h=clearInterval,log:m=console}={}){let d=null,S=()=>{d?.timer&&h(d.timer),d=null},y=async()=>{if(!d)return;let g=!0;try{g=await e()!==!1}catch{g=!0}if(g){if(!d.stuckFired&&a()-d.since>=s){d.stuckFired=!0;try{await n?.({to:d.to,from:d.from,since:d.since})}catch{}}return}let b=d;S();let M=await t({to:b.to,from:b.from,kind:b.kind,reason:"auto"});m.log?.(`[self-update] stasis reached \u2192 ${M.ok?"started":`not started: ${M.reason}`}`);try{await r?.({...b,result:M})}catch{}};return{arm({to:g,from:b=hn,kind:M=Qe()}){return d?.to===g?!1:(S(),d={to:g,from:b,kind:M,since:a(),stuckFired:!1,timer:l(y,o)},d.timer.unref?.(),!0)},tick:y,cancel:S,get armed(){return d?{to:d.to,from:d.from,kind:d.kind,since:d.since}:null}}}var hn,Cu,mn,gn,Bu,Du,Rr,Nr,Mr,fn,zi,Vi,qi,wn,Q,Fu,Br,Wu,Qi=R(()=>{Or();Gi();hn=(()=>{try{return Pu(import.meta.url)("../package.json").version||null}catch{return null}})(),Cu=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||Nu.tmpdir(),".bostrat"),mn=U.join(Cu,"self-update"),gn=U.join(mn,"status.json"),Bu=1440*6e4,Du=6e4,Rr=60,Nr=15,Mr=3,fn=6,zi=20,Vi=U.join(mn,"supervisor.pid"),qi="SIGUSR2",wn=new Set(["npm-global","git-checkout"]);Q=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Fu=new Set(["updating","restarting","rolling-back"]),Br=e=>!!(e&&Fu.has(e.status));Wu=45*6e4});Gt();Qn();lr();import z from"node:fs";import L from"node:path";import tt from"node:os";import{createRequire as Dr}from"node:module";import{execFile as zu,spawn as Vu}from"node:child_process";import{promisify as qu}from"node:util";import Yu from"node:readline/promises";import{randomUUID as Xu}from"node:crypto";import{fileURLToPath as Ju}from"node:url";import an from"node:fs";import ze from"node:fs/promises";import ll from"node:os";import At from"node:path";import ul from"node:readline";import{spawn as dl}from"node:child_process";var pl="^(ugrep|rg|2\\.1\\.[0-9]+|cursor-agent|codex|npm|node|MainThread)",fl="^(bostrat-|tmux|earlyoom|systemd|sshd)",hl=()=>["-m","10","-s","70","-r","600","--prefer",pl,"--avoid",fl],bs="BOSTRAT_OOM_GUARD_OWNER",ml=6e4,gl=5e3;function Ss(e=process.env){return!["0","off","false","no"].includes(String(e.BOSTRAT_OOM_GUARD??"").trim().toLowerCase())}function _s(e=process.env){let t=e.BOSTRAT_STATE_DIR||At.join(e.HOME||ll.tmpdir(),".bostrat");return At.join(t,"oom-guard.pid")}function Ts(e=process.env){if(e.BOSTRAT_EARLYOOM_BIN)return an.existsSync(e.BOSTRAT_EARLYOOM_BIN)?e.BOSTRAT_EARLYOOM_BIN:null;let t=[...String(e.PATH||"").split(":").filter(Boolean),"/usr/bin","/usr/sbin","/usr/local/bin","/bin"];for(let n of t){let r=At.join(n,"earlyoom");if(an.existsSync(r))return r}return null}async function xs({procRoot:e="/proc"}={}){let t=[];try{t=await ze.readdir(e)}catch{return[]}let n=[];for(let r of t){if(!/^\d+$/.test(r))continue;(await ze.readFile(At.join(e,r,"comm"),"utf8").catch(()=>"")).trim()==="earlyoom"&&n.push({pid:Number(r)})}return n}async function $s(e){let t=Number((await ze.readFile(e,"utf8").catch(()=>"")).trim());return Number.isInteger(t)&&t>0?t:null}async function As({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc"}={}){if(!Ss(e))return{state:"off"};if(t!=="linux")return{state:"unsupported",platform:t};let r=await xs({procRoot:n}),o=await $s(_s(e)),s=r.find(l=>l.pid===o);if(s)return{state:"own",pid:s.pid};if(r.length)return{state:"host",pid:r[0].pid};let a=Ts(e);return a?{state:"stopped",bin:a}:{state:"absent"}}function pr(e){switch(e?.state){case"own":return`earlyoom running under the node (pid ${e.pid}; acts at 10% memory available and 70% swap free)`;case"host":return`the host's own earlyoom is running (pid ${e.pid}) \u2014 the node starts none beside it`;case"stopped":return`earlyoom is installed (${e.bin}) and not running \u2014 the node starts it at boot`;case"absent":return"none \u2014 earlyoom is not installed, so memory exhaustion is left to the kernel's OOM killer";case"off":return"disabled (BOSTRAT_OOM_GUARD=0)";case"unsupported":return`not available on ${e.platform}`;default:return"not checked yet"}}function vs({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc",log:r=console.log,spawnImpl:o=dl,checkMs:s=ml,relaunchMs:a=gl}={}){let l=null,h={state:null},m=null,d=!1,S="",y=_s(e),g=E=>{h=E;let A=`[oom-guard] ${pr(E)}`;return A!==S&&r(A),S=A,E},b=E=>{d||(clearTimeout(m),m=setTimeout(()=>M().catch(()=>{}),E),m.unref?.())},M=async()=>{if(d||l)return h;if(!Ss(e))return g({state:"off"});if(t!=="linux")return g({state:"unsupported",platform:t});let E=await $s(y),A=await xs({procRoot:n});if(E&&A.some(x=>x.pid===E)){try{process.kill(E,"SIGTERM")}catch{}A=A.filter(x=>x.pid!==E)}if(A.length)return b(s),g({state:"host",pid:A[0].pid});let O=Ts(e);if(!O)return b(s),g({state:"absent"});let k;try{k=o(O,hl(),{stdio:["ignore","pipe","pipe"]})}catch(x){return r(`[oom-guard] could not start ${O}: ${x?.message||x}`),b(s),h}l=k;for(let x of[k.stdout,k.stderr])x&&ul.createInterface({input:x}).on("line",C=>r(`[earlyoom] ${C}`));return k.on("error",x=>{r(`[oom-guard] ${O}: ${x?.message||x}`),!(l!==k||k.pid)&&(l=null,b(s))}),k.on("exit",(x,C)=>{l===k&&(l=null,ze.rm(y,{force:!0}).catch(()=>{}),!d&&(r(`[oom-guard] earlyoom exited (${C||`code ${x}`}) \u2014 relaunching in ${Math.round(a/1e3)} s`),h={state:"stopped",bin:O},S="",b(a)))}),k.pid&&(await ze.mkdir(At.dirname(y),{recursive:!0}).catch(()=>{}),await ze.writeFile(y,`${k.pid}
|
|
222
|
-
`).catch(()=>{})),b(s),g({state:"own",pid:k.pid})},T=()=>{l&&(l.kill("SIGTERM"),an.rmSync(y,{force:!0}))};return process.on("exit",T),{ready:M().catch(()=>h),status:()=>h,stop(){d=!0,clearTimeout(m),process.off("exit",T);let E=l;l=null,E&&(E.kill("SIGTERM"),an.rmSync(y,{force:!0}))}}}Un();Gt();import wl from"node:fs";import ks from"node:path";import yl from"node:os";var bl=()=>process.env.BOSTRAT_STATE_DIR||ks.join(process.env.HOME||yl.tmpdir(),".bostrat"),Sl=()=>ks.join(bl(),"plane-link","public-host.json");var vt=null;function _l(){if(vt)return vt;try{let e=JSON.parse(wl.readFileSync(Sl(),"utf8"));vt={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{vt={viewBase:null}}return vt}function Tl(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),o=(r?r[2]:n).replace(/\/.*$/,"").toLowerCase(),s=/:(\d+)$/.exec(o)?.[1]??null,a=o.replace(/:\d+$/,"");return a?a==="localhost"?{proto:r?r[1].toLowerCase():"http",host:a,...s?{port:Number(s)}:{}}:{proto:r?r[1].toLowerCase():t,host:a}:null}var Es=e=>e?`${e.host}${e.port?`:${e.port}`:""}`:null;function Os(e=process.env){return lo(e)?null:_l().viewBase}function Rs(e=process.env.BOSTRAT_PUBLIC_HOST){return Tl(e,"https")}function Ns(e=process.env.BOSTRAT_PLANE_URL){let t=String(e||"").trim();if(!t)return null;let n=/^(wss?|https?):\/\/([^/?#]+)/i.exec(t);return n?`${/^(wss|https)$/i.test(n[1])?"https":"http"}://${n[2]}`:null}wt();import xl from"node:fs";import $l from"node:os";import Ms from"node:path";var Is=3*6e4;function fr(e=process.env){let t=e.BOSTRAT_STATE_DIR||Ms.join(e.HOME||$l.tmpdir(),".bostrat");return Ms.join(t,"heartbeat.json")}function Ps(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return Is;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):Is}function Cs(e=fr()){try{let t=JSON.parse(xl.readFileSync(e,"utf8"));if(!t||typeof t!="object")return null;let n=Number(t.ts),r=Number(t.pid);if(!Number.isFinite(n)||!Number.isFinite(r))return null;let o=Number(t.loopLagMs);return{pid:r,ts:n,loopLagMs:Number.isFinite(o)?o:null}}catch{return null}}wt();var Ds="BOSTRAT_RESTART_NOTICE",$m=2*6e4;var Bs=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function js({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:Bs(e),staleS:Bs(t)!=null?Math.round(t/1e3):null})}Ee();ar();var ea=(e,t)=>{let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let o=0;o<Math.max(n.length,r.length);o++){let s=(n[o]||0)-(r[o]||0);if(s)return s<0}return!1},Se=qu(zu),jr=L.dirname(Ju(import.meta.url)),Me=L.resolve(jr,".."),Zu=L.join(jr,"index.js"),Qu="wss://plane.bostrat.ai/v1/node",et=Dr(import.meta.url)("../package.json").version,I=(e,t)=>({name:e,level:"pass",detail:t}),H=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),V=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function ed(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?I("node runtime",`${process.version} at ${process.execPath}`):V("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function td(e){return e.BOSTRAT_OWNER?H("owner stamp",`BOSTRAT_OWNER=${String(e.BOSTRAT_OWNER).slice(0,12)}\u2026 is set \u2014 ignored by this release; on older releases it got every event refused (forgedUserId)`,"remove BOSTRAT_OWNER from node.env and any shell rc, then restart the node"):I("owner stamp","none (the plane infers the owner from the token)")}function nd(e){let t;try{t=z.statSync(e)}catch{return H("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?H("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):I("node.env",`${e} (0600)`)}async function rd(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await Se(t,["-V"],{timeout:5e3});return I("tmux",`${t} (${n.trim()})`)}catch{return V("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function ta(e,{required:t=!1}={}){if(await dr(e,{loginShell:!0,failOpen:!1}))return I(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=sn[e]?`${sn[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?V(e,r,o):H(e,r,o)}async function od(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await Se(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return I("gh (GitHub CLI)",n)}catch{return H("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",sn.gh)}}async function sd(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>ta(t)));return e.some(t=>t.level==="pass")||e.push(V("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 id(){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 dr(t,{failOpen:!1})?I(t,"resolves on the service PATH"):H(t,`not on the service PATH \u2014 ${n}`,r)))}async function ad(){try{let t=Dr(L.join(Me,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let o=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),s=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(s),n()})}),I("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${Me} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Dr(L.join(Me,"package.json")),r=L.join(L.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");z.existsSync(r)&&!(z.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return V("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function cd(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(z.existsSync(t))return I("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"?V:H)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function ld(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?V("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"):I("claude lane",t?"BYO API key (injected per new box)":"box-local login (subscription \u2014 you type `claude login` inside the box)")}async function ud(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return H("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=pt(e.BOSTRAT_PLANE_URL);return await new Promise(s=>{let a=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),l=null,h=null,m=S=>{clearTimeout(d);try{a.close()}catch{}s({...S,...l?{viewBase:l}:{},...h?{planeMode:h}:{}})},d=setTimeout(()=>m(V("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-${Xu().slice(0,8)}`,ephemeral:!0}))),a.on("message",S=>{try{let y=JSON.parse(S);y.type==="hello_ok"?(typeof y.viewBase=="string"&&y.viewBase&&(l=y.viewBase),h=y.mode==="local"?"local":"default",y.minNodeVersion&&ea(et,y.minNodeVersion)?m(V("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${y.minNodeVersion} \u2014 this node is ${et}; the real link is refused until it updates`,`bostrat-node self-update --to ${y.latestNodeVersion||y.minNodeVersion}`)):y.latestNodeVersion&&ea(et,y.latestNodeVersion)?m(H("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${y.latestNodeVersion} is available (this node: ${et})`,`bostrat-node self-update --to ${y.latestNodeVersion}`)):m(I("plane link",`hello_ok in ${Date.now()-r}ms (${o})`))):y.type==="error"&&m(V("plane link",`plane said: ${y.code} ${y.message||""}`,"check the token"))}catch{}}),a.on("error",S=>m(V("plane link",`${S?.message||S}`,"check the URL, the token, and the plane's IP gate")))})}function dd(e,t=null){let n=Wt(e),r=t?.planeMode??null;return!n&&r!=="local"?null:r===null?I("mode","local (BOSTRAT_LOCAL_MODE; no plane answered to confirm it)"):n&&r==="local"?I("mode","local (BOSTRAT_LOCAL_MODE and the plane's hello_ok agree)"):r==="local"?H("mode","local \u2014 the plane runs local mode but BOSTRAT_LOCAL_MODE is unset here; the node follows the plane","set BOSTRAT_LOCAL_MODE=1 in node.env so boot-time decisions agree with the plane"):H("mode","default \u2014 BOSTRAT_LOCAL_MODE is set here but the plane does not run local mode; the node follows the plane","unset BOSTRAT_LOCAL_MODE, or start the plane with PLANE_LOCAL_MODE=1")}function pd(e){let t=`nightly export: ${e.s3?.backup?"armed by BACKUP_S3_*":"off (BACKUP_S3_* unset)"}`,n=e.s3?.content==="CONTENT_S3"?"armed by CONTENT_S3_*":e.s3?.content==="BACKUP_S3"?"armed by BACKUP_S3_* (CONTENT_S3_* unset \u2014 the fallback)":null;return e.s3?.content==="file"?I("video blobs","ready \u2014 this plane runs without a database and keeps video on its own disk; no S3 block is involved"):e.state==="ready"?I("video blobs",`ready \u2014 ${n||"armed"}; ${t}`):e.state==="needs-s3"?I("video blobs",`off \u2014 no S3 block is armed for video (CONTENT_S3_* and BACKUP_S3_* unset on the plane); \`bostrat-mock add\` refuses mp4/webm, text and PNG mocks are unaffected; ${t}`):e.state==="unreachable"?H("video blobs",`unreachable \u2014 ${n||"an S3 block is armed"} but the bucket failed the plane's probe; video mocks are refused; ${t}`,"check the bucket name, region, endpoint and credentials on the plane (GET /plane/admin/health \u2192 videoBlobs.error); the plane probes again within the hour"):I("video blobs",`not probed yet \u2014 ${n||"an S3 block is armed"}; the plane answers once its first bucket probe lands; ${t}`)}async function fd(e,t){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN||t?.level==="fail")return null;let n=await ns({env:e});return n&&n.source==="plane"?pd(n):null}function hd(){let e;try{e=JSON.parse(z.readFileSync(L.join(Ht,"content-outbox.json"),"utf8"))}catch{return I("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 V("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?H("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"):I("content outbox",t?`${t} op(s) in flight`:"drained")}async function md(e){let t=await ps({env:e}),n=fs(t);return t.available?I("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?H("box caps",n,"boxes run under nice only on this node; if Fly's init mounts /sys/fs/cgroup read-only this is the expected state (blueprint BP-NG-I4)"):I("box caps",n)}async function gd(e){let t=await As({env:e}),n=pr(t);return t.state==="absent"?H("oom guard",n,"install earlyoom (apt install earlyoom) \u2014 the node starts it with its own tuning at the next boot"):I("oom guard",n)}async function wd(e){let t=await Lo({env:e}),n=Fo(t);return t.level==="misconfigured"?V("box containment",n,"fix the user (scripts/pi/box-user-setup.sh) or unset BOSTRAT_BOX_USER in node.env, then restart"):t.level==="root-capable"?H("box containment",n,"opt in to a dedicated box uid: BP-AU-I10 runbook (scripts/pi/box-user-setup.sh, then BOSTRAT_BOX_USER in node.env)"):t.level==="uid"&&(t.problems.length||t.auditd?.rule!==!0||!t.auditd?.readable)?H("box containment",n,"re-run scripts/pi/box-user-setup.sh (idempotent) \u2014 it installs the auditd rule, the log group and the mirror"):I("box containment",n)}function yd(e){let t=Fn(e),n=Ro(t);return t.unknown?.length?H("audit guard",n,`BOSTRAT_AUDIT_GUARD names unknown rule(s): ${t.unknown.join(", ")}`):I("audit guard",n)}function bd(e){if(e.BOSTRAT_STATE_REMOTE)return I("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`);let t=/^(on|1|true)$/i.test(String(e.BOSTRAT_STATE_SYNC||""));return I("state remote",t?"unset \u2014 local git mirror on (BOSTRAT_STATE_SYNC=on), nothing pushes":"unset \u2014 git export off; the plane holds node state (set BOSTRAT_STATE_REMOTE for an off-box copy)")}function Sd(e,t){let n=t?.planeMode?t.planeMode==="local":Wt(e),r=n?null:t?.viewBase??null,o=n?null:Os(e),s=Rs(e.BOSTRAT_PUBLIC_HOST),a=(()=>{let l=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(l)return`${l.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let h=Ns(e.BOSTRAT_PLANE_URL);return h?`${h}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(r){let l=s&&s.host!==r?`; BOSTRAT_PUBLIC_HOST=${s.host} is set but the plane's value wins`:"";return I("public host",`views https://<slug>.${r}/ (plane hello_ok)${l} \xB7 track links ${a}`)}return o?I("public host",`views https://<slug>.${o}/ (persisted from the last hello) \xB7 track links ${a}`):s?I("public host",`views ${s.proto}://<slug>.${Es(s)}/ (BOSTRAT_PUBLIC_HOST${n?", local mode: this machine only":""}) \xB7 track links ${a}`):n?V("public host",`none \u2014 \`bostrat-view up\` refuses on this node (local mode: views are served by the node itself, and BOSTRAT_PUBLIC_HOST is unset) \xB7 track links ${a}`,`set BOSTRAT_PUBLIC_HOST=${Cn(e)} in node.env (\`bostrat-node init --local\` writes it)`):V("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${a}`,"link a plane that sets PLANE_VIEW_BASE (bostrat-node init), or set BOSTRAT_PUBLIC_HOST in node.env for a plane-less node")}async function na(e,t={}){let n=[];n.push(await ed()),n.push(nd(t.envFile||Fe())),n.push(await rd(e)),n.push(await md(e)),n.push(await gd(e)),n.push(yd(e)),n.push(await wd(e)),n.push(...await sd()),n.push(await ta("git",{required:!0})),n.push(await od()),n.push(...await id()),n.push(await ad()),n.push(cd(e)),n.push(ld(e)),n.push(td(e));let r=await ud(e,t);n.push(r);let o=dd(e,r);o&&n.push(o),n.push(Sd(e,r));let s=await fd(e,r);return s&&n.push(s),n.push(hd()),n.push(bd(e)),n}function ra(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let s of e)t(`${n[s.level]} ${s.name}: ${s.detail}`),s.fix&&s.level!=="pass"&&t(` fix: ${s.fix}`);let r=e.filter(s=>s.level==="fail").length,o=e.filter(s=>s.level==="warn").length;return t(r?`
|
|
152
|
+
`}async function wi(e=to){try{return JSON.parse(await We.readFile(e,"utf8"))}catch{return null}}async function xu({to:e,from:t=Qr,kind:n=Gt(),reason:r="manual",force:o=!1,statusFile:s=to,spawnImpl:a=aw,now:i=Date.now,npmPrefix:c=void 0,log:l=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!no.has(n))return{ok:!1,reason:`install kind "${n}" updates elsewhere`};if(t&&!zt(t,e))return{ok:!1,reason:`already on ${t} (target ${e})`};let u=await wi(s);if(yi(u))return{ok:!1,reason:`an update to ${u.to} is already in flight`,status:u};let f=u?.to===e?Number(u.attempts)||1:0;if(!o&&u&&u.to===e&&(u.status==="failed"||u.status==="rolled-back")&&!(u.status==="failed"&&u.retryable===!0&&f<hi))return{ok:!1,reason:`update to ${e} already ${u.status} (${u.error||"no detail"}) \u2014 retried when a newer release exists, or tap Update now / Try again to retry it`,status:u};let p=u?.to===e&&(u.status==="failed"||u.status==="rolled-back")?f+1:1;await We.mkdir(G.dirname(s),{recursive:!0});let g=c!==void 0?c:n==="npm-global"?Kn(await mw())||G.resolve(G.dirname(process.execPath),".."):null,S=gi(),x=Tu({kind:n,to:e,from:t,statusFile:s,npmPrefix:g,startedAt:i(),attempts:p,restart:S}),_=G.join(G.dirname(s),`update-${e}.sh`),R=G.join(G.dirname(s),"last.log");await We.writeFile(_,x,{mode:448}),await We.writeFile(s,JSON.stringify({status:"updating",from:t,to:e,kind:n,reason:r,attempts:p,startedAt:i(),updatedAt:i()}));let M=Gn.existsSync("/run/systemd/system")&&await gw("systemd-run"),A=M?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",_]]:["bash",[_]],$=async E=>{let L=`could not spawn updater: ${E?.message||E}`;return await We.writeFile(s,JSON.stringify({status:"failed",from:t,to:e,kind:n,reason:r,attempts:p,startedAt:i(),updatedAt:i(),error:L})).catch(()=>{}),l.error?.(`[self-update] ${L}`),L},I=null;try{M||(I=Gn.openSync(R,"a"));let E=a(A[0],A[1],{detached:!0,stdio:M?"ignore":["ignore",I,I]});E.on?.("error",L=>{$(L)}),E.unref?.()}catch(E){return{ok:!1,reason:await $(E)}}finally{I!==null&&Gn.closeSync(I)}return l.log?.(`[self-update] ${t??"?"} \u2192 ${e} (${n}, ${r}, restart via ${S.mode}) started \u2014 status ${s}`),{ok:!0,to:e,from:t,kind:n,scriptFile:_,statusFile:s}}async function mw(){try{return await We.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function gw(e){for(let t of String(process.env.PATH||"").split(G.delimiter))try{return await We.access(G.join(t,e),Gn.constants.X_OK),!0}catch{}return!1}async function yw({statusFile:e=to,current:t=Qr,now:n=Date.now,staleMs:r=ww}={}){let o=await wi(e);if(!o)return null;let s=a=>We.writeFile(e,JSON.stringify(a)).catch(()=>{});if(yi(o)){if(t&&o.to===t){let a={...o,status:"done",updatedAt:n(),finishedAt:n(),announced:!0};return await s(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 s(a),a}return null}if(["failed","rolled-back","done"].includes(o.status)&&!o.announced){let a={...o,announced:!0};return await s(a),a}return null}function Sw({isBusy:e,allowed:t=()=>!0,start:n=xu,onStuck:r=null,onStarted:o=null,tickMs:s=pw,stuckMs:a=dw,now:i=Date.now,setIntervalImpl:c=setInterval,clearIntervalImpl:l=clearInterval,log:u=console}={}){let f=null,p=()=>{f?.timer&&l(f.timer),f=null},g=async()=>{if(!f)return;if(!t())return p();let S=!0;try{S=await e()!==!1}catch{S=!0}if(S){if(!f.stuckFired&&i()-f.since>=a){f.stuckFired=!0;try{await r?.({to:f.to,from:f.from,since:f.since})}catch{}}return}let x=f;p();let _=await n({to:x.to,from:x.from,kind:x.kind,reason:"auto"});u.log?.(`[self-update] stasis reached \u2192 ${_.ok?"started":`not started: ${_.reason}`}`);try{await o?.({...x,result:_})}catch{}};return{arm({to:S,from:x=Qr,kind:_=Gt()}){return!t()||f?.to===S?!1:(p(),f={to:S,from:x,kind:_,since:i(),stuckFired:!1,timer:c(g,s)},f.timer.unref?.(),!0)},tick:g,cancel:p,get armed(){return f?{to:f.to,from:f.from,kind:f.kind,since:f.since}:null}}}var Qr,uw,eo,to,dw,pw,pi,fi,hi,Zr,wu,yu,Su,no,ue,hw,yi,ww,bi=k(()=>{jr();gu();q();Qr=(()=>{try{return lw(import.meta.url)("../package.json").version||null}catch{return null}})(),uw=process.env.BOSTRAT_STATE_DIR||G.join(process.env.HOME||iw.tmpdir(),".bostrat"),eo=G.join(uw,"self-update"),to=G.join(eo,"status.json"),dw=1440*6e4,pw=6e4,pi=60,fi=15,hi=3,Zr=6,wu=20,yu=G.join(eo,"supervisor.pid"),Su="SIGUSR2",no=new Set(["npm-global","git-checkout"]);ue=e=>`'${String(e).replace(/'/g,"'\\''")}'`;hw=new Set(["updating","restarting","rolling-back"]),yi=e=>!!(e&&hw.has(e.status));ww=45*6e4;j("npm-self-update",({env:e,local:t})=>{let n=bu({env:e}),r=!t&&n==="auto";return{class:"registry",mode:r?"timer":"manual",host:Qt(e),armedBy:[r?`BOSTRAT_UPDATE_POLICY (${n})`:"bostrat-node self-update --to (by hand)"],purpose:"this node's own releases"}})});var Du={};Z(Du,{LINK_MARKER:()=>co,LOCKFILE:()=>$w,LOCKFILES:()=>Aw,MANIFEST:()=>ht,TOOLS:()=>ze,childEnv:()=>Cu,configureDepsStore:()=>cy,defaultCapBytes:()=>Eu,depsConfig:()=>de,detectTool:()=>Ru,dropScratch:()=>$i,ensurePrepared:()=>ny,failureReason:()=>Mu,holdScratch:()=>Ai,inspectPackage:()=>Lw,isPreparing:()=>Uw,keyFor:()=>Cw,laneBusy:()=>Ww,lastFailure:()=>Dw,linkPackage:()=>iy,linkState:()=>Bu,listStores:()=>Iu,markUsed:()=>ay,preparingKeys:()=>Hw,pruneStore:()=>Ii,relDirSlug:()=>Ou,resolveCapBytes:()=>vu,resolveTool:()=>Nu,runExclusive:()=>Kw,spawnBounded:()=>ju,stopPrepares:()=>ry,storeReady:()=>po,sweepStaging:()=>oy,tailLines:()=>ki});import O from"node:fs/promises";import $u from"node:os";import b from"node:path";import{createHash as bw,randomUUID as Ei}from"node:crypto";import{execFile as _w,spawn as Tw}from"node:child_process";import{promisify as xw}from"node:util";function de(e=process.env){return{enabled:String(e.BOSTRAT_DEPS||"").toLowerCase()!=="off",root:e.BOSTRAT_DEPS_DIR||b.join(Nw(e),"deps"),capBytes:String(e.BOSTRAT_DEPS_CAP_GB??"").trim()===""?null:Math.max(0,Yn(e.BOSTRAT_DEPS_CAP_GB,5))*vi,generations:Math.max(1,Math.floor(Yn(e.BOSTRAT_DEPS_GENERATIONS,2))),timeoutMs:Math.max(1e3,Yn(e.BOSTRAT_DEPS_TIMEOUT_MS,20*6e4)),setup:String(e.BOSTRAT_DEPS_SETUP||"").toLowerCase()!=="off",devcontainer:String(e.BOSTRAT_DEPS_DEVCONTAINER||"").toLowerCase()!=="off",setupTimeoutMs:Math.max(1e3,Yn(e.BOSTRAT_DEPS_SETUP_TIMEOUT_MS,15*6e4)),retryMs:Math.max(0,Yn(e.BOSTRAT_DEPS_RETRY_MS,30*6e4)),bins:{npm:e.BOSTRAT_DEPS_NPM||null,pnpm:e.BOSTRAT_DEPS_PNPM||null,yarn:e.BOSTRAT_DEPS_YARN||null}}}function Eu(e){return!Number.isFinite(e)||e<=0?_i:Math.min(_i,Math.floor(e*Iw))}async function vu(e=de(),{statfs:t=O.statfs}={}){if(e.capBytes!=null)return e.capBytes;let n=b.resolve(e.root);for(;;)try{let r=await t(n);return Eu(Number(r.bsize)*Number(r.blocks))}catch{let r=b.dirname(n);if(r===n)return _i;n=r}}function Cw({repoId:e,relDir:t,lockHash:n,nodeMajor:r=Mw},o=de()){let s=String(e).toLowerCase(),a=t||".",i=`${r}-${n}`,c=b.join(o.root,...s.split("/").map(Oi),Ou(a));return{repo:s,relDir:a,gen:i,key:`${s}:${a}:${i}`,group:c,dir:b.join(c,i)}}async function Ru(e,t=null){let n=[];for(let[c,l]of Object.entries(ze))(t?t.includes(l.lockfile):await O.lstat(b.join(e,l.lockfile)).catch(()=>null)!==null)&&n.push(c);if(!n.length)return null;let r=null;if(n.length>1){let c=await qn(b.join(e,ht)).then(l=>JSON.parse(l),()=>null).catch(()=>null);r=n.find(l=>String(c?.packageManager??"").startsWith(`${l}@`))??null}let o=r??n[0],s=ze[o];if(o!=="yarn")return{tool:o,lockfile:s.lockfile,command:s.command};let a=(await qn(b.join(e,s.lockfile))??"").slice(0,2e3),i=/^__metadata:/m.test(a);return{tool:o,lockfile:s.lockfile,flavor:i?"berry":"classic",command:i?s.berry.command:s.command}}async function jw(e,t,n){let r;try{r=JSON.parse(n)}catch{return te("unparseable manifest or lockfile")}return t.workspaces||r?.packages?.[""]?.workspaces?te("npm workspaces"):[...Object.values(r?.packages??{}),...Object.values(r?.dependencies??{})].some(a=>a&&(a.link===!0||/^file:/.test(String(a.resolved??""))||/^file:/.test(String(a.version??""))))?te(io):{configs:[{name:".npmrc",ephemeral:!0}]}}async function Pw(e,t,n){let r=await qn(b.join(e,"pnpm-workspace.yaml"));return t.workspaces||r!==null&&/^packages\s*:/m.test(r)?te("pnpm workspace"):/^\s+(?:specifier|version):\s*['"]?(?:link|file|workspace):/m.test(n)||/@(?:file|link):/.test(n)?te(io):{configs:[{name:".npmrc",ephemeral:!0},{name:"pnpm-workspace.yaml"},{name:".pnpmfile.cjs"}]}}async function Bw(e,t,n,r){if(t.workspaces)return te("yarn workspaces");if(r==="classic")return/@(?:file|link):/.test(n)||/^\s+resolved "file:/m.test(n)?te(io):{configs:[{name:".npmrc",ephemeral:!0},{name:".yarnrc",ephemeral:!0}]};let o=await qn(b.join(e,".yarnrc.yml"))??"";return/^nodeLinker:\s*["']?node-modules["']?\s*$/m.test(o)?/^(?:yarnPath|plugins)\s*:/m.test(o)?te("yarn is vendored in the repo (yarnPath / plugins)"):/@(?:portal|link|file):/.test(n)||/@workspace:(?!\.["',\s])/.test(n)?te(io):{configs:[{name:".yarnrc.yml",ephemeral:!0}]}:te("yarn Plug'n'Play (no node_modules to share)")}async function Lw(e,t=null){let n=await Ru(e,t);if(!n)return te("no lockfile");let r={tool:n.tool,command:n.command},o=await qn(b.join(e,ht));if(o===null)return te(`no ${ht}`,r);let s=await O.readFile(b.join(e,n.lockfile)).catch(()=>null);if(s===null)return te(`no ${n.lockfile}`,r);let a;try{a=JSON.parse(o)}catch{return te("unparseable manifest or lockfile",r)}if(!a||typeof a!="object"||Array.isArray(a))return te("unparseable manifest or lockfile",r);let i=s.toString("utf8"),c=n.tool==="npm"?await jw(e,a,i):n.tool==="pnpm"?await Pw(e,a,i):await Bw(e,a,i,n.flavor);if(c.storable===!1)return{...c,...r};let{scripts:l,...u}=a,f=[{name:n.lockfile,data:s}];for(let p of c.configs){let g=await O.readFile(b.join(e,p.name)).catch(()=>null);g!==null&&f.push({name:p.name,data:g,ephemeral:p.ephemeral===!0})}return{storable:!0,...r,lockHash:bw("sha256").update(s).digest("hex").slice(0,12),inputs:{tool:n.tool,flavor:n.flavor??null,command:n.command,manifest:JSON.stringify(u,null,2)+`
|
|
153
|
+
`,files:f}}}async function po(e){let t=await uo(b.join(e.dir,lo));return!t||t.relDir!==e.relDir||t.repo!==e.repo?null:await Ke(b.join(e.dir,"node_modules"))?t:null}async function Dw(e,t=de()){let n=await uo(Ti(e));return n?.at?{...n,fresh:Date.now()-n.at<t.retryMs}:null}async function Iu(e=de()){let t=[],n=async(r,o)=>{let s=await O.readdir(r,{withFileTypes:!0}).catch(()=>[]);for(let a of s){if(!a.isDirectory()||a.name.startsWith("."))continue;let i=b.join(r,a.name),c=await uo(b.join(i,lo));c?t.push({dir:i,group:r,meta:c,sizeBytes:c.sizeBytes||0,lastUsed:await Fw(i,c)}):o<6&&await n(i,o+1)}};return await n(e.root,0),t.sort((r,o)=>r.lastUsed-o.lastUsed)}function Kw(e){xi++;let t=ao.then(e);return ao=t.then(()=>{},()=>{}).finally(()=>{xi--}),t}async function zw(e,t){for(let n of(t||"").split(b.delimiter).filter(Boolean)){let r=b.join(n,e);if(await O.access(r,O.constants.X_OK).then(()=>!0,()=>!1))return r}return null}async function Nu(e,t=de(),{runtimeDir:n=b.dirname(process.execPath),pathEnv:r=process.env.PATH}={}){if(t.bins?.[e])return{bin:t.bins[e],pre:[]};if(await Ke(b.join(n,e)))return{bin:b.join(n,e),pre:[]};if(e!=="npm"&&await Ke(b.join(n,"corepack")))return{bin:b.join(n,"corepack"),pre:[e]};let o=await zw(e,r);return o?{bin:o,pre:[]}:e==="npm"?{bin:"npm",pre:[]}:null}function ki(e,t=vw){return Gw(String(e||"")).split(/\r?\n/).map(n=>n.trimEnd()).filter(n=>n.trim()).slice(-t)}function Mu(e,{code:t=null,signal:n=null,timedOut:r=!1,timeoutMs:o=0,command:s=ze.npm.command}={}){let a=s.split(" ").slice(0,2).join(" ");if(r)return`${a} timed out after ${Math.max(1,Math.round(o/6e4))} min`;let i=f=>f.length>so?`${f.slice(0,so-1)}\u2026`:f,c=e.find(f=>Yw.test(f));if(c)return i(c.trim());let l=e.map(f=>Vw.map(p=>p.exec(f.trim())?.[1]?.trim()).find(Boolean)).filter(Boolean),u=l.find(f=>!qw.test(f))??l.find(f=>/^code\b/.test(f));return u?i(`${a}: ${u}`):n?`${a} was killed (${n})`:`${a} exited with code ${t??"?"}`}function Cu(e=de(),t=process.env){let n={};for(let[r,o]of Object.entries(t))o==null||/^BOSTRAT_/i.test(r)||Xw.test(r)&&!Jw.has(r)||(n[r]=o);return n.PATH=[b.dirname(process.execPath),t.PATH||""].filter(Boolean).join(b.delimiter),n.TMPDIR=b.join(e.root,".tmp"),n}function ju(e,t,{cwd:n,env:r,timeoutMs:o,onChunk:s=null}){return new Promise(a=>{let i="",c=!1,l;try{l=Tw(e,t,{cwd:n,env:r,stdio:["ignore","pipe","pipe"],detached:!0})}catch(S){return a({code:null,signal:null,timedOut:c,out:String(S?.message||S)})}oo=l;try{$u.setPriority(l.pid,10)}catch{}let u=S=>{let x=S.toString("utf8");i=(i+x).slice(-Ew);try{s?.(x)}catch{}};l.stdout.on("data",u),l.stderr.on("data",u);let f=S=>{try{process.kill(-l.pid,S)}catch{try{l.kill(S)}catch{}}},p=setTimeout(()=>{c=!0,f("SIGTERM"),setTimeout(()=>f("SIGKILL"),Ow).unref()},o);p.unref();let g=(S,x,_="")=>{clearTimeout(p),oo===l&&(oo=null),a({code:S,signal:x,timedOut:c,out:i+_})};l.on("error",S=>g(null,null,`
|
|
154
|
+
${S?.message||S}`)),l.on("close",(S,x)=>g(S,x))})}function Zw(e){return{npm_config_cache:b.join(e,"npm"),npm_config_store_dir:b.join(e,"pnpm"),YARN_CACHE_FOLDER:b.join(e,"yarn"),YARN_ENABLE_GLOBAL_CACHE:"false"}}function Qw({bin:e,pre:t},n,r,o,s,a){let i={...Cu(o),...Zw(s),TMPDIR:a,COREPACK_ENABLE_DOWNLOAD_PROMPT:"0",YARN_ENABLE_TELEMETRY:"0",npm_config_audit:"false",npm_config_fund:"false",npm_config_progress:"false",npm_config_update_notifier:"false"};return ju(e,[...t,...n],{cwd:r,env:i,timeoutMs:o.timeoutMs})}async function ey(e){try{let{stdout:t}=await kw("du",["-sk",e],{timeout:6e4});return(parseInt(t,10)||0)*1024}catch{return 0}}async function Ai(e){return Ri.add(e),await O.mkdir(e,{recursive:!0}),e}async function $i(e){await O.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Ri.delete(e)}async function ku(e,t,n){let r=`${Oi(e.key)}-${process.pid}-${Ei().slice(0,8)}`,o=b.join(n.root,".staging",r),s=b.join(n.root,".tmp",`cache-${r}`),a=b.join(s,"tmp"),i=async(c,l=[])=>({status:"failed",reason:c,tail:l,lost:!(await Ke(b.join(o,ht))&&await Ke(a))});try{await Ai(o),await Ai(s),await O.mkdir(a,{recursive:!0}),await O.writeFile(b.join(o,ht),t.manifest);for(let g of t.files)await O.writeFile(b.join(o,g.name),g.data,g.ephemeral?{mode:384}:void 0);let c=t.tool??"npm",l=await Nu(c,n);if(!l)return await i(`${c} is not available on this node \u2014 run \`${t.command}\` in place once it is installed`);let u=t.flavor==="berry"?ze.yarn.berry.args:ze[c].args,f=await Qw(l,u,o,n,s,a);for(let g of t.files)g.ephemeral&&await O.rm(b.join(o,g.name),{force:!0}).catch(()=>{});if(f.code!==0||f.timedOut){let g=ki(f.out);return await i(Mu(g,{...f,timeoutMs:n.timeoutMs,command:t.command}),g)}if(!await Ke(b.join(o,ht)))return await i("the install's staging directory was removed while it ran",ki(f.out));await O.mkdir(b.join(o,"node_modules"),{recursive:!0});let p=await ey(o);await De(b.join(o,lo),{key:e.key,repo:e.repo,relDir:e.relDir,gen:e.gen,tool:c,node:process.version,preparedAt:Date.now(),sizeBytes:p}),await O.writeFile(b.join(o,en),""),await O.mkdir(e.group,{recursive:!0});try{await O.rename(o,e.dir)}catch{await po(e)||(await O.rm(e.dir,{recursive:!0,force:!0}),await O.rename(o,e.dir))}return{status:"ready",cached:!1,sizeBytes:p}}catch(c){return await i(`could not prepare the store: ${String(c?.message||c).slice(0,so-30)}`)}finally{await $i(o),await $i(s)}}async function ty(e,t,n){let r=Date.now(),o=async(l,u=[])=>(await O.mkdir(e.group,{recursive:!0}).catch(()=>{}),await De(Ti(e),{key:e.key,at:Date.now(),reason:l,tail:u}).catch(()=>{}),{status:"failed",reason:l,tail:u,durationMs:Date.now()-r}),s=await po(e);if(s)return{status:"ready",cached:!0,sizeBytes:s.sizeBytes||0,durationMs:0};let{totalBytes:a,capBytes:i}=await Ii({cfg:n});if(i&&a>=i)return o(`the dependency store is full (${(i/vi).toFixed(1)} GB cap, all of it in use) \u2014 install in place`);let c=await ku(e,t,n);return c.lost&&(console.warn(`[deps] ${e.key}: the install's staging or cache was removed under it (${c.reason}) \u2014 running it again`),c=await ku(e,t,n)),c.status==="failed"?o(c.reason,c.tail):(await O.rm(Ti(e),{force:!0}).catch(()=>{}),{status:"ready",cached:!1,sizeBytes:c.sizeBytes,durationMs:Date.now()-r})}function ny(e,t,{cfg:n=de()}={}){let r=tn.get(e.key);if(r)return r;let s=ao.then(()=>ty(e,t,n)).catch(a=>({status:"failed",reason:String(a?.message||a).slice(0,so),tail:[],durationMs:0})).then(async a=>(tn.delete(e.key),a.status==="ready"&&!a.cached&&await Ii({cfg:n,keep:[e.dir]}).catch(()=>{}),a));return ao=s.then(()=>{},()=>{}),tn.set(e.key,s),s}function ry(){let e=oo;if(e?.pid)try{process.kill(-e.pid,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}}async function oy(e=de()){for(let t of[".staging",".tmp",".trash"]){let n=b.join(e.root,t);for(let r of await O.readdir(n).catch(()=>[])){let o=b.join(n,r);Ri.has(o)||await O.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}}async function Bu(e){let t=b.join(e,"node_modules"),n=await uo(b.join(t,co));if(!n?.store||!n?.key)return null;let r=o=>({key:n.key,store:n.store,links:o});for(let o of await O.readdir(t,{withFileTypes:!0}).catch(()=>[]))if(!(o.name.startsWith(".")||o.isSymbolicLink())){if(!o.isDirectory()||!o.name.startsWith("@"))return r("replaced");for(let s of await O.readdir(b.join(t,o.name),{withFileTypes:!0}).catch(()=>[]))if(!s.isSymbolicLink())return r("replaced")}if(n.probe){let o=b.join(t,n.probe),s=await O.readlink(o).catch(()=>null),a=s===null?null:b.resolve(b.dirname(o),s);if(a===null||!Pu(b.join(n.store,"node_modules"),a))return r("replaced")}return r(await Ke(b.join(n.store,lo))?"intact":"dangling")}async function sy(e,t){let n=async r=>{for(let o of await O.readdir(r,{withFileTypes:!0}).catch(()=>[])){if(!o.isSymbolicLink())continue;let s=await O.readlink(b.join(r,o.name)).catch(()=>null);s&&Pu(t,b.resolve(r,s))&&await O.rm(b.join(r,o.name),{force:!0})}};for(let r of await O.readdir(e,{withFileTypes:!0}).catch(()=>[]))r.isDirectory()&&(r.name===".bin"||r.name.startsWith("@"))&&(await n(b.join(e,r.name)),await O.rmdir(b.join(e,r.name)).catch(()=>{}));await n(e),await O.rm(b.join(e,co),{force:!0}).catch(()=>{})}async function Au(e,t){let n=b.join(t.dir,"node_modules"),r=(s,a)=>O.symlink(s,a).catch(i=>{if(i?.code!=="EEXIST")throw i}),o=null;for(let s of await O.readdir(n,{withFileTypes:!0}))if(!(s.name.startsWith(".")&&s.name!==".bin")){if(s.isDirectory()&&(s.name===".bin"||s.name.startsWith("@"))){await O.mkdir(b.join(e,s.name),{recursive:!0});for(let a of await O.readdir(b.join(n,s.name)))await r(b.join(n,s.name,a),b.join(e,s.name,a)),!o&&s.name!==".bin"&&(o=b.join(s.name,a));continue}await r(b.join(n,s.name),b.join(e,s.name)),!o&&!s.name.startsWith(".")&&(o=s.name)}await O.writeFile(b.join(e,co),JSON.stringify({key:t.key,store:t.dir,probe:o,linkedAt:Date.now()},null,2)+`
|
|
155
|
+
`)}async function iy(e,t,n=de()){if(!await po(e))return{linked:!1,why:"store not ready"};let r=b.join(t,"node_modules"),o=await O.lstat(r).catch(()=>null);if(o){let a=o.isDirectory()?await Bu(t):null;return a?a.links==="replaced"?{linked:!1,why:"node_modules exists"}:a.links==="intact"&&a.key===e.key?(await ro(b.join(e.dir,en)),{linked:!0,already:!0}):(await sy(r,n.root),await Au(r,e),await ro(b.join(e.dir,en)),{linked:!0,relinked:!0}):{linked:!1,why:"node_modules exists"}}let s=`${r}.bostrat-${Ei().slice(0,8)}`;try{await O.mkdir(s),await Au(s,e),await O.rename(s,r)}catch(a){return await O.rm(s,{recursive:!0,force:!0}).catch(()=>{}),await Ke(r)?{linked:!1,why:"node_modules exists"}:{linked:!1,why:String(a?.message||a)}}return await ro(b.join(e.dir,en)),{linked:!0}}function cy({referenced:e}={}){typeof e=="function"&&(Lu=e)}async function ly(e,t){let n=b.join(t.root,".trash",`${b.basename(e)}-${Ei().slice(0,8)}`);await O.mkdir(b.dirname(n),{recursive:!0}),await O.rename(e,n),await O.rm(n,{recursive:!0,force:!0}).catch(()=>{})}async function Ii({cfg:e=de(),keep:t=[]}={}){let n=new Set([...await Lu().catch(()=>[]),...t].map(l=>b.resolve(l))),r=await Iu(e);for(let l of r)Date.now()-(l.meta.preparedAt||0)<Rw&&n.add(b.resolve(l.dir));let o=[],s=async l=>{try{await ly(l.dir,e),o.push(l.dir),l.gone=!0}catch{}},a=new Map;for(let l of r)a.set(l.group,[...a.get(l.group)??[],l]);for(let l of a.values())for(let u of l){if(l.filter(p=>!p.gone).length<=e.generations)break;n.has(b.resolve(u.dir))||await s(u)}let i=()=>r.filter(l=>!l.gone).reduce((l,u)=>l+u.sizeBytes,0),c=await vu(e);if(c)for(let l of r){if(i()<=c)break;!l.gone&&!n.has(b.resolve(l.dir))&&await s(l)}return{removed:o,totalBytes:i(),capBytes:c,count:r.filter(l=>!l.gone).length}}var kw,ze,Aw,$w,ht,co,lo,en,vi,Ew,vw,so,Ow,Rw,_i,Iw,Nw,Yn,Mw,Oi,Ou,qn,te,io,uo,Ke,Ti,ro,Fw,tn,ao,oo,xi,Uw,Hw,Ww,Gw,Yw,qw,Vw,Jw,Xw,Ri,Pu,ay,Lu,Fu=k(()=>{ot();q();kw=xw(_w),ze=Object.freeze({npm:{lockfile:"package-lock.json",command:"npm ci",args:["ci"]},pnpm:{lockfile:"pnpm-lock.yaml",command:"pnpm install --frozen-lockfile",args:["install","--frozen-lockfile","--package-import-method=copy"]},yarn:{lockfile:"yarn.lock",command:"yarn install --frozen-lockfile",args:["install","--frozen-lockfile","--non-interactive"],berry:{command:"yarn install --immutable",args:["install","--immutable"]}}}),Aw=Object.freeze(Object.values(ze).map(e=>e.lockfile)),$w=ze.npm.lockfile,ht="package.json",co=".bostrat-deps.json",lo="meta.json",en=".last-used",vi=1024**3,Ew=16*1024,vw=30,so=160,Ow=5e3,Rw=10*6e4,_i=5*vi,Iw=.25,Nw=e=>e.BOSTRAT_STATE_DIR||b.join(e.HOME||$u.tmpdir(),".bostrat"),Yn=(e,t)=>Number.isFinite(Number(e))&&String(e??"").trim()!==""?Number(e):t;Mw=process.versions.node.split(".")[0],Oi=e=>{let t=String(e).replace(/[^A-Za-z0-9._-]/g,"_");return!t||t.startsWith(".")?`_${t}`:t},Ou=e=>e==="."||!e?"_root":e.split("/").map(Oi).join("__");qn=e=>O.readFile(e,"utf8").catch(()=>null);te=(e,t={})=>({storable:!1,why:e,...t}),io="local file: dependency";uo=e=>O.readFile(e,"utf8").then(JSON.parse,()=>null),Ke=e=>O.lstat(e).then(()=>!0,()=>!1);Ti=e=>`${e.dir}.failed.json`;ro=e=>{let t=new Date;return O.utimes(e,t,t).catch(()=>O.writeFile(e,"").catch(()=>{}))},Fw=async(e,t)=>(await O.stat(b.join(e,en)).catch(()=>null))?.mtimeMs??t?.preparedAt??0;tn=new Map,ao=Promise.resolve(),oo=null,xi=0,Uw=e=>tn.has(e),Hw=()=>[...tn.keys()],Ww=()=>tn.size>0||xi>0;Gw=e=>e.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g,"");Yw=/gyp ERR! find Python|not found: make|make: .*not found|g\+\+: .*not found|g\+\+: not found|ENOSPC|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|EINTEGRITY|in sync|E40[134]|ERR_PNPM_\w+|lockfile needs to be updated|YN0028/,qw=/^(code|errno|syscall|path|dest|command|cwd|node|A complete log of this run)\b/,Vw=[/^npm (?:error|ERR!)\s+(.*)$/,/^error\s+(.*)$/i,/^➤ YN(?!0000)\d{4}: [│┌└ ]*(.*)$/];Jw=new Set(["NPM_TOKEN","NODE_AUTH_TOKEN"]),Xw=/(TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|API_?KEY|PRIVATE_?KEY)$/i;Ri=new Set;Pu=(e,t)=>t===e||t.startsWith(e+b.sep);ay=e=>ro(b.join(e,en)),Lu=async()=>[];j("npm-workspace-deps",({env:e})=>de(e).enabled?{class:"registry",mode:"request",host:Qt(e),armedBy:['BOSTRAT_DEPS (on unless "off")'],purpose:"workspace dependencies, installed when a Track opens on a lockfile the store has no tree for"}:null)});import uy from"node:fs/promises";import Uu from"node:path";import dy from"node:os";async function mt(){try{return JSON.parse(await uy.readFile(py(),"utf8"))||{}}catch{return{}}}function Hu(e){let t=e.linear||{},n=t.transitions===!0?"auto":"prompt",r={};for(let o of fy){let s=gy(o),a=s.includes(n)?n:"prompt",i=e.ticketFlow?.[o]??t.ticketFlow?.[o];r[o]=s.includes(i)?i:a}return r}async function Wu(){let e=await mt(),t=process.env.BOSTRAT_LINEAR_API_KEY||e.linear?.apiKey,n=process.env.BOSTRAT_LINEAR_DEFAULT_TEAM||e.linear?.defaultTeam||null;return t?{apiKey:t,ticketFlow:Hu(e),defaultTeam:n}:null}async function Ku(){let e=await mt(),t=e.jira||{},n=process.env.BOSTRAT_JIRA_BASE_URL||t.baseUrl,r=process.env.BOSTRAT_JIRA_EMAIL||t.email,o=process.env.BOSTRAT_JIRA_API_TOKEN||t.apiToken;return!n||!r||!o?null:{baseUrl:String(n).replace(/\/$/,""),email:r,apiToken:o,tokenExpiresAt:t.tokenExpiresAt??null,ticketFlow:Hu(e)}}async function fo(){let e=(await mt()).deepgram||{},t=process.env.DEEPGRAM_API_KEY||e.apiKey;return t?{apiKey:t}:null}async function wy(){let e=(await mt()).openai||{},t=process.env.BOSTRAT_OPENAI_API_KEY||e.apiKey;return t?{apiKey:t}:null}async function Vn(){let t=(await mt()).voiceChat||{},n=t.provider||"openai",r=yy[n];if(!r)return null;let o=n==="openai"?await wy():null;return o?{provider:n,model:t.model||r.model,voice:t.voice||r.voice,apiKey:o.apiKey}:null}async function Ni(){if(le())return null;let e=(await mt()).cedar||{},t=process.env.BOSTRAT_CEDAR_INGEST_KEY||e.ingestKey,n=process.env.BOSTRAT_CEDAR_URL||e.url||"https://cedar-api.fly.dev";return t?{url:n,ingestKey:t}:null}async function zu(){let e=(await mt()).slack||{},t=process.env.BOSTRAT_SLACK_BOT_TOKEN||e.botToken,n=process.env.BOSTRAT_SLACK_APP_TOKEN||e.appToken;return!t||!n?null:{botToken:t,appToken:n,channel:process.env.BOSTRAT_SLACK_CHANNEL||e.channel||null,maxConcurrent:Number.isInteger(e.maxConcurrent)&&e.maxConcurrent>0?e.maxConcurrent:2}}var py,fy,hy,my,gy,yy,gt=k(()=>{ot();Ue();py=()=>Uu.join(process.env.BOSTRAT_STATE_DIR||Uu.join(process.env.HOME||dy.tmpdir(),".bostrat"),"integrations.json");fy=["linked","prOpened","prMerged","create"],hy=["prompt","auto","off"],my={create:["prompt","off"]},gy=e=>my[e]??hy;yy={openai:{model:"gpt-realtime-2.1-mini",voice:"marin"}}});import Gu from"node:fs/promises";import ho from"node:path";import{execFile as Sy}from"node:child_process";import{promisify as by}from"node:util";import{fileURLToPath as _y}from"node:url";function $y(e){let t=[],n=0,r=0;for(let o of e){let s=Ay.get(o);if(s===void 0)return t;n+=(s&31)<<r,s&32?r+=5:(t.push(n&1?-(n>>>1):n>>>1),n=0,r=0)}return t}function Ey(e){let t=[],n=0,r=0,o=0;for(let s of e.split(";")){let a=[],i=0;if(s)for(let c of s.split(",")){let l=$y(c);l.length!==0&&(i+=l[0],l.length>=4&&(n+=l[1],r+=l[2],o+=l[3],a.push([i,n,r,o])))}t.push(a)}return t}function vy(e,t){if(!e||e.length===0||e[0][0]>t)return null;let n=0,r=e.length-1;for(;n<r;){let o=n+r+1>>1;e[o][0]<=t?n=o:r=o-1}return e[n]}async function Oy(e){let t;try{t=await Gu.stat(e)}catch{return null}let n=Yu.get(e);if(n&&n.mtimeMs===t.mtimeMs)return n;try{let r=JSON.parse(await Gu.readFile(e,"utf8")),o={mtimeMs:t.mtimeMs,sources:r.sources||[],lines:Ey(r.mappings||"")};return Yu.set(e,o),o}catch{return null}}function Ry(){return Mi||(Mi=process.env.BOSTRAT_RELEASE?Promise.resolve(process.env.BOSTRAT_RELEASE):Ty("git",["rev-parse","--short","HEAD"],{cwd:ho.resolve(qu,"..","..")}).then(e=>e.stdout.trim()).catch(()=>null)),Mi}async function Ny(e,{distDir:t=xy}={}){let n=[],r=0,o=!1;for(let s of e.matchAll(Iy)){let[a,i,c,l]=s,u=await Oy(ho.join(t,"assets",`${i}.map`)),f=u?vy(u.lines[Number(c)-1],Number(l)-1):null;if(n.push(e.slice(r,s.index)),f&&u.sources[f[1]]){let p=u.sources[f[1]].replace(/^(\.\.\/)+/,"");n.push(`${p}:${f[2]+1}:${f[3]+1}`),o=!0}else n.push(a);r=s.index+a.length}return n.push(e.slice(r)),{stack:n.join(""),symbolicated:o}}async function Vu(e,t={}){try{if(!e?.error?.stack||!e.release||e.release==="unknown")return e;let n=t.release??await Ry();if(!n||e.release!==n)return e;let{stack:r,symbolicated:o}=await Ny(e.error.stack,t);o&&(e.error.stack=r,e.error.symbolicated=!0)}catch{}return e}var Ty,qu,xy,ky,Ay,Yu,Mi,Iy,Ju=k(()=>{Ty=by(Sy),qu=ho.dirname(_y(import.meta.url)),xy=ho.resolve(qu,"..","..","client","dist"),ky="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ay=new Map([...ky].map((e,t)=>[e,t]));Yu=new Map;Mi=null;Iy=/(?:https?:\/\/[^\s()]*)?\/assets\/([^\s()/]+\.js):(\d+):(\d+)/g});var ad={};Z(ad,{ingestTelemetry:()=>Ly,pruneTelemetry:()=>nd,relayOnce:()=>id,startTelemetryRelay:()=>Fy,telemetryAllowed:()=>Dy,toCedarEvent:()=>sd});import Ce from"node:fs/promises";import nn from"node:path";import Qu from"node:os";function By(e,t){if(!e||typeof e!="object")return null;let n=ie(e.name,64);if(!n)return null;let r=Number.isFinite(e.ts)?e.ts:t,o={name:n,ts:Math.abs(r-t)<168*3600*1e3?r:t,receivedAt:t,anonId:ie(e.anonId,64),sessionId:ie(e.sessionId,64),userId:ie(e.userId,64),release:ie(e.release,64),appVersion:ie(e.appVersion,32),route:ie(e.route,128),deviceClass:e.deviceClass==="phone"||e.deviceClass==="desktop"?e.deviceClass:""};return e.props&&typeof e.props=="object"&&!Array.isArray(e.props)&&(JSON.stringify(e.props).length<=8192?o.props=e.props:o.props={clamped:!0}),e.error&&typeof e.error=="object"&&(o.error={kind:ie(e.error.kind,256),message:ie(e.error.message,8192),stack:ie(e.error.stack,32768),fingerprint:ie(e.error.fingerprint,64)}),Array.isArray(e.breadcrumbs)&&(o.breadcrumbs=e.breadcrumbs.slice(-50).map(s=>({t:Number.isFinite(s?.t)?s.t:0,n:ie(s?.n,64),r:ie(s?.r,128)}))),o}async function Ly(e,t=Date.now()){let r=(Array.isArray(e?.events)?e.events.slice(0,Cy):[]).map(s=>By(s,t)).filter(Boolean);if(!r.length)return 0;for(let s of r)s.error?.stack&&await Vu(s);await Ce.mkdir(Ge(),{recursive:!0});let o=nn.join(Ge(),`${td(t)}.ndjson`);return await Ce.appendFile(o,r.map(s=>JSON.stringify(s)+`
|
|
156
|
+
`).join(""),"utf8"),t-Zu>6*3600*1e3&&(Zu=t,nd(t).catch(()=>{})),r.length}async function nd(e=Date.now()){let t=td(e-jy*24*3600*1e3),n=[];try{n=await Ce.readdir(Ge())}catch{return}let r=n.filter(s=>s.endsWith(".ndjson")&&s.slice(0,10)<t);if(!r.length)return;for(let s of r)await Ce.rm(nn.join(Ge(),s),{force:!0});let o=await rd();for(let s of r)delete o[s];await od(o)}function Dy(e,t=Date.now()){let n=e||"unknown",r=mo.get(n);return r||(mo.size>512&&mo.clear(),r={tokens:40,at:t},mo.set(n,r)),r.tokens=Math.min(40,r.tokens+(t-r.at)/6e4*20),r.at=t,r.tokens<1?!1:(r.tokens-=1,!0)}async function rd(){try{return JSON.parse(await Ce.readFile(ed(),"utf8"))||{}}catch{return{}}}async function od(e){await Ce.mkdir(Ge(),{recursive:!0}),await Ce.writeFile(ed(),JSON.stringify(e),"utf8")}function sd(e,{env:t,host:n}={}){let r=e.name==="app.error"&&e.error,o={};for(let[a,i]of[["event",e.name],["route",e.route],["session",e.sessionId],["anon",e.anonId],["user",e.userId],["release",e.release],["appVersion",e.appVersion],["device",e.deviceClass]])i&&(o[a]=i);let s={timestamp:new Date(e.ts).toISOString(),service:"bostrat-client",source:"treetop-js",env:t||process.env.BOSTRAT_ENV||"pi",host:n||Qu.hostname(),level:r?"error":"info",message:r?`${e.error.kind||"Error"}: ${e.error.message||"(no message)"}`.slice(0,8192):e.name,tags:o,attributes:{...e.props?{props:e.props}:{},receivedAt:e.receivedAt}};return r&&(s.error={kind:e.error.kind,message:e.error.message,stack:e.error.stack},e.error.fingerprint&&(s.fingerprint=e.error.fingerprint),e.error.symbolicated&&(s.attributes.symbolicated=!0),e.breadcrumbs&&(s.attributes.breadcrumbs=e.breadcrumbs)),s}async function id({fetchImpl:e=fetch}={}){let t=await Ni();if(!t)return{sent:0,disabled:!0};let n;try{n=(await Ce.readdir(Ge())).filter(s=>s.endsWith(".ndjson")).sort()}catch{return{sent:0,disabled:!1}}let r=await rd(),o=0;for(let s of n){let a=nn.join(Ge(),s),i=r[s]||0,c;try{let p=await Ce.open(a,"r");try{let g=(await p.stat()).size;if(g<=i)continue;c=Buffer.alloc(g-i),await p.read(c,0,c.length,i)}finally{await p.close()}}catch{continue}let l=c.lastIndexOf(10);if(l<0)continue;let u=c.toString("utf8",0,l+1).split(`
|
|
157
|
+
`).filter(Boolean),f=[];for(let p of u)try{f.push(JSON.parse(p))}catch{}for(let p=0;p<f.length;p+=Xu){let g=f.slice(p,p+Xu).map(x=>sd(x)),S=await e(`${t.url.replace(/\/$/,"")}/v1/logs`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.ingestKey}`},body:JSON.stringify({events:g})}).catch(()=>null);if(!S||!S.ok)return{sent:o,disabled:!1};o+=g.length}r[s]=i+l+1,await od(r)}return{sent:o,disabled:!1}}function Fy(){Ci||(Ci=setInterval(async()=>{if(!ji){ji=!0;try{await id()}catch(e){console.error("[telemetry] relay failed:",e?.message||e)}finally{ji=!1}}},Py),Ci.unref?.())}var My,Ge,ed,Cy,jy,Py,Xu,ie,td,Zu,mo,Ci,ji,cd=k(()=>{gt();Ju();q();My=()=>process.env.BOSTRAT_STATE_DIR||nn.join(process.env.HOME||Qu.tmpdir(),".bostrat"),Ge=()=>nn.join(My(),"telemetry"),ed=()=>nn.join(Ge(),".relay-offsets.json"),Cy=50,jy=14,Py=3e4,Xu=500,ie=(e,t)=>typeof e=="string"?e.slice(0,t):"";td=e=>new Date(e).toISOString().slice(0,10),Zu=0;mo=new Map;Ci=null,ji=!1;j("cedar",async({env:e,local:t})=>{let n=t?null:await Ni();return n?{class:"telemetry",mode:"timer",host:n.url,armedBy:pe(e,["BOSTRAT_CEDAR_INGEST_KEY"],"cedar.ingestKey"),purpose:"client and node error telemetry"}:null})});var bd={};Z(bd,{__resetDictationForTest:()=>Xy,addTerms:()=>Gy,dictationProblem:()=>Vy,glossaryTerms:()=>Pi,learnFromEdit:()=>Yy,selectKeyterms:()=>yd,transcribe:()=>Jy});import wo from"node:fs/promises";import fd from"node:path";import Uy from"node:os";function ld(){let e={},t=Date.now();for(let n of Ky)e[n.toLowerCase()]={term:n,count:1,lastUsed:t,source:"seed"};return e}async function gd(){return Jn||(yo??=wo.readFile(md(),"utf8").then(e=>JSON.parse(e)?.terms??ld()).catch(()=>ld()).then(e=>Jn=e).finally(()=>yo=null),yo)}async function ud(){let e=JSON.stringify({terms:Jn},null,2),t=md(),n=`${t}.${process.pid}.tmp`;await wo.mkdir(hd(),{recursive:!0}),await wo.writeFile(n,e),await wo.rename(n,t)}function wd(){return So=So.then(ud,ud),So.catch(()=>{})}async function Pi(){return Object.values(await gd()).sort((t,n)=>n.count-t.count||n.lastUsed-t.lastUsed)}async function yd(){let e=[],t=0;for(let{term:n}of await Pi()){let r=zy(n);if(!(t+r>Wy)&&(e.push(n),t+=r,e.length>=Hy))break}return e}async function Sd(e,t){let n=await gd(),r=e.toLowerCase(),o=n[r];n[r]={term:e,count:(o?.count??0)+1,lastUsed:Date.now(),source:o?.source??t}}async function Gy(e){for(let t of e)await Sd(t,"manual");return await wd(),Pi()}function pd(e){return!new RegExp("\\p{L}","u").test(e)||e.length<3?!1:/^[a-z]+$/.test(e)?e.length>=4:!0}async function Yy(e,t){let n=dd(e),r=dd(t);if(!n.length||!r.length)return[];let o=n.length,s=r.length,a=Array.from({length:o+1},()=>new Array(s+1).fill(0));for(let u=o-1;u>=0;u--)for(let f=s-1;f>=0;f--)a[u][f]=go(n[u])===go(r[f])?a[u+1][f+1]+1:Math.max(a[u+1][f],a[u][f+1]);let i=new Set,c=0,l=0;for(;c<o&&l<s;)go(n[c])===go(r[l])?(c++,l++):a[c+1][l]>=a[c][l+1]?c++:(pd(r[l])&&i.add(r[l]),l++);for(;l<s;l++)pd(r[l])&&i.add(r[l]);if(!i.size)return[];for(let u of i)await Sd(u,"learned");return await wd(),[...i]}function qy(e,t){let n=null;try{n=JSON.parse(t)}catch{}let r=n?.err_code||n?.error_code||n?.category||"";return e===402||/PAYMENT_REQUIRED/i.test(r)?{status:402,code:"credits_exhausted",persistent:!0,message:"Deepgram credits are exhausted \u2014 dictation is down until you top up at console.deepgram.com or drop a new key into ~/.bostrat/integrations.json."}:e===401||e===403?{status:502,code:"key_invalid",persistent:!0,message:"Deepgram rejected the API key (revoked, or missing ASR scope) \u2014 replace it in ~/.bostrat/integrations.json."}:{status:502,code:"transcription_failed",persistent:!1,message:`Deepgram error ${e}: ${t.slice(0,300)}`}}async function Vy(){if(!rn)return null;let e=await fo();if(!e||e.apiKey.slice(-6)!==rn.keyTail)return null;let{keyTail:t,...n}=rn;return n}async function Jy(e,t){let n=await fo();if(!n){let i=new Error("Deepgram is not configured \u2014 add deepgram.apiKey to ~/.bostrat/integrations.json");throw i.status=503,i.code="not_configured",i}let r=new URL("https://api.deepgram.com/v1/listen");r.searchParams.set("model","nova-3"),r.searchParams.set("smart_format","true");for(let i of await yd())r.searchParams.append("keyterm",i);let o=await fetch(r,{method:"POST",headers:{Authorization:`Token ${n.apiKey}`,"Content-Type":t||"application/octet-stream"},body:e});if(!o.ok){let i=await o.text().catch(()=>""),c=qy(o.status,i);c.persistent&&(rn={code:c.code,message:c.message,at:Date.now(),keyTail:n.apiKey.slice(-6)});let l=new Error(c.message);throw l.status=c.status,l.code=c.code,l}return rn=null,{transcript:(await o.json())?.results?.channels?.[0]?.alternatives?.[0]?.transcript??""}}function Xy(){Jn=null,yo=null,So=Promise.resolve(),rn=null}var hd,md,Hy,Wy,Ky,Jn,yo,So,zy,dd,go,rn,_d=k(()=>{gt();q();hd=()=>process.env.BOSTRAT_STATE_DIR||fd.join(process.env.HOME||Uy.tmpdir(),".bostrat"),md=()=>fd.join(hd(),"dictation-glossary.json"),Hy=100,Wy=500,Ky=["bostrat","globopi","codex","tmux","worktree","Deepgram","Linear","Firecracker","Tigris","WireGuard","misous","postyx","cedar","gerbil","Anthropic","Opus","Haiku","Sonnet","keyterm","monorepo","dogfood"],Jn=null,yo=null,So=Promise.resolve();zy=e=>Math.max(1,Math.ceil(e.length/4));dd=e=>(e||"").split(/\s+/).map(t=>t.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu,"")).filter(Boolean),go=e=>e.toLowerCase();rn=null;j("deepgram",async({env:e})=>await fo()?{class:"integration",mode:"request",host:"api.deepgram.com",armedBy:pe(e,["DEEPGRAM_API_KEY"],"deepgram.apiKey"),purpose:"voice dictation"}:null)});var Ad={};Z(Ad,{REALTIME_PRICES:()=>bo,__resetVoiceAgentForTest:()=>o0,mintVoiceSession:()=>n0,recordVoiceUsage:()=>r0,resolveRealtimeModel:()=>Td,voiceChatProblem:()=>kd,voiceChatStatus:()=>t0,voiceUsageCost:()=>xd});function Td(e){if(!e)return null;let t=String(e).trim();if(bo[t])return t;let n=null;for(let r of Object.keys(bo))t.startsWith(r)&&(!n||r.length>n.length)&&(n=r);return n}function xd(e,t={}){let n=bo[Td(e)];if(!n)return 0;let r=0;for(let o of Object.keys(n))r+=(Number(t[o])||0)*n[o];return r/1e6}function Zy(e,t){let n=null;try{n=JSON.parse(t)}catch{}let r=n?.error?.code||n?.error?.type||"";return e===429&&/insufficient_quota/i.test(r)?{status:402,code:"credits_exhausted",persistent:!0,message:"The OpenAI account is out of credit \u2014 voice chat is down until you top up at platform.openai.com or drop a new key into ~/.bostrat/integrations.json."}:e===401||e===403?{status:502,code:"key_invalid",persistent:!0,message:"OpenAI rejected the API key (revoked, or missing Realtime access) \u2014 replace it in ~/.bostrat/integrations.json."}:{status:502,code:"mint_failed",persistent:!1,message:`OpenAI realtime session mint failed (${e}): ${t.slice(0,300)}`}}async function kd(){if(!on)return null;let e=await Vn();if(!e||e.apiKey.slice(-6)!==on.keyTail)return null;let{keyTail:t,...n}=on;return n}async function Qy(e){let t=await fetch("https://api.openai.com/v1/realtime/client_secrets",{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({session:{type:"realtime",model:e.model,audio:{output:{voice:e.voice}}}})});if(!t.ok){let o=await t.text().catch(()=>""),s=Zy(t.status,o);s.persistent&&(on={code:s.code,message:s.message,at:Date.now(),keyTail:e.apiKey.slice(-6)});let a=new Error(s.message);throw a.status=s.status,a.code=s.code,a}on=null;let n=await t.json(),r=n?.value??n?.client_secret?.value;if(!r){let o=new Error("OpenAI returned no client secret");throw o.status=502,o.code="mint_failed",o}return{clientSecret:{value:r,expiresAt:n?.expires_at??n?.client_secret?.expires_at??null}}}async function t0(){let e=await Vn();return e?{configured:!0,provider:e.provider,model:e.model,voice:e.voice,problem:await kd()}:{configured:!1}}async function n0(){let e=await Vn();if(!e){let n=new Error("Voice chat is not configured \u2014 add openai.apiKey to ~/.bostrat/integrations.json");throw n.status=503,n.code="not_configured",n}let t=await e0[e.provider](e);return{provider:e.provider,model:e.model,voice:e.voice,...t}}async function r0(e,{model:t,usage:n={},seconds:r}={}){let o=c=>Math.max(0,Math.round(Number(c)||0)),s={textIn:o(n.textIn),textInCached:o(n.textInCached),textOut:o(n.textOut),audioIn:o(n.audioIn),audioInCached:o(n.audioInCached),audioOut:o(n.audioOut)},a=xd(t,s),i=await Nt(e,{type:"cost.recorded",actor:"user",provider:"openai-realtime",payload:{model:t||"unknown",usd:a,tokens:{input:s.textIn+s.audioIn,output:s.textOut+s.audioOut,cacheRead:s.textInCached+s.audioInCached,cacheWrite:0},voice:s,seconds:Math.max(0,Math.round(Number(r)||0)),source:"voice-chat"}});return{usd:a,seq:i.seq}}function o0(){on=null}var bo,on,e0,$d=k(()=>{gt();Mt();q();bo={"gpt-realtime-2.1":{textIn:4,textInCached:.4,textOut:24,audioIn:32,audioInCached:.4,audioOut:64},"gpt-realtime-2":{textIn:4,textInCached:.4,textOut:24,audioIn:32,audioInCached:.4,audioOut:64},"gpt-realtime":{textIn:4,textInCached:.4,textOut:16,audioIn:32,audioInCached:.4,audioOut:64},"gpt-realtime-2.1-mini":{textIn:.6,textInCached:.06,textOut:2.4,audioIn:10,audioInCached:.3,audioOut:20},"gpt-realtime-mini":{textIn:.6,textInCached:.06,textOut:2.4,audioIn:10,audioInCached:.3,audioOut:20}};on=null;e0={openai:Qy};j("openai-realtime",async({env:e})=>await Vn()?{class:"integration",mode:"request",host:"api.openai.com",armedBy:pe(e,["BOSTRAT_OPENAI_API_KEY"],"openai.apiKey"),purpose:"voice chat sessions"}:null)});var vd={};Z(vd,{postMessage:()=>i0,respond:()=>c0,slackCall:()=>Xn,slackForm:()=>Ed,startSocket:()=>d0,updateMessage:()=>a0,uploadFileToThread:()=>l0});import s0 from"ws";async function Xn(e,t,n={}){let r=await fetch(`${Bi()}/${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json; charset=utf-8"},body:JSON.stringify(n)}),o=await r.json().catch(()=>null);if(!o?.ok)throw new Error(`slack ${e}: ${o?.error||`http ${r.status}`}`);return o}async function c0(e,t){await fetch(e,{method:"POST",headers:{"content-type":"application/json; charset=utf-8"},body:JSON.stringify(t)}).catch(()=>{})}async function Ed(e,t,n={}){let r=await fetch(`${Bi()}/${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded; charset=utf-8"},body:new URLSearchParams(n).toString()}),o=await r.json().catch(()=>null);if(!o?.ok)throw new Error(`slack ${e}: ${o?.error||`http ${r.status}`}`);return o}async function l0(e,{filename:t,buffer:n,title:r,channelId:o,threadTs:s,initialComment:a}){let{upload_url:i,file_id:c}=await Ed("files.getUploadURLExternal",e,{filename:t,length:String(n.length)}),l=await fetch(i,{method:"POST",body:n});if(!l.ok)throw new Error(`slack upload: http ${l.status}`);return Xn("files.completeUploadExternal",e,{files:[{id:c,title:r}],channel_id:o,thread_ts:s,...a?{initial_comment:a}:{}})}function d0({getToken:e,onEnvelope:t,log:n=()=>{}}){let r=!1,o=null,s=null,a=1e3;async function i(){if(r)return;let l;try{let u=await e();if(!u)throw new Error("app token missing");({url:l}=await Xn("apps.connections.open",u))}catch(u){return n(`connections.open failed: ${u?.message||u}`),c()}o=new s0(l),o.on("message",u=>{let f;try{f=JSON.parse(u)}catch{return}if(f.type==="hello"){a=1e3,n("socket connected");return}if(f.type==="disconnect"){try{o.close()}catch{}return}if(!f.envelope_id)return;let p=x=>{try{o.send(JSON.stringify(x?{envelope_id:f.envelope_id,payload:x}:{envelope_id:f.envelope_id}))}catch{}},g=!1,S=setTimeout(()=>{g=!0,p()},u0);Promise.resolve().then(()=>t(f)).then(x=>{clearTimeout(S),!g&&(g=!0,p(f.accepts_response_payload?x:void 0))},x=>{clearTimeout(S),g||(g=!0,p()),n(`envelope handler failed: ${x?.message||x}`)})}),o.on("close",c),o.on("error",u=>{n(`socket error: ${u?.message||u}`);try{o.close()}catch{}})}function c(){if(r||s)return;let l=a;a=Math.min(a*2,6e4),s=setTimeout(()=>{s=null,i()},l)}return i(),()=>{r=!0,s&&clearTimeout(s);try{o?.close()}catch{}}}var Bi,i0,a0,u0,Od=k(()=>{q();gt();Bi=()=>process.env.BOSTRAT_SLACK_API_BASE||"https://slack.com/api";i0=(e,t)=>Xn("chat.postMessage",e,t),a0=(e,t)=>Xn("chat.update",e,t);u0=2200;j("slack",async({env:e})=>await zu()?{class:"integration",mode:"timer",host:[Bi(),"*.slack.com"],armedBy:pe(e,["BOSTRAT_SLACK_BOT_TOKEN","BOSTRAT_SLACK_APP_TOKEN"],"slack.botToken + slack.appToken"),purpose:"the Slack bridge (Socket Mode)"}:null)});var Nd={};Z(Nd,{createBlockingRelation:()=>$0,createComment:()=>y0,createIssue:()=>A0,createProject:()=>k0,findIssueUrl:()=>m0,issueStates:()=>_0,moveIssue:()=>T0,parseIssueRef:()=>h0,resolveIssue:()=>g0,teams:()=>x0,uploadImage:()=>b0,upsertCard:()=>w0,whoami:()=>S0});async function be(e,t,n={}){let r=await fetch(Id(),{method:"POST",headers:{"content-type":"application/json",authorization:e.apiKey},body:JSON.stringify({query:t,variables:n})}),o=await r.json().catch(()=>null);if(!r.ok)throw new Error(`linear: HTTP ${r.status}${o?.errors?.[0]?.message?` \u2014 ${o.errors[0].message}`:""}`);if(o?.errors?.length){let s=o.errors[0],a=(s.extensions?.validationErrors??[]).flatMap(i=>Object.values(i?.constraints??{})).join("; ");throw new Error(`linear: ${s.message}${a?` \u2014 ${a}`:""}`)}return o?.data??{}}function h0(e){let t=String(e||"").trim(),n=t.match(p0);if(n)return n[1].toUpperCase();let r=t.match(f0);return r?r[1]:null}function m0(e){let t=String(e||"").match(/https?:\/\/linear\.app\/[^/\s]+\/issue\/[A-Za-z][A-Za-z0-9]{0,9}-\d+[^\s)]*/);return t?t[0]:null}async function g0(e,t){let r=(await be(e,"query($id: String!) { issue(id: $id) { id identifier title url state { name } team { key } } }",{id:t})).issue;if(!r)throw new Error(`linear: issue "${t}" not found`);return{issueId:r.id,key:r.identifier,title:r.title,url:r.url,state:r.state?.name??null,team:r.team?.key??null}}async function w0(e,t,{url:n,title:r,subtitle:o}){let s=await be(e,"mutation($input: AttachmentCreateInput!) { attachmentCreate(input: $input) { success attachment { id } } }",{input:{issueId:t.issueId,url:n,title:r,subtitle:o}});if(!s.attachmentCreate?.success)throw new Error("linear: attachmentCreate did not succeed");return s.attachmentCreate.attachment?.id??null}async function y0(e,t,n){let r=await be(e,"mutation($input: CommentCreateInput!) { commentCreate(input: $input) { success comment { url } } }",{input:{issueId:t.issueId,body:n}});if(!r.commentCreate?.success)throw new Error("linear: commentCreate did not succeed");return r.commentCreate.comment?.url??null}async function S0(e){let t=await be(e,"query { viewer { name email } organization { name urlKey } }");return{user:t.viewer?.name??t.viewer?.email??null,org:t.organization?.name??t.organization?.urlKey??null}}async function b0(e,{filename:t,contentType:n,buffer:r}){let o=await be(e,`mutation($contentType: String!, $filename: String!, $size: Int!) {
|
|
158
|
+
fileUpload(contentType: $contentType, filename: $filename, size: $size) {
|
|
159
|
+
success
|
|
160
|
+
uploadFile { uploadUrl assetUrl headers { key value } }
|
|
161
|
+
}
|
|
162
|
+
}`,{contentType:n,filename:t,size:r.length}),s=o.fileUpload?.uploadFile;if(!o.fileUpload?.success||!s?.uploadUrl)throw new Error("linear: fileUpload did not succeed");let a={"content-type":n};for(let c of s.headers||[])a[c.key]=c.value;let i=await fetch(s.uploadUrl,{method:"PUT",headers:a,body:r});if(!i.ok)throw new Error(`linear: asset PUT failed (HTTP ${i.status})`);return s.assetUrl}async function _0(e,t){let n=await be(e,"query($id: String!) { issue(id: $id) { state { id name type } team { states { nodes { id name type position } } } } }",{id:t.key});if(!n.issue)throw new Error(`linear: issue "${t.key}" not found`);return{current:n.issue.state??null,states:n.issue.team?.states?.nodes??[]}}async function T0(e,t,n){if(!(await be(e,"mutation($id: String!, $input: IssueUpdateInput!) { issueUpdate(id: $id, input: $input) { success } }",{id:t.issueId,input:{stateId:n}})).issueUpdate?.success)throw new Error("linear: issueUpdate did not succeed")}async function x0(e){return((await be(e,"query { teams(first: 100) { nodes { id key name } } }")).teams?.nodes??[]).map(n=>({id:n.id,key:n.key,name:n.name}))}async function k0(e,{teamId:t,name:n,description:r}){let o=r||null,s=!!o&&o.length>Rd,a=s?`${o.slice(0,Rd-1).trimEnd()}\u2026`:o,i=await be(e,"mutation($input: ProjectCreateInput!) { projectCreate(input: $input) { success project { id url name } } }",{input:{teamIds:[t],name:n,...a?{description:a}:{},...s?{content:o}:{}}}),c=i.projectCreate?.project;if(!i.projectCreate?.success||!c)throw new Error("linear: projectCreate did not succeed");return{id:c.id,url:c.url,name:c.name}}async function A0(e,{teamId:t,title:n,description:r,projectId:o,priority:s}){let a=await be(e,"mutation($input: IssueCreateInput!) { issueCreate(input: $input) { success issue { id identifier url title } } }",{input:{teamId:t,title:n,...r?{description:r}:{},...o?{projectId:o}:{},...Number.isInteger(s)?{priority:s}:{}}}),i=a.issueCreate?.issue;if(!a.issueCreate?.success||!i)throw new Error("linear: issueCreate did not succeed");return{id:i.id,key:i.identifier,url:i.url,title:i.title}}async function $0(e,{blockerId:t,blockedId:n}){if(!(await be(e,"mutation($input: IssueRelationCreateInput!) { issueRelationCreate(input: $input) { success } }",{input:{issueId:t,relatedIssueId:n,type:"blocks"}})).issueRelationCreate?.success)throw new Error("linear: issueRelationCreate did not succeed")}var Id,p0,f0,Rd,Md=k(()=>{q();gt();Id=()=>process.env.BOSTRAT_LINEAR_API_URL||"https://api.linear.app/graphql";p0=/linear\.app\/[^/\s]+\/issue\/([A-Za-z][A-Za-z0-9]{0,9}-\d+)/,f0=/^([A-Z][A-Z0-9]{0,9}-\d+)$/;Rd=255;j("linear",async({env:e})=>await Wu()?{class:"integration",mode:"request",host:Id(),armedBy:pe(e,["BOSTRAT_LINEAR_API_KEY"],"linear.apiKey"),purpose:"ticket cards, comments and status moves"}:null)});var Bd={};Z(Bd,{createComment:()=>j0,findIssueUrl:()=>R0,issueStates:()=>D0,mdToAdf:()=>Pd,moveIssue:()=>F0,parseIssueRef:()=>O0,resolveIssue:()=>I0,uploadImage:()=>B0,upsertCard:()=>N0,whoami:()=>P0});async function wt(e,t,n,r){let o=await fetch(`${sn(e)}${n}`,{method:t,headers:{authorization:jd(e),accept:"application/json",...r!==void 0?{"content-type":"application/json"}:{}},body:r!==void 0?JSON.stringify(r):void 0}),s=await o.text(),a=null;try{a=s?JSON.parse(s):null}catch{a=null}if(!o.ok){let i=a?.errorMessages?.[0]??Object.values(a?.errors??{})[0]??`HTTP ${o.status}`,c=new Error(`jira: ${i}`);throw c.status=o.status,c}return a}function O0(e){let t=String(e||"").trim();if(/^https?:\/\//i.test(t)){let r=t.match(E0);return r?r[1].toUpperCase():null}let n=t.match(v0);return n?n[1]:null}function R0(e,t=null){let n=null;try{n=t?.baseUrl?new URL(t.baseUrl).host:null}catch{n=null}let r=/https?:\/\/[^\s)]+\/browse\/[A-Za-z][A-Za-z0-9]{0,9}-\d+[^\s)]*/g;for(let o of String(e||"").matchAll(r))try{let s=new URL(o[0]).host;if(s===n||/\.atlassian\.net$/i.test(s))return o[0]}catch{}return null}async function I0(e,t){let n;try{n=await wt(e,"GET",`/rest/api/3/issue/${encodeURIComponent(t)}?fields=summary,status`)}catch(r){throw r.status===404?new Error(`jira: issue "${t}" not found`):r}return{issueId:n.id,key:n.key,title:n.fields?.summary??null,url:`${sn(e)}/browse/${n.key}`,state:n.fields?.status?.name??null}}async function N0(e,t,{url:n,title:r,subtitle:o}){await wt(e,"POST",`/rest/api/3/issue/${encodeURIComponent(t.key)}/remotelink`,{globalId:n,application:{type:"com.bostrat.tracks",name:"Bostrat"},object:{url:n,title:r,summary:o,icon:{title:"Bostrat"}}})}function C0(e){let t=[],n=0;for(let r of e.matchAll(M0)){r.index>n&&t.push({type:"text",text:e.slice(n,r.index)});let o=r[0];if(o.startsWith("![")){let[,s,a]=o.match(/^!\[([^\]]*)\]\(([^)\s]+)\)$/);t.push({type:"text",text:s||a,marks:[{type:"link",attrs:{href:a}}]})}else o.startsWith("**")?t.push({type:"text",text:o.slice(2,-2),marks:[{type:"strong"}]}):o.startsWith("`")?t.push({type:"text",text:o.slice(1,-1),marks:[{type:"code"}]}):o.startsWith("_")?t.push({type:"text",text:o.slice(1,-1),marks:[{type:"em"}]}):t.push({type:"text",text:o,marks:[{type:"link",attrs:{href:o}}]});n=r.index+o.length}return n<e.length&&t.push({type:"text",text:e.slice(n)}),t}function Pd(e){let t=String(e??"").split(/\n{2,}/).map(n=>n.trim()).filter(Boolean).map(n=>{let r=[];return n.split(`
|
|
163
|
+
`).forEach((o,s)=>{s>0&&r.push({type:"hardBreak"}),r.push(...C0(o))}),{type:"paragraph",content:r.length?r:[{type:"text",text:" "}]}});return{type:"doc",version:1,content:t.length?t:[{type:"paragraph",content:[{type:"text",text:" "}]}]}}async function j0(e,t,n){let r=await wt(e,"POST",`/rest/api/3/issue/${encodeURIComponent(t.key)}/comment`,{body:Pd(n)});return r?.id?`${sn(e)}/browse/${t.key}?focusedCommentId=${r.id}`:null}async function P0(e){let t=await wt(e,"GET","/rest/api/3/myself"),n=null;try{n=new URL(sn(e)).host}catch{n=e.baseUrl??null}return{user:t?.displayName??t?.emailAddress??null,org:n}}async function B0(e,{issue:t,filename:n,contentType:r,buffer:o}){let s=new FormData;s.append("file",new Blob([o],{type:r}),n);let a=await fetch(`${sn(e)}/rest/api/3/issue/${encodeURIComponent(t)}/attachments`,{method:"POST",headers:{authorization:jd(e),"x-atlassian-token":"no-check",accept:"application/json"},body:s}),i=await a.json().catch(()=>null),c=Array.isArray(i)?i[0]:null;if(!a.ok||!c)throw new Error(`jira: attachment upload failed (HTTP ${a.status})`);return c.content??`${sn(e)}/rest/api/3/attachment/content/${c.id}`}async function D0(e,t){let n=encodeURIComponent(t.key),[r,o]=await Promise.all([wt(e,"GET",`/rest/api/3/issue/${n}?fields=status`),wt(e,"GET",`/rest/api/3/issue/${n}/transitions`)]),s=r?.fields?.status??null,a=s?{id:`status:${s.id}`,name:s.name,type:Cd(s.statusCategory)}:null,i=(o?.transitions??[]).map((c,l)=>({id:c.id,name:c.to?.name??c.name,type:Cd(c.to?.statusCategory),position:l}));return{current:a,states:i}}async function F0(e,t,n){await wt(e,"POST",`/rest/api/3/issue/${encodeURIComponent(t.key)}/transitions`,{transition:{id:String(n)}})}var sn,jd,E0,v0,M0,L0,Cd,Ld=k(()=>{q();gt();sn=e=>String(e.baseUrl||"").replace(/\/$/,""),jd=e=>`Basic ${Buffer.from(`${e.email}:${e.apiToken}`).toString("base64")}`;E0=/\/browse\/([A-Za-z][A-Za-z0-9]{0,9}-\d+)/,v0=/^([A-Z][A-Z0-9]{0,9}-\d+)$/;M0=/(!\[[^\]]*\]\([^)\s]+\)|\*\*[^*\n]+\*\*|`[^`\n]+`|_[^_\n]+_|https?:\/\/[^\s)]+)/g;L0={new:"unstarted",indeterminate:"started",done:"completed"},Cd=e=>L0[e?.key]??"started";j("jira",async({env:e})=>{let t=await Ku();return t?{class:"integration",mode:"request",host:t.baseUrl,armedBy:pe(e,["BOSTRAT_JIRA_BASE_URL","BOSTRAT_JIRA_EMAIL","BOSTRAT_JIRA_API_TOKEN"],"jira.baseUrl + jira.email + jira.apiToken"),purpose:"ticket links, comments and transitions"}:null})});import U0 from"node:path";var r$,Dd=k(()=>{Ie();r$=process.env.BOSTRAT_CLAUDE_PROJECTS||U0.join(Pt(),".claude","projects")});var Fd=k(()=>{});var Ud=k(()=>{Dd();Fd()});function Ye(e,t){if(!e)return null;let n=String(e);if(t){let o=t.endsWith("/")?t:`${t}/`;if(n===t)return".";if(n.startsWith(o))return n.slice(o.length)||"."}let r=n.split("/").filter(Boolean);return n.startsWith("/")&&r.length>2?r.slice(-2).join("/"):n}function H0(e,t){if(!e)return null;let n=String(e);if(!n.startsWith("/"))return n.replace(/^\.\//,"")||null;if(!t)return null;let r=t.endsWith("/")?t:`${t}/`;return n.startsWith(r)&&n.slice(r.length)||null}function W0(e){let t=typeof e=="string"?e:String(e?.patch??e?.input??""),n=[];for(let r of t.matchAll(/^\*{3} (?:Update|Add|Delete) File: (.+)$/gm))n.push(r[1].trim());return n}function Wd(e,t,n){switch(e){case"Shell":{let r=String(t?.command||"").trim();return r?{command:r,description:String(t?.description||"").trim()}:null}case"Read":{let r=t?.path;if(!r)return null;let o=Number(t?.offset)||null,s=o&&Number(t?.limit)?o+Number(t.limit)-1:null;return{command:_e(`read ${Ye(r,n)}${o?` (lines ${o}\u2013${s??"end"})`:""}`,140),description:o?`Read lines ${o}\u2013${s??"end"} of ${an(r)}`:`Read ${an(r)}`}}case"Grep":{let r=t?.pattern;if(!r)return null;let o=t?.path?Ye(t.path,n):null,s=t?.glob?` --glob ${Li(t.glob)}`:"",a=_e(String(r),40);return{command:_e(`grep ${Li(r)}${o&&o!=="."?` ${o}`:""}${s}`,140),description:o&&o!=="."?`Search for \u201C${a}\u201D in ${o}`:`Search for \u201C${a}\u201D`}}case"Glob":{let r=t?.glob_pattern;if(!r)return null;let o=t?.target_directory?Ye(t.target_directory,n):null;return{command:_e(`glob ${Li(r)}${o&&o!=="."?` ${o}`:""}`,140),description:`Find files matching \u201C${_e(String(r),40)}\u201D`}}case"StrReplace":return t?.path?{command:_e(`edit ${Ye(t.path,n)}`,140),description:`Edit ${an(t.path)}`,..._o([t.path],n)}:null;case"Write":return t?.path?{command:_e(`write ${Ye(t.path,n)}`,140),description:`Write ${an(t.path)}`,..._o([t.path],n)}:null;case"Delete":return t?.path?{command:_e(`delete ${Ye(t.path,n)}`,140),description:`Delete ${an(t.path)}`,..._o([t.path],n)}:null;case"ReadLints":{let o=(Array.isArray(t?.paths)?t.paths:[]).map(s=>Ye(s,n)).filter(Boolean);return{command:_e(o.length?`lints ${o.join(" ")}`:"lints",140),description:"Check lints"}}case"ApplyPatch":{let r=W0(t);if(!r.length)return null;let o=r.length>1?` (+${r.length-1} more)`:"";return{command:_e(`apply_patch ${Ye(r[0],n)}${o}`,140),description:r.length>1?`Patch ${r.length} files`:`Patch ${an(r[0])}`,..._o(r,n)}}case"Await":{let r=t?.shell_id??t?.task_id;return{command:_e(`await ${r??"background output"}`,140),description:"Wait for a background command"}}default:return null}}var Hd,_e,an,_o,Li,Kd=k(()=>{Hd=new Set(["Shell","Read","Grep","Glob","StrReplace","Write","ReadLints","Delete","ApplyPatch","Await"]),_e=(e,t=88)=>e.length>t?`${e.slice(0,t).trimEnd()}\u2026`:e,an=e=>String(e).replace(/\/+$/,"").split("/").pop()||String(e);_o=(e,t)=>{let n=e.map(r=>H0(r,t)).filter(Boolean);return n.length?{paths:n}:{}},Li=e=>`"${String(e).replace(/"/g,'\\"')}"`});import To from"node:fs";import yt from"node:path";import K0 from"node:crypto";import z0 from"node:zlib";function Yd(e){let t=K0.createHash("md5").update(String(e)).digest("hex");return yt.join(G0,t)}function qd(e){try{let t=JSON.parse(To.readFileSync(yt.join(e,"meta.json"),"utf8"));return{createdAtMs:Number(t.createdAtMs)||null,updatedAtMs:Number(t.updatedAtMs)||Number(t.createdAtMs)||null,hasConversation:t.hasConversation===!0}}catch{return null}}function Y0(e){let t=Yd(e),n;try{n=To.readdirSync(t,{withFileTypes:!0}).filter(o=>o.isDirectory())}catch{return null}let r=null;for(let o of n){let s=yt.join(t,o.name),a=yt.join(s,"store.db");if(!To.existsSync(a))continue;let i=qd(s);if(!i)continue;let c={id:o.name,dir:s,store:a,...i};(!r||c.hasConversation&&!r.hasConversation||c.hasConversation===r.hasConversation&&(c.updatedAtMs||0)>(r.updatedAtMs||0))&&(r=c)}return r}function q0(e,t){if(!e)return null;if(t){let n=yt.join(Yd(e),t),r=yt.join(n,"store.db");if(To.existsSync(r))return{id:t,dir:n,store:r,...qd(n)||{createdAtMs:null,updatedAtMs:null}}}return Y0(e)}function zd(e,t){let n=e.prepare("SELECT data FROM blobs WHERE id = ?").get(t);return n?Buffer.from(n.data):null}function V0(e){if(!e)return null;let t=e;if(t.length>1&&t[0]===31&&t[1]===139)try{t=z0.gunzipSync(t)}catch{}try{return JSON.parse(t.toString("utf8"))}catch{return null}}function J0(e){let t=[],n=0,r=e.length,o=()=>{let s=0,a=0;for(;n<r;){let i=e[n++];if(s+=(i&127)*2**a,!(i&128))break;a+=7}return s};for(;n<r;){let s=o(),a=s>>>3,i=s&7;if(i===2){let c=o(),l=e.subarray(n,n+c);n+=c,a===1&&c===32&&t.push(l.toString("hex"))}else if(i===0)o();else if(i===5)n+=4;else if(i===1)n+=8;else break}return t}function X0(e,t){if(!Array.isArray(e))return[];let n=[];for(let r of e){if(!r||r.type!=="tool-call"||!Hd.has(r.toolName))continue;let o=Wd(r.toolName,r.args,t);!o||!o.command||n.push({id:r.toolCallId||null,tool:r.toolName,command:o.command,description:o.description||"",...o.paths?{paths:o.paths}:{}})}return n}function tS(e){let n=(typeof e=="string"?e:Array.isArray(e)?e.filter(r=>r&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join(`
|
|
164
|
+
`):"").match(eS);return n?n[1]:null}async function nS(e,t){if(!Gd)return cn;let{DatabaseSync:n}=Gd,r;try{r=new n(e,{readOnly:!0})}catch{return cn}try{let o=r.prepare("SELECT value FROM meta WHERE key = '0'").get()||r.prepare("SELECT value FROM meta LIMIT 1").get();if(!o)return cn;let s;try{s=JSON.parse(Buffer.from(String(o.value),"hex").toString("utf8"))}catch{return cn}let a=s.lastUsedModel||null,i=s.latestRootBlobId?zd(r,s.latestRootBlobId):null;if(!i)return{...cn,model:a};let c=[],l=[],u=[],f=null,p=[],g=null,S=()=>g?{turnId:g.id,...g.head?{turnHead:g.head}:{}}:{};for(let x of J0(i)){let _=V0(zd(r,x));if(!_)continue;let R=_.providerOptions?.cursor;if(R?.requestId&&p.push(R.requestId),R?.modelProviderMessageId&&p.push(R.modelProviderMessageId),_.role==="user"){let $=tS(_.content);$!=null&&(g={id:x,head:$||null});continue}if(_.role!=="assistant")continue;if(Array.isArray(_.content))for(let $ of _.content){let I=$?.providerOptions?.cursor?.modelName;I&&(f=I)}l.push(...X0(_.content,t).map(($,I)=>({...$,id:$.id||`${x}:${I}`,...S()}))),u.push(...Q0(_.content));let M=Z0(_.content);if(!M)continue;let A=[...new Set(u)];u=[],c.push({id:x,text:M,tools:A.length?A:void 0,commands:l,model:f}),l=[]}return{turns:c,trailingCommands:l,model:a,requestIds:p}}catch{return cn}finally{try{r.close()}catch{}}}async function Vd(e,t){let n=q0(e,t);if(!n)return null;let{turns:r,requestIds:o,model:s}=await nS(n.store,e);return{chatId:n.id,requestIds:o,models:[...new Set(r.map(a=>a.model).filter(Boolean))],configuredModel:s,updatedAtMs:n.updatedAtMs||null}}var G0,Z0,Q0,Gd,eS,cn,Jd=k(()=>{Ud();Kd();Ie();G0=process.env.BOSTRAT_CURSOR_CHATS||yt.join(Pt(),".cursor","chats");Z0=e=>typeof e=="string"?e.trim():Array.isArray(e)?e.filter(t=>t&&t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
165
|
+
`).trim():"",Q0=e=>Array.isArray(e)?e.filter(t=>t&&t.type==="tool-call"&&t.toolName).map(t=>t.toolName):[],Gd=process.getBuiltinModule?.("node:sqlite"),eS=/<user_query>\s*([\s\S]*?)\s*<\/user_query>/i;cn={turns:[],trailingCommands:[],model:null,requestIds:[]}});var tp={};Z(tp,{cursorUsageEnabled:()=>$o,cursorUsageStatus:()=>uS,forgetCursorBox:()=>fS,ingestCursorUsage:()=>pS,normalizeUsageEvent:()=>Qd,resetCursorUsageCache:()=>hS});import xo from"node:fs";import Di from"node:path";import rS from"node:os";async function sS({sinceMs:e,cookie:t,fetchImpl:n=fetch}){let r=[];for(let o=1;o<=20;o++){let s=await n(Zd,{method:"POST",headers:{"content-type":"application/json",origin:"https://cursor.com",cookie:`WorkosCursorSessionToken=${t}`},body:JSON.stringify({teamId:0,startDate:String(e),endDate:String(Date.now()),page:o,pageSize:Xd})});if(!s.ok)throw new Error(`cursor usage feed: HTTP ${s.status}`);let a=await s.json(),i=a?.usageEventsDisplay||a?.usageEvents||[];if(r.push(...i),i.length<Xd)break}return r}function Qd(e){if(!e)return null;let t=Number(e.timestamp)||null,n=e.tokenUsage||null,r=n?{input:n.inputTokens||0,output:n.outputTokens||0,cacheRead:n.cacheReadTokens||0,cacheWrite:n.cacheWriteTokens||0}:null,o=e.conversationId||null;return{id:[o||"?",t??"?",r?`${r.input}.${r.output}.${r.cacheRead}.${r.cacheWrite}`:"?"].join(":"),conversationId:o,ts:t,model:e.model||e.modelIntent||null,kind:e.kindLabel||e.kind||null,isHeadless:e.isHeadless===!0,tokens:r,vendorCents:n?.totalCents??null,chargedCents:e.chargedCents??null}}function ep(){try{return JSON.parse(xo.readFileSync(ko(),"utf8"))}catch{return{sinceMs:0,seen:[]}}}function aS(e){try{xo.mkdirSync(Di.dirname(ko()),{recursive:!0});let t=ko()+".tmp";xo.writeFileSync(t,JSON.stringify(e)),xo.renameSync(t,ko())}catch{}}async function lS({fetchImpl:e,now:t=Date.now()}={}){if(je.rows&&t-je.at<iS)return je.rows;let n=process.env.BOSTRAT_CURSOR_USAGE_COOKIE;if(!n)return null;let r=ep(),o=Math.max(r.sinceMs-6e4,t-24*36e5);try{let s=await sS({sinceMs:o,cookie:n,fetchImpl:e});je={at:t,rows:s.map(Qd).filter(Boolean),error:null}}catch(s){je={at:t,rows:null,error:String(s?.message||s)}}return je.rows}async function dS(e,t){let n=`${e.id}:${t.name}`;if(!Ao.has(n)){let r=await rt(e),o=new Set;for(let s of r)s.type==="cost.recorded"&&s.boxId===t.name&&s.payload?.cursorEventId&&o.add(s.payload.cursorEventId);Ao.set(n,o)}return Ao.get(n)}async function pS(e,t,{fetchImpl:n}={}){try{if(t?.agent!=="cursor"||!t.cwd||!$o())return;let r=await lS({fetchImpl:n});if(!r||!r.length)return;let o=await Vd(t.cwd,t.pinned?t.sessionId:null);if(!o?.chatId)return;let s=await dS(e,t),a=ep(),i=new Set(a.seen||[]),c=a.sinceMs||0;for(let l of r){if(!l.conversationId||l.conversationId!==o.chatId||s.has(l.id)||i.has(`${e.id}:${t.name}:${l.id}`))continue;s.add(l.id),i.add(`${e.id}:${t.name}:${l.id}`),l.ts&&l.ts>c&&(c=l.ts);let u=l.model||o.models[o.models.length-1]||"cursor-unknown",f=l.tokens||null,p=l.vendorCents!=null?l.vendorCents/100:0;!p&&f&&(p=es(u,f,l.ts??void 0)),!p&&l.chargedCents!=null&&(p=l.chargedCents/100),await Nt(e,{type:"cost.recorded",actor:"agent",source:"vendor",boxId:t.name,provider:"cursor",payload:{usd:p,model:u,...f?{tokens:f}:{},...l.vendorCents!=null?{vendorCents:l.vendorCents}:{},...l.chargedCents!=null?{chargedCents:l.chargedCents}:{},...l.kind?{kind:l.kind}:{},conversationId:l.conversationId,cursorEventId:l.id,ts:l.ts??void 0}})}aS({sinceMs:c,seen:[...i].slice(-cS)})}catch{}}function fS(e,t){Ao.delete(`${e}:${t}`)}function hS(){je={at:0,rows:null,error:null}}var oS,$o,Zd,Xd,iS,je,ko,cS,uS,Ao,np=k(()=>{Mt();Jd();ts();q();oS=process.env.BOSTRAT_STATE_DIR||Di.join(process.env.HOME||rS.tmpdir(),".bostrat"),$o=(e=process.env)=>!!e.BOSTRAT_CURSOR_USAGE_COOKIE,Zd="https://cursor.com/api/dashboard/get-filtered-usage-events",Xd=100;iS=5*6e4,je={at:0,rows:null,error:null},ko=()=>Di.join(oS,"cursor-usage.json");cS=5e3;uS=()=>({enabled:$o(),lastPollAt:je.at||null,error:je.error}),Ao=new Map;j("cursor-usage",({env:e})=>$o(e)?{class:"integration",mode:"timer",host:Zd,armedBy:["BOSTRAT_CURSOR_USAGE_COOKIE"],purpose:"per-task cost for cursor boxes"}:null)});function Gs(e){let t=String(e??"").trim();if(!t)return"";if(/\s/.test(t))return t;let n=/^[^@/\s]+@([^:/\s]+):/.exec(t);if(n)return n[1].toLowerCase();try{let r=new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`x://${t}`);if(r.hostname)return r.hostname.toLowerCase()}catch{}return t.toLowerCase()}function wS(e){let t=String(e?.name||"").trim();if(!t)throw new Error("egress: an entry needs a name");let n=[...new Set(Fi(e.host??e.hosts).map(Gs).filter(Boolean))];if(!n.length)throw new Error(`egress: "${t}" names no host`);let r=String(e.mode||"");if(!rp.includes(r))throw new Error(`egress: "${t}" has mode "${r}" \u2014 one of ${rp.join(", ")}`);return{name:t,hosts:n,host:n.join(", "),armedBy:Fi(e.armedBy).map(String),mode:r,class:String(e.class||"integration"),...e.purpose?{purpose:String(e.purpose)}:{}}}function pe(e,t,n){let r=t.filter(o=>e?.[o]);return r.length?r:[`integrations.json: ${n}`]}function yS(e){if(e.hosts.every(gS))return{verdict:"allowed",reason:"loopback \u2014 never leaves this machine"};let t=e.armedBy.length?` \u2014 remove ${e.armedBy.join(", ")}`:"";return e.class==="registry"?e.mode==="timer"?{verdict:"outside",reason:`the package registry is reached on a timer; local mode allows it by hand or on request only${t}`}:{verdict:"allowed",reason:`package registry, ${e.mode==="manual"?"by hand only":"on request only"}`}:Eo.includes(e.class)?{verdict:"allowed",reason:e.class==="plane"?"the plane this node joined":"forge host"}:{verdict:"outside",reason:`outside the local-mode allowlist${t}`}}function j(e,t){Ui.set(String(e),t)}async function op(){return await Promise.resolve().then(()=>(jr(),Hs)),await Promise.resolve().then(()=>(zs(),wl)),await Promise.resolve().then(()=>(Al(),kl)),await Promise.resolve().then(()=>(bi(),Si)),await Promise.resolve().then(()=>(Un(),di)),await Promise.resolve().then(()=>(Fu(),Du)),await Promise.resolve().then(()=>(cd(),ad)),await Promise.resolve().then(()=>(Ue(),ap)),await Promise.resolve().then(()=>(_d(),bd)),await Promise.resolve().then(()=>($d(),Ad)),await Promise.resolve().then(()=>(Od(),vd)),await Promise.resolve().then(()=>(Md(),Nd)),await Promise.resolve().then(()=>(Ld(),Bd)),await Promise.resolve().then(()=>(np(),tp)),await Promise.resolve().then(()=>($s(),Mc)),SS()}async function sp({env:e=process.env,local:t=!1}={}){let n=[],r=[];for(let[a,i]of Ui)try{for(let c of Fi(await i({env:e,local:t}))){if(!c)continue;let l=wS({name:a,...c});n.push(t?{...l,...yS(l)}:l)}}catch(c){r.push({name:a,error:String(c?.message||c).slice(0,200)})}let o=a=>Eo.indexOf(a.class)+1||Eo.length+1;n.sort((a,i)=>o(a)-o(i)||a.name.localeCompare(i.name));let s=n.filter(a=>a.verdict==="outside").map(a=>a.name);return{process:"node",mode:t?"local":"default",ok:s.length===0&&!(t&&r.length),...t?{allowlist:{classes:[...Eo],registry:"manual or request only",loopback:!0},outside:s}:{},rows:n,errors:r,note:"What the node process is configured to reach, with what armed it. Not listed: what the agent CLIs inside the boxes dial themselves \u2014 their model vendors, and anything a command they run reaches."}}function ip(e){let t=[`egress \u2014 node, mode: ${e.mode}`];e.rows.length||t.push(" (no outbound destination is configured)");for(let n of e.rows){let r=n.verdict==="outside"?"\u2717":n.verdict==="allowed"?"\u2713":"\xB7";t.push(`${r} ${n.name}: ${n.host} [${n.mode}]${n.purpose?` ${n.purpose}`:""}`),t.push(` armed by: ${n.armedBy.join(", ")||"(always on)"}${n.reason?`
|
|
166
|
+
${n.verdict}: ${n.reason}`:""}`)}for(let n of e.errors)t.push(`! ${n.name}: could not be read \u2014 ${n.error}`);return t.push(""),t.push(e.note),e.mode==="local"?t.push(e.ok?`
|
|
167
|
+
OK \u2014 ${e.rows.length} destination(s), all inside the local-mode allowlist (the plane, the forge host(s), the package registry by hand or on request)`:`
|
|
168
|
+
FAIL \u2014 ${e.outside.length} destination(s) outside the local-mode allowlist${e.errors.length?`, ${e.errors.length} unreadable`:""}`):t.push(`
|
|
169
|
+
${e.rows.length} destination(s). Default mode has no allowlist; local mode (BOSTRAT_LOCAL_MODE=1) judges each row.`),t}var rp,Eo,mS,gS,Qt,Fi,Ui,SS,q=k(()=>{rp=Object.freeze(["timer","manual","request"]),Eo=Object.freeze(["plane","forge","registry"]),mS=/^(localhost|.*\.localhost|127(?:\.\d{1,3}){3}|::1|\[::1\]|0\.0\.0\.0)$/i,gS=e=>mS.test(String(e||"").trim());Qt=(e=process.env)=>e?.npm_config_registry||e?.NPM_CONFIG_REGISTRY||"registry.npmjs.org",Fi=e=>Array.isArray(e)?e:e==null||e===""?[]:[e];Ui=new Map;SS=()=>[...Ui.keys()]});var ap={};Z(ap,{LOCAL_OFF_COPY:()=>up,MODE_DEFAULT:()=>Ki,MODE_LOCAL:()=>ln,OFF_LOCAL:()=>lp,STATE_DIR:()=>Zn,exposedBind:()=>_S,loadEnvFile:()=>Ro,localMode:()=>le,localModeFlag:()=>_t,localOff:()=>$S,localPublicHost:()=>Oo,modeOf:()=>AS,nodeEnvPath:()=>bt,normalizePlaneUrl:()=>lt,ntfyUrl:()=>Hi,parseEnvFile:()=>un,planeStatedMode:()=>kS,platformDefaults:()=>Gi,resolveHost:()=>cp,setPlaneMode:()=>xS,writeEnvFile:()=>zi});import vo from"node:fs";import Wi from"node:path";import bS from"node:os";function cp(e=process.env){let t=(e.BOSTRAT_HOST||"").trim();if(t!=="all")return t||(e.BOSTRAT_PLANE_URL?"127.0.0.1":void 0)}function _S(e=process.env){if(!e.BOSTRAT_PLANE_URL)return null;let t=cp(e);return t==="127.0.0.1"||t==="::1"||t==="localhost"?null:{host:t}}function _t(e=process.env){return TS.has(String(e?.BOSTRAT_LOCAL_MODE??"").trim().toLowerCase())}function xS(e,t=process.env){St=e==null?null:e===ln?ln:Ki;let n=_t(t);return{mode:St,flag:n,disagrees:St!=null&&n!==(St===ln)}}function le(e=process.env){return St!=null?St===ln:_t(e)}function Oo(e=process.env){return`http://localhost:${Number(e?.BOSTRAT_AGENT_PORT)||3362}`}function $S(e){let t=up[e];return{off:lp,feature:e,reason:t,error:t}}function Hi(e=process.env){return le(e)?"":String(e?.BOSTRAT_NTFY_URL||"")}function lt(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 un(e){let t;try{t=vo.readFileSync(e,"utf8")}catch{return{}}let n={};for(let r of t.split(`
|
|
170
|
+
`)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!s)continue;let a=s[2].trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n[s[1]]=a}return n}function Ro(e,t=process.env){let n=un(e);for(let[r,o]of Object.entries(n))r in t||(t[r]=o);return n}function zi(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
|
|
171
|
+
`).map(o=>o?`# ${o}`:"#"));for(let[o,s]of Object.entries(t))s==null||s===""||r.push(`${o}=${s}`);vo.mkdirSync(Wi.dirname(e),{recursive:!0}),vo.writeFileSync(e,r.join(`
|
|
172
|
+
`)+`
|
|
173
|
+
`,{mode:384}),vo.chmodSync(e,384)}function Gi(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 Zn,bt,ln,Ki,TS,St,kS,AS,lp,up,Ue=k(()=>{q();Zn=process.env.BOSTRAT_STATE_DIR||Wi.join(process.env.HOME||bS.tmpdir(),".bostrat"),bt=()=>Wi.join(Zn,"node.env");ln="local",Ki="default",TS=new Set(["1","true","on","yes"]);St=null;kS=()=>St;AS=(e=process.env)=>le(e)?ln:Ki,lp="local-mode",up=Object.freeze({loops:"Loops are off in local mode: this plane runs no scheduler.",push:"Phone notifications are off in local mode: this plane sends nothing to ntfy or web push.",share:"Share links are off in local mode: views are reachable on this machine only."});j("ntfy",({env:e,local:t})=>!t&&Hi(e)?{class:"notify",mode:"request",host:Hi(e),armedBy:["BOSTRAT_NTFY_URL"],purpose:"phone pages from this node"}:null)});var Pp={};Z(Pp,{NODE_IMAGE:()=>Ji,commandPlan:()=>Mp,flyToml:()=>Np,flyWizard:()=>JS,parseFlyFlags:()=>Cp,stageConfig:()=>jp});import Vi from"node:fs";import Tt from"node:path";import WS from"node:os";import KS from"node:readline/promises";import{execFile as zS}from"node:child_process";import{createRequire as GS}from"node:module";import{randomUUID as YS}from"node:crypto";function Np({app:e,region:t,nodeName:n=e,planeUrl:r=Ip,image:o=Ji}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
|
|
174
|
+
# Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
|
|
175
|
+
# No [http_service] and none should be added: the node dials OUT to the plane;
|
|
176
|
+
# nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
|
|
177
|
+
app = "${e}"
|
|
178
|
+
primary_region = "${t}"
|
|
179
|
+
# Swap absorbs agent-CLI memory spikes that would otherwise hang the whole
|
|
180
|
+
# guest (the 2026-08-13 hang class); much slower than RAM \u2014 scale memory for
|
|
181
|
+
# sustained multi-session use.
|
|
182
|
+
swap_size_mb = 1024
|
|
183
|
+
|
|
184
|
+
[build]
|
|
185
|
+
# The published node image (claude + cursor-agent + codex baked in, logged
|
|
186
|
+
# out), pinned to the bostrat-node version that wrote this file. Update with:
|
|
187
|
+
# npm i -g bostrat-node && bostrat-node fly (re-run is safe), or bump the tag.
|
|
188
|
+
image = "${o}"
|
|
189
|
+
|
|
190
|
+
[env]
|
|
191
|
+
PORT = "3362"
|
|
192
|
+
# $HOME on the volume: your agent logins, repos, and node state survive
|
|
193
|
+
# machine replacement (the "your login stays on your node" promise).
|
|
194
|
+
HOME = "/data/home"
|
|
195
|
+
BOSTRAT_PLANE_URL = "${r}"
|
|
196
|
+
BOSTRAT_NODE_ID = "${e}"
|
|
197
|
+
BOSTRAT_NODE_NAME = "${n}"
|
|
198
|
+
BOSTRAT_REPOS_ROOT = "/data/home/repos"
|
|
199
|
+
BOSTRAT_TMUX_SOCKET = "/tmp/tmux-0/default"
|
|
200
|
+
# claude refuses --dangerously-skip-permissions as root unless sandboxed;
|
|
201
|
+
# this dedicated Firecracker microVM IS the sandbox.
|
|
202
|
+
IS_SANDBOX = "1"
|
|
203
|
+
|
|
204
|
+
[[mounts]]
|
|
205
|
+
source = "node_data"
|
|
206
|
+
destination = "/data"
|
|
207
|
+
|
|
208
|
+
[[vm]]
|
|
209
|
+
# Agent CLIs are RAM-hungry; 2GB is the floor for one lead box.
|
|
210
|
+
# Scale later with: fly scale memory 4096 -a ${e}
|
|
211
|
+
size = "shared-cpu-2x"
|
|
212
|
+
memory = "2gb"
|
|
213
|
+
`}function Mp({app:e,org:t,region:n,sizeGb:r,token:o,dir:s}){let a=[`BOSTRAT_PLANE_TOKEN=${o}`];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> via stdin`,stdin:a.join(`
|
|
214
|
+
`)+`
|
|
215
|
+
`},{argv:["deploy",s,"-c",Tt.join(s,"fly.toml"),"-a",e,"--ha=false"],display:`fly deploy ${s} -c ${Tt.join(s,"fly.toml")} -a ${e} --ha=false`}]}function Cp(e=[]){let t={},n={"--app":"app","--org":"org","--region":"region","--size-gb":"sizeGb","--name":"name","--plane-url":"planeUrl","--token":"token","--image":"image"};for(let r=0;r<e.length;r++){let o=e[r];if(o==="--yes"||o==="-y")t.yes=!0;else if(n[o])t[n[o]]=e[++r]??"";else if(o.startsWith("--")&&o.includes("=")){let[s,...a]=o.split("=");n[s]?t[n[s]]=a.join("="):s==="--yes"&&(t.yes=!0)}}return t.sizeGb!=null&&(t.sizeGb=Number(t.sizeGb)||10),t}function jp({app:e,dest:t,toml:n}){let r=t||Tt.join(WS.homedir(),".bostrat","fly",e);Vi.mkdirSync(r,{recursive:!0});for(let o of["Dockerfile",".dockerignore","package.json","package-lock.json","src","dist","bin","node-entrypoint.sh"])Vi.rmSync(Tt.join(r,o),{recursive:!0,force:!0});return Vi.writeFileSync(Tt.join(r,"fly.toml"),n),{dir:r,manifest:["fly.toml"]}}async function VS({ask:e,output:t,exec:n,flag:r}){if(r)return r;try{let{stdout:o}=await No(["orgs","list","--json"],{exec:n}),s=JSON.parse(o),a=Array.isArray(s)?s.map(i=>i.Slug||i.slug).filter(Boolean):Object.keys(s);if(a.length===1)return t.write(`Org: ${a[0]} (your only org)
|
|
216
|
+
`),a[0];if(a.length>1)return await e(`Fly org (${a.join(" / ")})`,a[0])}catch{}return await e("Fly org slug (see `fly orgs list`)","personal")}async function JS({argv:e=[],input:t=process.stdin,output:n=process.stdout,exec:r,stageDest:o}={}){let s=Cp(e),a=KS.createInterface({input:t,output:n}),i=async(A,$)=>(await a.question($?`${A} [${$}]: `:`${A}: `)).trim()||$||"",c=A=>(a.close(),A);n.write(`bostrat-node fly \u2014 a node on YOUR Fly org, on your bill.
|
|
217
|
+
bostrat never sees your Fly account: this wizard only runs your own \`fly\` CLI.
|
|
218
|
+
|
|
219
|
+
`);try{await No(["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"),c(1)}try{let{stdout:A}=await No(["auth","whoami"],{exec:r});n.write(`\u2713 signed in to Fly as ${A.trim()}
|
|
220
|
+
`)}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"),c(1)}let l=await VS({ask:i,output:n,exec:r,flag:s.org}),u=s.app||await i("App name",`bostrat-node-${YS().slice(0,4)}`),f=s.region||await i("Region (see `fly platform regions`)","iad"),p=s.sizeGb||Number(await i("Volume size GB (logins + repos live here)","10"))||10,g=s.name||u,S=s.planeUrl||Ip,x=s.token||await i("Node token (minted in the bostrat setup chat \u2014 shown once)");if(!x)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.
|
|
221
|
+
`),c(1);let _=s.image||Ji,{dir:R}=jp({app:u,dest:o,toml:Np({app:u,region:f,nodeName:g,planeUrl:S,image:_})});n.write(`
|
|
222
|
+
wrote ${Tt.join(R,"fly.toml")} \u2014 deploys the prebuilt node image ${_}
|
|
223
|
+
(claude + cursor-agent + codex baked in, logged out; nothing builds on your machine)
|
|
224
|
+
|
|
225
|
+
Plan (your flyctl, your org, your bill):
|
|
226
|
+
`);let M=Mp({app:u,org:l,region:f,sizeGb:p,token:x,dir:R});for(let A of M)n.write(` $ ${A.display}
|
|
227
|
+
`);if(!s.yes&&(await i(`
|
|
228
|
+
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.
|
|
229
|
+
`),c(1);for(let A of M){n.write(`
|
|
230
|
+
\u2192 ${A.display}
|
|
231
|
+
`);try{let{stdout:$,stderr:I}=await No(A.argv,{stdin:A.stdin,exec:r}),E=`${$||""}${I||""}`.trim();E&&n.write(E.split(`
|
|
232
|
+
`).map(L=>` ${L}`).join(`
|
|
233
|
+
`)+`
|
|
234
|
+
`)}catch($){let I=`${$?.stdout||""}${$?.stderr||""}${$?.message||""}`;if(A.tolerate&&A.tolerate.test(I)){n.write(` (already exists \u2014 continuing)
|
|
235
|
+
`);continue}return n.write(`\u2717 failed: ${I.trim().split(`
|
|
236
|
+
`).slice(-4).join(`
|
|
237
|
+
`)}
|
|
238
|
+
fix and re-run \`bostrat-node fly\` \u2014 every step is safe to repeat.
|
|
239
|
+
`),c(1)}}return n.write(`
|
|
240
|
+
\u2713 deployed. The node dials out to the plane by itself \u2014 watch the bostrat setup
|
|
241
|
+
chat: the node step advances on its own within a minute.
|
|
242
|
+
logs: fly logs -a ${u}
|
|
243
|
+
redeploy: fly deploy ${R} -c ${Tt.join(R,"fly.toml")} -a ${u} --ha=false
|
|
244
|
+
Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
|
|
245
|
+
boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
|
|
246
|
+
`),c(0)}var Ip,qS,Ji,No,Bp=k(()=>{Ip="wss://plane.bostrat.ai/v1/node",qS=GS(import.meta.url)("../package.json").version,Ji=`ghcr.io/globocodes/bostrat-node:${qS}`;No=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let s=zS("fly",e,{timeout:6e5,maxBuffer:16*1024*1024},(a,i,c)=>a?o(Object.assign(a,{stdout:i,stderr:c})):r({stdout:i,stderr:c}));t!=null&&s.stdin?.end(t)})});Ue();ri();ei();import ne from"node:fs";import W from"node:path";import fn from"node:os";import{createRequire as Xi}from"node:module";import{execFile as XS,spawn as ZS}from"node:child_process";import{promisify as QS}from"node:util";import eb from"node:readline/promises";import{randomUUID as tb}from"node:crypto";import{fileURLToPath as nb}from"node:url";import Io from"node:fs";import dn from"node:fs/promises";import ES from"node:os";import Qn from"node:path";import vS from"node:readline";import{spawn as OS}from"node:child_process";var RS="^(ugrep|rg|2\\.1\\.[0-9]+|cursor-agent|codex|npm|node|MainThread)",IS="^(bostrat-|tmux|earlyoom|systemd|sshd)",NS=()=>["-m","10","-s","70","-r","600","--prefer",RS,"--avoid",IS],dp="BOSTRAT_OOM_GUARD_OWNER",MS=6e4,CS=5e3;function pp(e=process.env){return!["0","off","false","no"].includes(String(e.BOSTRAT_OOM_GUARD??"").trim().toLowerCase())}function fp(e=process.env){let t=e.BOSTRAT_STATE_DIR||Qn.join(e.HOME||ES.tmpdir(),".bostrat");return Qn.join(t,"oom-guard.pid")}function hp(e=process.env){if(e.BOSTRAT_EARLYOOM_BIN)return Io.existsSync(e.BOSTRAT_EARLYOOM_BIN)?e.BOSTRAT_EARLYOOM_BIN:null;let t=[...String(e.PATH||"").split(":").filter(Boolean),"/usr/bin","/usr/sbin","/usr/local/bin","/bin"];for(let n of t){let r=Qn.join(n,"earlyoom");if(Io.existsSync(r))return r}return null}async function mp({procRoot:e="/proc"}={}){let t=[];try{t=await dn.readdir(e)}catch{return[]}let n=[];for(let r of t){if(!/^\d+$/.test(r))continue;(await dn.readFile(Qn.join(e,r,"comm"),"utf8").catch(()=>"")).trim()==="earlyoom"&&n.push({pid:Number(r)})}return n}async function gp(e){let t=Number((await dn.readFile(e,"utf8").catch(()=>"")).trim());return Number.isInteger(t)&&t>0?t:null}async function wp({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc"}={}){if(!pp(e))return{state:"off"};if(t!=="linux")return{state:"unsupported",platform:t};let r=await mp({procRoot:n}),o=await gp(fp(e)),s=r.find(i=>i.pid===o);if(s)return{state:"own",pid:s.pid};if(r.length)return{state:"host",pid:r[0].pid};let a=hp(e);return a?{state:"stopped",bin:a}:{state:"absent"}}function Yi(e){switch(e?.state){case"own":return`earlyoom running under the node (pid ${e.pid}; acts at 10% memory available and 70% swap free)`;case"host":return`the host's own earlyoom is running (pid ${e.pid}) \u2014 the node starts none beside it`;case"stopped":return`earlyoom is installed (${e.bin}) and not running \u2014 the node starts it at boot`;case"absent":return"none \u2014 earlyoom is not installed, so memory exhaustion is left to the kernel's OOM killer";case"off":return"disabled (BOSTRAT_OOM_GUARD=0)";case"unsupported":return`not available on ${e.platform}`;default:return"not checked yet"}}function yp({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc",log:r=console.log,spawnImpl:o=OS,checkMs:s=MS,relaunchMs:a=CS}={}){let i=null,c={state:null},l=null,u=!1,f="",p=fp(e),g=M=>{c=M;let A=`[oom-guard] ${Yi(M)}`;return A!==f&&r(A),f=A,M},S=M=>{u||(clearTimeout(l),l=setTimeout(()=>x().catch(()=>{}),M),l.unref?.())},x=async()=>{if(u||i)return c;if(!pp(e))return g({state:"off"});if(t!=="linux")return g({state:"unsupported",platform:t});let M=await gp(p),A=await mp({procRoot:n});if(M&&A.some(E=>E.pid===M)){try{process.kill(M,"SIGTERM")}catch{}A=A.filter(E=>E.pid!==M)}if(A.length)return S(s),g({state:"host",pid:A[0].pid});let $=hp(e);if(!$)return S(s),g({state:"absent"});let I;try{I=o($,NS(),{stdio:["ignore","pipe","pipe"]})}catch(E){return r(`[oom-guard] could not start ${$}: ${E?.message||E}`),S(s),c}i=I;for(let E of[I.stdout,I.stderr])E&&vS.createInterface({input:E}).on("line",L=>r(`[earlyoom] ${L}`));return I.on("error",E=>{r(`[oom-guard] ${$}: ${E?.message||E}`),!(i!==I||I.pid)&&(i=null,S(s))}),I.on("exit",(E,L)=>{i===I&&(i=null,dn.rm(p,{force:!0}).catch(()=>{}),!u&&(r(`[oom-guard] earlyoom exited (${L||`code ${E}`}) \u2014 relaunching in ${Math.round(a/1e3)} s`),c={state:"stopped",bin:$},f="",S(a)))}),I.pid&&(await dn.mkdir(Qn.dirname(p),{recursive:!0}).catch(()=>{}),await dn.writeFile(p,`${I.pid}
|
|
247
|
+
`).catch(()=>{})),S(s),g({state:"own",pid:I.pid})},_=()=>{i&&(i.kill("SIGTERM"),Io.rmSync(p,{force:!0}))};return process.on("exit",_),{ready:x().catch(()=>c),status:()=>c,stop(){u=!0,clearTimeout(l),process.off("exit",_);let M=i;i=null,M&&(M.kill("SIGTERM"),Io.rmSync(p,{force:!0}))}}}cs();Ue();import jS from"node:fs";import Sp from"node:path";import PS from"node:os";var BS=()=>process.env.BOSTRAT_STATE_DIR||Sp.join(process.env.HOME||PS.tmpdir(),".bostrat"),LS=()=>Sp.join(BS(),"plane-link","public-host.json");var er=null;function DS(){if(er)return er;try{let e=JSON.parse(jS.readFileSync(LS(),"utf8"));er={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{er={viewBase:null}}return er}function FS(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),o=(r?r[2]:n).replace(/\/.*$/,"").toLowerCase(),s=/:(\d+)$/.exec(o)?.[1]??null,a=o.replace(/:\d+$/,"");return a?a==="localhost"?{proto:r?r[1].toLowerCase():"http",host:a,...s?{port:Number(s)}:{}}:{proto:r?r[1].toLowerCase():t,host:a}:null}var bp=e=>e?`${e.host}${e.port?`:${e.port}`:""}`:null;function _p(e=process.env){return le(e)?null:DS().viewBase}function Tp(e=process.env.BOSTRAT_PUBLIC_HOST){return FS(e,"https")}function xp(e=process.env.BOSTRAT_PLANE_URL){let t=String(e||"").trim();if(!t)return null;let n=/^(wss?|https?):\/\/([^/?#]+)/i.exec(t);return n?`${/^(wss|https)$/i.test(n[1])?"https":"http"}://${n[2]}`:null}ot();import US from"node:fs";import HS from"node:os";import kp from"node:path";var Ap=3*6e4;function qi(e=process.env){let t=e.BOSTRAT_STATE_DIR||kp.join(e.HOME||HS.tmpdir(),".bostrat");return kp.join(t,"heartbeat.json")}function $p(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return Ap;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):Ap}function Ep(e=qi()){try{let t=JSON.parse(US.readFileSync(e,"utf8"));if(!t||typeof t!="object")return null;let n=Number(t.ts),r=Number(t.pid);if(!Number.isFinite(n)||!Number.isFinite(r))return null;let o=Number(t.loopLagMs);return{pid:r,ts:n,loopLagMs:Number.isFinite(o)?o:null}}catch{return null}}ot();var Op="BOSTRAT_RESTART_NOTICE",X$=2*6e4;var vp=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Rp({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:vp(e),staleS:vp(t)!=null?Math.round(t/1e3):null})}Ie();Zs();q();var Lp=(e,t)=>{let n=String(e).split(".").map(Number),r=String(t).split(".").map(Number);if(n.some(Number.isNaN)||r.some(Number.isNaN))return!1;for(let o=0;o<Math.max(n.length,r.length);o++){let s=(n[o]||0)-(r[o]||0);if(s)return s<0}return!1},qe=QS(XS),Zi=W.dirname(nb(import.meta.url)),xt=W.resolve(Zi,".."),rb=W.join(Zi,"index.js"),ob="wss://plane.bostrat.ai/v1/node",pn=Xi(import.meta.url)("../package.json").version,P=(e,t)=>({name:e,level:"pass",detail:t}),Y=(e,t,n)=>({name:e,level:"warn",detail:t,fix:n}),Q=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function sb(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?P("node runtime",`${process.version} at ${process.execPath}`):Q("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function ib(e){return e.BOSTRAT_OWNER?Y("owner stamp",`BOSTRAT_OWNER=${String(e.BOSTRAT_OWNER).slice(0,12)}\u2026 is set \u2014 ignored by this release; on older releases it got every event refused (forgedUserId)`,"remove BOSTRAT_OWNER from node.env and any shell rc, then restart the node"):P("owner stamp","none (the plane infers the owner from the token)")}function ab(e){let t;try{t=ne.statSync(e)}catch{return Y("node.env",`${e} missing`,"run `bostrat-node init`")}let n=t.mode&511;return n&63?Y("node.env",`${e} mode ${n.toString(8)} \u2014 group/world readable and it can hold a key`,`chmod 600 ${e}`):P("node.env",`${e} (0600)`)}async function cb(e){let t=e.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";try{let{stdout:n}=await qe(t,["-V"],{timeout:5e3});return P("tmux",`${t} (${n.trim()})`)}catch{return Q("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function Dp(e,{required:t=!1}={}){if(await ni(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=Wr[e]?`${Wr[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?Q(e,r,o):Y(e,r,o)}async function lb(){let e=process.env.SHELL||"/bin/sh";try{let{stdout:t}=await qe(e,["-lic","gh --version"],{timeout:1e4}),n=String(t).match(/gh version [^\s]+/)?.[0]||"runs on the login-shell PATH";return P("gh (GitHub CLI)",n)}catch{return Y("gh (GitHub CLI)","no real gh on the login-shell PATH (the bostrat gh shim alone doesn't count) \u2014 PR tab, ship offers, and Fix-CI are unavailable on this node",Wr.gh)}}async function ub(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>Dp(t)));return e.some(t=>t.level==="pass")||e.push(Q("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 db(){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 ni(t,{failOpen:!1})?P(t,"resolves on the service PATH"):Y(t,`not on the service PATH \u2014 ${n}`,r)))}async function pb(){try{let t=Xi(W.join(xt,"src","node-cli.js"))("node-pty");return await new Promise((n,r)=>{let o=t.spawn("/bin/echo",["ok"],{cols:20,rows:5}),s=setTimeout(()=>r(new Error("spawn timeout")),5e3);o.onExit(()=>{clearTimeout(s),n()})}),P("node-pty","loads and spawns under this runtime")}catch(e){let t=`cd ${xt} && npm rebuild node-pty # with THIS node first on PATH \u2014 never the system npm`;try{let n=Xi(W.join(xt,"package.json")),r=W.join(W.dirname(n.resolve("node-pty/package.json")),"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper");ne.existsSync(r)&&!(ne.statSync(r).mode&73)&&(t=`chmod +x ${r} # node-pty ships it non-executable`)}catch{}return Q("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function fb(e){let t=e.BOSTRAT_CHROMIUM_BIN||"/usr/bin/chromium";if(ne.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"?Q:Y)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function hb(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?Q("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 Fp(e,{WebSocketImpl:t}={}){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN)return Y("plane link","BOSTRAT_PLANE_URL/TOKEN unset \u2014 node runs pure M1 (local only)","run `bostrat-node init`");let n=t||(await import("ws")).default,r=Date.now(),o=lt(e.BOSTRAT_PLANE_URL);return await new Promise(s=>{let a=new n(o,{headers:{authorization:`Bearer ${e.BOSTRAT_PLANE_TOKEN}`}}),i=null,c=null,l=f=>{clearTimeout(u);try{a.close()}catch{}s({...f,...i?{viewBase:i}:{},...c?{planeMode:c}:{}})},u=setTimeout(()=>l(Q("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-${tb().slice(0,8)}`,ephemeral:!0}))),a.on("message",f=>{try{let p=JSON.parse(f);p.type==="hello_ok"?(typeof p.viewBase=="string"&&p.viewBase&&(i=p.viewBase),c=p.mode==="local"?"local":"default",p.minNodeVersion&&Lp(pn,p.minNodeVersion)?l(Q("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${p.minNodeVersion} \u2014 this node is ${pn}; the real link is refused until it updates`,`bostrat-node self-update --to ${p.latestNodeVersion||p.minNodeVersion}`)):p.latestNodeVersion&&Lp(pn,p.latestNodeVersion)?l(Y("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${p.latestNodeVersion} is available (this node: ${pn})`,`bostrat-node self-update --to ${p.latestNodeVersion}`)):l(P("plane link",`hello_ok in ${Date.now()-r}ms (${o})`))):p.type==="error"&&l(Q("plane link",`plane said: ${p.code} ${p.message||""}`,"check the token"))}catch{}}),a.on("error",f=>l(Q("plane link",`${f?.message||f}`,"check the URL, the token, and the plane's IP gate")))})}function mb(e,t=null){let n=_t(e),r=t?.planeMode??null;return!n&&r!=="local"?null:r===null?P("mode","local (BOSTRAT_LOCAL_MODE; no plane answered to confirm it)"):n&&r==="local"?P("mode","local (BOSTRAT_LOCAL_MODE and the plane's hello_ok agree)"):r==="local"?Y("mode","local \u2014 the plane runs local mode but BOSTRAT_LOCAL_MODE is unset here; the node follows the plane","set BOSTRAT_LOCAL_MODE=1 in node.env so boot-time decisions agree with the plane"):Y("mode","default \u2014 BOSTRAT_LOCAL_MODE is set here but the plane does not run local mode; the node follows the plane","unset BOSTRAT_LOCAL_MODE, or start the plane with PLANE_LOCAL_MODE=1")}var Up=(e,t=null)=>_t(e)||t?.planeMode==="local";async function Hp(e,t=null){return await op(),sp({env:e,local:Up(e,t)})}function gb(e){if(e.mode!=="local")return null;let t=[...new Set(e.rows.flatMap(o=>o.hosts))];if(e.ok)return P("egress",`${e.rows.length} destination(s), all inside the local-mode allowlist (${t.join(", ")||"none"})`);let n=e.rows.filter(o=>o.verdict==="outside").map(o=>`${o.name} \u2192 ${o.host}`),r=e.errors.map(o=>`${o.name} (unreadable)`);return Q("egress",`outside the local-mode allowlist: ${[...n,...r].join("; ")}`,"`bostrat-node doctor --egress` lists each destination with what armed it; remove those keys, then run doctor again")}async function wb(e,t){return Up(e,t)?gb(await Hp(e,t)):null}async function yb(e,t={},n=console.log){let r=e.BOSTRAT_PLANE_URL&&e.BOSTRAT_PLANE_TOKEN?await Fp(e,t):null,o=await Hp(e,r);if(t.json)n(JSON.stringify(o,null,2));else{for(let s of ip(o))n(s);o.rows.some(s=>s.class==="plane")||n(`
|
|
248
|
+
note: no BOSTRAT_PLANE_URL in node.env or this shell. If the service takes it from elsewhere, the running agent's own report is GET /api/egress on the node.`)}return o}function Sb(e){let t=`nightly export: ${e.s3?.backup?"armed by BACKUP_S3_*":"off (BACKUP_S3_* unset)"}`,n=e.s3?.content==="CONTENT_S3"?"armed by CONTENT_S3_*":e.s3?.content==="BACKUP_S3"?"armed by BACKUP_S3_* (CONTENT_S3_* unset \u2014 the fallback)":null;return e.s3?.content==="file"?P("video blobs","ready \u2014 this plane runs without a database and keeps video on its own disk; no S3 block is involved"):e.state==="ready"?P("video blobs",`ready \u2014 ${n||"armed"}; ${t}`):e.state==="needs-s3"?P("video blobs",`off \u2014 no S3 block is armed for video (CONTENT_S3_* and BACKUP_S3_* unset on the plane); \`bostrat-mock add\` refuses mp4/webm, text and PNG mocks are unaffected; ${t}`):e.state==="unreachable"?Y("video blobs",`unreachable \u2014 ${n||"an S3 block is armed"} but the bucket failed the plane's probe; video mocks are refused; ${t}`,"check the bucket name, region, endpoint and credentials on the plane (GET /plane/admin/health \u2192 videoBlobs.error); the plane probes again within the hour"):P("video blobs",`not probed yet \u2014 ${n||"an S3 block is armed"}; the plane answers once its first bucket probe lands; ${t}`)}async function bb(e,t){if(!e.BOSTRAT_PLANE_URL||!e.BOSTRAT_PLANE_TOKEN||t?.level==="fail")return null;let n=await Il({env:e});return n&&n.source==="plane"?Sb(n):null}function _b(){let e;try{e=JSON.parse(ne.readFileSync(W.join(Zn,"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 Q("content outbox",`${n} op(s) PARKED \u2014 the plane refuses them (e.g. ${r?.op} ${r?.family}/${r?.id}: ${r?.error})`,"fix the plane-side cause; parked ops re-drive on their own once it accepts them")}return t>20?Y("content outbox",`${t} ops queued \u2014 the plane is unreachable, slow, or refusing the op at the head`,"check `plane link` above and the agent log for a [content-plane] ALARM; the queue drains on its own once the plane accepts again"):P("content outbox",t?`${t} op(s) in flight`:"drained")}async function Tb(e){let t=await Ul({env:e}),n=Hl(t);return t.available?P("box caps",n):e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID?Y("box caps",n,"boxes run under nice only on this node; if Fly's init mounts /sys/fs/cgroup read-only this is the expected state (blueprint BP-NG-I4)"):P("box caps",n)}async function xb(e){let t=await wp({env:e}),n=Yi(t);return t.state==="absent"?Y("oom guard",n,"install earlyoom (apt install earlyoom) \u2014 the node starts it with its own tuning at the next boot"):P("oom guard",n)}async function kb(e){let t=await Sc({env:e}),n=bc(t);return t.level==="misconfigured"?Q("box containment",n,"fix the user (scripts/pi/box-user-setup.sh) or unset BOSTRAT_BOX_USER in node.env, then restart"):t.level==="root-capable"?Y("box containment",n,"opt in to a dedicated box uid: BP-AU-I10 runbook (scripts/pi/box-user-setup.sh, then BOSTRAT_BOX_USER in node.env)"):t.level==="uid"&&(t.problems.length||t.auditd?.rule!==!0||!t.auditd?.readable)?Y("box containment",n,"re-run scripts/pi/box-user-setup.sh (idempotent) \u2014 it installs the auditd rule, the log group and the mirror"):P("box containment",n)}function Ab(e){let t=as(e),n=dc(t);return t.unknown?.length?Y("audit guard",n,`BOSTRAT_AUDIT_GUARD names unknown rule(s): ${t.unknown.join(", ")}`):P("audit guard",n)}function $b(e){if(e.BOSTRAT_STATE_REMOTE)return P("state remote",`${e.BOSTRAT_STATE_REMOTE} (this node's own \u2014 never another node's repo)`);let t=/^(on|1|true)$/i.test(String(e.BOSTRAT_STATE_SYNC||""));return P("state remote",t?"unset \u2014 local git mirror on (BOSTRAT_STATE_SYNC=on), nothing pushes":"unset \u2014 git export off; the plane holds node state (set BOSTRAT_STATE_REMOTE for an off-box copy)")}function Eb(e,t){let n=t?.planeMode?t.planeMode==="local":_t(e),r=n?null:t?.viewBase??null,o=n?null:_p(e),s=Tp(e.BOSTRAT_PUBLIC_HOST),a=(()=>{let i=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(i)return`${i.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let c=xp(e.BOSTRAT_PLANE_URL);return c?`${c}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(r){let i=s&&s.host!==r?`; BOSTRAT_PUBLIC_HOST=${s.host} is set but the plane's value wins`:"";return P("public host",`views https://<slug>.${r}/ (plane hello_ok)${i} \xB7 track links ${a}`)}return o?P("public host",`views https://<slug>.${o}/ (persisted from the last hello) \xB7 track links ${a}`):s?P("public host",`views ${s.proto}://<slug>.${bp(s)}/ (BOSTRAT_PUBLIC_HOST${n?", local mode: this machine only":""}) \xB7 track links ${a}`):n?Q("public host",`none \u2014 \`bostrat-view up\` refuses on this node (local mode: views are served by the node itself, and BOSTRAT_PUBLIC_HOST is unset) \xB7 track links ${a}`,`set BOSTRAT_PUBLIC_HOST=${Oo(e)} in node.env (\`bostrat-node init --local\` writes it)`):Q("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${a}`,"link a plane that sets PLANE_VIEW_BASE (bostrat-node init), or set BOSTRAT_PUBLIC_HOST in node.env for a plane-less node")}async function Wp(e,t={}){let n=[];n.push(await sb()),n.push(ab(t.envFile||bt())),n.push(await cb(e)),n.push(await Tb(e)),n.push(await xb(e)),n.push(Ab(e)),n.push(await kb(e)),n.push(...await ub()),n.push(await Dp("git",{required:!0})),n.push(await lb()),n.push(...await db()),n.push(await pb()),n.push(fb(e)),n.push(hb(e)),n.push(ib(e));let r=await Fp(e,t);n.push(r);let o=mb(e,r);o&&n.push(o),n.push(Eb(e,r));let s=await bb(e,r);s&&n.push(s);let a=await wb(e,r);return a&&n.push(a),n.push(_b()),n.push($b(e)),n}function Kp(e,t=console.log){let n={pass:"\u2713",warn:"!",fail:"\u2717"};for(let s of e)t(`${n[s.level]} ${s.name}: ${s.detail}`),s.fix&&s.level!=="pass"&&t(` fix: ${s.fix}`);let r=e.filter(s=>s.level==="fail").length,o=e.filter(s=>s.level==="warn").length;return t(r?`
|
|
223
249
|
FAIL \u2014 ${r} blocking, ${o} warnings`:`
|
|
224
|
-
OK \u2014 0 blocking, ${o} warnings`),r===0}async function
|
|
250
|
+
OK \u2014 0 blocking, ${o} warnings`),r===0}async function vb({envFile:e=bt(),input:t=process.stdin,output:n=process.stdout,local:r=!1}={}){let o=un(e),s=eb.createInterface({input:t,output:n}),a=async(A,$)=>(await s.question($?`${A} [${$}]: `:`${A}: `)).trim()||$||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
|
|
225
251
|
you type those inside each box, later (box-auth-policy).
|
|
226
252
|
|
|
227
|
-
`);let
|
|
228
|
-
`);let
|
|
229
|
-
`);let
|
|
253
|
+
`);let i=await a("Plane URL",o.BOSTRAT_PLANE_URL||ob),c=lt(i);c!==i.trim()&&n.write(` \u2192 using ${c}
|
|
254
|
+
`);let l=await a("Node token (minted plane-side; stored 0600)",o.BOSTRAT_PLANE_TOKEN);o.BOSTRAT_OWNER&&n.write(` \u2192 dropping BOSTRAT_OWNER from node.env \u2014 the plane infers the owner from the token; a stale id here got every event refused.
|
|
255
|
+
`);let u=await a("Node name",o.BOSTRAT_NODE_NAME||fn.hostname().split(".")[0]),f=await a("Repos root",o.BOSTRAT_REPOS_ROOT||W.join(fn.homedir(),"Documents")),p=await a("State remote (per-node private repo; empty = local-only)",o.BOSTRAT_STATE_REMOTE||""),g=(await a("Route NEW claude boxes through a BYO API key? (y/N)",o.BOSTRAT_CLAUDE_USE_API_KEY==="1"?"y":"N")).toLowerCase().startsWith("y");g&&n.write(`
|
|
230
256
|
BYO API key (box-auth-policy rule 5): claude boxes on this node bill to YOUR key,
|
|
231
257
|
injected per box, stored 0600 in node.env, never sent to the plane.
|
|
232
258
|
\u2022 create/copy a key: https://console.anthropic.com/settings/keys
|
|
233
259
|
\u2022 set a monthly spend limit while you're there \u2014 the key is live.
|
|
234
260
|
|
|
235
|
-
`);let
|
|
236
|
-
`),s.close();let
|
|
261
|
+
`);let S=g?await a("ANTHROPIC_API_KEY (starts sk-ant-)",o.ANTHROPIC_API_KEY):"";g&&S&&!/^sk-ant-/.test(S)&&n.write(` ! that doesn't look like an Anthropic key (expected sk-ant-\u2026) \u2014 saved as-is; re-run init to correct.
|
|
262
|
+
`),s.close();let x={...Gi(),...o,BOSTRAT_PLANE_URL:c,BOSTRAT_PLANE_TOKEN:l,BOSTRAT_NODE_NAME:u,BOSTRAT_NODE_ID:o.BOSTRAT_NODE_ID||u,BOSTRAT_REPOS_ROOT:f,BOSTRAT_STATE_REMOTE:p,BOSTRAT_CLAUDE_USE_API_KEY:g?"1":"0",ANTHROPIC_API_KEY:g?S:o.ANTHROPIC_API_KEY,...r?{BOSTRAT_PUBLIC_HOST:o.BOSTRAT_PUBLIC_HOST||Oo({...o,...process.env})}:{}};delete x.BOSTRAT_OWNER,zi(e,x,{header:`bostrat node config \u2014 written by \`bostrat-node init\` ${new Date().toISOString()}
|
|
237
263
|
0600: BOSTRAT_PLANE_TOKEN always lives here, ANTHROPIC_API_KEY may. Never commit.
|
|
238
264
|
Bind host: unset = loopback-only while plane-linked; BOSTRAT_HOST=all restores bind-all (LAN).`}),n.write(`
|
|
239
265
|
wrote ${e}
|
|
240
266
|
|
|
241
|
-
`);let
|
|
242
|
-
`));return
|
|
243
|
-
`)}catch{}let r
|
|
267
|
+
`);let _={...x,...process.env},R=await Wp(_,{envFile:e}),M=Kp(R,A=>n.write(A+`
|
|
268
|
+
`));return M&&n.write("\nnext: `bostrat-node run` (foreground) or `bostrat-node install-service`\n"),{ok:M,results:R}}var Ob="SIGUSR2",Rb=5*6e4,Ib=1e4,Mo=W.join(Zn,"self-update","supervisor.pid");function Nb({spawnChild:e,exit:t=l=>process.exit(l),now:n=Date.now,setTimeoutImpl:r=setTimeout,clearTimeoutImpl:o=clearTimeout,killGraceMs:s=15e3,rollbackGraceMs:a=Rb,stall:i=null,log:c=console}={}){let l=null,u=0,f=!1,p="update",g=0,S=null,x=null,_=null,R=0,M=0,A=0,$=!1,I=i&&i.staleMs>0?i.staleMs:0,E=i?.checkMs>0?i.checkMs:Ib,L=()=>{S&&o(S),S=null},fe=()=>{l.kill("SIGTERM"),x=r(()=>l?.kill("SIGKILL"),s),x.unref?.()},hn=null,kt=0,Co=()=>{let B=null;try{B=i.readHeartbeat()}catch{}return B&&B.pid===l.pid&&Number.isFinite(B.ts)&&B.ts!==hn&&(hn=B.ts,kt=Math.max(kt,Math.min(B.ts,n()))),n()-kt},tr=()=>{if(!l||$||f||!I)return!1;let B=Co();return B<I?!1:(M++,A=B,c.error?.(`[bostrat-node] the agent (pid ${l.pid}) has written no heartbeat for ${Math.round(B/1e3)} s \u2014 stalled; relaunching it in place (boxes keep running on the host tmux server; stall relaunch #${M})`),p="stall",f=!0,fe(),!0)},nr=()=>{I&&(_&&o(_),_=r(()=>{_=null,tr(),nr()},E),_.unref?.())},At=(B=null)=>{let Te=e(B);return l=Te,u=n(),hn=null,kt=u,Te.on("exit",(gn,he)=>mn(Te,gn,he)),_||nr(),Te},mn=(B,Te,gn)=>{if(B!==l)return;if(l=null,x&&o(x),x=null,f){f=!1,Ve(p);return}let he=gn?1:Te??1;if(!$&&he!==0&&n()<g){let rr=g-n();c.error?.(`[bostrat-node] the agent exited (code ${he}) right after a self-update restart \u2014 holding ${Math.ceil(rr/1e3)} s for the updater's rollback signal`),S=r(()=>t(he),rr);return}t(he)},Ve=(B="update")=>{R++,B==="stall"?c.log?.(`[bostrat-node] relaunched the agent after a stall (restart #${R}, stall relaunch #${M})`):(g=n()+a,c.log?.(`[bostrat-node] restarting the agent (self-update, restart #${R})`)),p="update",At(B==="stall"?{at:n(),staleMs:A}:null)};return{start:()=>At(),restart(){if($=!1,L(),p="update",!l){Ve("update");return}f||(f=!0,fe())},checkStall:tr,forward(B){$=!0,l?l.kill(B):(L(),t(1))},get child(){return l},get state(){return{alive:!!l,restartPending:f,restartReason:p,holding:!!S,restarts:R,stallRelaunches:M,stopping:$}}}}function Mb({envFile:e=bt()}={}){Ro(e),process.title="bostrat-node";let t=process.env.BOSTRAT_NODE_BIN||process.execPath,n={...process.env,BOSTRAT_RUN_SUPERVISOR_PID:String(process.pid),[dp]:"supervisor"};yp();try{ne.mkdirSync(W.dirname(Mo),{recursive:!0}),ne.writeFileSync(Mo,`${process.pid}
|
|
269
|
+
`)}catch{}let r=$p(process.env),o=qi(process.env);console.log(r?`[bostrat-node] stall watchdog: relaunch the agent after ${Math.round(r/1e3)} s without a heartbeat (${o})`:"[bostrat-node] stall watchdog: off (BOSTRAT_HEARTBEAT_STALE_MS)");let s=Nb({spawnChild:a=>ZS(t,[rb],{cwd:xt,stdio:"inherit",env:a?{...n,[Op]:Rp(a)}:n}),stall:r?{readHeartbeat:()=>Ep(o),staleMs:r}:null});for(let a of["SIGINT","SIGTERM"])process.on(a,()=>s.forward(a));return process.on(Ob,()=>s.restart()),process.on("exit",()=>{try{ne.readFileSync(Mo,"utf8").trim()===String(process.pid)&&ne.rmSync(Mo,{force:!0})}catch{}}),s.start()}function Cb({agentDir:e=xt,nodeBin:t=process.execPath,envFile:n=bt(),home:r=fn.homedir()}={}){let o=W.dirname(t),s=W.join(W.basename(Zi),"index.js");return`# bostrat node \u2014 written by \`bostrat-node install-service\`. Config lives in
|
|
244
270
|
# ${n} (edit + \`systemctl --user restart bostrat-node\`), not here.
|
|
245
271
|
[Unit]
|
|
246
272
|
Description=bostrat node \u2014 box runtime dialing out to the coordination plane (plane-p1-package-node-scope-2026-07-14.md)
|
|
@@ -264,7 +290,7 @@ RestartSec=2
|
|
|
264
290
|
|
|
265
291
|
[Install]
|
|
266
292
|
WantedBy=default.target
|
|
267
|
-
`}function
|
|
293
|
+
`}function jb({agentDir:e=xt,nodeBin:t=process.execPath,home:n=fn.homedir()}={}){let r=W.dirname(t),o=`${n}/Library/Logs/bostrat`;return`<?xml version="1.0" encoding="UTF-8"?>
|
|
268
294
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
269
295
|
<plist version="1.0">
|
|
270
296
|
<dict>
|
|
@@ -286,14 +312,18 @@ WantedBy=default.target
|
|
|
286
312
|
<key>StandardErrorPath</key><string>${o}/node.err.log</string>
|
|
287
313
|
</dict>
|
|
288
314
|
</plist>
|
|
289
|
-
`}function
|
|
315
|
+
`}function Pb(e=process.platform,t=fn.homedir()){return e==="darwin"?{kind:"launchd",file:W.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:W.join(t,".config","systemd","user","bostrat-node.service")}}async function Bb({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=xt}={}){let{kind:s,file:a}=Pb(n);if(!e&&o.split(W.sep).includes("_npx"))return r("\u2717 running from the npx cache \u2014 a service must point at a durable install."),r(" fix: npm install -g bostrat-node && bostrat-node install-service"),1;if(e){s==="systemd"?(await qe("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),ne.rmSync(a,{force:!0}),await qe("systemctl",["--user","daemon-reload"])):(await qe("launchctl",["unload","-w",a]).catch(()=>{}),ne.rmSync(a,{force:!0})),r(`removed ${a}`);return}ne.mkdirSync(W.dirname(a),{recursive:!0}),s==="systemd"?(ne.writeFileSync(a,Cb()),await qe("systemctl",["--user","daemon-reload"]),t&&await qe("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${a}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(ne.mkdirSync(W.join(fn.homedir(),"Library","Logs","bostrat"),{recursive:!0}),ne.writeFileSync(a,jb()),t&&await qe("launchctl",["load","-w",a]),r(`installed ${a}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function $E(e=process.argv.slice(2)){let t=e[0],n=bt();if(t==="--version"||t==="-v"||t==="version")return console.log(pn),0;if(t==="init")return(await vb({envFile:n,local:e.includes("--local")})).ok?0:1;if(t==="doctor"){let r={...un(n),...process.env};return e.includes("--egress")?(Ro(n),(await yb({...un(n),...process.env},{json:e.includes("--json")})).ok?0:1):Kp(await Wp(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return Mb({envFile:n}),null;if(t==="install-service")return await Bb({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(Bp(),Pp));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:s}=await Promise.resolve().then(()=>(bi(),Si)),{detectInstallKind:a}=await Promise.resolve().then(()=>(jr(),Hs)),i=a(),c=e.indexOf("--to"),l=c>=0?String(e[c+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:pn,installKind:i,policy:s({kind:i}),status:await o()},null,2)),0;if(!l)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let u=await r({to:l,kind:i,reason:"cli",force:!0});return u.ok?(console.log(`\u2713 self-update ${u.from??"?"} \u2192 ${u.to} started (${u.kind}) \u2014 status: ${u.statusFile}; the node restarts when the install completes`),0):(console.error(`\u2717 not started: ${u.reason}`),1)}if(t==="cli-update"){let{updateNow:r,CLIS:o}=await Promise.resolve().then(()=>(Un(),di)),s=Object.keys(o),a=e.indexOf("--to"),i=a>=0?String(e[a+1]||""):null,c=e.slice(1).filter((p,g,S)=>!p.startsWith("--")&&S[g-1]!=="--to"),l=c[0]||"codex";if(c.length>1||!s.includes(l)||a>=0&&!i)return console.error(`bostrat-node cli-update [${s.join("|")}] [--to X.Y.Z] (default: codex, onto the registry's latest release)`),1;console.log(`updating ${l}${i?` to ${i}`:""} \u2026`);let u=await r(l,{to:i});if(u.ok&&u.status==="current")return console.log(`\u2713 ${l} ${u.version} is already ${i?"installed":"the current release"}`),0;if(u.ok)return console.log(`\u2713 ${l} ${u.from??"(not launching)"} \u2192 ${u.version} (${u.via==="vendor"?`${l}'s own updater`:"pinned install, verified"}) \u2014 boxes started from now on run it`),0;let f=u.rolledBack===!0?` \u2014 rolled back to ${u.from}`:u.rolledBack===!1?` \u2014 the rollback to ${u.from} failed too; ${l} may not launch`:"";return console.error(`\u2717 ${l} not updated: ${u.error}${f}`),1}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
|
|
290
316
|
|
|
291
|
-
usage: bostrat-node <init [--local] | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
|
|
317
|
+
usage: bostrat-node <init [--local] | doctor [--egress [--json]] | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | cli-update [codex|claude] | --version>
|
|
292
318
|
|
|
293
319
|
init interactive setup \u2192 writes ${n}, then runs doctor
|
|
294
320
|
(--local: also writes BOSTRAT_PUBLIC_HOST for a local-mode plane)
|
|
295
321
|
doctor check this machine (CLIs, tmux, node-pty, plane reachability)
|
|
322
|
+
doctor --egress list every outbound destination this node is configured to reach, with
|
|
323
|
+
what armed it; in local mode, exit 1 on any outside the allowlist
|
|
296
324
|
run start the node in the foreground (sources node.env)
|
|
297
325
|
install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
|
|
298
326
|
fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
|
|
299
|
-
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)
|
|
327
|
+
self-update move this install onto a release (--to X.Y.Z; --status shows the last one)
|
|
328
|
+
cli-update update a vendor CLI now: codex (default) or claude; --to X.Y.Z pins a release.
|
|
329
|
+
The only way they move in local mode, where no update runs on a timer`),t?1:0}export{Ob as RESTART_SIGNAL,Rb as ROLLBACK_GRACE_MS,Ib as STALL_CHECK_MS,Mo as SUPERVISOR_PID_FILE,mb as checkMode,Nb as createRunSupervisor,gb as describeEgress,Sb as describeVideoBlobs,Up as egressIsLocal,vb as init,Bb as installService,jb as launchdPlist,$E as main,Hp as nodeEgress,Kp as printDoctor,Mb as runAgent,Wp as runDoctor,yb as runEgressDoctor,Pb as servicePaths,Cb as systemdUnit};
|