bostrat-node 1.17.7 → 1.17.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- var y=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function f(e,a,o){let i=await fetch(`${y}${a}`,{method:e,headers:o?{"content-type":"application/json"}:void 0,body:o?JSON.stringify(o):void 0}),s=await i.json().catch(()=>({}));if(!i.ok)throw Object.assign(new Error(s.error||`HTTP ${i.status}`),{status:i.status,data:s});return s}function u(e){console.error(`[bostrat-blueprint] ${e}`),process.exit(1)}function v(e,a){if(console.error(`[bostrat-blueprint] refused: ${e.error}`),e.code==="stale-base"){if(console.error(` plane holds v${e.current}; this copy was built on v${e.yourBase}.`),e.drift?.length){console.error(" item-level difference:");for(let o of e.drift)console.error(` ${String(o.itemId).padEnd(12)} plane: ${String(o.plane).padEnd(7)} file: ${o.file}`)}else console.error(" no item differs \u2014 the newer version changed prose only.");console.error(" Bring this copy up to date, then republish:"),console.error(" git fetch origin && git merge origin/main # siblings' ticks land on main with their PRs"),console.error(" (copy any ticked item you still lack VERBATIM \u2014 never invent a sibling's note)"),console.error(` bostrat-blueprint show && bostrat-blueprint update ${a}`),console.error(` Or, once the file carries everything above: bostrat-blueprint update --base ${e.current} ${a}`)}else e.code==="untick"&&(console.error(` would un-tick: ${e.untick.join(", ")} (plane v${e.current} has them [x]).`),console.error(" Copy their ticks + status notes into the file (merge origin/main first), then republish."));console.error(" --force publishes the file exactly as it is (un-ticking the items above). Only when that is the intent."),process.exit(1)}function w(e){if(e){console.log(` parsed: ${e.sections.recognized} recognized section(s), ${e.items.total} item(s) (${e.items.bindable} bindable)`);for(let a of e.issues??[])console.log(` \u26A0 ${a.message}`)}}var r=process.argv.slice(2),g=r.shift();if(g==="add"||g==="update"){let e=null,a=null,o=null,i=null,s=null,l=!1;for(let n=0;n<r.length;n++)r[n]==="--circuit"?e=r[++n]:r[n]==="--new-circuit"?a=r[++n]:r[n]==="--name"?o=r[++n]:r[n]==="--base"?s=r[++n]:r[n]==="--force"?l=!0:i=r[n];i||u(`usage: bostrat-blueprint ${g} [--circuit <name-or-id>] [--new-circuit "<name>"] [--name "<title>"] [--base <v>] [--force] <file.md>`),s!=null&&!/^[1-9]\d*$/.test(String(s))&&u(`--base takes a version number (what \`show\` prints), got "${s}"`);try{let n=await(await import("node:fs/promises")).readFile(i,"utf8"),h=null,m=null;try{let{execFileSync:t}=await import("node:child_process"),p=await import("node:path"),c=p.resolve(i),b=t("git",["rev-parse","--show-toplevel"],{cwd:p.dirname(c),encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),$=p.relative(b,c);$&&!$.startsWith("..")&&(h=$.split(p.sep).join("/"),m=b)}catch{}let d=await f("POST","/api/blueprints/publish",{cwd:process.cwd(),circuit:e,newCircuit:a,name:o,markdown:n,base:s==null?null:Number(s),force:l,path:h,root:m});console.log(`[bostrat-blueprint] published \u201C${d.blueprint.name}\u201D v${d.blueprint.version} on circuit \u201C${d.circuit.name}\u201D${d.base?` (on v${d.base})`:""}${l?" (forced)":""}`),w(d.report),d.linked&&console.log(` This Track is now in circuit \u201C${d.circuit.name}\u201D (it was in none) \u2014 the blueprint's item ids in a closing message are launch controls from here.`),d.blueprint.version===1&&console.log(" The circuit page now carries this blueprint; PRs/commits mentioning BP ids show as evidence \u2014 tick [x] + a *(done \u2026)* note in the same PR as the item's work.")}catch(n){n.status===409&&n.data?.code&&v(n.data,i),u(n.message)}}else if(g==="show"||g==="report")try{let e=await f("GET",`/api/blueprints/show?cwd=${encodeURIComponent(process.cwd())}${r[0]?`&circuit=${encodeURIComponent(r[0])}`:""}`);if(console.log(`[bostrat-blueprint] \u201C${e.blueprint.name}\u201D v${e.blueprint.version} (circuit ${e.blueprint.circuitId})`),w(e.report),g==="show"){let a=!!e.graph?.edges,o=e.readyAt||"merged",i=new Set,s=t=>{let p=Array.isArray(t.waits)&&t.waits.length?t.waits:null;return p?p.map(c=>c.gate&&c.gate!==o?(i.add(c.gate),`${c.itemId} ${c.gate}`):c.itemId).join(", "):(t.waitsOn??[]).join(", ")},l=t=>t.bindable?t.done?"done":a?t.ready?`ready${t.seam?" \xB7 seam":""}`:`waits on ${s(t)}`:"":"",n=e.items.some(t=>t.bindable&&t.stageLine),h=e.items.map(t=>({i:t,id:t.bindable?t.itemId:"(no id)",pose:l(t)})),m=Math.max(8,...h.map(t=>t.id.length)),d=n?Math.max(0,...h.map(t=>t.pose?t.pose.length+2:0)):0;for(let{i:t,id:p,pose:c}of h){if(!n){console.log(` ${p.padEnd(8)} ${t.sectionKind.padEnd(14)} ${c?`[${c}] `:""}${t.text}`);continue}let b=t.bindable&&t.stageLine?t.stageLine:"";console.log(` ${p.padEnd(m)} ${t.sectionKind.padEnd(14)} ${(c?`[${c}]`:"").padEnd(d)}${d?" ":""}${b}`.trimEnd()),t.text&&console.log(` ${"".padEnd(m)} ${t.text}`)}n&&console.log(" (stage = what the plane observed, with its evidence. merged or higher is a fact \u2014 do not re-verify it; copy it as printed)"),a&&(console.log(e.readyAt?` (readiness = every \`after\` item is at ${e.readyAt} or higher \u2014 this blueprint's ready-at; a What-remains list bolds only ready items)`:" (readiness = every `after` item presents as done; a What-remains list bolds only ready items)"),i.size&&console.log(" (gate words: merged = the dependency's code is on main; released = it is in a cut release; live = it is running on the repo's deploy surfaces. A word beside an id is that edge's own gate; an edge with no word waits at ready-at)"))}}catch(e){u(e.message)}else if(g==="remains"){let e='usage: bostrat-blueprint remains [--brief <BP-id>="<one sentence>"]\u2026',a={};for(let o=0;o<r.length;o++){r[o]!=="--brief"&&u(`unknown argument "${r[o]}" \u2014 ${e}`);let i=r[++o];i==null&&u(e);let s=i.indexOf("="),l=(s>0?i.slice(0,s):i).trim(),n=s>0?i.slice(s+1):r[++o];(!/^BP-[A-Z0-9]+(?:-[A-Z0-9]+)*$/i.test(l)||!String(n??"").trim())&&u(`--brief takes <BP-id>="<one sentence>", got "${i}" \u2014 ${e}`),a[l.toUpperCase()]=String(n).trim()}try{let o=await f("POST","/api/blueprints/remains",{cwd:process.cwd(),briefs:a}),i=o.counts;console.log(`[bostrat-blueprint] status card posted for \u201C${o.name??"blueprint"}\u201D v${o.version} \u2014 ${i.done} of ${i.total} merged \xB7 ${i.ready} ready \xB7 ${i.waiting} waiting`),o.mine?.length&&console.log(` this Track: ${o.mine.map(s=>`${s.itemId} (${s.stageLine??s.stage??"open"})`).join(", ")}`);for(let s of o.ready??[])console.log(` ready ${s.itemId} ${s.text}${o.briefs?.[s.itemId]?` \u2014 brief: ${o.briefs[s.itemId]}`:""}`);for(let s of o.waiting??[])console.log(` waiting ${s.itemId} ${s.text} \u2014 waits on ${(s.waits??[]).map(l=>`${l.itemId}${l.gate?` ${l.gate}`:""}`).join(", ")||"(unmet)"}`);!i.ready&&!i.waiting&&console.log(" nothing open \u2014 every item presents done."),console.log(" The card carries these rows under your closing message. Do not repeat them in your message \u2014 close by saying what you did and end your turn.")}catch(o){console.error(`[bostrat-blueprint] no status card posted: ${o.message}`),console.error(' Fall back to prose: end your message with a short "What remains" list \u2014 "Ready now" items with the FULL id in bold first (**BP-X-I3**: what it still needs), then "Waiting" items (id not bold) with what each waits on.'),process.exit(1)}}else if(g==="tag"){r.length||u("usage: bostrat-blueprint tag <BP-id> [<BP-id>\u2026]");try{let e=await f("POST","/api/blueprints/tag",{cwd:process.cwd(),itemIds:r});console.log(`[bostrat-blueprint] tagged this Track onto ${e.itemIds.join(", ")}`),console.log(" (association + cost attribution \u2014 completion still comes from merged PRs or a manual tick)")}catch(e){u(e.message)}}else if(g==="hubs")try{let e=await f("GET",`/api/blueprints/hubs?cwd=${encodeURIComponent(process.cwd())}${r[0]?`&repo=${encodeURIComponent(r[0])}`:""}`);if(!e.hubs?.length)console.log(`[bostrat-blueprint] ${e.repo}: no hub files yet (${e.tracks??0} Track(s) with observed edits)`);else{console.log(`[bostrat-blueprint] ${e.repo}: hub files \u2014 share of ${e.tracks} Track(s) with observed edits that wrote each`);for(let a of e.hubs)console.log(` ${String(Math.round(a.share*100)).padStart(3)}% ${a.path}`);console.log(" (route edits to these through the seam item, or order the items that touch them with `after`)")}}catch(e){u(e.message)}else u("usage: bostrat-blueprint <add|update|show|report|tag|hubs|remains> \u2026 (add [--circuit <ref>] <file.md>)");
2
+ var y=process.env.BOSTRAT_AGENT_URL||`http://127.0.0.1:${process.env.BOSTRAT_AGENT_PORT||3362}`;async function f(e,r,a){let o=await fetch(`${y}${r}`,{method:e,headers:a?{"content-type":"application/json"}:void 0,body:a?JSON.stringify(a):void 0}),i=await o.json().catch(()=>({}));if(!o.ok)throw Object.assign(new Error(i.error||`HTTP ${o.status}`),{status:o.status,data:i});return i}function h(e){console.error(`[bostrat-blueprint] ${e}`),process.exit(1)}function v(e,r){if(console.error(`[bostrat-blueprint] refused: ${e.error}`),e.code==="stale-base"){if(console.error(` plane holds v${e.current}; this copy was built on v${e.yourBase}.`),e.drift?.length){console.error(" item-level difference:");for(let a of e.drift)console.error(` ${String(a.itemId).padEnd(12)} plane: ${String(a.plane).padEnd(7)} file: ${a.file}`)}else console.error(" no item differs \u2014 the newer version changed prose only.");console.error(" Bring this copy up to date, then republish:"),console.error(" git fetch origin && git merge origin/main # siblings' ticks land on main with their PRs"),console.error(" (copy any ticked item you still lack VERBATIM \u2014 never invent a sibling's note)"),console.error(` bostrat-blueprint show && bostrat-blueprint update ${r}`),console.error(` Or, once the file carries everything above: bostrat-blueprint update --base ${e.current} ${r}`)}else e.code==="untick"&&(console.error(` would un-tick: ${e.untick.join(", ")} (plane v${e.current} has them [x]).`),console.error(" Copy their ticks + status notes into the file (merge origin/main first), then republish."));console.error(" --force publishes the file exactly as it is (un-ticking the items above). Only when that is the intent."),process.exit(1)}function $(e){if(e){console.log(` parsed: ${e.sections.recognized} recognized section(s), ${e.items.total} item(s) (${e.items.bindable} bindable)`);for(let r of e.issues??[])console.log(` \u26A0 ${r.message}`)}}var n=process.argv.slice(2),g=n.shift();if(g==="add"||g==="update"){let e=null,r=null,a=null,o=null,i=null,l=!1;for(let t=0;t<n.length;t++)n[t]==="--circuit"?e=n[++t]:n[t]==="--new-circuit"?r=n[++t]:n[t]==="--name"?a=n[++t]:n[t]==="--base"?i=n[++t]:n[t]==="--force"?l=!0:o=n[t];o||h(`usage: bostrat-blueprint ${g} [--circuit <name-or-id>] [--new-circuit "<name>"] [--name "<title>"] [--base <v>] [--force] <file.md>`),i!=null&&!/^[1-9]\d*$/.test(String(i))&&h(`--base takes a version number (what \`show\` prints), got "${i}"`);try{let t=await(await import("node:fs/promises")).readFile(o,"utf8"),d=null,m=null;try{let{execFileSync:s}=await import("node:child_process"),p=await import("node:path"),c=p.resolve(o),b=s("git",["rev-parse","--show-toplevel"],{cwd:p.dirname(c),encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),w=p.relative(b,c);w&&!w.startsWith("..")&&(d=w.split(p.sep).join("/"),m=b)}catch{}let u=await f("POST","/api/blueprints/publish",{cwd:process.cwd(),circuit:e,newCircuit:r,name:a,markdown:t,base:i==null?null:Number(i),force:l,path:d,root:m});console.log(`[bostrat-blueprint] published \u201C${u.blueprint.name}\u201D v${u.blueprint.version} on circuit \u201C${u.circuit.name}\u201D${u.base?` (on v${u.base})`:""}${l?" (forced)":""}`),$(u.report),u.linked&&console.log(` This Track is now in circuit \u201C${u.circuit.name}\u201D (it was in none) \u2014 the blueprint's item ids in a closing message are launch controls from here.`),u.blueprint.version===1&&console.log(" The circuit page now carries this blueprint; PRs/commits mentioning BP ids show as evidence \u2014 tick [x] + a *(done \u2026)* note in the same PR as the item's work.")}catch(t){t.status===409&&t.data?.code&&v(t.data,o),h(t.message)}}else if(g==="show"||g==="report")try{let e=await f("GET",`/api/blueprints/show?cwd=${encodeURIComponent(process.cwd())}${n[0]?`&circuit=${encodeURIComponent(n[0])}`:""}`);if(console.log(`[bostrat-blueprint] \u201C${e.blueprint.name}\u201D v${e.blueprint.version} (circuit ${e.blueprint.circuitId})`),$(e.report),g==="show"){let r=!!e.graph?.edges,a=e.readyAt||"merged",o=new Set,i=s=>{let p=Array.isArray(s.waits)&&s.waits.length?s.waits:null;return p?p.map(c=>c.gate&&c.gate!==a?(o.add(c.gate),`${c.itemId} ${c.gate}`):c.itemId).join(", "):(s.waitsOn??[]).join(", ")},l=s=>s.bindable?s.done?"done":r?s.ready?`ready${s.seam?" \xB7 seam":""}`:`waits on ${i(s)}`:"":"",t=e.items.some(s=>s.bindable&&s.stageLine),d=e.items.map(s=>({i:s,id:s.bindable?s.itemId:"(no id)",pose:l(s)})),m=Math.max(8,...d.map(s=>s.id.length)),u=t?Math.max(0,...d.map(s=>s.pose?s.pose.length+2:0)):0;for(let{i:s,id:p,pose:c}of d){if(!t){console.log(` ${p.padEnd(8)} ${s.sectionKind.padEnd(14)} ${c?`[${c}] `:""}${s.text}`);continue}let b=s.bindable&&s.stageLine?s.stageLine:"";console.log(` ${p.padEnd(m)} ${s.sectionKind.padEnd(14)} ${(c?`[${c}]`:"").padEnd(u)}${u?" ":""}${b}`.trimEnd()),s.text&&console.log(` ${"".padEnd(m)} ${s.text}`)}t&&console.log(" (stage = what the plane observed, with its evidence. merged or higher is a fact \u2014 do not re-verify it; copy it as printed)"),r&&(console.log(e.readyAt?` (readiness = every \`after\` item is at ${e.readyAt} or higher \u2014 this blueprint's ready-at; a What-remains list bolds only ready items)`:" (readiness = every `after` item presents as done; a What-remains list bolds only ready items)"),o.size&&console.log(" (gate words: merged = the dependency's code is on main; released = it is in a cut release; live = it is running on the repo's deploy surfaces. A word beside an id is that edge's own gate; an edge with no word waits at ready-at)"))}}catch(e){h(e.message)}else if(g==="remains"){let e='usage: bostrat-blueprint remains [--asked] [--brief <BP-id>="<one sentence>"]\u2026',r={},a=!1;for(let o=0;o<n.length;o++){if(n[o]==="--asked"){a=!0;continue}n[o]!=="--brief"&&h(`unknown argument "${n[o]}" \u2014 ${e}`);let i=n[++o];i==null&&h(e);let l=i.indexOf("="),t=(l>0?i.slice(0,l):i).trim(),d=l>0?i.slice(l+1):n[++o];(!/^BP-[A-Z0-9]+(?:-[A-Z0-9]+)*$/i.test(t)||!String(d??"").trim())&&h(`--brief takes <BP-id>="<one sentence>", got "${i}" \u2014 ${e}`),r[t.toUpperCase()]=String(d).trim()}try{let o=await f("POST","/api/blueprints/remains",{cwd:process.cwd(),briefs:r,asked:a}),i=o.counts,l=o.show==="now"||o.show==="published";console.log(`[bostrat-blueprint] status card ${l?"posted":"recorded"} for \u201C${o.name??"blueprint"}\u201D v${o.version} \u2014 ${i.done} of ${i.total} merged \xB7 ${i.ready} ready \xB7 ${i.waiting} waiting`),o.mine?.length&&console.log(` this Track: ${o.mine.map(t=>`${t.itemId} (${t.stageLine??t.stage??"open"})`).join(", ")}`);for(let t of o.ready??[])console.log(` ready ${t.itemId} ${t.text}${o.briefs?.[t.itemId]?` \u2014 brief: ${o.briefs[t.itemId]}`:""}`);for(let t of o.waiting??[])console.log(` waiting ${t.itemId} ${t.text} \u2014 waits on ${(t.waits??[]).map(d=>`${d.itemId}${d.gate?` ${d.gate}`:""}`).join(", ")||"(unmet)"}`);!i.ready&&!i.waiting&&console.log(" nothing open \u2014 every item presents done."),console.log(l?o.show==="now"?" The card carries these rows under your closing message (the operator asked). Do not repeat them in your message \u2014 close by saying what you did and end your turn.":" The card carries these rows under your closing message while this Track has no pull request to wait for (this turn published the blueprint). Do not repeat them in your message \u2014 close by saying what you did and end your turn.":" The card shows under the Merged record once this Track's pull request has merged, with your briefs \u2014 not before. Do not list these rows in your message \u2014 close by saying what you did and end your turn.")}catch(o){console.error(`[bostrat-blueprint] no status card recorded: ${o.message}`),console.error(' Fall back to prose: end your message with a short "What remains" list \u2014 "Ready now" items with the FULL id in bold first (**BP-X-I3**: what it still needs), then "Waiting" items (id not bold) with what each waits on.'),process.exit(1)}}else if(g==="tag"){n.length||h("usage: bostrat-blueprint tag <BP-id> [<BP-id>\u2026]");try{let e=await f("POST","/api/blueprints/tag",{cwd:process.cwd(),itemIds:n});console.log(`[bostrat-blueprint] tagged this Track onto ${e.itemIds.join(", ")}`),console.log(" (association + cost attribution \u2014 completion still comes from merged PRs or a manual tick)")}catch(e){h(e.message)}}else if(g==="hubs")try{let e=await f("GET",`/api/blueprints/hubs?cwd=${encodeURIComponent(process.cwd())}${n[0]?`&repo=${encodeURIComponent(n[0])}`:""}`);if(!e.hubs?.length)console.log(`[bostrat-blueprint] ${e.repo}: no hub files yet (${e.tracks??0} Track(s) with observed edits)`);else{console.log(`[bostrat-blueprint] ${e.repo}: hub files \u2014 share of ${e.tracks} Track(s) with observed edits that wrote each`);for(let r of e.hubs)console.log(` ${String(Math.round(r.share*100)).padStart(3)}% ${r.path}`);console.log(" (route edits to these through the seam item, or order the items that touch them with `after`)")}}catch(e){h(e.message)}else h("usage: bostrat-blueprint <add|update|show|report|tag|hubs|remains> \u2026 (add [--circuit <ref>] <file.md>)");
package/dist/cli.js CHANGED
@@ -2,10 +2,10 @@ var fa=Object.defineProperty;var O=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(
2
2
  `)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(o);if(!s)continue;let a=s[2].trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n[s[1]]=a}return n}function so(e,t=process.env){let n=Wt(e);for(let[r,o]of Object.entries(n))r in t||(t[r]=o);return n}function io(e,t,{header:n=""}={}){let r=[];n&&r.push(...n.split(`
3
3
  `).map(o=>o?`# ${o}`:"#"));for(let[o,s]of Object.entries(t))s==null||s===""||r.push(`${o}=${s}`);Ut.mkdirSync(Nn.dirname(e),{recursive:!0}),Ut.writeFileSync(e,r.join(`
4
4
  `)+`
5
- `,{mode:384}),Ut.chmodSync(e,384)}function ao(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,ma,Mn=O(()=>{Ht=process.env.BOSTRAT_STATE_DIR||Nn.join(process.env.HOME||ha.tmpdir(),".bostrat"),Fe=()=>Nn.join(Ht,"node.env"),ma=new Set(["1","true","on","yes"])});var $d,Kt=O(()=>{$d=16*1024});var pe,ft,Gt=O(()=>{pe="BOSTRAT_HOOK_TOKEN",ft="x-bostrat-hook"});var ga,kd,co=O(()=>{ga=(e,t)=>{if(e==null||e==="")return t;let n=Number(e);return Number.isFinite(n)&&n>=0?n:t},kd=ga(process.env.BOSTRAT_HOOK_FOLD_MS,250)});function Ta(e,t=ya){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 zt(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function yo(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 mo(e){let t=zt(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 _o(e){let{cmd:t,at:n}=yo(e);if(t==="sudo"){for(n++;n<e.length&&e[n].startsWith("-");)n++;t=e[n]??null}return{cmd:t,at:n}}function To(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=zt(e),{cmd:a}=_o(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 Ca(e){let t=zt(e),{cmd:n,at:r}=_o(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&&ka.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=To(e,So);return s?`${s} unit/cron path`:null}function ja(e){let t=new Set;for(let n of String(e??"").matchAll(Na))t.add(n[1].toLowerCase());return[...t]}var wa,ya,lo,uo,po,fo,ho,Md,ba,Sa,In,_a,fe,Dn,xa,$a,va,Aa,bo,So,ka,Ea,Oa,Ra,Na,go,wo,Ma,Ia,Pa,Da,q,ht,Pn,xo,Id,Pd,$o=O(()=>{co();wa="BP-AU-R4",ya=160,lo=200,uo=5,po=8,fo=5,ho=10*6e4,Md=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"]),ba=5e3,Sa=new Set(["tool.called","tool.failed"]),In=new Set(["Write","Edit","NotebookEdit"]),_a=e=>String(e??"").replace(/\s+/g," ").trim(),fe=(e,t=120)=>_a(e).slice(0,t);Dn=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,xa=new RegExp(`${Dn}/\\.ssh(?:/|\\b)`),$a=new RegExp(`${Dn}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),va=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,Aa=/^\.env\.(?:example|sample|template|dist)$/,bo=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,So=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${Dn}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),ka=/^(?: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)$/,Ea=/^\/tmp\/|\/\.bostrat\/tmp\//,Oa=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,Ra=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,Na=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,go=e=>xa.test(e)||$a.test(e),wo=e=>[...String(e??"").matchAll(va)].some(t=>!Aa.test(t[1])),Ma=e=>bo.test(e),Ia=e=>So.test(e),Pa=e=>(e.startsWith("/")||e.startsWith("~"))&&!Ea.test(e);Da=e=>To(e,bo);q=(e,t,n,r)=>Object.freeze({severity:e,requirement:wa,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 Ta(o.head,e.headCap)){let a=t(s,o);a&&(n++,r??=fe(a))}return n?{count:n,sample:r}:null},Pn=(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},xo=Object.freeze({"force-push":q("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=mo(n);return r&&r.force&&!r.lease?n:null})),"protected-config-write":q("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)In.has(s.tool)&&s.path&&Ma(s.path)&&(n++,r??=fe(`${s.tool} ${s.path}`));let o=ht(t,s=>{let a=Da(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"persistence-install":q("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)In.has(s.tool)&&s.path&&Ia(s.path)&&(n++,r??=fe(`${s.tool} ${s.path}`));let o=ht(t,s=>{let a=Ca(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"push-outside-track":q("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=mo(n);return r&&(r.remote&&!/^(?:origin|upstream)$/.test(r.remote)&&!r.remote.startsWith("$")&&!r.remote.startsWith("-")||r.dsts.some(o=>Oa.test(o)||!Ra.test(o)))?n:null})),"credential-read":q("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)=>Pn(t,n=>n.head&&go(n.head)?n.head:n.path&&go(n.path)?`${n.tool} ${n.path}`:null)),"dotenv-read":q("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)=>Pn(t,n=>n.head&&wo(n.head)?n.head:n.path&&wo(n.path)?`${n.tool} ${n.path}`:null)),"privileged-command":q("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}=yo(zt(n));return r==="sudo"||r==="docker"?n:null})),"write-outside-workspace":q("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)=>Pn(t,n=>In.has(n.tool)&&n.path&&Pa(n.path)?`${n.tool} ${n.path}`:null)),"egress-new-host":q("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 ja(o.head))t.state.known.has(s)||t.state.hosts.has(s)||(t.state.hosts.add(s),t.state.hosts.size>ba&&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":q("low",`a cost.recorded turn over ${po}\xD7 the Track's running median (its last ${lo} cost events, at least ${uo} of them) and over $${fo} \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>=uo&&r>=fo){let s=[...n].sort((l,h)=>l-h),a=s[Math.floor(s.length/2)];r>po*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>lo&&n.shift(),o}),"peer-injected-call":q("medium",`a tool call within ${ho/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>ho||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":q("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":q("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":q("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}`:""}`)}})}),Id=Object.freeze(Object.keys(xo)),Pd=new Set([...Sa,"cost.recorded","peer.message","turn.user","audit.procs","harness.shape.seen"])});function Fa(e){let t=String(e??"").trim().toLowerCase();if(Ba.has(t))return{enabled:!1,rules:[],unknown:[]};if(La.has(t))return{enabled:!0,rules:[...Cn],unknown:[]};let n=[],r=[];for(let o of t.split(",")){let s=o.trim();s&&(Cn.includes(s)?n.includes(s)||n.push(s):r.push(s))}return{enabled:n.length>0,rules:n,unknown:r}}function vo(e){return e?.enabled?`on \xB7 denies ${e.rules.length===Cn.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 Cn,Ba,La,jn,Bn=O(()=>{$o();Cn=Object.freeze(["force-push","protected-config-write","credential-read","persistence-install"]),Ba=new Set(["","off","0","false","no","none"]),La=new Set(["on","1","true","yes","all"]);jn=(e=process.env)=>Fa(e.BOSTRAT_AUDIT_GUARD)});import Ue from"node:fs";import ko from"node:fs/promises";import qt from"node:os";import Y from"node:path";import{execFile as Eo}from"node:child_process";import{promisify as Ua}from"node:util";function No(e){try{return Ue.readFileSync(e,"utf8").split(`
5
+ `,{mode:384}),Ut.chmodSync(e,384)}function ao(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,ma,xd,Mn=O(()=>{Ht=process.env.BOSTRAT_STATE_DIR||Nn.join(process.env.HOME||ha.tmpdir(),".bostrat"),Fe=()=>Nn.join(Ht,"node.env"),ma=new Set(["1","true","on","yes"]);xd=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."})});var vd,Kt=O(()=>{vd=16*1024});var pe,ft,Gt=O(()=>{pe="BOSTRAT_HOOK_TOKEN",ft="x-bostrat-hook"});var ga,Ed,co=O(()=>{ga=(e,t)=>{if(e==null||e==="")return t;let n=Number(e);return Number.isFinite(n)&&n>=0?n:t},Ed=ga(process.env.BOSTRAT_HOOK_FOLD_MS,250)});function Ta(e,t=ya){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 zt(e){return String(e??"").replace(/\d?>>?\s*\S+|<\s*\S+|2>&1/g," ").trim().split(/\s+/).filter(Boolean)}function yo(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 mo(e){let t=zt(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 _o(e){let{cmd:t,at:n}=yo(e);if(t==="sudo"){for(n++;n<e.length&&e[n].startsWith("-");)n++;t=e[n]??null}return{cmd:t,at:n}}function To(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=zt(e),{cmd:a}=_o(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 Ca(e){let t=zt(e),{cmd:n,at:r}=_o(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&&ka.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=To(e,So);return s?`${s} unit/cron path`:null}function ja(e){let t=new Set;for(let n of String(e??"").matchAll(Na))t.add(n[1].toLowerCase());return[...t]}var wa,ya,lo,uo,po,fo,ho,Id,ba,Sa,In,_a,fe,Dn,xa,$a,va,Aa,bo,So,ka,Ea,Oa,Ra,Na,go,wo,Ma,Ia,Pa,Da,q,ht,Pn,xo,Pd,Dd,$o=O(()=>{co();wa="BP-AU-R4",ya=160,lo=200,uo=5,po=8,fo=5,ho=10*6e4,Id=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"]),ba=5e3,Sa=new Set(["tool.called","tool.failed"]),In=new Set(["Write","Edit","NotebookEdit"]),_a=e=>String(e??"").replace(/\s+/g," ").trim(),fe=(e,t=120)=>_a(e).slice(0,t);Dn=String.raw`(?:~|\$HOME|\$\{HOME\}|/home/[^\s/"']+|/root|/Users/[^\s/"']+)`,xa=new RegExp(`${Dn}/\\.ssh(?:/|\\b)`),$a=new RegExp(`${Dn}/(?:\\.claude\\.json\\b|\\.claude/\\.credentials\\.json|\\.codex/auth\\.json|\\.cursor(?:/|\\b))`),va=/(?:^|[\s/"'=(])(\.env(?:\.[A-Za-z0-9_.-]+)?)(?=$|[\s"'|;&)])/g,Aa=/^\.env\.(?:example|sample|template|dist)$/,bo=/(\.claude\/settings(?:\.local)?\.json|\.claude\/hooks\/[^\s"']*|\.bostrat\/events(?:\/[^\s"']*)?)/,So=new RegExp(`((?:/etc|/usr/lib|/lib|/run)/systemd/[^\\s"']*|${Dn}/\\.config/systemd/[^\\s"']*|/etc/cron(?:tab|\\.d|\\.hourly|\\.daily|\\.weekly|\\.monthly)(?:/[^\\s"']*)?|/var/spool/cron(?:/[^\\s"']*)?)`),ka=/^(?: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)$/,Ea=/^\/tmp\/|\/\.bostrat\/tmp\//,Oa=/^(?:refs\/heads\/)?(?:main|master|develop|development|trunk|production|prod|staging|release(?:\/|$)|v\d)/,Ra=/(?:^|\/)track\/|^HEAD$|^refs\/bostrat\//,Na=/https?:\/\/([a-z0-9.-]+\.[a-z]{2,}|localhost|\d+\.\d+\.\d+\.\d+)(?::\d+)?/gi,go=e=>xa.test(e)||$a.test(e),wo=e=>[...String(e??"").matchAll(va)].some(t=>!Aa.test(t[1])),Ma=e=>bo.test(e),Ia=e=>So.test(e),Pa=e=>(e.startsWith("/")||e.startsWith("~"))&&!Ea.test(e);Da=e=>To(e,bo);q=(e,t,n,r)=>Object.freeze({severity:e,requirement:wa,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 Ta(o.head,e.headCap)){let a=t(s,o);a&&(n++,r??=fe(a))}return n?{count:n,sample:r}:null},Pn=(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},xo=Object.freeze({"force-push":q("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=mo(n);return r&&r.force&&!r.lease?n:null})),"protected-config-write":q("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)In.has(s.tool)&&s.path&&Ma(s.path)&&(n++,r??=fe(`${s.tool} ${s.path}`));let o=ht(t,s=>{let a=Da(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"persistence-install":q("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)In.has(s.tool)&&s.path&&Ia(s.path)&&(n++,r??=fe(`${s.tool} ${s.path}`));let o=ht(t,s=>{let a=Ca(s);return a?`${a}: ${s}`:null});return o&&(n+=o.count,r??=o.sample),n?{count:n,sample:r}:null}),"push-outside-track":q("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=mo(n);return r&&(r.remote&&!/^(?:origin|upstream)$/.test(r.remote)&&!r.remote.startsWith("$")&&!r.remote.startsWith("-")||r.dsts.some(o=>Oa.test(o)||!Ra.test(o)))?n:null})),"credential-read":q("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)=>Pn(t,n=>n.head&&go(n.head)?n.head:n.path&&go(n.path)?`${n.tool} ${n.path}`:null)),"dotenv-read":q("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)=>Pn(t,n=>n.head&&wo(n.head)?n.head:n.path&&wo(n.path)?`${n.tool} ${n.path}`:null)),"privileged-command":q("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}=yo(zt(n));return r==="sudo"||r==="docker"?n:null})),"write-outside-workspace":q("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)=>Pn(t,n=>In.has(n.tool)&&n.path&&Pa(n.path)?`${n.tool} ${n.path}`:null)),"egress-new-host":q("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 ja(o.head))t.state.known.has(s)||t.state.hosts.has(s)||(t.state.hosts.add(s),t.state.hosts.size>ba&&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":q("low",`a cost.recorded turn over ${po}\xD7 the Track's running median (its last ${lo} cost events, at least ${uo} of them) and over $${fo} \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>=uo&&r>=fo){let s=[...n].sort((l,h)=>l-h),a=s[Math.floor(s.length/2)];r>po*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>lo&&n.shift(),o}),"peer-injected-call":q("medium",`a tool call within ${ho/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>ho||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":q("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":q("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":q("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}`:""}`)}})}),Pd=Object.freeze(Object.keys(xo)),Dd=new Set([...Sa,"cost.recorded","peer.message","turn.user","audit.procs","harness.shape.seen"])});function Fa(e){let t=String(e??"").trim().toLowerCase();if(Ba.has(t))return{enabled:!1,rules:[],unknown:[]};if(La.has(t))return{enabled:!0,rules:[...Cn],unknown:[]};let n=[],r=[];for(let o of t.split(",")){let s=o.trim();s&&(Cn.includes(s)?n.includes(s)||n.push(s):r.push(s))}return{enabled:n.length>0,rules:n,unknown:r}}function vo(e){return e?.enabled?`on \xB7 denies ${e.rules.length===Cn.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 Cn,Ba,La,jn,Bn=O(()=>{$o();Cn=Object.freeze(["force-push","protected-config-write","credential-read","persistence-install"]),Ba=new Set(["","off","0","false","no","none"]),La=new Set(["on","1","true","yes","all"]);jn=(e=process.env)=>Fa(e.BOSTRAT_AUDIT_GUARD)});import Ue from"node:fs";import ko from"node:fs/promises";import qt from"node:os";import Y from"node:path";import{execFile as Eo}from"node:child_process";import{promisify as Ua}from"node:util";function No(e){try{return Ue.readFileSync(e,"utf8").split(`
6
6
  `).filter(t=>t&&!t.startsWith("#")).map(t=>t.split(":"))}catch{return[]}}function Mo(e,t=process.env){let r=No(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 Io(e,t=process.env){let n=No(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 mt(e=process.env){let t=String(e[Hn]||"").trim();if(Ka.has(t.toLowerCase()))return null;let n=`${t}|${e.BOSTRAT_PASSWD_FILE||""}|${e.BOSTRAT_GROUP_FILE||""}|${e.BOSTRAT_BOX_HOME_VIEW||""}`;if(Ln?.key===n)return Ln.value;let r;if(!Wa.test(t))r={name:t,error:`${Hn}="${t}" is not a valid user name`};else{let o=Mo(t,e),s=Vt();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=Io(o,e),l=a.filter(h=>Oo.includes(h));r=l.length?{name:t,error:`user "${t}" is in ${l.join(", ")} \u2014 a box user must hold no route to root`}:{...o,groups:a,nodeUid:s,rootNode:s===0}}}return Ln={key:n,value:r},r}function He(e=process.env){let t=mt(e);return t&&!t.error?t.home:qt.homedir()}function Ao(e=process.env){let t=mt(e);return!t||t.error||t.rootNode?He(e):e.BOSTRAT_BOX_HOME_VIEW||Y.join(Ro(e),"box-home")}function Ga(e,t=process.env){let n=mt(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 Fn(e,{env:t=process.env,input:n=null,timeout:r=15e3}={}){let[o,...s]=Ga(e,t);return n==null?Wn(o,s,{timeout:r}):new Promise((a,l)=>{Eo(o,s,{timeout:r},(m,d,S)=>m?l(m):a({stdout:d,stderr:S})).stdin.end(n)})}function za(e){return e.BOSTRAT_SETFACL_BIN?e.BOSTRAT_SETFACL_BIN:(Un===void 0&&(Un=["/usr/bin/setfacl","/bin/setfacl"].find(t=>Ue.existsSync(t))||null),Un)}function Va(e=process.env){let t=qt.homedir(),n=Ro(e);return[Y.join(t,".ssh"),Y.join(t,".claude.json"),Y.join(t,".claude",".credentials.json"),Y.join(t,".codex","auth.json"),Y.join(t,".config","gh","hosts.yml"),Y.join(t,".cursor","cli-config.json"),Y.join(n,"node.env"),Y.join(n,"api-token"),Y.join(n,"plane-link"),Y.join(n,"secure-inputs")]}async function Po({env:e=process.env,probe:t=!0}={}){let n=mt(e),r=await Xa(e);if(!n){let s=Mo(Vt(),e)||{name:qt.userInfo().username,uid:Vt(),gid:-1},a=s.uid===0?["root"]:Io(s,e).filter(m=>Oo.includes(m)),l=s.uid!==0&&t?await Ya():!1,h=[...a,...l&&!a.includes("sudo")?["sudo (sudoers)"]:[]];return{level:h.length?"root-capable":"node-uid",user:s.name,routes:h,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:h}=await Fn(["id","-u"],{env:e,timeout:5e3});Number(h.trim())!==n.uid&&o.push(`switching to ${n.name} landed as uid ${h.trim()}`)}catch(h){o.push(`the node cannot switch to ${n.name} (${n.rootNode?"setpriv":"sudo -n -u"} failed: ${qa(h)})`)}if(!o.length){await Fn(["sudo","-n","true"],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&o.push(`${n.name} can sudo`);let h=[];for(let m of Va(e))Ue.existsSync(m)&&await Fn(["test","-r",m],{env:e,timeout:5e3}).then(()=>!0,()=>!1)&&h.push(m);h.length&&o.push(`${n.name} can read ${h.join(", ")}`)}za(e)||o.push("setfacl is missing (apt install acl)");let s=Ao(e);s!==n.home&&!Ue.existsSync(Y.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=Y.join(n.home,".claude","settings.json"),l=await ko.stat(a).catch(()=>null);l&&l.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:Ao(e),problems:o,auditd:r}}async function Ya(){try{return await Wn("sudo",["-n","true"],{timeout:3e3}),!0}catch{return!1}}async function Xa(e=process.env,{ask:t=!0}={}){let n=e.BOSTRAT_AUDIT_LOG||"/var/log/audit/audit.log",r=!1;try{await ko.access(n,Ue.constants.R_OK),r=!0}catch{}let o=e.BOSTRAT_AUDIT_RULES_FILE||"/etc/audit/rules.d/bostrat-box.rules",s=Ue.existsSync(o),a=null;if(t&&s){let l=Vt()===0?["auditctl",["-l"]]:["sudo",["-n","auditctl","-l"]];try{let{stdout:h}=await Wn(l[0],l[1],{timeout:5e3});a=h.includes(`key=${Ha}`)}catch{a=null}}else s||(a=!1);return{log:n,readable:r,configured:s,rule:a,rulesFile:o}}function Do(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"?`${Hn} 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 Wn,Hn,Ha,Oo,Wa,Ka,Ro,Vt,Ln,gt,Un,qa,Ee=O(()=>{Wn=Ua(Eo),Hn="BOSTRAT_BOX_USER",Ha="bostrat-box",Oo=Object.freeze(["root","sudo","wheel","admin","docker","lxd","libvirt","disk"]),Wa=/^[a-z_][a-z0-9_-]{0,31}$/,Ka=new Set(["","off","0","false","no","none"]),Ro=e=>e.BOSTRAT_STATE_DIR||Y.join(e.HOME||qt.homedir(),".bostrat");Vt=()=>typeof process.getuid=="function"?process.getuid():0,Ln=null;gt=(e=process.env)=>{let t=mt(e);return!!(t&&!t.error)};qa=e=>String(e?.stderr||e?.message||e).trim().split(`
7
- `)[0].slice(0,160)});var wt=O(()=>{});import Qa from"node:os";import Kn from"node:path";function jo(){return gt()?Kn.join(He(),".claude.json"):process.env.CLAUDE_CONFIG_DIR?Kn.join(process.env.CLAUDE_CONFIG_DIR,".claude.json"):Kn.join(Qa.homedir(),".claude.json")}var zn=O(()=>{Gt();Bn();Ee();wt()});import ec from"node:os";import Vn from"node:path";function Bo(){if(gt())return Vn.join(He(),".codex","config.toml");let e=process.env.CODEX_HOME||Vn.join(ec.homedir(),".codex");return Vn.join(e,"config.toml")}var tc,ip,qn=O(()=>{Ee();tc="check_for_update_on_startup",ip=`${tc} = false`});import rc from"node:os";import Lo from"node:path";var oc,pp,fp,Yn=O(()=>{Xn();Kt();oc=process.env.BOSTRAT_DEBUG_DIR||Lo.join(rc.homedir(),".bostrat","debug"),pp=Lo.join(oc,"handoff.jsonl"),fp=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as ic}from"node:child_process";import{promisify as ac}from"node:util";function Jn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var bp,Sp,_p,Tp,xp,Zn=O(()=>{Yn();bp=ac(ic),Sp=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,_p=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,Tp=Number(process.env.BOSTRAT_CLI_PROBE_TIMEOUT_MS)||8e3,xp=Promise.resolve()});var Fo=O(()=>{Ee()});import Qn from"node:path";import{execFile as cc}from"node:child_process";import{promisify as lc}from"node:util";var Rp,Uo,uc,Np,Mp,Ho=O(()=>{Rp=lc(cc),Uo=process.env.HOME||"/home/globo",uc=Qn.join(process.env.BOSTRAT_STATE_DIR||Qn.join(Uo,".bostrat"),"repos"),Np=[...(process.env.BOSTRAT_REPOS_ROOT||Qn.join(Uo,"Documents")).split(","),uc].map(e=>e.trim()).filter(Boolean),Mp=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function Jt(e=Date.now()){if(Re)return{tripped:!1,holdMs:1/0};if(Oe>e)return{tripped:!1,holdMs:Oe-e};if((!bt||e-bt>=Yt.windowMs)&&(bt=e,yt=0),yt++,yt<Yt.trip)return{tripped:!1,holdMs:0};Xt++;let t=Math.min(Yt.minMs*2**(Xt-1),Yt.maxMs);return Oe=e+t,yt=0,bt=0,{tripped:!0,holdMs:t}}function Wo(){yt=0,bt=0,Xt=0,Oe=0}function St(e=Date.now()){return Re?1/0:Oe>e?Oe-e:0}function Zt(e=Date.now()){return St(e)>0}function er(e={}){Re={at:Date.now(),...e},Oe=1/0}function tr(){return Re}function Ko(e=Date.now()){return{held:Zt(e),holdMs:Re?null:St(e),holds:Xt,removed:Re?{...Re}:null}}var dc,Yt,yt,bt,Xt,Oe,Re,nr=O(()=>{dc={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},Yt={...dc},yt=0,bt=0,Xt=0,Oe=0,Re=null});import Go from"node:path";import pc from"node:os";import{execFile as fc}from"node:child_process";import{promisify as hc}from"node:util";var Hp,mc,Wp,Kp,Gp,rr=O(()=>{Ho();nr();Hp=hc(fc),mc=process.env.BOSTRAT_STATE_DIR||Go.join(process.env.HOME||pc.tmpdir(),".bostrat"),Wp=Go.join(mc,"repos"),Kp=5*6e4,Gp=10*6e4});var zo=O(()=>{rr()});var Vo=O(()=>{});import wc from"node:fs/promises";import _t from"node:path";import yc from"node:os";import{EventEmitter as bc}from"node:events";function Sc(e){return e?.cwd?_t.join(e.cwd,".bostrat","events"):_t.join(qo,"events")}async function Qt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?_t.join(qo,"events"):Sc(e));let o;try{o=await wc.readFile(_c(n,r),"utf8")}catch{return[]}return vc(o)}function vc(e){let t=[];for(let n of e.split(`
8
- `))if(n.trim())try{t.push(JSON.parse(xc(n)?$c(n):n))}catch{}return t}var Tt,qo,_c,Tc,xc,$c,en=O(()=>{Vo();Kt();Tt=new bc;Tt.setMaxListeners(0);qo=process.env.BOSTRAT_STATE_DIR||_t.join(process.env.HOME||yc.tmpdir(),".bostrat");_c=(e,t)=>_t.join(e,`${t}.ndjson`),Tc=/(?<!\\)((?:\\\\)*)\\u0000/g,xc=e=>e.includes("\\u0000"),$c=e=>e.replace(Tc,"$1\\ufffd")});import kc from"node:os";import Ec from"node:path";import{execFile as Oc}from"node:child_process";import{promisify as Rc}from"node:util";var gf,wf,yf,bf,Sf,_f,Yo=O(()=>{zo();en();gf=Rc(Oc),wf=process.env.BOSTRAT_STATE_DIR||Ec.join(process.env.HOME||kc.tmpdir(),".bostrat"),yf=25*1024,bf=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,Sf=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,_f=Promise.resolve()});var vf,Xo=O(()=>{rr();wt();vf=60*6e4});var Jo=O(()=>{Xo()});import Zo from"node:path";import Nc from"node:os";var We,Mc,Lf,or,Ff,Uf,Hf,Qo=O(()=>{Gt();Ee();We="BOSTRAT_NODE_URL",Mc=process.env.BOSTRAT_STATE_DIR||Zo.join(process.env.HOME||Nc.tmpdir(),".bostrat"),Lf=Zo.join(Mc,"git-hooks"),or=`#!/bin/sh
7
+ `)[0].slice(0,160)});var wt=O(()=>{});import Qa from"node:os";import Kn from"node:path";function jo(){return gt()?Kn.join(He(),".claude.json"):process.env.CLAUDE_CONFIG_DIR?Kn.join(process.env.CLAUDE_CONFIG_DIR,".claude.json"):Kn.join(Qa.homedir(),".claude.json")}var zn=O(()=>{Gt();Bn();Ee();wt()});import ec from"node:os";import Vn from"node:path";function Bo(){if(gt())return Vn.join(He(),".codex","config.toml");let e=process.env.CODEX_HOME||Vn.join(ec.homedir(),".codex");return Vn.join(e,"config.toml")}var tc,ap,qn=O(()=>{Ee();tc="check_for_update_on_startup",ap=`${tc} = false`});import rc from"node:os";import Lo from"node:path";var oc,fp,hp,Yn=O(()=>{Xn();Kt();oc=process.env.BOSTRAT_DEBUG_DIR||Lo.join(rc.homedir(),".bostrat","debug"),fp=Lo.join(oc,"handoff.jsonl"),hp=Number(process.env.BOSTRAT_HANDOFF_DEBUG_MAX)||500});import{execFile as ic}from"node:child_process";import{promisify as ac}from"node:util";function Jn(e){let t=String(e||""),n=t.indexOf("/lib/node_modules/");return n>0?t.slice(0,n):null}var Sp,_p,Tp,xp,$p,Zn=O(()=>{Yn();Sp=ac(ic),_p=Number(process.env.BOSTRAT_CODEX_UPDATE_TIMEOUT_MS)||5*6e4,Tp=Number(process.env.BOSTRAT_CLI_REGISTRY_TIMEOUT_MS)||15e3,xp=Number(process.env.BOSTRAT_CLI_PROBE_TIMEOUT_MS)||8e3,$p=Promise.resolve()});var Fo=O(()=>{Ee()});import Qn from"node:path";import{execFile as cc}from"node:child_process";import{promisify as lc}from"node:util";var Np,Uo,uc,Mp,Ip,Ho=O(()=>{Np=lc(cc),Uo=process.env.HOME||"/home/globo",uc=Qn.join(process.env.BOSTRAT_STATE_DIR||Qn.join(Uo,".bostrat"),"repos"),Mp=[...(process.env.BOSTRAT_REPOS_ROOT||Qn.join(Uo,"Documents")).split(","),uc].map(e=>e.trim()).filter(Boolean),Ip=Number(process.env.BOSTRAT_REPOS_DEPTH)||3});function Jt(e=Date.now()){if(Re)return{tripped:!1,holdMs:1/0};if(Oe>e)return{tripped:!1,holdMs:Oe-e};if((!bt||e-bt>=Yt.windowMs)&&(bt=e,yt=0),yt++,yt<Yt.trip)return{tripped:!1,holdMs:0};Xt++;let t=Math.min(Yt.minMs*2**(Xt-1),Yt.maxMs);return Oe=e+t,yt=0,bt=0,{tripped:!0,holdMs:t}}function Wo(){yt=0,bt=0,Xt=0,Oe=0}function St(e=Date.now()){return Re?1/0:Oe>e?Oe-e:0}function Zt(e=Date.now()){return St(e)>0}function er(e={}){Re={at:Date.now(),...e},Oe=1/0}function tr(){return Re}function Ko(e=Date.now()){return{held:Zt(e),holdMs:Re?null:St(e),holds:Xt,removed:Re?{...Re}:null}}var dc,Yt,yt,bt,Xt,Oe,Re,nr=O(()=>{dc={trip:3,windowMs:3e5,minMs:3e5,maxMs:216e5},Yt={...dc},yt=0,bt=0,Xt=0,Oe=0,Re=null});import Go from"node:path";import pc from"node:os";import{execFile as fc}from"node:child_process";import{promisify as hc}from"node:util";var Wp,mc,Kp,Gp,zp,rr=O(()=>{Ho();nr();Wp=hc(fc),mc=process.env.BOSTRAT_STATE_DIR||Go.join(process.env.HOME||pc.tmpdir(),".bostrat"),Kp=Go.join(mc,"repos"),Gp=5*6e4,zp=10*6e4});var zo=O(()=>{rr()});var Vo=O(()=>{});import wc from"node:fs/promises";import _t from"node:path";import yc from"node:os";import{EventEmitter as bc}from"node:events";function Sc(e){return e?.cwd?_t.join(e.cwd,".bostrat","events"):_t.join(qo,"events")}async function Qt(e,t){let n,r;typeof e=="string"&&t?(n=e,r=t):(r=typeof e=="string"?e:e?.id,n=typeof e=="string"?_t.join(qo,"events"):Sc(e));let o;try{o=await wc.readFile(_c(n,r),"utf8")}catch{return[]}return vc(o)}function vc(e){let t=[];for(let n of e.split(`
8
+ `))if(n.trim())try{t.push(JSON.parse(xc(n)?$c(n):n))}catch{}return t}var Tt,qo,_c,Tc,xc,$c,en=O(()=>{Vo();Kt();Tt=new bc;Tt.setMaxListeners(0);qo=process.env.BOSTRAT_STATE_DIR||_t.join(process.env.HOME||yc.tmpdir(),".bostrat");_c=(e,t)=>_t.join(e,`${t}.ndjson`),Tc=/(?<!\\)((?:\\\\)*)\\u0000/g,xc=e=>e.includes("\\u0000"),$c=e=>e.replace(Tc,"$1\\ufffd")});import kc from"node:os";import Ec from"node:path";import{execFile as Oc}from"node:child_process";import{promisify as Rc}from"node:util";var wf,yf,bf,Sf,_f,Tf,Yo=O(()=>{zo();en();wf=Rc(Oc),yf=process.env.BOSTRAT_STATE_DIR||Ec.join(process.env.HOME||kc.tmpdir(),".bostrat"),bf=25*1024,Sf=Number(process.env.BOSTRAT_MEMORY_SPAWN_PULL_MS)||1500,_f=Number(process.env.BOSTRAT_MEMORY_HARVEST_DEBOUNCE_MS)||2e3,Tf=Promise.resolve()});var Af,Xo=O(()=>{rr();wt();Af=60*6e4});var Jo=O(()=>{Xo()});import Zo from"node:path";import Nc from"node:os";var We,Mc,Ff,or,Uf,Hf,Wf,Qo=O(()=>{Gt();Ee();We="BOSTRAT_NODE_URL",Mc=process.env.BOSTRAT_STATE_DIR||Zo.join(process.env.HOME||Nc.tmpdir(),".bostrat"),Ff=Zo.join(Mc,"git-hooks"),or=`#!/bin/sh
9
9
  # bostrat git hook shim (agent/src/git-hooks.js) \u2014 chains to the repo's own hook,
10
10
  # then stamps/reports for rework attribution when running inside a bostrat box.
11
11
  hook=$(basename "$0")
@@ -20,7 +20,7 @@ esac
20
20
  if [ -x "$orig/$hook" ] && [ "$orig/$hook" != "$0" ]; then
21
21
  "$orig/$hook" "$@" || exit $?
22
22
  fi
23
- `,Ff=`${or}
23
+ `,Uf=`${or}
24
24
  # \u2500\u2500 bostrat: append provenance trailers (Layer 0). Skipped for merge commits
25
25
  # (nobody "wrote" a merge) and outside a box (no token / no node url).
26
26
  [ -z "$${pe}" ] && exit 0
@@ -32,7 +32,7 @@ printf '%s\\n' "$trailers" | while IFS= read -r line; do
32
32
  [ -n "$line" ] && git interpret-trailers --in-place --if-exists addIfDifferent --trailer "$line" "$1" >/dev/null 2>&1 || true
33
33
  done
34
34
  exit 0
35
- `,Uf=`${or}
35
+ `,Hf=`${or}
36
36
  # \u2500\u2500 bostrat: report the commit (code.committed + rework analysis, node-side).
37
37
  [ -z "$${pe}" ] && exit 0
38
38
  [ -z "$${We}" ] && exit 0
@@ -41,7 +41,7 @@ cwd=$(git rev-parse --show-toplevel 2>/dev/null)
41
41
  printf '{"sha":"%s","cwd":"%s"}' "$sha" "$cwd" | curl -sS -m 5 -X POST "$${We}/api/git/committed" \\
42
42
  -H 'content-type: application/json' -H "${ft}: $${pe}" --data-binary @- >/dev/null 2>&1 || true
43
43
  exit 0
44
- `,Hf=`${or}
44
+ `,Wf=`${or}
45
45
  # \u2500\u2500 bostrat: the tree moved \u2014 let the node re-read this workspace's lockfiles.
46
46
  [ -z "$${pe}" ] && exit 0
47
47
  [ -z "$${We}" ] && exit 0
@@ -50,7 +50,7 @@ curl -sS -m 3 -X POST "$${We}/api/deps/refresh" \\
50
50
  -H 'content-type: application/json' -H "${ft}: $${pe}" --data-binary '{}' >/dev/null 2>&1 || true
51
51
  exit 0
52
52
  `});import xt from"node:fs/promises";import tn from"node:os";import Ke from"node:path";import{execFile as Ic}from"node:child_process";import{promisify as Pc}from"node:util";function rs(e=process.env){return e.BOSTRAT_CGROUP_ROOT||"/sys/fs/cgroup"}function os(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 Fc(e=process.env){let t=os(e);return t==="on"?!0:t==="off"?!1:e.BOSTRAT_INSTALL_KIND==="container"||!!e.FLY_MACHINE_ID}function ss(e=tn.totalmem()){return Math.max(e-Cc*$t,Math.floor(e/2))}function Uc(e=tn.totalmem(),t=process.env){let n=Number(t.BOSTRAT_BOX_MEMORY_MAX_MB);return Number.isFinite(n)&&n>=256?Math.floor(n)*$t:Math.min(Bc*$t,ss(e))}function Hc(e=process.env){return Ke.join(rs(e),jc)}async function Wc(e){return(await xt.readFile(e,"utf8")).trim()}async function is({env:e=process.env,totalBytes:t=tn.totalmem(),force:n=!1,platform:r=process.platform}={}){if(!n&&!Fc(e))return Ge=os(e)==="off"?{available:!1,reason:"disabled (BOSTRAT_BOX_CGROUPS=0)"}:await Kc({env:e,totalBytes:t,platform:r}),Ge;let o=rs(e),s=Hc(e);try{let a;try{a=(await Wc(Ke.join(o,"cgroup.controllers"))).split(/\s+/).filter(Boolean)}catch(d){throw new Error(`no cgroup v2 tree at ${o} (${d?.code||d?.message||d})`)}let l=["cpu","memory"].filter(d=>a.includes(d));if(!l.length)throw new Error(`cgroup v2 at ${o} offers neither cpu nor memory (controllers: ${a.join(" ")||"none"})`);await xt.mkdir(s,{recursive:!0});let h=`+${l.join(" +")}`;for(let d of[Ke.join(o,"cgroup.subtree_control"),Ke.join(s,"cgroup.subtree_control")])try{await xt.writeFile(d,h)}catch(S){throw new Error(`cannot enable ${h} in ${d} (${S?.code||S?.message||S})`)}let m=ss(t);l.includes("cpu")&&await xt.writeFile(Ke.join(s,"cpu.weight"),String(es)),l.includes("memory")&&await xt.writeFile(Ke.join(s,"memory.max"),String(m)),Ge={available:!0,backend:"cgroupfs",path:s,controllers:l,cpuWeight:l.includes("cpu")?es:null,memoryMaxMb:l.includes("memory")?Math.round(m/$t):null}}catch(a){Ge={available:!1,reason:a?.message||String(a)}}return Ge}async function Kc({env:e=process.env,totalBytes:t=tn.totalmem(),platform:n=process.platform}={}){if(n!=="linux")return{available:!1,reason:`not a Fly/container node, and no systemd on ${n}`};try{await Dc(ts(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(`
53
- `)[0]})`}}let r=Uc(t,e);return{available:!0,backend:"systemd",path:null,controllers:["memory"],cpuWeight:null,memoryMaxMb:Math.round(r/$t),swapMaxMb:Lc,systemctl:ts(e),procRoot:e.BOSTRAT_PROC_ROOT||"/proc"}}function as(e=Ge){let t=`nice ${ns} 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 Dc,ns,es,Cc,jc,Bc,Lc,$t,Ge,ts,sr=O(()=>{Dc=Pc(Ic),ns=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),es=50,Cc=768,jc="bostrat-boxes",Bc=4096,Lc=512,$t=1024*1024;Ge=null;ts=(e=process.env)=>e.BOSTRAT_SYSTEMCTL_BIN||"systemctl"});import{execFile as Gc}from"node:child_process";import{promisify as zc}from"node:util";import us from"node:fs";import Vc from"node:os";function ds(e){return`/tmp/tmux-${e}/default`}function Yc({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=ds(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function ar(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Jc(e,{loginShell:t});return r===ps?!0:r===ir?!1:n}async function Jc(e,{loginShell:t=!1,timeoutMs:n=Xc}={}){if(!e)return ir;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await qc(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),ps}catch(s){return s?.killed||s?.signal?ls:s?.code===1||s?.code===127?ir:ls}}var qc,Ph,cs,Dh,Ch,jh,Bh,Lh,ps,ir,ls,Xc,nn,Fh,Uh,Hh,Wh,Kh,Gh,Xn=O(()=>{Kt();zn();qn();Zn();Fo();Yo();Jo();Yn();Gt();Qo();sr();Ee();qc=zc(Gc),Ph=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";cs=typeof process.getuid=="function"?process.getuid():0,Dh=Yc({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return us.existsSync(ds(cs))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:cs}),Ch=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",jh=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Bh=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),Lh=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);ps="present",ir="absent",ls="unknown",Xc=5e3;nn={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"},Fh=(()=>{try{let e=Vc.homedir();if(e&&us.existsSync(e))return e}catch{}return"/"})(),Uh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Hh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Wh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Kh=Number(process.env.BOSTRAT_BOX_COLS)||120,Gh=Number(process.env.BOSTRAT_BOX_ROWS)||40});var js={};Rn(js,{NODE_IMAGE:()=>dr,commandPlan:()=>Ps,flyToml:()=>Is,flyWizard:()=>_l,parseFlyFlags:()=>Ds,stageConfig:()=>Cs});import ur from"node:fs";import Ne from"node:path";import hl from"node:os";import ml from"node:readline/promises";import{execFile as gl}from"node:child_process";import{createRequire as wl}from"node:module";import{randomUUID as yl}from"node:crypto";function Is({app:e,region:t,nodeName:n=e,planeUrl:r=Ms,image:o=dr}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
53
+ `)[0]})`}}let r=Uc(t,e);return{available:!0,backend:"systemd",path:null,controllers:["memory"],cpuWeight:null,memoryMaxMb:Math.round(r/$t),swapMaxMb:Lc,systemctl:ts(e),procRoot:e.BOSTRAT_PROC_ROOT||"/proc"}}function as(e=Ge){let t=`nice ${ns} 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 Dc,ns,es,Cc,jc,Bc,Lc,$t,Ge,ts,sr=O(()=>{Dc=Pc(Ic),ns=(()=>{let e=Number(process.env.BOSTRAT_BOX_NICE);return Number.isInteger(e)&&e>=0&&e<=19?e:10})(),es=50,Cc=768,jc="bostrat-boxes",Bc=4096,Lc=512,$t=1024*1024;Ge=null;ts=(e=process.env)=>e.BOSTRAT_SYSTEMCTL_BIN||"systemctl"});import{execFile as Gc}from"node:child_process";import{promisify as zc}from"node:util";import us from"node:fs";import Vc from"node:os";function ds(e){return`/tmp/tmux-${e}/default`}function Yc({explicit:e,legacyExists:t,runtimeDir:n,uid:r}){if(e)return e;let o=ds(r);return t?o:n?`${n}/bostrat/tmux-default`:o}async function ar(e,{loginShell:t=!1,failOpen:n=!1}={}){let r=await Jc(e,{loginShell:t});return r===ps?!0:r===ir?!1:n}async function Jc(e,{loginShell:t=!1,timeoutMs:n=Xc}={}){if(!e)return ir;let r=t?process.env.SHELL||"/bin/sh":"sh",o=t?"-lic":"-c";try{return await qc(r,[o,'command -v "$1" >/dev/null 2>&1',"_",e],{timeout:n}),ps}catch(s){return s?.killed||s?.signal?ls:s?.code===1||s?.code===127?ir:ls}}var qc,Dh,cs,Ch,jh,Bh,Lh,Fh,ps,ir,ls,Xc,nn,Uh,Hh,Wh,Kh,Gh,zh,Xn=O(()=>{Kt();zn();qn();Zn();Fo();Yo();Jo();Yn();Gt();Qo();sr();Ee();qc=zc(Gc),Dh=process.env.BOSTRAT_TMUX_BIN||"/usr/bin/tmux";cs=typeof process.getuid=="function"?process.getuid():0,Ch=Yc({explicit:process.env.BOSTRAT_TMUX_SOCKET,legacyExists:(()=>{try{return us.existsSync(ds(cs))}catch{return!1}})(),runtimeDir:process.env.XDG_RUNTIME_DIR,uid:cs}),jh=process.env.BOSTRAT_DEFAULT_CWD||process.env.HOME||"/",Bh=process.env.BOSTRAT_AGENT_CMD||"claude --dangerously-skip-permissions",Lh=Object.freeze(["BOSTRAT_PLANE_URL","BOSTRAT_PLANE_TOKEN"]),Fh=Object.freeze(["TMPDIR","CLAUDE_CODE_TMPDIR"]);ps="present",ir="absent",ls="unknown",Xc=5e3;nn={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"},Uh=(()=>{try{let e=Vc.homedir();if(e&&us.existsSync(e))return e}catch{}return"/"})(),Hh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_COLS)||100,Wh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_ROWS)||40,Kh=Number(process.env.BOSTRAT_PROMPT_CAPTURE_LINES)||80,Gh=Number(process.env.BOSTRAT_BOX_COLS)||120,zh=Number(process.env.BOSTRAT_BOX_ROWS)||40});var js={};Rn(js,{NODE_IMAGE:()=>dr,commandPlan:()=>Ps,flyToml:()=>Is,flyWizard:()=>_l,parseFlyFlags:()=>Ds,stageConfig:()=>Cs});import ur from"node:fs";import Ne from"node:path";import hl from"node:os";import ml from"node:readline/promises";import{execFile as gl}from"node:child_process";import{createRequire as wl}from"node:module";import{randomUUID as yl}from"node:crypto";function Is({app:e,region:t,nodeName:n=e,planeUrl:r=Ms,image:o=dr}){return`# bostrat node on YOUR Fly org \u2014 written by \`bostrat-node fly\`.
54
54
  # Redeploy after edits: fly deploy <this dir> -c <this file> -a ${e} --ha=false
55
55
  # No [http_service] and none should be added: the node dials OUT to the plane;
56
56
  # nothing inbound, ever. The node token lives in \`fly secrets\`, not here.
@@ -123,7 +123,7 @@ Run it? (Y/n)`,"Y")).toLowerCase().startsWith("n"))return n.write(`aborted \u201
123
123
  redeploy: fly deploy ${R} -c ${Ne.join(R,"fly.toml")} -a ${d} --ha=false
124
124
  Vendor logins (Claude/Codex) are NOT set up here \u2014 you type those later, inside
125
125
  boxes, and they land on this machine's volume, never on bostrat (box-auth-policy).
126
- `),h(0)}var Ms,bl,dr,on,Bs=O(()=>{Ms="wss://plane.bostrat.ai/v1/node",bl=wl(import.meta.url)("../package.json").version,dr=`ghcr.io/globocodes/bostrat-node:${bl}`;on=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let s=gl("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 Ls(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!xl.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 $l(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:Ls(o.from,"from",n),toMs:Ls(o.to,"to",n)}))}return t}var Tl,xl,bm,Sm,Fs=O(()=>{Tl={"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."}]},xl=/^\d{4}-\d{2}-\d{2}$/;bm=$l(Tl),Sm=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var Us=O(()=>{Fs()});import Hs from"node:fs/promises";import Gs from"node:path";import vl from"node:os";function Vs(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function qs(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Ys(e){let t=new Date(Vs(e));return t.setDate(t.getDate()+7),t.getTime()}function Xs(e){let t=new Date(qs(e));return t.setMonth(t.getMonth()+1),t.getTime()}function Rl(e=Date.now()){for(let[t,n]of Object.entries(El)){let r=n.startOf(e);if(r!==sn[t]){sn[t]=r;for(let o of pr.values())o[t]=0;for(let o of Ws)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&Ws.delete(o)}}}function Nl(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 Js(e,{source:t="local",updatedAt:n=Date.now()}={}){Ve={caps:Nl(e),updatedAt:n,source:t};try{await Hs.mkdir(zs,{recursive:!0}),await Hs.writeFile(Al(),JSON.stringify(Ve,null,2))}catch{}return Ml()}function Ml(e=Date.now()){Rl(e);let t=new Set([...pr.keys(),...Object.keys(Ve?.caps||{})]),n={};for(let r of t){let o=pr.get(r);n[r]={weeklyUsd:Ks(o?.weekly||0),monthlyUsd:Ks(o?.monthly||0)}}return{caps:Ve?.caps||{},configured:!!Ve,seeded:Ol,updatedAt:Ve?.updatedAt??null,spent:n,windows:{weekly:{start:sn.weekly,resetsAt:Ys(e)},monthly:{start:sn.monthly,resetsAt:Xs(e)}},warnPct:kl}}var zs,Al,kl,El,Ve,Ol,sn,pr,Ws,Ks,Zs=O(()=>{en();Us();zs=process.env.BOSTRAT_STATE_DIR||Gs.join(process.env.HOME||vl.tmpdir(),".bostrat"),Al=()=>Gs.join(zs,"usage-caps.json"),kl=.8;El={weekly:{startOf:Vs,nextStart:Ys,capKey:"weeklyUsd"},monthly:{startOf:qs,nextStart:Xs,capKey:"monthlyUsd"}},Ve=null,Ol=!1,sn={weekly:0,monthly:0},pr=new Map,Ws=new Set;Ks=e=>Math.round(e*1e4)/1e4});function ni(){return Object.fromEntries(Object.entries(Qs.tokens).filter(([,e])=>ti(e)).map(([e,t])=>[e,t.access]))}function ri(){let e={};for(let[t,n]of Object.entries(Qs.tokens)){let r=ti(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 ei)e[t]||(e[t]={state:"login-pending",source:"broker",startedAt:n.startedAt,redirectUri:n.redirectUri});return e}var Im,Pm,Qs,ei,ti,oi,si=O(()=>{Im=10*6e4,Pm=5*6e4,Qs={tokens:{},clients:{}},ei=new Map,ti=e=>typeof e?.access=="string"&&e.access&&!e.needsLogin&&(e.expiresAt==null||e.expiresAt>Date.now());oi=()=>[...ei.keys()]});import Il from"node:fs";import ye from"node:fs/promises";import di from"node:os";import Ye from"node:path";function fi(e){return mr.add(e),()=>mr.delete(e)}function an(){return{entries:structuredClone(hr),at:Date.now()}}function Ll(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 Fl(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 = ${ai(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 = ${ai(r)}`)}return n.join(`
126
+ `),h(0)}var Ms,bl,dr,on,Bs=O(()=>{Ms="wss://plane.bostrat.ai/v1/node",bl=wl(import.meta.url)("../package.json").version,dr=`ghcr.io/globocodes/bostrat-node:${bl}`;on=(e,{stdin:t,exec:n}={})=>new Promise((r,o)=>{if(n)return n(e,{stdin:t}).then(r,o);let s=gl("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 Ls(e,t,n){if(e==null)return t==="from"?-1/0:1/0;if(!xl.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 $l(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:Ls(o.from,"from",n),toMs:Ls(o.to,"to",n)}))}return t}var Tl,xl,Sm,_m,Fs=O(()=>{Tl={"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."}]},xl=/^\d{4}-\d{2}-\d{2}$/;Sm=$l(Tl),_m=Object.freeze({staleDays:90,leadDays:14,confirmDays:30})});var Us=O(()=>{Fs()});import Hs from"node:fs/promises";import Gs from"node:path";import vl from"node:os";function Vs(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}function qs(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(1),t.getTime()}function Ys(e){let t=new Date(Vs(e));return t.setDate(t.getDate()+7),t.getTime()}function Xs(e){let t=new Date(qs(e));return t.setMonth(t.getMonth()+1),t.getTime()}function Rl(e=Date.now()){for(let[t,n]of Object.entries(El)){let r=n.startOf(e);if(r!==sn[t]){sn[t]=r;for(let o of pr.values())o[t]=0;for(let o of Ws)o.includes(`:${t}:`)&&!o.endsWith(`:${r}`)&&Ws.delete(o)}}}function Nl(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 Js(e,{source:t="local",updatedAt:n=Date.now()}={}){Ve={caps:Nl(e),updatedAt:n,source:t};try{await Hs.mkdir(zs,{recursive:!0}),await Hs.writeFile(Al(),JSON.stringify(Ve,null,2))}catch{}return Ml()}function Ml(e=Date.now()){Rl(e);let t=new Set([...pr.keys(),...Object.keys(Ve?.caps||{})]),n={};for(let r of t){let o=pr.get(r);n[r]={weeklyUsd:Ks(o?.weekly||0),monthlyUsd:Ks(o?.monthly||0)}}return{caps:Ve?.caps||{},configured:!!Ve,seeded:Ol,updatedAt:Ve?.updatedAt??null,spent:n,windows:{weekly:{start:sn.weekly,resetsAt:Ys(e)},monthly:{start:sn.monthly,resetsAt:Xs(e)}},warnPct:kl}}var zs,Al,kl,El,Ve,Ol,sn,pr,Ws,Ks,Zs=O(()=>{en();Us();zs=process.env.BOSTRAT_STATE_DIR||Gs.join(process.env.HOME||vl.tmpdir(),".bostrat"),Al=()=>Gs.join(zs,"usage-caps.json"),kl=.8;El={weekly:{startOf:Vs,nextStart:Ys,capKey:"weeklyUsd"},monthly:{startOf:qs,nextStart:Xs,capKey:"monthlyUsd"}},Ve=null,Ol=!1,sn={weekly:0,monthly:0},pr=new Map,Ws=new Set;Ks=e=>Math.round(e*1e4)/1e4});function ni(){return Object.fromEntries(Object.entries(Qs.tokens).filter(([,e])=>ti(e)).map(([e,t])=>[e,t.access]))}function ri(){let e={};for(let[t,n]of Object.entries(Qs.tokens)){let r=ti(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 ei)e[t]||(e[t]={state:"login-pending",source:"broker",startedAt:n.startedAt,redirectUri:n.redirectUri});return e}var Pm,Dm,Qs,ei,ti,oi,si=O(()=>{Pm=10*6e4,Dm=5*6e4,Qs={tokens:{},clients:{}},ei=new Map,ti=e=>typeof e?.access=="string"&&e.access&&!e.needsLogin&&(e.expiresAt==null||e.expiresAt>Date.now());oi=()=>[...ei.keys()]});import Il from"node:fs";import ye from"node:fs/promises";import di from"node:os";import Ye from"node:path";function fi(e){return mr.add(e),()=>mr.delete(e)}function an(){return{entries:structuredClone(hr),at:Date.now()}}function Ll(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 Fl(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 = ${ai(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 = ${ai(r)}`)}return n.join(`
127
127
  `)+`
128
128
 
129
129
  `}function hi(e){let t=[],n=`(?:[A-Za-z0-9_-]+|"[^"
@@ -219,7 +219,7 @@ fi
219
219
  ${y("failed",'"deploy-pi.sh v$TO failed AND the rollback failed"')}
220
220
  exit 1
221
221
  `}async function Nr(e=fn){try{return JSON.parse(await be.readFile(e,"utf8"))}catch{return null}}async function Ki({to:e,from:t=dn,kind:n=Qe(),reason:r="manual",force:o=!1,statusFile:s=fn,spawnImpl:a=_u,now:l=Date.now,npmPrefix:h=void 0,log:m=console}={}){if(!e)return{ok:!1,reason:"no target version"};if(!hn.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 Nr(s);if(Mr(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<Er))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 w=d?.to===e&&(d.status==="failed"||d.status==="rolled-back")?S+1:1;await be.mkdir(U.dirname(s),{recursive:!0});let y=h!==void 0?h:n==="npm-global"?Jn(await Ru())||U.resolve(U.dirname(process.execPath),".."):null,b=Rr(),M=Wi({kind:n,to:e,from:t,statusFile:s,npmPrefix:y,startedAt:l(),attempts:w,restart:b}),T=U.join(U.dirname(s),`update-${e}.sh`),R=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:w,startedAt:l(),updatedAt:l()}));let A=Rt.existsSync("/run/systemd/system")&&await Nu("systemd-run"),v=A?["systemd-run",["--user","--collect","--quiet",`--unit=bostrat-self-update-${e}`,"--property=KillMode=process","bash",T]]:["bash",[T]],N=async x=>{let D=`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:w,startedAt:l(),updatedAt:l(),error:D})).catch(()=>{}),m.error?.(`[self-update] ${D}`),D},E=null;try{A||(E=Rt.openSync(R,"a"));let x=a(v[0],v[1],{detached:!0,stdio:A?"ignore":["ignore",E,E]});x.on?.("error",D=>{N(D)}),x.unref?.()}catch(x){return{ok:!1,reason:await N(x)}}finally{E!==null&&Rt.closeSync(E)}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 Ru(){try{return await be.realpath(new URL(import.meta.url).pathname)}catch{return""}}async function Nu(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 Iu({statusFile:e=fn,current:t=dn,now:n=Date.now,staleMs:r=Mu}={}){let o=await Nr(e);if(!o)return null;let s=a=>be.writeFile(e,JSON.stringify(a)).catch(()=>{});if(Mr(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 Pu({isBusy:e,start:t=Ki,onStuck:n=null,onStarted:r=null,tickMs:o=Au,stuckMs:s=vu,now:a=Date.now,setIntervalImpl:l=setInterval,clearIntervalImpl:h=clearInterval,log:m=console}={}){let d=null,S=()=>{d?.timer&&h(d.timer),d=null},w=async()=>{if(!d)return;let y=!0;try{y=await e()!==!1}catch{y=!0}if(y){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:y,from:b=dn,kind:M=Qe()}){return d?.to===y?!1:(S(),d={to:y,from:b,kind:M,since:a(),stuckFired:!1,timer:l(w,o)},d.timer.unref?.(),!0)},tick:w,cancel:S,get armed(){return d?{to:d.to,from:d.from,kind:d.kind,since:d.since}:null}}}var dn,$u,pn,fn,vu,Au,Ar,kr,Er,un,Li,Fi,Ui,hn,Q,Ou,Mr,Mu,zi=O(()=>{vr();Bi();dn=(()=>{try{return xu(import.meta.url)("../package.json").version||null}catch{return null}})(),$u=process.env.BOSTRAT_STATE_DIR||U.join(process.env.HOME||Su.tmpdir(),".bostrat"),pn=U.join($u,"self-update"),fn=U.join(pn,"status.json"),vu=1440*6e4,Au=6e4,Ar=60,kr=15,Er=3,un=6,Li=20,Fi=U.join(pn,"supervisor.pid"),Ui="SIGUSR2",hn=new Set(["npm-global","git-checkout"]);Q=e=>`'${String(e).replace(/'/g,"'\\''")}'`;Ou=new Set(["updating","restarting","rolling-back"]),Mr=e=>!!(e&&Ou.has(e.status));Mu=45*6e4});Mn();Xn();sr();import z from"node:fs";import L from"node:path";import tt from"node:os";import{createRequire as Ir}from"node:module";import{execFile as Du,spawn as Cu}from"node:child_process";import{promisify as ju}from"node:util";import Bu from"node:readline/promises";import{randomUUID as Lu}from"node:crypto";import{fileURLToPath as Fu}from"node:url";import rn from"node:fs";import ze from"node:fs/promises";import Zc from"node:os";import vt from"node:path";import Qc from"node:readline";import{spawn as el}from"node:child_process";var tl="^(ugrep|rg|2\\.1\\.[0-9]+|cursor-agent|codex|npm|node|MainThread)",nl="^(bostrat-|tmux|earlyoom|systemd|sshd)",rl=()=>["-m","10","-s","70","-r","600","--prefer",tl,"--avoid",nl],fs="BOSTRAT_OOM_GUARD_OWNER",ol=6e4,sl=5e3;function hs(e=process.env){return!["0","off","false","no"].includes(String(e.BOSTRAT_OOM_GUARD??"").trim().toLowerCase())}function ms(e=process.env){let t=e.BOSTRAT_STATE_DIR||vt.join(e.HOME||Zc.tmpdir(),".bostrat");return vt.join(t,"oom-guard.pid")}function gs(e=process.env){if(e.BOSTRAT_EARLYOOM_BIN)return rn.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=vt.join(n,"earlyoom");if(rn.existsSync(r))return r}return null}async function ws({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(vt.join(e,r,"comm"),"utf8").catch(()=>"")).trim()==="earlyoom"&&n.push({pid:Number(r)})}return n}async function ys(e){let t=Number((await ze.readFile(e,"utf8").catch(()=>"")).trim());return Number.isInteger(t)&&t>0?t:null}async function bs({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc"}={}){if(!hs(e))return{state:"off"};if(t!=="linux")return{state:"unsupported",platform:t};let r=await ws({procRoot:n}),o=await ys(ms(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=gs(e);return a?{state:"stopped",bin:a}:{state:"absent"}}function cr(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 Ss({env:e=process.env,platform:t=process.platform,procRoot:n=e.BOSTRAT_PROC_ROOT||"/proc",log:r=console.log,spawnImpl:o=el,checkMs:s=ol,relaunchMs:a=sl}={}){let l=null,h={state:null},m=null,d=!1,S="",w=ms(e),y=A=>{h=A;let v=`[oom-guard] ${cr(A)}`;return v!==S&&r(v),S=v,A},b=A=>{d||(clearTimeout(m),m=setTimeout(()=>M().catch(()=>{}),A),m.unref?.())},M=async()=>{if(d||l)return h;if(!hs(e))return y({state:"off"});if(t!=="linux")return y({state:"unsupported",platform:t});let A=await ys(w),v=await ws({procRoot:n});if(A&&v.some(x=>x.pid===A)){try{process.kill(A,"SIGTERM")}catch{}v=v.filter(x=>x.pid!==A)}if(v.length)return b(s),y({state:"host",pid:v[0].pid});let N=gs(e);if(!N)return b(s),y({state:"absent"});let E;try{E=o(N,rl(),{stdio:["ignore","pipe","pipe"]})}catch(x){return r(`[oom-guard] could not start ${N}: ${x?.message||x}`),b(s),h}l=E;for(let x of[E.stdout,E.stderr])x&&Qc.createInterface({input:x}).on("line",D=>r(`[earlyoom] ${D}`));return E.on("error",x=>{r(`[oom-guard] ${N}: ${x?.message||x}`),!(l!==E||E.pid)&&(l=null,b(s))}),E.on("exit",(x,D)=>{l===E&&(l=null,ze.rm(w,{force:!0}).catch(()=>{}),!d&&(r(`[oom-guard] earlyoom exited (${D||`code ${x}`}) \u2014 relaunching in ${Math.round(a/1e3)} s`),h={state:"stopped",bin:N},S="",b(a)))}),E.pid&&(await ze.mkdir(vt.dirname(w),{recursive:!0}).catch(()=>{}),await ze.writeFile(w,`${E.pid}
222
- `).catch(()=>{})),b(s),y({state:"own",pid:E.pid})},T=()=>{l&&(l.kill("SIGTERM"),rn.rmSync(w,{force:!0}))};return process.on("exit",T),{ready:M().catch(()=>h),status:()=>h,stop(){d=!0,clearTimeout(m),process.off("exit",T);let A=l;l=null,A&&(A.kill("SIGTERM"),rn.rmSync(w,{force:!0}))}}}Bn();import il from"node:fs";import _s from"node:path";import al from"node:os";var cl=()=>process.env.BOSTRAT_STATE_DIR||_s.join(process.env.HOME||al.tmpdir(),".bostrat"),ll=()=>_s.join(cl(),"plane-link","public-host.json");var At=null;function ul(){if(At)return At;try{let e=JSON.parse(il.readFileSync(ll(),"utf8"));At={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{At={viewBase:null}}return At}function dl(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),o=r?r[1].toLowerCase():t,s=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return s?{proto:o,host:s}:null}function Ts(){return ul().viewBase}function xs(e=process.env.BOSTRAT_PUBLIC_HOST){return dl(e,"https")}function $s(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 pl from"node:fs";import fl from"node:os";import vs from"node:path";var As=3*6e4;function lr(e=process.env){let t=e.BOSTRAT_STATE_DIR||vs.join(e.HOME||fl.tmpdir(),".bostrat");return vs.join(t,"heartbeat.json")}function ks(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return As;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):As}function Es(e=lr()){try{let t=JSON.parse(pl.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 Rs="BOSTRAT_RESTART_NOTICE",um=2*6e4;var Os=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Ns({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:Os(e),staleS:Os(t)!=null?Math.round(t/1e3):null})}Ee();var Vi=(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=ju(Du),Pr=L.dirname(Fu(import.meta.url)),Me=L.resolve(Pr,".."),Uu=L.join(Pr,"index.js"),Hu="wss://plane.bostrat.ai/v1/node",et=Ir(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}),X=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function Wu(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?I("node runtime",`${process.version} at ${process.execPath}`):X("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Ku(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 Gu(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 zu(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 X("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function qi(e,{required:t=!1}={}){if(await ar(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=nn[e]?`${nn[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?X(e,r,o):H(e,r,o)}async function Vu(){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",nn.gh)}}async function qu(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>qi(t)));return e.some(t=>t.level==="pass")||e.push(X("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 Yu(){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 ar(t,{failOpen:!1})?I(t,"resolves on the service PATH"):H(t,`not on the service PATH \u2014 ${n}`,r)))}async function Xu(){try{let t=Ir(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=Ir(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 X("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function Ju(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"?X:H)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function Zu(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?X("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 Qu(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(X("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-${Lu().slice(0,8)}`,ephemeral:!0}))),a.on("message",S=>{try{let w=JSON.parse(S);w.type==="hello_ok"?(typeof w.viewBase=="string"&&w.viewBase&&(l=w.viewBase),h=w.mode==="local"?"local":"default",w.minNodeVersion&&Vi(et,w.minNodeVersion)?m(X("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${w.minNodeVersion} \u2014 this node is ${et}; the real link is refused until it updates`,`bostrat-node self-update --to ${w.latestNodeVersion||w.minNodeVersion}`)):w.latestNodeVersion&&Vi(et,w.latestNodeVersion)?m(H("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${w.latestNodeVersion} is available (this node: ${et})`,`bostrat-node self-update --to ${w.latestNodeVersion}`)):m(I("plane link",`hello_ok in ${Date.now()-r}ms (${o})`))):w.type==="error"&&m(X("plane link",`plane said: ${w.code} ${w.message||""}`,"check the token"))}catch{}}),a.on("error",S=>m(X("plane link",`${S?.message||S}`,"check the URL, the token, and the plane's IP gate")))})}function ed(e,t=null){let n=oo(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 td(){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 X("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 nd(e){let t=await is({env:e}),n=as(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 rd(e){let t=await bs({env:e}),n=cr(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 od(e){let t=await Po({env:e}),n=Do(t);return t.level==="misconfigured"?X("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 sd(e){let t=jn(e),n=vo(t);return t.unknown?.length?H("audit guard",n,`BOSTRAT_AUDIT_GUARD names unknown rule(s): ${t.unknown.join(", ")}`):I("audit guard",n)}function id(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 ad(e,t){let n=t?.viewBase??null,r=Ts(),o=xs(e.BOSTRAT_PUBLIC_HOST),s=(()=>{let a=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(a)return`${a.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let l=$s(e.BOSTRAT_PLANE_URL);return l?`${l}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let a=o&&o.host!==n?`; BOSTRAT_PUBLIC_HOST=${o.host} is set but the plane's value wins`:"";return I("public host",`views https://<slug>.${n}/ (plane hello_ok)${a} \xB7 track links ${s}`)}return r?I("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${s}`):o?I("public host",`views ${o.proto}://<slug>.${o.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${s}`):X("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${s}`,"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 Yi(e,t={}){let n=[];n.push(await Wu()),n.push(Gu(t.envFile||Fe())),n.push(await zu(e)),n.push(await nd(e)),n.push(await rd(e)),n.push(sd(e)),n.push(await od(e)),n.push(...await qu()),n.push(await qi("git",{required:!0})),n.push(await Vu()),n.push(...await Yu()),n.push(await Xu()),n.push(Ju(e)),n.push(Zu(e)),n.push(Ku(e));let r=await Qu(e,t);n.push(r);let o=ed(e,r);return o&&n.push(o),n.push(ad(e,r)),n.push(td()),n.push(id(e)),n}function Xi(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?`
222
+ `).catch(()=>{})),b(s),y({state:"own",pid:E.pid})},T=()=>{l&&(l.kill("SIGTERM"),rn.rmSync(w,{force:!0}))};return process.on("exit",T),{ready:M().catch(()=>h),status:()=>h,stop(){d=!0,clearTimeout(m),process.off("exit",T);let A=l;l=null,A&&(A.kill("SIGTERM"),rn.rmSync(w,{force:!0}))}}}Bn();import il from"node:fs";import _s from"node:path";import al from"node:os";var cl=()=>process.env.BOSTRAT_STATE_DIR||_s.join(process.env.HOME||al.tmpdir(),".bostrat"),ll=()=>_s.join(cl(),"plane-link","public-host.json");var At=null;function ul(){if(At)return At;try{let e=JSON.parse(il.readFileSync(ll(),"utf8"));At={viewBase:typeof e?.viewBase=="string"&&e.viewBase?e.viewBase:null}}catch{At={viewBase:null}}return At}function dl(e,t){let n=String(e||"").trim();if(!n)return null;let r=/^(https?):\/\/(.+?)\/?$/i.exec(n),o=r?r[1].toLowerCase():t,s=(r?r[2]:n).replace(/\/.*$/,"").replace(/:\d+$/,"").toLowerCase();return s?{proto:o,host:s}:null}function Ts(){return ul().viewBase}function xs(e=process.env.BOSTRAT_PUBLIC_HOST){return dl(e,"https")}function $s(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 pl from"node:fs";import fl from"node:os";import vs from"node:path";var As=3*6e4;function lr(e=process.env){let t=e.BOSTRAT_STATE_DIR||vs.join(e.HOME||fl.tmpdir(),".bostrat");return vs.join(t,"heartbeat.json")}function ks(e=process.env){let t=String(e.BOSTRAT_HEARTBEAT_STALE_MS??"").trim().toLowerCase();if(!t)return As;if(t==="off"||t==="0"||t==="false")return 0;let n=Number(t);return Number.isFinite(n)&&n>0?Math.round(n):As}function Es(e=lr()){try{let t=JSON.parse(pl.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 Rs="BOSTRAT_RESTART_NOTICE",dm=2*6e4;var Os=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Ns({at:e,staleMs:t}={}){return JSON.stringify({kind:"supervisor",at:Os(e),staleS:Os(t)!=null?Math.round(t/1e3):null})}Ee();var Vi=(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=ju(Du),Pr=L.dirname(Fu(import.meta.url)),Me=L.resolve(Pr,".."),Uu=L.join(Pr,"index.js"),Hu="wss://plane.bostrat.ai/v1/node",et=Ir(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}),X=(e,t,n)=>({name:e,level:"fail",detail:t,fix:n});async function Wu(){let[e,t]=process.versions.node.split(".").map(Number);return e>22||e===22&&t>=5?I("node runtime",`${process.version} at ${process.execPath}`):X("node runtime",`${process.version} < 22.5`,"install Node \u226522.5 via nvm and re-run under it")}function Ku(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 Gu(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 zu(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 X("tmux",`${t} not runnable`,process.platform==="darwin"?"brew install tmux (then BOSTRAT_TMUX_BIN=/opt/homebrew/bin/tmux)":"install tmux")}}async function qi(e,{required:t=!1}={}){if(await ar(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=nn[e]?`${nn[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?X(e,r,o):H(e,r,o)}async function Vu(){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",nn.gh)}}async function qu(){let e=await Promise.all(["claude","codex","cursor-agent"].map(t=>qi(t)));return e.some(t=>t.level==="pass")||e.push(X("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 Yu(){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 ar(t,{failOpen:!1})?I(t,"resolves on the service PATH"):H(t,`not on the service PATH \u2014 ${n}`,r)))}async function Xu(){try{let t=Ir(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=Ir(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 X("node-pty",`load/spawn failed: ${e?.message||e}`,t)}}function Ju(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"?X:H)("chromium (mocks)",`${t} missing \u2014 mock rendering unavailable (bostrat-mock add fails)`,n)}function Zu(e){let t=e.BOSTRAT_CLAUDE_USE_API_KEY==="1";return t&&!e.ANTHROPIC_API_KEY?X("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 Qu(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(X("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-${Lu().slice(0,8)}`,ephemeral:!0}))),a.on("message",S=>{try{let w=JSON.parse(S);w.type==="hello_ok"?(typeof w.viewBase=="string"&&w.viewBase&&(l=w.viewBase),h=w.mode==="local"?"local":"default",w.minNodeVersion&&Vi(et,w.minNodeVersion)?m(X("plane link",`plane answers, but REQUIRES bostrat-node \u2265 ${w.minNodeVersion} \u2014 this node is ${et}; the real link is refused until it updates`,`bostrat-node self-update --to ${w.latestNodeVersion||w.minNodeVersion}`)):w.latestNodeVersion&&Vi(et,w.latestNodeVersion)?m(H("plane link",`hello_ok in ${Date.now()-r}ms (${o}); bostrat-node ${w.latestNodeVersion} is available (this node: ${et})`,`bostrat-node self-update --to ${w.latestNodeVersion}`)):m(I("plane link",`hello_ok in ${Date.now()-r}ms (${o})`))):w.type==="error"&&m(X("plane link",`plane said: ${w.code} ${w.message||""}`,"check the token"))}catch{}}),a.on("error",S=>m(X("plane link",`${S?.message||S}`,"check the URL, the token, and the plane's IP gate")))})}function ed(e,t=null){let n=oo(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 td(){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 X("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 nd(e){let t=await is({env:e}),n=as(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 rd(e){let t=await bs({env:e}),n=cr(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 od(e){let t=await Po({env:e}),n=Do(t);return t.level==="misconfigured"?X("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 sd(e){let t=jn(e),n=vo(t);return t.unknown?.length?H("audit guard",n,`BOSTRAT_AUDIT_GUARD names unknown rule(s): ${t.unknown.join(", ")}`):I("audit guard",n)}function id(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 ad(e,t){let n=t?.viewBase??null,r=Ts(),o=xs(e.BOSTRAT_PUBLIC_HOST),s=(()=>{let a=String(e.BOSTRAT_PUBLIC_URL||"").trim();if(a)return`${a.replace(/\/+$/,"")}/track/<id> (BOSTRAT_PUBLIC_URL)`;let l=$s(e.BOSTRAT_PLANE_URL);return l?`${l}/track/<id> (from BOSTRAT_PLANE_URL)`:"no app URL \u2014 ticket links can't be made (link a plane or set BOSTRAT_PUBLIC_URL)"})();if(n){let a=o&&o.host!==n?`; BOSTRAT_PUBLIC_HOST=${o.host} is set but the plane's value wins`:"";return I("public host",`views https://<slug>.${n}/ (plane hello_ok)${a} \xB7 track links ${s}`)}return r?I("public host",`views https://<slug>.${r}/ (persisted from the last hello) \xB7 track links ${s}`):o?I("public host",`views ${o.proto}://<slug>.${o.host}/ (BOSTRAT_PUBLIC_HOST) \xB7 track links ${s}`):X("public host",`none \u2014 \`bostrat-view up\` refuses on this node (no plane-stated view domain, no BOSTRAT_PUBLIC_HOST) \xB7 track links ${s}`,"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 Yi(e,t={}){let n=[];n.push(await Wu()),n.push(Gu(t.envFile||Fe())),n.push(await zu(e)),n.push(await nd(e)),n.push(await rd(e)),n.push(sd(e)),n.push(await od(e)),n.push(...await qu()),n.push(await qi("git",{required:!0})),n.push(await Vu()),n.push(...await Yu()),n.push(await Xu()),n.push(Ju(e)),n.push(Zu(e)),n.push(Ku(e));let r=await Qu(e,t);n.push(r);let o=ed(e,r);return o&&n.push(o),n.push(ad(e,r)),n.push(td()),n.push(id(e)),n}function Xi(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
223
  FAIL \u2014 ${r} blocking, ${o} warnings`:`
224
224
  OK \u2014 0 blocking, ${o} warnings`),r===0}async function cd({envFile:e=Fe(),input:t=process.stdin,output:n=process.stdout}={}){let r=Wt(e),o=Bu.createInterface({input:t,output:n}),s=async(A,v)=>(await o.question(v?`${A} [${v}]: `:`${A}: `)).trim()||v||"";n.write(`bostrat-node init \u2014 plane link + machine config. No vendor logins here:
225
225
  you type those inside each box, later (box-auth-policy).
@@ -286,7 +286,7 @@ WantedBy=default.target
286
286
  <key>StandardErrorPath</key><string>${o}/node.err.log</string>
287
287
  </dict>
288
288
  </plist>
289
- `}function gd(e=process.platform,t=tt.homedir()){return e==="darwin"?{kind:"launchd",file:L.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:L.join(t,".config","systemd","user","bostrat-node.service")}}async function wd({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=Me}={}){let{kind:s,file:a}=gd(n);if(!e&&o.split(L.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 Se("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),z.rmSync(a,{force:!0}),await Se("systemctl",["--user","daemon-reload"])):(await Se("launchctl",["unload","-w",a]).catch(()=>{}),z.rmSync(a,{force:!0})),r(`removed ${a}`);return}z.mkdirSync(L.dirname(a),{recursive:!0}),s==="systemd"?(z.writeFileSync(a,hd()),await Se("systemctl",["--user","daemon-reload"]),t&&await Se("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${a}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(z.mkdirSync(L.join(tt.homedir(),"Library","Logs","bostrat"),{recursive:!0}),z.writeFileSync(a,md()),t&&await Se("launchctl",["load","-w",a]),r(`installed ${a}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function Ug(e=process.argv.slice(2)){let t=e[0],n=Fe();if(t==="--version"||t==="-v"||t==="version")return console.log(et),0;if(t==="init")return(await cd({envFile:n})).ok?0:1;if(t==="doctor"){let r={...Wt(n),...process.env};return Xi(await Yi(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return fd({envFile:n}),null;if(t==="install-service")return await wd({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(Bs(),js));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:s}=await Promise.resolve().then(()=>(zi(),Gi)),{detectInstallKind:a}=await Promise.resolve().then(()=>(vr(),ji)),l=a(),h=e.indexOf("--to"),m=h>=0?String(e[h+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:et,installKind:l,policy:s({kind:l}),status:await o()},null,2)),0;if(!m)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let d=await r({to:m,kind:l,reason:"cli",force:!0});return d.ok?(console.log(`\u2713 self-update ${d.from??"?"} \u2192 ${d.to} started (${d.kind}) \u2014 status: ${d.statusFile}; the node restarts when the install completes`),0):(console.error(`\u2717 not started: ${d.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
289
+ `}function gd(e=process.platform,t=tt.homedir()){return e==="darwin"?{kind:"launchd",file:L.join(t,"Library","LaunchAgents","com.bostrat.node.plist")}:{kind:"systemd",file:L.join(t,".config","systemd","user","bostrat-node.service")}}async function wd({uninstall:e=!1,start:t=!0,platform:n=process.platform,log:r=console.log,agentDir:o=Me}={}){let{kind:s,file:a}=gd(n);if(!e&&o.split(L.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 Se("systemctl",["--user","disable","--now","bostrat-node.service"]).catch(()=>{}),z.rmSync(a,{force:!0}),await Se("systemctl",["--user","daemon-reload"])):(await Se("launchctl",["unload","-w",a]).catch(()=>{}),z.rmSync(a,{force:!0})),r(`removed ${a}`);return}z.mkdirSync(L.dirname(a),{recursive:!0}),s==="systemd"?(z.writeFileSync(a,hd()),await Se("systemctl",["--user","daemon-reload"]),t&&await Se("systemctl",["--user","enable","--now","bostrat-node.service"]),r(`installed ${a}${t?" (enabled + started)":""}`),r("logs: journalctl --user -u bostrat-node.service -f")):(z.mkdirSync(L.join(tt.homedir(),"Library","Logs","bostrat"),{recursive:!0}),z.writeFileSync(a,md()),t&&await Se("launchctl",["load","-w",a]),r(`installed ${a}${t?" (loaded)":""}`),r("logs: ~/Library/Logs/bostrat/node.{out,err}.log"))}async function Hg(e=process.argv.slice(2)){let t=e[0],n=Fe();if(t==="--version"||t==="-v"||t==="version")return console.log(et),0;if(t==="init")return(await cd({envFile:n})).ok?0:1;if(t==="doctor"){let r={...Wt(n),...process.env};return Xi(await Yi(r,{envFile:n}))?0:1}if(t==="run"||t==="start")return fd({envFile:n}),null;if(t==="install-service")return await wd({uninstall:e.includes("--uninstall"),start:!e.includes("--no-start")})||0;if(t==="fly"){let{flyWizard:r}=await Promise.resolve().then(()=>(Bs(),js));return await r({argv:e.slice(1)})}if(t==="self-update"){let{startSelfUpdate:r,readStatus:o,updatePolicy:s}=await Promise.resolve().then(()=>(zi(),Gi)),{detectInstallKind:a}=await Promise.resolve().then(()=>(vr(),ji)),l=a(),h=e.indexOf("--to"),m=h>=0?String(e[h+1]||"").replace(/^v/,""):null;if(e.includes("--status"))return console.log(JSON.stringify({current:et,installKind:l,policy:s({kind:l}),status:await o()},null,2)),0;if(!m)return console.error("bostrat-node self-update --to X.Y.Z (the release to move onto; the Nodes page / chat notice names the current one)"),1;let d=await r({to:m,kind:l,reason:"cli",force:!0});return d.ok?(console.log(`\u2713 self-update ${d.from??"?"} \u2192 ${d.to} started (${d.kind}) \u2014 status: ${d.statusFile}; the node restarts when the install completes`),0):(console.error(`\u2717 not started: ${d.reason}`),1)}return console.log(`bostrat-node \u2014 install and run a bostrat node (plane P1)
290
290
 
291
291
  usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-start] | fly | self-update --to X.Y.Z | --version>
292
292
 
@@ -295,4 +295,4 @@ usage: bostrat-node <init | doctor | run | install-service [--uninstall] [--no-s
295
295
  run start the node in the foreground (sources node.env)
296
296
  install-service run at boot/login: systemd --user (Linux) / launchd (macOS)
297
297
  fly provision this node on YOUR OWN Fly.io org (uses your flyctl)
298
- self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{ld as RESTART_SIGNAL,ud as ROLLBACK_GRACE_MS,dd as STALL_CHECK_MS,mn as SUPERVISOR_PID_FILE,ed as checkMode,pd as createRunSupervisor,cd as init,wd as installService,md as launchdPlist,Ug as main,Xi as printDoctor,fd as runAgent,Yi as runDoctor,gd as servicePaths,hd as systemdUnit};
298
+ self-update move this install onto a release (--to X.Y.Z; --status shows the last one)`),t?1:0}export{ld as RESTART_SIGNAL,ud as ROLLBACK_GRACE_MS,dd as STALL_CHECK_MS,mn as SUPERVISOR_PID_FILE,ed as checkMode,pd as createRunSupervisor,cd as init,wd as installService,md as launchdPlist,Hg as main,Xi as printDoctor,fd as runAgent,Yi as runDoctor,gd as servicePaths,hd as systemdUnit};