@reddb-io/red-skills 3.4.0 → 3.4.2

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,85 +1,94 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var Op=Object.defineProperty;var Ap=(e,n)=>()=>(e&&(n=e(e=0)),n);var Lp=(e,n)=>{for(var t in n)Op(e,t,{get:n[t],enumerable:!0})};var Ea={};Lp(Ea,{REDSKILLED_BIN_ENV:()=>Oo,REDSKILLED_BUNDLE_ASSET:()=>de,REDSKILLED_ENTRY_UNRESOLVED:()=>Fn,RedskilledDaemonEntryError:()=>Hn,isRedskilledEntryPath:()=>Lo,isResolvedRedskilledEntry:()=>ce,redskilledBundleCacheRoot:()=>Ft,redskilledServeArgv:()=>Ce,requireRedskilledEntry:()=>Ht,resolveRedskilledEntry:()=>Pe});import{existsSync as Mh,readdirSync as Ch}from"node:fs";import{homedir as Wh}from"node:os";import{basename as jo,dirname as Do,join as Y,resolve as Bt}from"node:path";function ce(e){return"command"in e}function Ce(e,n={}){let t=["serve","--socket",e.socketPath,"--lease",e.leasePath,"--events",e.eventLanePath,"--session-key-hash",e.sessionKeyHash,"--machine-id-hash",e.machineIdHash,"--machine-claim",e.machineClaimPath];return n.idleMs!=null&&t.push("--idle-ms",String(n.idleMs)),n.daemonVersion!=null&&t.push("--daemon-version",n.daemonVersion),t}function Ft(e=process.env){return va(e)}function Pe(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??Mh,o=n.execPath??process.execPath,s=n.execArgv??[],i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,l=(u,p)=>({command:o,args:[...s,u],source:p,entry:u}),a=t[Oo];if(a)return{command:a,args:[],source:"env-redskilled-bin",entry:a};if(i&&Lo(i))return l(Bt(i),"caller-entry");let d=[];for(let[u,p]of Uh(i,n.rootDir,t,n.listDir??Vh))if(d.push(u),r(u))return l(u,p);return{diagnostic:Fn,searched:d,...i?{callerEntry:Bt(i)}:{}}}function Ht(e={},n={}){let t=Pe(e,n);if(ce(t))return t;throw new Hn(t)}function Lo(e){let n=jo(e);return n===de||Ao.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:Hh(Bt(e))}function Hh(e){let n=Do(e);for(let t=0;t<4;t++){if(jo(n)==="redskilled")return!0;let r=Do(n);if(r===n)return!1;n=r}return!1}function*Uh(e,n,t,r){if(e){let s=Do(Bt(e));yield[Y(s,de),"caller-sibling-bundle"];let i=Bh.exec(jo(e));i&&(yield[Y(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[Y(s,"..","dist",de),"caller-sibling-bundle"]}for(let s of Fh){let i=t[s];i&&(yield[Y(i,"dist",de),"plugin-root-bundle"],yield[Y(i,"..","..","dist",de),"plugin-root-bundle"])}n&&(yield[Y(n,"dist",de),"repo-bundle"],yield[Y(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[Y(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=va(t);yield[Y(o,de),"bundle-cache"];for(let s of Gh(o,r))yield[Y(o,s),"bundle-cache"]}function va(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Y(e.HOME||Wh(),".cache");return Y(n,"red-skills","bundles")}function Gh(e,n){return n(e).filter(t=>Ao.test(t)).sort((t,r)=>Kh(Sa(r),Sa(t)))}function Sa(e){return Ao.exec(e)?.[1]??""}function Kh(e,n){let t=s=>s.split(".").map(i=>Number.parseInt(i,10)),[r,o]=[t(e),t(n)];for(let s=0;s<Math.max(r.length,o.length);s++){let[i,l]=[r[s],o[s]];if(Number.isNaN(i)||i===void 0)return Number.isNaN(l)||l===void 0?e.localeCompare(n):-1;if(Number.isNaN(l)||l===void 0)return 1;if(i!==l)return i-l}return 0}function Vh(e){try{return Ch(e)}catch{return[]}}var de,Fn,Oo,Hn,Bh,Ao,Fh,_e=Ap(()=>{"use strict";de="redskilled.bundle.min.mjs",Fn="redskilled-daemon-entry-unresolved",Oo="REDSKILLED_BIN";Hn=class extends Error{code=Fn;searched;callerEntry;constructor(n){super(`${Fn}: no published ${de} found to spawn the redskilled daemon from${n.callerEntry?` (caller entry: ${n.callerEntry}, which is NOT used as a fallback)`:""}
3
+ var Yp=Object.defineProperty;var Xp=(e,n)=>()=>(e&&(n=e(e=0)),n);var Zp=(e,n)=>{for(var t in n)Yp(e,t,{get:n[t],enumerable:!0})};var Wa={};Zp(Wa,{REDSKILLED_BIN_ENV:()=>Bo,REDSKILLED_BUNDLE_ASSET:()=>ue,REDSKILLED_ENTRY_UNRESOLVED:()=>Vn,RedskilledDaemonEntryError:()=>qn,isRedskilledEntryPath:()=>Uo,isResolvedRedskilledEntry:()=>pe,redskilledBundleCacheRoot:()=>qt,redskilledServeArgv:()=>Ue,requireRedskilledEntry:()=>Jt,resolveRedskilledEntry:()=>Ae});import{existsSync as og,readdirSync as sg}from"node:fs";import{homedir as ig}from"node:os";import{basename as Ho,dirname as Wo,join as Z,resolve as Vt}from"node:path";function pe(e){return"command"in e}function Ue(e,n={}){let t=["serve","--socket",e.socketPath,"--lease",e.leasePath,"--events",e.eventLanePath,"--session-key-hash",e.sessionKeyHash,"--machine-id-hash",e.machineIdHash,"--machine-claim",e.machineClaimPath];return n.idleMs!=null&&t.push("--idle-ms",String(n.idleMs)),n.daemonVersion!=null&&t.push("--daemon-version",n.daemonVersion),t}function qt(e=process.env){return Ca(e)}function Ae(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??og,o=n.execPath??process.execPath,s=n.execArgv??[],i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,l=(u,p)=>({command:o,args:[...s,u],source:p,entry:u}),a=t[Bo];if(a)return{command:a,args:[],source:"env-redskilled-bin",entry:a};if(i&&Uo(i))return l(Vt(i),"caller-entry");let d=[];for(let[u,p]of cg(i,n.rootDir,t,n.listDir??fg))if(d.push(u),r(u))return l(u,p);return{diagnostic:Vn,searched:d,...i?{callerEntry:Vt(i)}:{}}}function Jt(e={},n={}){let t=Ae(e,n);if(pe(t))return t;throw new qn(t)}function Uo(e){let n=Ho(e);return n===ue||Fo.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:dg(Vt(e))}function dg(e){let n=Wo(e);for(let t=0;t<4;t++){if(Ho(n)==="redskilled")return!0;let r=Wo(n);if(r===n)return!1;n=r}return!1}function*cg(e,n,t,r){if(e){let s=Wo(Vt(e));yield[Z(s,ue),"caller-sibling-bundle"];let i=lg.exec(Ho(e));i&&(yield[Z(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[Z(s,"..","dist",ue),"caller-sibling-bundle"]}for(let s of ag){let i=t[s];i&&(yield[Z(i,"dist",ue),"plugin-root-bundle"],yield[Z(i,"..","..","dist",ue),"plugin-root-bundle"])}n&&(yield[Z(n,"dist",ue),"repo-bundle"],yield[Z(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[Z(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=Ca(t);yield[Z(o,ue),"bundle-cache"];for(let s of ug(o,r))yield[Z(o,s),"bundle-cache"]}function Ca(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Z(e.HOME||ig(),".cache");return Z(n,"red-skills","bundles")}function ug(e,n){return n(e).filter(t=>Fo.test(t)).sort((t,r)=>pg(Ma(r),Ma(t)))}function Ma(e){return Fo.exec(e)?.[1]??""}function pg(e,n){let t=s=>s.split(".").map(i=>Number.parseInt(i,10)),[r,o]=[t(e),t(n)];for(let s=0;s<Math.max(r.length,o.length);s++){let[i,l]=[r[s],o[s]];if(Number.isNaN(i)||i===void 0)return Number.isNaN(l)||l===void 0?e.localeCompare(n):-1;if(Number.isNaN(l)||l===void 0)return 1;if(i!==l)return i-l}return 0}function fg(e){try{return sg(e)}catch{return[]}}var ue,Vn,Bo,qn,lg,Fo,ag,Se=Xp(()=>{"use strict";ue="redskilled.bundle.min.mjs",Vn="redskilled-daemon-entry-unresolved",Bo="REDSKILLED_BIN";qn=class extends Error{code=Vn;searched;callerEntry;constructor(n){super(`${Vn}: no published ${ue} found to spawn the redskilled daemon from${n.callerEntry?` (caller entry: ${n.callerEntry}, which is NOT used as a fallback)`:""}
4
4
  searched:
5
5
  ${n.searched.map(t=>` ${t}`).join(`
6
- `)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};Bh=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Ao=/^redskilled-(.+)\.bundle\.min\.mjs$/,Fh=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as M_}from"node:child_process";import{homedir as ui}from"node:os";import{join as Ju}from"node:path";var en=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},Le=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonlError",this.line=n,this.reason=t}};function b(e,n){return new en(e,n)}function E(e,n){return new Le(e,n)}function nn(e){return e instanceof Le?e:e instanceof en?new Le(e.line,e.reason):new Le(0,String(e&&e.message?e.message:e))}var Ki=["type","kind","event"],Te="|",Vi=new Set(["order","discriminator","rows","common"]);var L=",";function vt(e){let n=e.split(`
7
- `);return n.length>0&&n[n.length-1]===""&&n.pop(),n.map(t=>t.endsWith("\r")?t.slice(0,-1):t)}function se(e){return b(e,"invalid quoted string")}function J(e,n){if(e==="")return"";if(e.startsWith('"'))return Qi(e,n);if(e.includes('"'))throw se(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:Tp(e)?Number(e):e}function Z(e,n){let t=e.trim();if(t.startsWith('"'))return[Qi(t,n),!0];if(t.includes('"')||/\s/.test(t))throw b(n,"expected non-empty field name");return[t,!1]}var qi=/["\\\u0000-\u0008\u000a-\u001f]/g;function Qi(e,n){if(e.charCodeAt(0)!==34)throw se(n);let t="",r=1;for(;r<e.length;){qi.lastIndex=r;let o=qi.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(r,o.index);throw se(n)}if(o[0]!=="\\")throw se(n);t+=e.slice(r,o.index);let s=e[o.index+1];switch(r=o.index+2,s){case'"':t+='"';break;case"\\":t+="\\";break;case"n":t+=`
8
- `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let i=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(i))throw se(n);let l=Number.parseInt(i,16);if(l>=55296&&l<=57343)throw se(n);t+=String.fromCharCode(l),r+=4;break}default:throw se(n)}}throw se(n)}function zi(e,n,t){for(;;){let r=e.indexOf('"',n),o=e.indexOf("\\",n);if(o!==-1&&(r===-1||o<r)){if(o===e.length-1)throw se(t);n=o+2;continue}if(r===-1)throw se(t);return r+1}}function ee(e,n,t){if(e==="")return[];let r=[],o=0,s=0;for(;s<e.length;){let i=e.indexOf('"',s),l=e.indexOf(n,s);if(l!==-1&&(i===-1||l<i))r.push(e.slice(o,l).trim()),o=l+1,s=l+1;else if(i!==-1)s=zi(e,i+1,t);else break}return r.push(e.slice(o).trim()),r}function F(e,n,t){let r=0;for(;r<e.length;){let o=e.indexOf('"',r),s=e.indexOf(n,r);if(s!==-1&&(o===-1||s<o))return s;if(o===-1)return-1;r=zi(e,o+1,t)}return-1}function Tp(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function $p(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Ip(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw b(0,"number is not representable in TOON");return String(e)}function ie(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function H(e,n){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Ip(e);if(typeof e=="string")return Mp(e,n);throw b(0,"not a primitive")}function Np(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function M(e){return Np(e)?e:Et(e)}function Mp(e,n){return Mr(e,n)?Et(e):e}function Mr(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||$p(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}var Ji=/["\\\u0000-\u001f]/g;function Et(e){let n='"',t=0;Ji.lastIndex=0;let r;for(;(r=Ji.exec(e))!==null;){let o=e.charCodeAt(r.index),s;o===34?s='\\"':o===92?s="\\\\":o===10?s="\\n":o===13?s="\\r":o===9?s="\\t":s=`\\u${o.toString(16).padStart(4,"0")}`,n+=e.slice(t,r.index)+s,t=r.index+1}return`${n}${e.slice(t)}"`}function ne(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function T(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yi(e={}){let n=e.maxDepth??1e3,t=n===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(n));return{indent:Math.max(1,e.indent??2),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0,cyclicDiscriminatedArrays:e.cyclicDiscriminatedArrays!==!1,maxDepth:t}}function Xi(e,n){let t=[],r=!1;return vt(e).forEach((o,s)=>{let i=s+1;if(o.trim()===""){r=!0;return}let l=o.length-o.replace(/^ +/,"").length;if(o[l]===" ")throw b(i,"invalid indentation");if(n.strict&&l%n.indent!==0)throw b(i,"invalid indentation");let a=Math.floor(l/n.indent);le(a,i,n),t.push({number:i,depth:a,content:o.slice(l),blankBefore:r}),r=!1}),t}function le(e,n,t){if(t.maxDepth!==0&&e>t.maxDepth)throw b(n,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function $n(e,n,t){if(t.maxDepth===0)return;let r=0,o=!1,s=!1;for(let i of e){if(s){s=!1;continue}if(o&&i==="\\"){s=!0;continue}if(i==='"'){o=!o;continue}o||(i==="{"?(r+=1,le(r,n,t)):i==="}"&&(r=Math.max(0,r-1)))}}function nl(e){if(!T(e)||Object.keys(e).length===0)return e;let n={};for(let[t,r]of Object.entries(e)){let o=Cp(r,1);if(o===void 0)return e;ne(n,t,o)}return n}function Cp(e,n){if(!T(e)||!Wp(e))return;let{order:t,discriminator:r,rows:o}=e;if(typeof t!="string"||typeof r!="string"||!Number.isSafeInteger(o)||o<0)throw C(n);let s=Bp(t,o,n),i=e.common,l=i===void 0?Array.from({length:o},()=>({})):i;if(!Array.isArray(l)||l.length!==o||!l.every(T))throw tl(n);let a=new Map;for(let[p,f]of Object.entries(e))if(!Vi.has(p)){if(!Array.isArray(f)||!f.every(T))throw C(n);a.set(p,f)}if(a.size===0)throw C(n);let d=new Map,u=s.map((p,f)=>{let m=a.get(p);if(m===void 0)throw Cr(n);let g=d.get(p)??0,_=m[g];if(_===void 0)throw Cr(n);return d.set(p,g+1),Fp(r,p,l[f],_,n)});for(let[p,f]of a)if((d.get(p)??0)!==f.length)throw Cr(n);return u}function Wp(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function Bp(e,n,t){if(!e.startsWith("cycle("))throw C(t);let r=e.slice(6),o=r.indexOf(")*");if(o===-1)throw C(t);let s=r.slice(0,o),i=r.slice(o+2);if(s===""||i.includes("+tail("))throw C(t);let l=s.split(",").map(u=>Kp(u,t));if(l.some(u=>u===""))throw C(t);let a=Gp(i,t),d=l.length*a;if(!Number.isSafeInteger(d))throw C(t);if(d!==n)throw tl(t);return Array.from({length:d},(u,p)=>l[p%l.length])}function Fp(e,n,t,r,o){let s={};ne(s,e,n);for(let[i,l]of Object.entries(t??{})){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw C(o);ne(s,i,l)}for(let[i,l]of Object.entries(Hp(r,o))){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw C(o);ne(s,i,l)}return s}function Hp(e,n){let t={};for(let[r,o]of Object.entries(e))Up(t,r.split("."),o,n);return Pt(t,n)}function Up(e,n,t,r){if(n.some(s=>s===""))throw C(r);let o=e;for(let s=0;s<n.length;s+=1){let i=n[s];if(s===n.length-1){o[i]=t;return}if(o[i]??={},o=o[i],!T(o))throw C(r)}}function Pt(e,n){return Array.isArray(e)?e.map(t=>Pt(t,n)):T(e)?Number.isSafeInteger(e.length)&&e.length>=0?Array.from({length:e.length},(t,r)=>{if(!Object.prototype.hasOwnProperty.call(e,String(r)))throw C(n);return Pt(e[String(r)],n)}):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Pt(r,n)])):e}function Gp(e,n){if(e===""||e.length>1&&e.startsWith("0")||!/^[0-9]+$/.test(e))throw C(n);let t=Number(e);if(!Number.isSafeInteger(t))throw C(n);return t}function Kp(e,n){try{return decodeURIComponent(e)}catch{throw C(n)}}function Zi(e){return encodeURIComponent(e)}function C(e){return b(e,"invalid cyclic array wire")}function tl(e){return b(e,"cyclic array length mismatch")}function Cr(e){return b(e,"cyclic array group length mismatch")}function rl(e){if(!T(e))return;let n=Object.entries(e);if(n.length===0)return;let t=[];for(let[o,s]of n){let i=Vp(s);if(i===void 0)return;t.push([o,i])}let r=[];for(let[o,s]of t)zp(r,o,s);return r.join("")}function Vp(e){if(!Array.isArray(e)||e.length===0||!e.every(T))return;let n=qp(e);if(n===void 0)return;let t=e.map(l=>l[n]),r=Jp(t);if(r===void 0)return;let o=Qp(e,n),s=new Map;for(let l of e){let a=l[n];s.has(a)||s.set(a,[]);let d={};for(let[u,p]of Object.entries(l))if(u!==n&&!o.includes(u)&&!Wr(p,u,d))return;s.get(a).push(d)}let i=[];for(let l of r.cycle){let a=s.get(l),d=Xp(a);if(d===void 0||d.length===0)return;i.push({fields:d,label:l,rows:a})}return{common:o,commonRows:e.map(l=>Object.fromEntries(o.map(a=>[a,l[a]]))),discriminator:n,groups:i,order:r,rows:e}}function qp(e){return Ki.find(n=>e.every(t=>typeof t[n]=="string"))}function Jp(e){if(!(e.length<12))for(let n=2;n<=Math.min(8,Math.floor(e.length/3));n+=1){if(e.length%n!==0)continue;let t=e.slice(0,n);if(new Set(t).size<2||!e.every((i,l)=>i===t[l%n]))continue;let r=e.length/n;if(r<3)continue;let o=e.map(Zi).join(","),s=`cycle(${t.map(Zi).join(",")})*${r}`;if(s.length<=o.length*.4)return{cycle:t,encoded:s,repeats:r}}}function Qp(e,n){let t=[],r=Object.keys(e[0]),o=r.indexOf(n)+1;for(let s of r.slice(o).filter(i=>i!==n)){if(!Yp(s)||!e.every(i=>Object.prototype.hasOwnProperty.call(i,s))||!e.every(i=>ie(i[s])))break;t.push(s)}return t}function zp(e,n,t){e.push(M(n),`:
9
- `),e.push(" order: ",H(t.order.encoded,Te),`
10
- `),e.push(" discriminator: ",H(t.discriminator,Te),`
6
+ `)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};lg=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Fo=/^redskilled-(.+)\.bundle\.min\.mjs$/,ag=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as Dw}from"node:child_process";import{homedir as vr}from"node:os";import{join as hp}from"node:path";var sn=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},Me=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonlError",this.line=n,this.reason=t}};function R(e,n){return new sn(e,n)}function P(e,n){return new Me(e,n)}function ln(e){return e instanceof Me?e:e instanceof sn?new Me(e.line,e.reason):new Me(0,String(e&&e.message?e.message:e))}var ol=["type","kind","event"],Ce="|",sl=new Set(["order","discriminator","rows","common"]);var L=",";function At(e){let n=e.split(`
7
+ `);return n.length>0&&n[n.length-1]===""&&n.pop(),n.map(t=>t.endsWith("\r")?t.slice(0,-1):t)}function le(e){return R(e,"invalid quoted string")}function z(e,n){if(e==="")return"";if(e.startsWith('"'))return al(e,n);if(e.includes('"'))throw le(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:ef(e)?Number(e):e}function ee(e,n){let t=e.trim();if(t.startsWith('"'))return[al(t,n),!0];if(t.includes('"')||/\s/.test(t))throw R(n,"expected non-empty field name");return[t,!1]}var il=/["\\\u0000-\u0008\u000a-\u001f]/g;function al(e,n){if(e.charCodeAt(0)!==34)throw le(n);let t="",r=1;for(;r<e.length;){il.lastIndex=r;let o=il.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(r,o.index);throw le(n)}if(o[0]!=="\\")throw le(n);t+=e.slice(r,o.index);let s=e[o.index+1];switch(r=o.index+2,s){case'"':t+='"';break;case"\\":t+="\\";break;case"n":t+=`
8
+ `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let i=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(i))throw le(n);let l=Number.parseInt(i,16);if(l>=55296&&l<=57343)throw le(n);t+=String.fromCharCode(l),r+=4;break}default:throw le(n)}}throw le(n)}function dl(e,n,t){for(;;){let r=e.indexOf('"',n),o=e.indexOf("\\",n);if(o!==-1&&(r===-1||o<r)){if(o===e.length-1)throw le(t);n=o+2;continue}if(r===-1)throw le(t);return r+1}}function ne(e,n,t){if(e==="")return[];let r=[],o=0,s=0;for(;s<e.length;){let i=e.indexOf('"',s),l=e.indexOf(n,s);if(l!==-1&&(i===-1||l<i))r.push(e.slice(o,l).trim()),o=l+1,s=l+1;else if(i!==-1)s=dl(e,i+1,t);else break}return r.push(e.slice(o).trim()),r}function B(e,n,t){let r=0;for(;r<e.length;){let o=e.indexOf('"',r),s=e.indexOf(n,r);if(s!==-1&&(o===-1||s<o))return s;if(o===-1)return-1;r=dl(e,o+1,t)}return-1}function ef(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function nf(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function tf(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw R(0,"number is not representable in TOON");return String(e)}function ae(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function F(e,n){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return tf(e);if(typeof e=="string")return of(e,n);throw R(0,"not a primitive")}function rf(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function M(e){return rf(e)?e:Lt(e)}function of(e,n){return Jr(e,n)?Lt(e):e}function Jr(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||nf(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}var ll=/["\\\u0000-\u001f]/g;function Lt(e){let n='"',t=0;ll.lastIndex=0;let r;for(;(r=ll.exec(e))!==null;){let o=e.charCodeAt(r.index),s;o===34?s='\\"':o===92?s="\\\\":o===10?s="\\n":o===13?s="\\r":o===9?s="\\t":s=`\\u${o.toString(16).padStart(4,"0")}`,n+=e.slice(t,r.index)+s,t=r.index+1}return`${n}${e.slice(t)}"`}function te(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function T(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cl(e={}){let n=e.maxDepth??1e3,t=n===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(n));return{indent:Math.max(1,e.indent??2),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0,cyclicDiscriminatedArrays:e.cyclicDiscriminatedArrays!==!1,maxDepth:t}}function ul(e,n){let t=[],r=!1;return At(e).forEach((o,s)=>{let i=s+1;if(o.trim()===""){r=!0;return}let l=o.length-o.replace(/^ +/,"").length;if(o[l]===" ")throw R(i,"invalid indentation");if(n.strict&&l%n.indent!==0)throw R(i,"invalid indentation");let a=Math.floor(l/n.indent);de(a,i,n),t.push({number:i,depth:a,content:o.slice(l),blankBefore:r}),r=!1}),t}function de(e,n,t){if(t.maxDepth!==0&&e>t.maxDepth)throw R(n,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function Wn(e,n,t){if(t.maxDepth===0)return;let r=0,o=!1,s=!1;for(let i of e){if(s){s=!1;continue}if(o&&i==="\\"){s=!0;continue}if(i==='"'){o=!o;continue}o||(i==="{"?(r+=1,de(r,n,t)):i==="}"&&(r=Math.max(0,r-1)))}}function ml(e){if(!T(e)||Object.keys(e).length===0)return e;let n={};for(let[t,r]of Object.entries(e)){let o=sf(r,1);if(o===void 0)return e;te(n,t,o)}return n}function sf(e,n){if(!T(e)||!lf(e))return;let{order:t,discriminator:r,rows:o}=e;if(typeof t!="string"||typeof r!="string"||!Number.isSafeInteger(o)||o<0)throw C(n);let s=af(t,o,n),i=e.common,l=i===void 0?Array.from({length:o},()=>({})):i;if(!Array.isArray(l)||l.length!==o||!l.every(T))throw hl(n);let a=new Map;for(let[p,f]of Object.entries(e))if(!sl.has(p)){if(!Array.isArray(f)||!f.every(T))throw C(n);a.set(p,f)}if(a.size===0)throw C(n);let d=new Map,u=s.map((p,f)=>{let m=a.get(p);if(m===void 0)throw Qr(n);let g=d.get(p)??0,_=m[g];if(_===void 0)throw Qr(n);return d.set(p,g+1),df(r,p,l[f],_,n)});for(let[p,f]of a)if((d.get(p)??0)!==f.length)throw Qr(n);return u}function lf(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function af(e,n,t){if(!e.startsWith("cycle("))throw C(t);let r=e.slice(6),o=r.indexOf(")*");if(o===-1)throw C(t);let s=r.slice(0,o),i=r.slice(o+2);if(s===""||i.includes("+tail("))throw C(t);let l=s.split(",").map(u=>ff(u,t));if(l.some(u=>u===""))throw C(t);let a=pf(i,t),d=l.length*a;if(!Number.isSafeInteger(d))throw C(t);if(d!==n)throw hl(t);return Array.from({length:d},(u,p)=>l[p%l.length])}function df(e,n,t,r,o){let s={};te(s,e,n);for(let[i,l]of Object.entries(t??{})){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw C(o);te(s,i,l)}for(let[i,l]of Object.entries(cf(r,o))){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw C(o);te(s,i,l)}return s}function cf(e,n){let t={};for(let[r,o]of Object.entries(e))uf(t,r.split("."),o,n);return $t(t,n)}function uf(e,n,t,r){if(n.some(s=>s===""))throw C(r);let o=e;for(let s=0;s<n.length;s+=1){let i=n[s];if(s===n.length-1){o[i]=t;return}if(o[i]??={},o=o[i],!T(o))throw C(r)}}function $t(e,n){return Array.isArray(e)?e.map(t=>$t(t,n)):T(e)?Number.isSafeInteger(e.length)&&e.length>=0?Array.from({length:e.length},(t,r)=>{if(!Object.prototype.hasOwnProperty.call(e,String(r)))throw C(n);return $t(e[String(r)],n)}):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,$t(r,n)])):e}function pf(e,n){if(e===""||e.length>1&&e.startsWith("0")||!/^[0-9]+$/.test(e))throw C(n);let t=Number(e);if(!Number.isSafeInteger(t))throw C(n);return t}function ff(e,n){try{return decodeURIComponent(e)}catch{throw C(n)}}function pl(e){return encodeURIComponent(e)}function C(e){return R(e,"invalid cyclic array wire")}function hl(e){return R(e,"cyclic array length mismatch")}function Qr(e){return R(e,"cyclic array group length mismatch")}function gl(e){if(!T(e))return;let n=Object.entries(e);if(n.length===0)return;let t=[];for(let[o,s]of n){let i=mf(s);if(i===void 0)return;t.push([o,i])}let r=[];for(let[o,s]of t)kf(r,o,s);return r.join("")}function mf(e){if(!Array.isArray(e)||e.length===0||!e.every(T))return;let n=hf(e);if(n===void 0)return;let t=e.map(l=>l[n]),r=gf(t);if(r===void 0)return;let o=yf(e,n),s=new Map;for(let l of e){let a=l[n];s.has(a)||s.set(a,[]);let d={};for(let[u,p]of Object.entries(l))if(u!==n&&!o.includes(u)&&!zr(p,u,d))return;s.get(a).push(d)}let i=[];for(let l of r.cycle){let a=s.get(l),d=bf(a);if(d===void 0||d.length===0)return;i.push({fields:d,label:l,rows:a})}return{common:o,commonRows:e.map(l=>Object.fromEntries(o.map(a=>[a,l[a]]))),discriminator:n,groups:i,order:r,rows:e}}function hf(e){return ol.find(n=>e.every(t=>typeof t[n]=="string"))}function gf(e){if(!(e.length<12))for(let n=2;n<=Math.min(8,Math.floor(e.length/3));n+=1){if(e.length%n!==0)continue;let t=e.slice(0,n);if(new Set(t).size<2||!e.every((i,l)=>i===t[l%n]))continue;let r=e.length/n;if(r<3)continue;let o=e.map(pl).join(","),s=`cycle(${t.map(pl).join(",")})*${r}`;if(s.length<=o.length*.4)return{cycle:t,encoded:s,repeats:r}}}function yf(e,n){let t=[],r=Object.keys(e[0]),o=r.indexOf(n)+1;for(let s of r.slice(o).filter(i=>i!==n)){if(!Rf(s)||!e.every(i=>Object.prototype.hasOwnProperty.call(i,s))||!e.every(i=>ae(i[s])))break;t.push(s)}return t}function kf(e,n,t){e.push(M(n),`:
9
+ `),e.push(" order: ",F(t.order.encoded,Ce),`
10
+ `),e.push(" discriminator: ",F(t.discriminator,Ce),`
11
11
  `),e.push(" rows: ",String(t.rows.length),`
12
- `),t.common.length>0&&el(e,"common",t.common,t.commonRows);for(let r of t.groups)el(e,r.label,r.fields,r.rows)}function el(e,n,t,r){e.push(" ",M(n),"[",String(r.length),Te,"]{",t.map(M).join(Te),`}:
13
- `);for(let o of r)e.push(" ",t.map(s=>H(o[s],Te)).join(Te),`
14
- `)}function Yp(e){return e!==""&&Br(e)}function Wr(e,n,t,r=new Set){if(!Br(n))return!1;if(ie(e))return t[n]=e,!0;if(Array.isArray(e)){if(r.has(e))return!1;r.add(e),t[`${n}.length`]=e.length;let o=e.every((s,i)=>Wr(s,`${n}.${i}`,t,r));return r.delete(e),o}if(T(e)){if(r.has(e))return!1;r.add(e);let o=Object.entries(e).every(([s,i])=>!s.includes(".")&&Wr(i,`${n}.${s}`,t,r));return r.delete(e),o}return!1}function Xp(e){let n=Object.keys(e[0]??{});if(e.every(t=>Zp(Object.keys(t),n)))return n.every(Br)?n:void 0}function Zp(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function Br(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function tn(e,n){let t=e[n]??e[e.length-1];return b(t===void 0?1:t.number,"array length mismatch")}function Dt(e,n){if(n===-1)throw b(0,"array header missing colon");let t=e.slice(0,n),r=F(t,"[",0);if(r===-1)throw b(0,"invalid array header");let o,s;try{[o,s]=Z(t.slice(0,r),0)}catch{throw b(0,"invalid array header")}let i=t.slice(r+1),l=i.indexOf("]");if(l===-1)throw b(0,"invalid array header");let a=i.slice(0,l),d=/^[0-9]*/.exec(a)[0];if(d===""||d.length>1&&d.startsWith("0"))throw b(0,"invalid array header");let u=Number.parseInt(d,10),p;switch(a.slice(d.length)){case"":p=",";break;case" ":p=" ";break;case"|":p="|";break;default:throw b(0,"invalid array header")}let f=i.slice(l+1),m,g;if(f==="")m=void 0,g=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{g=nf(f.slice(1,-1),p),m=Hr(g)}catch(_){throw b(0,_.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw b(0,"invalid array header");return{key:o,keyQuoted:s,len:u,delimiter:p,fields:m,fieldTree:g}}function ol(e){let n=F(e,"{",0);if(n===-1||!e.endsWith("}"))throw b(0,"invalid keyed map header");let t,r;try{[t,r]=Z(e.slice(0,n),0)}catch{throw b(0,"invalid keyed map header")}if(t===""&&!r)throw b(0,"expected non-empty field name");let o=e.slice(n+1,-1),s=L;(o.startsWith("|")||o.startsWith(" "))&&(s=o[0],o=o.slice(1));let i;try{i=ef(o,s,s)}catch(l){throw b(0,l.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:s,fields:i}}function ef(e,n,t){let r=[],o=0;function s(a,d){let u=0;for(;o<e.length&&!(d&&e[o]==="}");){if(e[o]===n||e[o]==="}")throw b(0,"invalid array header");let p=o;for(;o<e.length;){let g=e[o];if(g==='"'){i();continue}if(g===n||g==="{"||g==="}"||g==="[")break;o+=1}let[f,m]=Z(e.slice(p,o),0);if(f===""&&!m)throw b(0,"invalid array header");if(u+=1,e[o]==="["){o+=1;let g=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw b(0,"invalid array header");let _=e.slice(g,o);if(!sl(_,t))throw b(0,"invalid array header");o+=1,r.push({path:[...a,f],listDelimiter:_})}else if(e[o]==="{"){o+=1;let g=r.length;if(s([...a,f],!0),e[o]!=="}"||r.length===g)throw b(0,"invalid array header");o+=1}else r.push({path:[...a,f],listDelimiter:void 0});if(e[o]===n){if(o+=1,o>=e.length||e[o]==="}")throw b(0,"invalid array header");continue}if(d?e[o]==="}":o===e.length)break;throw b(0,"invalid array header")}if(u===0)throw b(0,"invalid array header")}function i(){for(o+=1;o<e.length;){let a=e[o];if(o+=1,a==="\\")o+=1;else if(a==='"')return}}if(s([],!1),o!==e.length)throw b(0,"invalid array header");let l=new Set;for(let a=0;a<r.length;a+=1)for(let d=a+1;d<r.length;d+=1)if(il(r[a].path,r[d].path)||In(r[a].path,r[d].path)||In(r[d].path,r[a].path))throw b(0,"duplicate key");for(let a of r){let u=a.path.join("\0");if(l.has(u))throw b(0,"duplicate key");l.add(u)}return r}function nf(e,n){if(n!==L&&e.includes(L)&&(e.includes("[")||e.includes("{")))return Fr(e,L,n);try{return Fr(e,n,n)}catch(t){if(n!==L&&t.reason!=="duplicate key")return Fr(e,L,n);throw t}}function Fr(e,n,t){let r=0;function o(a){let d=[];for(;r<e.length&&!(a&&e[r]==="}");){if(e[r]===n||e[r]==="}")throw b(0,"invalid array header");let u=r;for(;r<e.length;){let g=e[r];if(g==='"'){s();continue}if(g===n||g==="{"||g==="}"||g==="[")break;r+=1}let[p,f]=Z(e.slice(u,r),0);if(p===""&&!f)throw b(0,"invalid array header");let m={key:p};if(e[r]==="["){r+=1;let g=r;for(;r<e.length&&e[r]!=="]";)r+=1;if(r>=e.length)throw b(0,"invalid array header");let _=e.slice(g,r);r+=1;let k=tf(_);if(k!==void 0){if(k.delimiter!==t)throw b(0,"invalid array header");m.fixedLength=k.len,m.fixedDelimiter=k.delimiter}else if(sl(_,t))m.listDelimiter=_;else throw b(0,"invalid array header")}else if(e[r]==="{"){if(r+=1,m.children=o(!0),e[r]!=="}"||m.children.length===0)throw b(0,"invalid array header");r+=1}if(d.push(m),e[r]===n){if(r+=1,r>=e.length||e[r]==="}")throw b(0,"invalid array header");continue}if(a?e[r]==="}":r===e.length)break;throw b(0,"invalid array header")}if(d.length===0)throw b(0,"invalid array header");return d}function s(){for(r+=1;r<e.length;){let a=e[r];if(r+=1,a==="\\")r+=1;else if(a==='"')return}}let i=o(!1);if(r!==e.length)throw b(0,"invalid array header");let l=Hr(i);for(let a=0;a<l.length;a+=1)for(let d=a+1;d<l.length;d+=1)if(il(l[a].path,l[d].path)||In(l[a].path,l[d].path)||In(l[d].path,l[a].path))throw b(0,"duplicate key");return i}function tf(e){let n=/^[0-9]+/.exec(e)?.[0];if(n===void 0||n.length>1&&n.startsWith("0"))return;let t=e.slice(n.length),r;switch(t){case"":r=L;break;case" ":r=" ";break;case"|":r="|";break;default:return}return{len:Number.parseInt(n,10),delimiter:r}}function Hr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?Hr(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function jt(e,n,t){return e.listDelimiter===void 0?J(n,t):ee(n,e.listDelimiter,t).map(r=>J(r,t))}function sl(e,n){return e.length===1&&e!==n&&!/[ \t\r\n"[\]{}:]/.test(e)}function il(e,n){return e.length===n.length&&In(e,n)}function In(e,n){return n.every((t,r)=>e[r]===t)}function Ot(e,n){return b(n,e.reason??String(e.message))}function Q(e,n){let t=Yi(n),r=Xi(e,t),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw b(o.number,"invalid indentation");let s=r.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){$n(o.content,o.number,t);let d;try{d=Dt(o.content,F(o.content,":",o.number))}catch(u){if(t.strict)throw Ot(u,o.number);d=void 0}if(d!==void 0)return sf(d,r,t)}if(s&&F(o.content,":",o.number)===-1)return J(o.content.trim(),o.number);let i={index:0},l=Gr(r,i,0,t),a=r[i.index];if(a!==void 0)throw b(a.number,"expected end of document");return t.cyclicDiscriminatedArrays?nl(l):l}function Gr(e,n,t,r){let o={};for(;n.index<e.length;){let s=e[n.index];if(s.depth<t)break;if(s.depth>t)throw b(s.number,"invalid indentation");let{key:i,quoted:l,value:a}=rf(e,n,t,r);fl(o,i,l,a,r,s.number)}return o}function rf(e,n,t,r){let o=e[n.index],s=o.content,i=F(s,":",o.number);if(i===-1)throw b(o.number,"expected `key: value`");let l=s.slice(0,i),a=s.slice(i+1),d=F(l,"[",o.number),u=F(l,"{",o.number);if(u!==-1&&(d===-1||u<d)){$n(l,o.number,r);let g;try{g=ol(l)}catch(k){if(r.strict)throw Ot(k,o.number);n.index+=1;let w=Ur(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:w}}if(a.trim()!=="")throw b(o.number,"expected keyed map rows");let _=of(g,e,n,t+1,r);return{key:g.key,quoted:g.keyQuoted,value:_}}if(d!==-1){$n(l,o.number,r);let g;try{g=Dt(l,i)}catch(k){if(r.strict)throw Ot(k,o.number);n.index+=1;let w=Ur(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:w}}if(g.key===""&&!g.keyQuoted)throw b(o.number,"expected non-empty field name");let _=Kr(g,a,e,n,t,r);return{key:g.key,quoted:g.keyQuoted,value:_}}let[p,f]=Z(l,o.number);if(p===""&&!f)throw b(o.number,"expected non-empty field name");n.index+=1;let m=Ur(e,n,t,a,o.number,r);return{key:p,quoted:f,value:m}}function Ur(e,n,t,r,o,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return J(i,o);let l=e[n.index];return l!==void 0&&l.depth>t?Gr(e,n,t+1,s):{}}function of(e,n,t,r,o){let s={};for(t.index+=1;t.index<n.length;){let i=n[t.index];if(i.depth<r)break;if(i.depth>r)throw b(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw b(i.number,"blank line inside keyed map");let l=F(i.content,":",i.number);if(l===-1)throw b(i.number,"expected `key: value`");let[a,d]=Z(i.content.slice(0,l),i.number);if(a===""&&!d)throw b(i.number,"expected non-empty field name");let u=ee(i.content.slice(l+1).trim(),e.delimiter,i.number);if(u.length!==e.fields.length)throw b(i.number,"keyed map row length mismatch");let p={};e.fields.forEach((f,m)=>{on(p,f.path,jt(f,u[m],i.number),o,i.number)}),fl(s,a,d,p,o,i.number),t.index+=1}return s}function sf(e,n,t){let r=n[0],o=F(r.content,":",r.number);if(o===-1)throw b(r.number,"expected `key: value`");let s=r.content.slice(o+1),i={index:0},l=Kr(e,s,n,i,0,t),a=n[i.index];if(a!==void 0)throw b(a.number,"expected end of document");return l}function Kr(e,n,t,r,o,s){let i=t[r.index].number,l=n.trim();if(r.index+=1,e.fields!==void 0){if(l!=="")throw b(i,"expected tabular rows");return lf(e,e.fields,t,r,o+1,s)}if(l!==""){let a=ee(l,e.delimiter,i).map(d=>J(d,i));if(a.length!==e.len)throw b(i,"array length mismatch");return a}return mf(e,t,r,o+1,s)}function lf(e,n,t,r,o,s){if(e.fieldTree!==void 0&&pf(e.fieldTree))return af(e,t,r,o,s);let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0)throw tn(t,r.index);if(a.depth<o)break;if(a.depth>o)throw b(a.number,"invalid indentation");if(a.blankBefore&&s.strict)throw b(a.number,"blank line inside array");if(!rn(a.content,e.delimiter,a.number))break;let d=ee(a.content,e.delimiter,a.number);if(d.length!==n.length)throw b(a.number,"array row length mismatch");let u={};n.forEach((p,f)=>{on(u,p.path,jt(p,d[f],a.number),s,a.number)}),i.push(u),r.index+=1}if(i.length!==e.len)throw tn(t,r.index);let l=t[r.index];if(l!==void 0&&l.depth>=o&&rn(l.content,e.delimiter,l.number))throw b(l.number,"array length mismatch");return i}function af(e,n,t,r,o){return ll(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function ll(e,n,t,r,o,s,i,l){let a=[],d=dl(e,n,t,r,o.index,s,i);for(;a.length<e;){let p=r[o.index];if(p===void 0)throw tn(r,o.index);if(p.depth<s)break;if(p.depth>s)throw b(p.number,"invalid indentation");if(p.blankBefore&&i.strict)throw b(p.number,"blank line inside array");if(!rn(p.content,t,p.number))break;let f=ee(p.content,t,p.number),m={cellIndex:0,nextIndex:o.index+1,flatWidth:At(n),childTableFields:d},g=al(n,f,p.number,r,m,s+1,t,i);if(m.cellIndex!==f.length)throw b(p.number,"array row length mismatch");a.push(uf(n,g,l)),o.index=m.nextIndex}if(a.length!==e)throw tn(r,o.index);let u=r[o.index];if(u!==void 0&&u.depth>=s&&rn(u.content,t,u.number))throw b(u.number,"array length mismatch");return a}function al(e,n,t,r,o,s,i,l){let a={};return e.forEach((d,u)=>{let p=e.slice(u+1),f=df(d,p,n,t,r,o,s,i,l);on(a,[d.key],f,l,t)}),a}function df(e,n,t,r,o,s,i,l,a){if(e.fixedLength!==void 0){if(s.cellIndex+e.fixedLength>t.length)throw b(r,"array row length mismatch");let u=t.slice(s.cellIndex,s.cellIndex+e.fixedLength).map(p=>J(p,r));return s.cellIndex+=e.fixedLength,u}if(e.children!==void 0){let u=At(e.children),p=t[s.cellIndex],f=ul(p),m=t.length-s.cellIndex-1,g=o[s.nextIndex],_=g!==void 0&&g.depth===i,k=s.childTableFields===void 0?void 0:s.childTableFields.has(e);if(k===void 0?f!==void 0&&(_||t.length!==s.flatWidth&&m<u+ff(n)):k){if(f===void 0)throw b(r,"array row length mismatch");return s.cellIndex+=1,ll(f,e.children,l,o,{get index(){return s.nextIndex},set index(O){s.nextIndex=O}},i,a,!1)}return al(e.children,t,r,o,s,i,l,a)}let d=t[s.cellIndex];if(d===void 0)throw b(r,"array row length mismatch");return s.cellIndex+=1,jt(e,d,r)}function dl(e,n,t,r,o,s,i){let l=n.filter(u=>u.children!==void 0);if(l.length===0)return new Set;if(l.length>12)return;let a,d=1<<l.length;for(let u=0;u<d;u+=1){let p=new Set;l.forEach((m,g)=>{u&1<<g&&p.add(m)});let f=cl(e,n,p,t,r,o,s,i);f!==void 0&&(a===void 0||f.consumedChildRows>a.consumedChildRows||f.consumedChildRows===a.consumedChildRows&&p.size<a.childTableFields.size)&&(a={childTableFields:p,consumedChildRows:f.consumedChildRows})}return a?.childTableFields}function cl(e,n,t,r,o,s,i,l){let a=s,d=0;try{for(let p=0;p<e;p+=1){let f=o[a];if(f===void 0||f.depth!==i||f.blankBefore&&l.strict||!rn(f.content,r,f.number))return;let m=ee(f.content,r,f.number),g=cf(n,t,m,r,o,a+1,i+1,l);if(g===void 0||o[g.nextIndex]?.depth>i)return;d+=g.consumedChildRows,a=g.nextIndex}let u=o[a];if(u!==void 0&&u.depth>=i&&rn(u.content,r,u.number))return}catch{return}return{nextIndex:a,consumedChildRows:d}}function cf(e,n,t,r,o,s,i,l){let a=0,d=s,u=0;for(let p of e){if(p.fixedLength!==void 0)a+=p.fixedLength;else if(p.children!==void 0)if(n.has(p)){let f=ul(t[a]);if(f===void 0)return;a+=1;let m=dl(f,p.children,r,o,d,i,l);if(m===void 0)return;let g=cl(f,p.children,m,r,o,d,i,l);if(g===void 0)return;d=g.nextIndex,u+=f+g.consumedChildRows}else a+=At(p.children);else a+=1;if(a>t.length)return}if(a===t.length)return{nextIndex:d,consumedChildRows:u}}function uf(e,n,t){return t&&e.length===1&&e[0].fixedLength!==void 0?n[e[0].key]:n}function ul(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function pf(e){return e.some(n=>n.fixedLength!==void 0||n.children!==void 0)}function At(e){return e.reduce((n,t)=>n+pl(t),0)}function pl(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?At(e.children):1}function ff(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+pl(t),0)}function rn(e,n,t){let r=F(e,":",t);if(r===-1)return!0;let o=F(e,n,t);return o===-1?!1:o<r}function mf(e,n,t,r,o){let s=[];for(;s.length<e.len;){let l=n[t.index];if(l===void 0||l.depth<r)throw tn(n,t.index);if(l.depth>r)throw b(l.number,"invalid indentation");if(l.blankBefore&&o.strict)throw b(l.number,"blank line inside array");s.push(hf(n,t,r,o))}let i=n[t.index];if(i!==void 0&&i.depth>=r)throw b(i.number,"array length mismatch");return s}function hf(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw b(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return n.index+=1,{};if(s.startsWith("[")){let i=F(s,":",o.number);$n(s,o.number,r);let l;try{l=Dt(s,i)}catch{l=void 0}if(l!==void 0){let a=s.slice(i+1);return Kr(l,a,e,n,t,r)}}if(F(s,":",o.number)!==-1){let i=[{number:o.number,depth:t+1,content:s,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let l=e[n.index];if(l.depth<=t)break;i.push(l),n.index+=1}return Gr(i,{index:0},t+1,r)}return n.index+=1,J(s,o.number)}function fl(e,n,t,r,o,s){if(o.expandPaths&&!t&&n.includes(".")){let i=n.split(".");if(i.every(gf)){on(e,i,r,o,s);return}}on(e,[n],r,o,s)}function on(e,n,t,r,o){le(n.length-1,o,r);let s=n[0],i=Object.prototype.hasOwnProperty.call(e,s);if(n.length===1){if(i&&r.strict)throw b(o,"duplicate key");ne(e,s,t);return}if(i&&!T(e[s])){if(r.strict)throw b(o,"path expansion conflict");ne(e,s,{})}else i||ne(e,s,{});on(e[s],n.slice(1),t,r,o)}function gf(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function W(e,n={}){let t=n.maxDepth??1e3,r=n.delimiter??L;if(![L,"|"," "].includes(r))throw b(0,"invalid array header");let o={nestedTabularHeaders:n.nestedTabularHeaders===!0,keyedMapCollapse:n.keyedMapCollapse===!0,primitiveArrayColumns:n.primitiveArrayColumns===!0,objectArrayColumns:n.objectArrayColumns===!0,cyclicDiscriminatedArrays:n.cyclicDiscriminatedArrays===!0,delimiter:r,maxDepth:t===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(t))};if(o.cyclicDiscriminatedArrays){let i=rl(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?Qr(s,void 0,e,0,!1,o):T(e)?ml(s,e,0,o):s.push(H(e,r)),s.join("")}function sn(e,n){e.push(" ".repeat(n*2))}function ml(e,n,t,r){le(t,0,r);for(let[o,s]of Object.entries(n))sn(e,t),qr(e,o,s,t,r)}function qr(e,n,t,r,o){if(le(r,0,o),Array.isArray(t)){Qr(e,n,t,r,!1,o);return}if(T(t)){let s=o.keyedMapCollapse?kf(t,o,r+1):void 0;if(s!==void 0){e.push(M(n),"{",zr(o.delimiter),s.fields.map(i=>Zr(i,o.delimiter)).join(o.delimiter),`}:
15
- `);for(let[i,l]of Object.entries(t)){sn(e,r+1);let a=[];e.push(M(i),": ",s.paths.map(d=>eo(Xr(l,d.path),d,o.delimiter,o,a,r+2)).join(o.delimiter),`
12
+ `),t.common.length>0&&fl(e,"common",t.common,t.commonRows);for(let r of t.groups)fl(e,r.label,r.fields,r.rows)}function fl(e,n,t,r){e.push(" ",M(n),"[",String(r.length),Ce,"]{",t.map(M).join(Ce),`}:
13
+ `);for(let o of r)e.push(" ",t.map(s=>F(o[s],Ce)).join(Ce),`
14
+ `)}function Rf(e){return e!==""&&Yr(e)}function zr(e,n,t,r=new Set){if(!Yr(n))return!1;if(ae(e))return t[n]=e,!0;if(Array.isArray(e)){if(r.has(e))return!1;r.add(e),t[`${n}.length`]=e.length;let o=e.every((s,i)=>zr(s,`${n}.${i}`,t,r));return r.delete(e),o}if(T(e)){if(r.has(e))return!1;r.add(e);let o=Object.entries(e).every(([s,i])=>!s.includes(".")&&zr(i,`${n}.${s}`,t,r));return r.delete(e),o}return!1}function bf(e){let n=Object.keys(e[0]??{});if(e.every(t=>_f(Object.keys(t),n)))return n.every(Yr)?n:void 0}function _f(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function Yr(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function an(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function Tt(e,n){if(n===-1)throw R(0,"array header missing colon");let t=e.slice(0,n),r=B(t,"[",0);if(r===-1)throw R(0,"invalid array header");let o,s;try{[o,s]=ee(t.slice(0,r),0)}catch{throw R(0,"invalid array header")}let i=t.slice(r+1),l=i.indexOf("]");if(l===-1)throw R(0,"invalid array header");let a=i.slice(0,l),d=/^[0-9]*/.exec(a)[0];if(d===""||d.length>1&&d.startsWith("0"))throw R(0,"invalid array header");let u=Number.parseInt(d,10),p;switch(a.slice(d.length)){case"":p=",";break;case" ":p=" ";break;case"|":p="|";break;default:throw R(0,"invalid array header")}let f=i.slice(l+1),m,g;if(f==="")m=void 0,g=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{g=xf(f.slice(1,-1),p),m=Zr(g)}catch(_){throw R(0,_.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw R(0,"invalid array header");return{key:o,keyQuoted:s,len:u,delimiter:p,fields:m,fieldTree:g}}function yl(e){let n=B(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=ee(e.slice(0,n),0)}catch{throw R(0,"invalid keyed map header")}if(t===""&&!r)throw R(0,"expected non-empty field name");let o=e.slice(n+1,-1),s=L;(o.startsWith("|")||o.startsWith(" "))&&(s=o[0],o=o.slice(1));let i;try{i=wf(o,s,s)}catch(l){throw R(0,l.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:s,fields:i}}function wf(e,n,t){let r=[],o=0;function s(a,d){let u=0;for(;o<e.length&&!(d&&e[o]==="}");){if(e[o]===n||e[o]==="}")throw R(0,"invalid array header");let p=o;for(;o<e.length;){let g=e[o];if(g==='"'){i();continue}if(g===n||g==="{"||g==="}"||g==="[")break;o+=1}let[f,m]=ee(e.slice(p,o),0);if(f===""&&!m)throw R(0,"invalid array header");if(u+=1,e[o]==="["){o+=1;let g=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw R(0,"invalid array header");let _=e.slice(g,o);if(!kl(_,t))throw R(0,"invalid array header");o+=1,r.push({path:[...a,f],listDelimiter:_})}else if(e[o]==="{"){o+=1;let g=r.length;if(s([...a,f],!0),e[o]!=="}"||r.length===g)throw R(0,"invalid array header");o+=1}else r.push({path:[...a,f],listDelimiter:void 0});if(e[o]===n){if(o+=1,o>=e.length||e[o]==="}")throw R(0,"invalid array header");continue}if(d?e[o]==="}":o===e.length)break;throw R(0,"invalid array header")}if(u===0)throw R(0,"invalid array header")}function i(){for(o+=1;o<e.length;){let a=e[o];if(o+=1,a==="\\")o+=1;else if(a==='"')return}}if(s([],!1),o!==e.length)throw R(0,"invalid array header");let l=new Set;for(let a=0;a<r.length;a+=1)for(let d=a+1;d<r.length;d+=1)if(Rl(r[a].path,r[d].path)||Hn(r[a].path,r[d].path)||Hn(r[d].path,r[a].path))throw R(0,"duplicate key");for(let a of r){let u=a.path.join("\0");if(l.has(u))throw R(0,"duplicate key");l.add(u)}return r}function xf(e,n){if(n!==L&&e.includes(L)&&(e.includes("[")||e.includes("{")))return Xr(e,L,n);try{return Xr(e,n,n)}catch(t){if(n!==L&&t.reason!=="duplicate key")return Xr(e,L,n);throw t}}function Xr(e,n,t){let r=0;function o(a){let d=[];for(;r<e.length&&!(a&&e[r]==="}");){if(e[r]===n||e[r]==="}")throw R(0,"invalid array header");let u=r;for(;r<e.length;){let g=e[r];if(g==='"'){s();continue}if(g===n||g==="{"||g==="}"||g==="[")break;r+=1}let[p,f]=ee(e.slice(u,r),0);if(p===""&&!f)throw R(0,"invalid array header");let m={key:p};if(e[r]==="["){r+=1;let g=r;for(;r<e.length&&e[r]!=="]";)r+=1;if(r>=e.length)throw R(0,"invalid array header");let _=e.slice(g,r);r+=1;let k=Sf(_);if(k!==void 0){if(k.delimiter!==t)throw R(0,"invalid array header");m.fixedLength=k.len,m.fixedDelimiter=k.delimiter}else if(kl(_,t))m.listDelimiter=_;else throw R(0,"invalid array header")}else if(e[r]==="{"){if(r+=1,m.children=o(!0),e[r]!=="}"||m.children.length===0)throw R(0,"invalid array header");r+=1}if(d.push(m),e[r]===n){if(r+=1,r>=e.length||e[r]==="}")throw R(0,"invalid array header");continue}if(a?e[r]==="}":r===e.length)break;throw R(0,"invalid array header")}if(d.length===0)throw R(0,"invalid array header");return d}function s(){for(r+=1;r<e.length;){let a=e[r];if(r+=1,a==="\\")r+=1;else if(a==='"')return}}let i=o(!1);if(r!==e.length)throw R(0,"invalid array header");let l=Zr(i);for(let a=0;a<l.length;a+=1)for(let d=a+1;d<l.length;d+=1)if(Rl(l[a].path,l[d].path)||Hn(l[a].path,l[d].path)||Hn(l[d].path,l[a].path))throw R(0,"duplicate key");return i}function Sf(e){let n=/^[0-9]+/.exec(e)?.[0];if(n===void 0||n.length>1&&n.startsWith("0"))return;let t=e.slice(n.length),r;switch(t){case"":r=L;break;case" ":r=" ";break;case"|":r="|";break;default:return}return{len:Number.parseInt(n,10),delimiter:r}}function Zr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?Zr(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function It(e,n,t){return e.listDelimiter===void 0?z(n,t):ne(n,e.listDelimiter,t).map(r=>z(r,t))}function kl(e,n){return e.length===1&&e!==n&&!/[ \t\r\n"[\]{}:]/.test(e)}function Rl(e,n){return e.length===n.length&&Hn(e,n)}function Hn(e,n){return n.every((t,r)=>e[r]===t)}function Nt(e,n){return R(n,e.reason??String(e.message))}function Y(e,n){let t=cl(n),r=ul(e,t),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw R(o.number,"invalid indentation");let s=r.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){Wn(o.content,o.number,t);let d;try{d=Tt(o.content,B(o.content,":",o.number))}catch(u){if(t.strict)throw Nt(u,o.number);d=void 0}if(d!==void 0)return Pf(d,r,t)}if(s&&B(o.content,":",o.number)===-1)return z(o.content.trim(),o.number);let i={index:0},l=no(r,i,0,t),a=r[i.index];if(a!==void 0)throw R(a.number,"expected end of document");return t.cyclicDiscriminatedArrays?ml(l):l}function no(e,n,t,r){let o={};for(;n.index<e.length;){let s=e[n.index];if(s.depth<t)break;if(s.depth>t)throw R(s.number,"invalid indentation");let{key:i,quoted:l,value:a}=vf(e,n,t,r);El(o,i,l,a,r,s.number)}return o}function vf(e,n,t,r){let o=e[n.index],s=o.content,i=B(s,":",o.number);if(i===-1)throw R(o.number,"expected `key: value`");let l=s.slice(0,i),a=s.slice(i+1),d=B(l,"[",o.number),u=B(l,"{",o.number);if(u!==-1&&(d===-1||u<d)){Wn(l,o.number,r);let g;try{g=yl(l)}catch(k){if(r.strict)throw Nt(k,o.number);n.index+=1;let x=eo(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:x}}if(a.trim()!=="")throw R(o.number,"expected keyed map rows");let _=Ef(g,e,n,t+1,r);return{key:g.key,quoted:g.keyQuoted,value:_}}if(d!==-1){Wn(l,o.number,r);let g;try{g=Tt(l,i)}catch(k){if(r.strict)throw Nt(k,o.number);n.index+=1;let x=eo(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:x}}if(g.key===""&&!g.keyQuoted)throw R(o.number,"expected non-empty field name");let _=to(g,a,e,n,t,r);return{key:g.key,quoted:g.keyQuoted,value:_}}let[p,f]=ee(l,o.number);if(p===""&&!f)throw R(o.number,"expected non-empty field name");n.index+=1;let m=eo(e,n,t,a,o.number,r);return{key:p,quoted:f,value:m}}function eo(e,n,t,r,o,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return z(i,o);let l=e[n.index];return l!==void 0&&l.depth>t?no(e,n,t+1,s):{}}function Ef(e,n,t,r,o){let s={};for(t.index+=1;t.index<n.length;){let i=n[t.index];if(i.depth<r)break;if(i.depth>r)throw R(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw R(i.number,"blank line inside keyed map");let l=B(i.content,":",i.number);if(l===-1)throw R(i.number,"expected `key: value`");let[a,d]=ee(i.content.slice(0,l),i.number);if(a===""&&!d)throw R(i.number,"expected non-empty field name");let u=ne(i.content.slice(l+1).trim(),e.delimiter,i.number);if(u.length!==e.fields.length)throw R(i.number,"keyed map row length mismatch");let p={};e.fields.forEach((f,m)=>{cn(p,f.path,It(f,u[m],i.number),o,i.number)}),El(s,a,d,p,o,i.number),t.index+=1}return s}function Pf(e,n,t){let r=n[0],o=B(r.content,":",r.number);if(o===-1)throw R(r.number,"expected `key: value`");let s=r.content.slice(o+1),i={index:0},l=to(e,s,n,i,0,t),a=n[i.index];if(a!==void 0)throw R(a.number,"expected end of document");return l}function to(e,n,t,r,o,s){let i=t[r.index].number,l=n.trim();if(r.index+=1,e.fields!==void 0){if(l!=="")throw R(i,"expected tabular rows");return Df(e,e.fields,t,r,o+1,s)}if(l!==""){let a=ne(l,e.delimiter,i).map(d=>z(d,i));if(a.length!==e.len)throw R(i,"array length mismatch");return a}return If(e,t,r,o+1,s)}function Df(e,n,t,r,o,s){if(e.fieldTree!==void 0&&$f(e.fieldTree))return jf(e,t,r,o,s);let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0)throw an(t,r.index);if(a.depth<o)break;if(a.depth>o)throw R(a.number,"invalid indentation");if(a.blankBefore&&s.strict)throw R(a.number,"blank line inside array");if(!dn(a.content,e.delimiter,a.number))break;let d=ne(a.content,e.delimiter,a.number);if(d.length!==n.length)throw R(a.number,"array row length mismatch");let u={};n.forEach((p,f)=>{cn(u,p.path,It(p,d[f],a.number),s,a.number)}),i.push(u),r.index+=1}if(i.length!==e.len)throw an(t,r.index);let l=t[r.index];if(l!==void 0&&l.depth>=o&&dn(l.content,e.delimiter,l.number))throw R(l.number,"array length mismatch");return i}function jf(e,n,t,r,o){return bl(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function bl(e,n,t,r,o,s,i,l){let a=[],d=wl(e,n,t,r,o.index,s,i);for(;a.length<e;){let p=r[o.index];if(p===void 0)throw an(r,o.index);if(p.depth<s)break;if(p.depth>s)throw R(p.number,"invalid indentation");if(p.blankBefore&&i.strict)throw R(p.number,"blank line inside array");if(!dn(p.content,t,p.number))break;let f=ne(p.content,t,p.number),m={cellIndex:0,nextIndex:o.index+1,flatWidth:Mt(n),childTableFields:d},g=_l(n,f,p.number,r,m,s+1,t,i);if(m.cellIndex!==f.length)throw R(p.number,"array row length mismatch");a.push(Lf(n,g,l)),o.index=m.nextIndex}if(a.length!==e)throw an(r,o.index);let u=r[o.index];if(u!==void 0&&u.depth>=s&&dn(u.content,t,u.number))throw R(u.number,"array length mismatch");return a}function _l(e,n,t,r,o,s,i,l){let a={};return e.forEach((d,u)=>{let p=e.slice(u+1),f=Of(d,p,n,t,r,o,s,i,l);cn(a,[d.key],f,l,t)}),a}function Of(e,n,t,r,o,s,i,l,a){if(e.fixedLength!==void 0){if(s.cellIndex+e.fixedLength>t.length)throw R(r,"array row length mismatch");let u=t.slice(s.cellIndex,s.cellIndex+e.fixedLength).map(p=>z(p,r));return s.cellIndex+=e.fixedLength,u}if(e.children!==void 0){let u=Mt(e.children),p=t[s.cellIndex],f=Sl(p),m=t.length-s.cellIndex-1,g=o[s.nextIndex],_=g!==void 0&&g.depth===i,k=s.childTableFields===void 0?void 0:s.childTableFields.has(e);if(k===void 0?f!==void 0&&(_||t.length!==s.flatWidth&&m<u+Tf(n)):k){if(f===void 0)throw R(r,"array row length mismatch");return s.cellIndex+=1,bl(f,e.children,l,o,{get index(){return s.nextIndex},set index(v){s.nextIndex=v}},i,a,!1)}return _l(e.children,t,r,o,s,i,l,a)}let d=t[s.cellIndex];if(d===void 0)throw R(r,"array row length mismatch");return s.cellIndex+=1,It(e,d,r)}function wl(e,n,t,r,o,s,i){let l=n.filter(u=>u.children!==void 0);if(l.length===0)return new Set;if(l.length>12)return;let a,d=1<<l.length;for(let u=0;u<d;u+=1){let p=new Set;l.forEach((m,g)=>{u&1<<g&&p.add(m)});let f=xl(e,n,p,t,r,o,s,i);f!==void 0&&(a===void 0||f.consumedChildRows>a.consumedChildRows||f.consumedChildRows===a.consumedChildRows&&p.size<a.childTableFields.size)&&(a={childTableFields:p,consumedChildRows:f.consumedChildRows})}return a?.childTableFields}function xl(e,n,t,r,o,s,i,l){let a=s,d=0;try{for(let p=0;p<e;p+=1){let f=o[a];if(f===void 0||f.depth!==i||f.blankBefore&&l.strict||!dn(f.content,r,f.number))return;let m=ne(f.content,r,f.number),g=Af(n,t,m,r,o,a+1,i+1,l);if(g===void 0||o[g.nextIndex]?.depth>i)return;d+=g.consumedChildRows,a=g.nextIndex}let u=o[a];if(u!==void 0&&u.depth>=i&&dn(u.content,r,u.number))return}catch{return}return{nextIndex:a,consumedChildRows:d}}function Af(e,n,t,r,o,s,i,l){let a=0,d=s,u=0;for(let p of e){if(p.fixedLength!==void 0)a+=p.fixedLength;else if(p.children!==void 0)if(n.has(p)){let f=Sl(t[a]);if(f===void 0)return;a+=1;let m=wl(f,p.children,r,o,d,i,l);if(m===void 0)return;let g=xl(f,p.children,m,r,o,d,i,l);if(g===void 0)return;d=g.nextIndex,u+=f+g.consumedChildRows}else a+=Mt(p.children);else a+=1;if(a>t.length)return}if(a===t.length)return{nextIndex:d,consumedChildRows:u}}function Lf(e,n,t){return t&&e.length===1&&e[0].fixedLength!==void 0?n[e[0].key]:n}function Sl(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function $f(e){return e.some(n=>n.fixedLength!==void 0||n.children!==void 0)}function Mt(e){return e.reduce((n,t)=>n+vl(t),0)}function vl(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?Mt(e.children):1}function Tf(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+vl(t),0)}function dn(e,n,t){let r=B(e,":",t);if(r===-1)return!0;let o=B(e,n,t);return o===-1?!1:o<r}function If(e,n,t,r,o){let s=[];for(;s.length<e.len;){let l=n[t.index];if(l===void 0||l.depth<r)throw an(n,t.index);if(l.depth>r)throw R(l.number,"invalid indentation");if(l.blankBefore&&o.strict)throw R(l.number,"blank line inside array");s.push(Nf(n,t,r,o))}let i=n[t.index];if(i!==void 0&&i.depth>=r)throw R(i.number,"array length mismatch");return s}function Nf(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw R(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return n.index+=1,{};if(s.startsWith("[")){let i=B(s,":",o.number);Wn(s,o.number,r);let l;try{l=Tt(s,i)}catch{l=void 0}if(l!==void 0){let a=s.slice(i+1);return to(l,a,e,n,t,r)}}if(B(s,":",o.number)!==-1){let i=[{number:o.number,depth:t+1,content:s,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let l=e[n.index];if(l.depth<=t)break;i.push(l),n.index+=1}return no(i,{index:0},t+1,r)}return n.index+=1,z(s,o.number)}function El(e,n,t,r,o,s){if(o.expandPaths&&!t&&n.includes(".")){let i=n.split(".");if(i.every(Mf)){cn(e,i,r,o,s);return}}cn(e,[n],r,o,s)}function cn(e,n,t,r,o){de(n.length-1,o,r);let s=n[0],i=Object.prototype.hasOwnProperty.call(e,s);if(n.length===1){if(i&&r.strict)throw R(o,"duplicate key");te(e,s,t);return}if(i&&!T(e[s])){if(r.strict)throw R(o,"path expansion conflict");te(e,s,{})}else i||te(e,s,{});cn(e[s],n.slice(1),t,r,o)}function Mf(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function W(e,n={}){let t=n.maxDepth??1e3,r=n.delimiter??L;if(![L,"|"," "].includes(r))throw R(0,"invalid array header");let o={nestedTabularHeaders:n.nestedTabularHeaders===!0,keyedMapCollapse:n.keyedMapCollapse===!0,primitiveArrayColumns:n.primitiveArrayColumns===!0,objectArrayColumns:n.objectArrayColumns===!0,cyclicDiscriminatedArrays:n.cyclicDiscriminatedArrays===!0,delimiter:r,maxDepth:t===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(t))};if(o.cyclicDiscriminatedArrays){let i=gl(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?io(s,void 0,e,0,!1,o):T(e)?Pl(s,e,0,o):s.push(F(e,r)),s.join("")}function un(e,n){e.push(" ".repeat(n*2))}function Pl(e,n,t,r){de(t,0,r);for(let[o,s]of Object.entries(n))un(e,t),oo(e,o,s,t,r)}function oo(e,n,t,r,o){if(de(r,0,o),Array.isArray(t)){io(e,n,t,r,!1,o);return}if(T(t)){let s=o.keyedMapCollapse?Wf(t,o,r+1):void 0;if(s!==void 0){e.push(M(n),"{",lo(o.delimiter),s.fields.map(i=>uo(i,o.delimiter)).join(o.delimiter),`}:
15
+ `);for(let[i,l]of Object.entries(t)){un(e,r+1);let a=[];e.push(M(i),": ",s.paths.map(d=>po(co(l,d.path),d,o.delimiter,o,a,r+2)).join(o.delimiter),`
16
16
  `),e.push(...a)}return}e.push(M(n),`:
17
- `),ml(e,t,r+1,o);return}e.push(M(n),": ",H(t,o.delimiter),`
18
- `)}function Qr(e,n,t,r,o,s){if(le(r,0,s),t.length===0){n!==void 0?e.push(M(n),`: []
17
+ `),Pl(e,t,r+1,o);return}e.push(M(n),": ",F(t,o.delimiter),`
18
+ `)}function io(e,n,t,r,o,s){if(de(r,0,s),t.length===0){n!==void 0?e.push(M(n),`: []
19
19
  `):o?e.push(`[0]:
20
20
  `):e.push(`[]
21
- `);return}if(t.every(ie)){Vr(e,n,t.length,void 0,s.delimiter),e.push(" "),e.push(t.map(l=>H(l,s.delimiter)).join(s.delimiter)),e.push(`
22
- `);return}let i=o?void 0:hl(t,s,r+1);if(i!==void 0){Vr(e,n,t.length,i.fields,s.delimiter),e.push(`
23
- `);for(let l of t){sn(e,r+1);let a=[];e.push(i.paths.map(d=>eo(Xr(l,d.path),d,s.delimiter,s,a,r+2)).join(s.delimiter)),e.push(`
24
- `),e.push(...a)}return}Vr(e,n,t.length,void 0,s.delimiter),e.push(`
25
- `);for(let l of t)sn(e,r+1),yf(e,l,r+1,s)}function yf(e,n,t,r){if(le(t,0,r),Array.isArray(n)){e.push("- "),Qr(e,void 0,n,t,!0,r);return}if(T(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
26
- `);return}e.push("- "),qr(e,o[0][0],o[0][1],t+1,r);for(let[s,i]of o.slice(1))sn(e,t+1),qr(e,s,i,t+1,r);return}e.push("- ",H(n,r.delimiter),`
27
- `)}function Vr(e,n,t,r,o){n!==void 0&&e.push(M(n)),e.push("[",String(t),zr(o),"]"),r!==void 0&&e.push("{",r.map(s=>Zr(s,o)).join(o),"}"),e.push(":")}function zr(e){return e===L?"":e}function hl(e,n,t){let r=Rf(e,n);if(r!==void 0)return r;let o=Jr(e.map(s=>({value:s})),n,t);return o===void 0?void 0:{fields:o,paths:Yr(o)}}function kf(e,n,t){let r=Object.values(e);if(!(r.length<2))return hl(r,n,t)}function Jr(e,n,t){le(t,0,n);let r=e[0]?.value;if(!T(r))return;let o=Object.keys(r).map(s=>({key:s}));if(o.length!==0){for(let{value:s}of e)if(!T(s)||Object.keys(s).length!==o.length||o.some(l=>!Object.prototype.hasOwnProperty.call(s,l.key)))return;for(let s of o){let i=e.map(({value:a})=>({value:a[s.key]}));if(i.every(({value:a})=>ie(a)))continue;if(n.primitiveArrayColumns&&i.every(({value:a})=>Array.isArray(a)&&a.every(ie))){s.listDelimiter=";";continue}if(n.objectArrayColumns&&i.every(({value:a})=>Array.isArray(a))){let a=gl(i.map(({value:u})=>u));if(a!==void 0){s.fixedLength=a.fixedLength,s.fixedDelimiter=n.delimiter;continue}let d=Jr(i.flatMap(({value:u})=>u.map(p=>({value:p}))),n,t+1);if(d!==void 0){s.children=d,s.childTable=!0;continue}}if(!n.nestedTabularHeaders)return;let l=Jr(i,n,t+1);if(l===void 0)return;s.children=l}return o}}function Rf(e,n){if(!n.objectArrayColumns)return;let t=gl(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:n.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function gl(e){let n=e[0]?.length;if(!(!Number.isInteger(n)||n===0)&&e.every(t=>Array.isArray(t)&&t.length===n&&t.every(ie)))return{fixedLength:n}}function Yr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.childTable===!0?[{path:r,childFields:t.children}]:t.fixedLength!==void 0?[{path:r,fixedLength:t.fixedLength}]:t.children===void 0?[{path:r,listDelimiter:t.listDelimiter}]:Yr(t.children,r)})}function Xr(e,n){let t=e;for(let r of n)t=t[r];return t}function Zr(e,n){return e.listDelimiter!==void 0?`${M(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${M(e.key)}[${e.fixedLength}${zr(n)}]`:e.children===void 0?M(e.key):`${M(e.key)}{${e.children.map(t=>Zr(t,n)).join(n)}}`}function eo(e,n,t,r,o,s){return n.childFields!==void 0?(bf(o,e,n.childFields,r,s),String(e.length)):n.fixedLength!==void 0?e.map(i=>H(i,t)).join(t):n.listDelimiter===void 0?H(e,t):e.map(i=>_f(i,t,n.listDelimiter)).join(n.listDelimiter)}function bf(e,n,t,r,o){for(let s of n){sn(e,o);let i=[];e.push(Yr(t).map(l=>eo(Xr(s,l.path),l,r.delimiter,r,i,o+1)).join(r.delimiter)),e.push(`
28
- `),e.push(...i)}}function _f(e,n,t){return typeof e!="string"?H(e,n):Mr(e,n)||e.includes(t)?Et(e):e}var Sl=[L,"|"," "];var vl=8,El=/^[A-Za-z0-9_-]+$/,ex=new TextEncoder,nx=new TextDecoder;function vf(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw E(n,"invalid trailer count");return Number.parseInt(t,10)}function Pl(e,n){if(!El.test(e))throw E(n,"invalid tag")}function Ef(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!El.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw E(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function Pf(e,n){if(!e.startsWith("["))return null;let t=e.slice(1),r=t.indexOf("]");if(r===-1)throw E(n,"invalid header");let o=t.slice(0,r),s=o.startsWith("~"),i=s?o.slice(1):o;if(!s&&i.startsWith("="))return null;if(!Sl.includes(i)&&i!=="")throw E(n,"invalid header delimiter");let l=i===""?L:i,a=t.slice(r+1),d=null;if(!s&&a.startsWith("<")){let f=a.indexOf(">");if(f===-1)throw E(n,"invalid tag");if(d=a.slice(1,f),Pl(d,n),i!=="")throw E(n,"invalid header delimiter");a=a.slice(f+1)}if(!a.startsWith("{")||!a.endsWith("}:"))throw E(n,"invalid header");let u=a.slice(1,-2),p;try{p=ee(u,l,n).map(f=>Z(f,n)[0])}catch(f){throw nn(f)}if(p.length===0||p.some(f=>f===""))throw E(n,"invalid header fields");return{delimiter:l,fields:p,fieldText:u,continuation:s,tag:d}}function Df(e,n,t){if(e===null||e.delimiter===void 0)throw E(t,"continuation header before header");if(e.delimiter!==n.delimiter||e.fieldText!==n.fieldText)throw E(t,"continuation header mismatch")}function yl(e,n,t,r){let o;try{o=ee(e,n,r)}catch(s){throw nn(s)}if(o.length!==t)throw E(r,"row arity mismatch");for(let s of o)try{J(s,r)}catch(i){throw nn(i)}return o}function jf(e,n,t){let r={};return e.forEach((o,s)=>{try{ne(r,o,J(n[s],t))}catch(i){throw nn(i)}}),r}function Of(e,n,t){if(e.startsWith("- "))throw E(n,"reserved line prefix");let r=vf(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw E(n,"trailer without header");if(t.rowCount!==r)throw E(n,"trailer count mismatch");return{kind:"trailer"}}let o=Pf(e,n);if(o!==null)return o.continuation?(Df(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=Ef(e,n);if(s!==null){let i=t?.taggedLanes?.get(s.tag);if(i===void 0)throw E(n,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:yl(s.cellsText,i.delimiter,i.fields.length,n)}}if(t===null||t.delimiter===void 0)throw E(n,"row before header");return{kind:"row",cells:yl(e,t.delimiter,t.fields.length,n)}}function Af(e,n={}){let t=[],r=new Map,o=[],s=[],i=null,l=!1,a=!1;function d(m,g){let _=s.at(-1);if(_!==void 0&&_.lane===m.lane&&_.delimiter===m.delimiter&&_.fieldText===m.fieldText){_.rows.push(g);return}s.push({lane:m.lane,delimiter:m.delimiter,fields:m.fields,fieldText:m.fieldText,rows:[g]})}function u(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function p(m,g,_){let k=r.get(m);if(k===void 0){if(r.size>=vl)throw E(_,"too many tagged lanes");k={segments:[],current:null},r.set(m,k),t.push(m)}else k.current!==null&&k.segments.push(k.current);k.current={lane:m,delimiter:g.delimiter,fields:g.fields,fieldText:g.fieldText,rows:[]},k.delimiter=g.delimiter,k.fields=g.fields,k.fieldText=g.fieldText}if(vt(e).forEach((m,g)=>{let _=g+1;if(m==="")return;let k=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},w=Of(m,_,k);if(w.kind==="trailer"){u(),i=null;return}if(w.kind!=="continuation"){if(w.kind==="tag-header"){a=!0,p(w.header.tag,w.header,_);return}if(w.kind==="header"){u(),l||(t.push(null),l=!0),i={lane:null,delimiter:w.header.delimiter,fields:w.header.fields,fieldText:w.header.fieldText,rows:[]};return}if(w.kind==="tagged-row"){a=!0;let O=r.get(w.tag).current;O.rows.push(w.cells),d(O,w.cells);return}if(i===null)throw E(_,"row before header");i.rows.push(w.cells),d(i,w.cells)}}),!a)return u(),n.preserveInterleaving===!0,o;let f=[];u();for(let m of t){if(m===null){f.push(...o);continue}let g=r.get(m);f.push(...g.segments),g.current!==null&&f.push(g.current)}return n.preserveInterleaving===!0?s:f}function ve(e){return Af(e).flatMap(n=>n.rows.map(t=>jf(n.fields,t,0)))}function Lf(e){if(!Sl.includes(e))throw E(0,"invalid header delimiter")}function kl(e,n,t=!1){return`[${`${t?"~":""}${e===L?"":e}`}]{${n}}:
29
- `}function Rl(e,n){return`[]<${e}>{${n}}:
30
- `}function no(e,n){return n.map(M).join(e)}function Tf(e){if(!Array.isArray(e)||e.length===0)throw E(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=Z(String(n),0)}catch(r){throw nn(r)}if(t==="")throw E(0,"TOONL header requires fields");return t})}function bl(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function _l(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw E(0,"TOONL continuation cadence must be positive")}function $f(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function wl(e){if(e===null||typeof e!="object"||Array.isArray(e))throw E(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw E(0,"TOONL output requires object rows");if(n.some(t=>!ie(e[t])))throw E(0,"TOONL rows must be flat objects");return n}function If(e){return JSON.stringify([...e].sort())}function xl(e,n){let t=If(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function be({delimiter:e=L,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){Lf(e),_l(t),_l(r);let o=null,s="",i=new Map,l=0,a=0,d=0,u=new Map,p=!1,f={continuationEveryRows:t,continuationEveryBytes:r},m=()=>o===null||!n?"":`[=${l}]
31
- `,g=()=>$f(f,a,d)?(a=0,d=0,kl(e,s,!0)):"",_=k=>{Pl(k,0);let w=u.get(k);if(w===void 0){if(u.size>=vl)throw E(0,"too many tagged lanes");w={fields:null,fieldsByShape:new Map},u.set(k,w)}return w};return{push(k){if(p)throw E(0,"TOONL encoder is closed");let w=xl(wl(k),i),O="";(o===null||o.length!==w.length||o.some((ge,qe)=>ge!==w[qe]))&&(O+=m(),o=w,s=no(e,o),l=0,a=0,d=0,O+=kl(e,s));let X=o.map(ge=>H(k[ge],e));O+=g();let he=`${X.join(e)}
32
- `;return O+=he,l+=1,a+=1,d+=he.length,O},declareLane(k,w){if(p)throw E(0,"TOONL encoder is closed");let O=Tf(w),X=no(L,O),he=_(k);return bl(he.fields,O)?"":(he.fields=O,Rl(k,X))},pushTagged(k,w){if(p)throw E(0,"TOONL encoder is closed");let O=_(k),X=xl(wl(w),O.fieldsByShape),he=no(L,X),ge=X.map(gr=>H(w[gr],L)),qe="";return bl(O.fields,X)||(O.fields=X,qe+=Rl(k,he)),`${qe}${k}:${ge.join(L)}
33
- `},end(){return p?"":(p=!0,m())}}}function to(e){let n={app:e,version:Nf(ln("__RED_BUILD_VERSION__",()=>"3.4.0")??"0.0.0-dev"),gitSha:ln("__RED_BUILD_GIT_SHA__",()=>"fcb63eef6c1ba0ca04107accdd7336499b338205")??"unknown",buildTime:ln("__RED_BUILD_TIME__",()=>"2026-08-03T21:27:55Z")??"unknown",bundleAsset:ln("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=ln("__REDDB_SDK_VERSION__",()=>""),r=ln("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function Nf(e){return e.startsWith("v")?e.slice(1):e}function Dl(e){return`${e.app} ${e.version} ${e.gitSha}`}function ln(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var jl={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Mf=/^[a-z][a-z0-9+.-]*:\/\//i;function Cf(e,n){return typeof n=="string"?{separator:e,to:n,typed:!1,prefix:!1}:{separator:e,to:n.to,typed:n.typed??!1,prefix:n.prefix??!1}}function Wf(e=jl){return Object.entries(e).map(([n,t])=>Cf(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function Bf(e){return/^-\d+(\.\d+)?$/.test(e)}function Nn(e){return!(!e||e.startsWith("-")&&!Bf(e))}function Lt(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e}function Ol(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e.includes(",")?e.split(",").map(t=>Ol(t.trim())):e}function $e(e,n){switch(n){case"boolean":return Ff(e);case"number":return Hf(e);case"array":return e.split(",").map(t=>Lt(t.trim()));case"string":default:return e}}function Ff(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function Hf(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let n=Number(e);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${e}" to number`);return n}function Ee(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Uf(e,n={}){return e.map(t=>{let r=n[t.type];return r?r(t.value):t.value}).join("")}function P(e,n){return{type:e,value:n}}function Gf(e){let n=[],t=Vf(e);if(n.push(P("section-header","Usage:"),P("text"," "),P("usage-text",t),P("newline",`
34
- `),P("newline",`
35
- `)),e.positional&&e.positional.length>0){n.push(P("section-header","Arguments:"),P("newline",`
36
- `));for(let r of e.positional)if(r.description){let o=r.variadic?`${r.name}...`:r.name;n.push(P("indent"," "),P("positional-name",`<${o}>`)),r.required||n.push(P("positional-optional"," (optional)")),n.push(P("newline",`
37
- `),P("indent"," "),P("option-description",r.description),P("newline",`
38
- `))}n.push(P("newline",`
39
- `))}if(e.options&&Object.keys(e.options).length>0){n.push(P("section-header","Options:"),P("newline",`
40
- `));let r=qf(e.options);n.push(...r)}return n}function Kf(e,n){let t=Gf(e);return Uf(t,n)}function Vf(e){let n=["[options]"];if(e.positional)for(let t of e.positional)t.variadic?n.push(t.required?`<${t.name}...>`:`[${t.name}...]`):n.push(t.required?`<${t.name}>`:`[${t.name}]`);return n.join(" ")}function qf(e,n=!1){let t=[],r=[],o=n?"global-option-flag":"option-flag",s=n?"global-option-type":"option-type",i=n?"global-option-default":"option-default",l=n?"global-option-description":"option-description";for(let[d,u]of Object.entries(e)){if(u.hidden)continue;let p=[],f=_=>{p.includes(_)||p.push(_)};u.short&&f(`-${u.short}`),f(`--${d}`);for(let _ of u.aliases??[])_.length===1?f(`-${_}`):f(`--${_}`);let m=p.join(", "),g=u.type&&u.type!=="boolean"?`<${u.type}>`:void 0;r.push({flags:m,type:g,desc:u.description??"",default:u.default!==void 0?String(u.default):void 0})}let a=Math.max(...r.map(d=>d.flags.length+(d.type?d.type.length+1:0)),20);for(let d of r){let u=d.flags.length+(d.type?d.type.length+1:0),p=" ".repeat(a-u+2);t.push(P("indent"," ")),t.push(P(o,d.flags)),d.type&&(t.push(P("text"," ")),t.push(P(s,d.type))),t.push(P("text",p)),t.push(P(l,d.desc)),d.default!==void 0&&(t.push(P("text"," ")),t.push(P(i,`(default: ${d.default})`))),t.push(P("newline",`
41
- `))}return t}function Al(e){let n=em(e.options??{},e.autoShort??!1),t=Wf(e.separators??jl);return{schema:e,parse(r){return Jf(r,e,n,t)},help(){return Kf(e,e.formatter)}}}function Jf(e,n,t,r){let o={positional:{},options:{},errors:[],rest:[]},s=new Set(r.map(u=>u.to));for(let u of s)o[u]={};let i=0,l=n.positional??[],a=0,d=!1;for(;a<e.length;){let u=e[a];if(n.stopEarly&&i>0){o.rest=e.slice(a);break}if(u==="--"&&!d){d=!0,a++;continue}if(d){if(i<l.length){let f=l[i];if(f.variadic){let m=[];for(;a<e.length;){let g=e[a];m.push(f.type?$e(g,f.type):g),a++}o.positional[f.name]=m,i++}else{let m=f.type?$e(u,f.type):u;o.positional[f.name]=m,i++,a++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(u)),a++;continue}if(u.startsWith("--")){a=Xf(u,a,e,o,t,n);continue}if(u.startsWith("-")&&u.length>1&&!sm(u)){a=Zf(u,a,e,o,t,n);continue}let p=Qf(u,r);if(p){let{key:f,value:m,config:g}=p,_=o,k=_[g.to]??(_[g.to]={});k[f]=g.typed?Ol(m):Ee(m),a++;continue}if(i<l.length){let f=l[i];if(f.variadic){let g=[];for(;a<e.length&&!e[a].startsWith("-");){let _=e[a];g.push(f.type?$e(_,f.type):_),a++}o.positional[f.name]=g,i++;continue}let m=f.type?$e(u,f.type):u;o.positional[f.name]=m,i++}else n.allowUnknown!==!1?o.rest.push(u):o.errors.push(`Unexpected positional argument: ${u}`);a++}return tm(o,n,t),rm(o,n,l),om(o,n,t),o}function Qf(e,n){if(Mf.test(e))return null;for(let t of n){if(t.prefix&&e.startsWith(t.separator)){let o=e.slice(t.separator.length),s=o.indexOf(":");if(s>0){let i=o.slice(0,s),l=o.slice(s+1);if(zf(i))return{key:i,value:l,config:t}}continue}let r=e.indexOf(t.separator);if(r>0){let o=e.slice(0,r),s=e.slice(r+t.separator.length);if(Yf(o,s,t))return{key:o,value:s,config:t}}}return null}function zf(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function Yf(e,n,t){return e?t.separator===":"?e.includes("/")||e.includes(".")||/^\d+$/.test(n)?!1:/^[A-Z][a-zA-Z0-9-]*$/.test(e):!((t.separator==="="||t.separator===":=")&&e.includes("/")):!1}function Xf(e,n,t,r,o,s){let i=e.slice(2);if(i.startsWith("no-")){let a=i.slice(3),d=o.get(a);if(d?.negatable!==!1&&d?.type==="boolean")return r.options[d.name]=!1,n+1}if(i.includes("=")){let a=i.indexOf("="),d=i.slice(0,a),u=i.slice(a+1);return Tt(d,u,n+1,r,o,s)}let l=o.get(i);if(l){if(l.type!=="boolean"){let a=t[n+1];return Nn(a)?Tt(l.name,a,n+2,r,o,s):(r.errors.push(`Option --${i} requires a value`),n+1)}return r.options[l.name]=!0,n+1}return s.strict?r.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(r.options[i]=!0),n+1}function Zf(e,n,t,r,o,s){let i=e.slice(1);if(i.includes("=")){let l=i.indexOf("="),a=i.slice(0,l),d=i.slice(l+1),u=ro(a,o);return u?Tt(u.name,d,n+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=Lt(Ee(d))),n+1)}if(i.length===1){let l=ro(i,o);if(l){if(l.type!=="boolean"){let a=t[n+1];return Nn(a)?Tt(l.name,a,n+2,r,o,s):(r.errors.push(`Option -${i} requires a value`),n+1)}return r.options[l.name]=!0,n+1}if(s.strict)r.errors.push(`Unknown option: -${i}`);else if(s.allowUnknown!==!1){let a=t[n+1];if(Nn(a))return r.options[i]=Lt(Ee(a)),n+2;r.options[i]=!0}return n+1}for(let l of i){let a=ro(l,o);a?a.type==="boolean"?r.options[a.name]=!0:r.errors.push(`Option -${l} requires a value`):s.strict?r.errors.push(`Unknown option: -${l}`):s.allowUnknown!==!1&&(r.options[l]=!0)}return n+1}function Tt(e,n,t,r,o,s){let i=o.get(e);if(i){if(i.choices){let a=i.type?$e(Ee(n),i.type):Ee(n);if(!i.choices.includes(a))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${i.choices.join(", ")}`),t}let l=i.type?$e(Ee(n),i.type):Ee(n);if(i.type==="array"){let a=r.options[e];Array.isArray(a)?a.push(...l):r.options[e]=l}else r.options[e]=l}else s.strict?r.errors.push(`Unknown option: --${e}`):s.allowUnknown!==!1&&(r.options[e]=Lt(Ee(n)));return t}function em(e,n=!1){let t=new Map,r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i)),o=new Set;for(let[,s]of r)s.short&&o.add(s.short);for(let[s,i]of r){let l=i.short??"";n&&!l&&(l=nm(s,o),l&&o.add(l));let a={name:s,short:l,aliases:i.aliases??[],type:i.type??"string",description:i.description??"",required:i.required??!1,hidden:i.hidden??!1,negatable:i.negatable??!0,default:i.default,choices:i.choices,env:i.env,validate:i.validate};t.set(s,a);for(let d of a.aliases)t.set(d,a)}return t}function nm(e,n){for(let t of e){if(!/[a-zA-Z]/.test(t))continue;let r=t.toLowerCase();if(!n.has(r))return r;let o=t.toUpperCase();if(!n.has(o))return o}return""}function ro(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function tm(e,n,t){for(let r of t.values())if(e.options[r.name]===void 0)if(r.env&&process.env[r.env]!==void 0){let o=process.env[r.env];e.options[r.name]=r.type?$e(o,r.type):o}else r.default!==void 0&&(e.options[r.name]=r.default);for(let r of n.positional??[])e.positional[r.name]===void 0&&r.default!==void 0&&(e.positional[r.name]=r.default)}function rm(e,n,t){if(n.options)for(let[r,o]of Object.entries(n.options))o.required&&e.options[r]===void 0&&e.errors.push(`Missing required option: --${r}`);for(let r of t)r.required&&e.positional[r.name]===void 0&&e.errors.push(`Missing required argument: <${r.name}>`)}function om(e,n,t){for(let r of t.values()){let o=e.options[r.name];if(r.validate&&o!==void 0){let s=r.validate(o);s!==!0&&e.errors.push(s)}}for(let r of n.positional??[]){let o=e.positional[r.name];if(r.validate&&o!==void 0){let s=r.validate(o);s!==!0&&e.errors.push(s)}}}function sm(e){return/^-\d+(\.\d+)?$/.test(e)}var oo=class extends Error{flag;known;constructor(n,t){super(`unknown flag '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownFlagError",this.flag=n,this.known=t}};function im(e){let n={};for(let[t,r]of Object.entries(e))n[t]={type:r.kind==="boolean"?"boolean":"string",...t.length===1?{short:t}:{},...r.aliases===void 0?{}:{aliases:r.aliases}};return n}function lm(e,n){let t=new Map;for(let[o,s]of Object.entries(n))if(!(s.kind!=="value"||s.type!=="array")){t.set(o,o);for(let i of s.aliases??[])t.set(i,o)}let r=new Map;for(let o=0;o<e.length;o+=1){let s=e[o];if(s==="--")break;let i=s.match(/^--([^=]+)(?:=(.*))?$/)??s.match(/^-([^=])(?:=(.*))?$/);if(i===null)continue;let l=t.get(i[1]);if(l===void 0)continue;let a=i[2];if(a===void 0&&Nn(e[o+1])&&(a=e[o+1],o+=1),a===void 0)continue;let d=r.get(l)??[];d.push(a),r.set(l,d)}return r}function Ie(e,n,t={}){let o=Al({options:im(n),separators:{},allowUnknown:!0}).parse([...e]),s={},i=lm(e,n),l=o.errors.find(a=>/^Option --?\S+ requires a value$/.test(a));if(l!==void 0)throw new Error(l.replace(/^Option /,""));if(o.errors.length>0)throw new Error(o.errors[0]);if(t.unknownFlags==="error"){let a=new Set(Object.keys(n));for(let d of Object.keys(o.options))if(!a.has(d))throw new oo(d.length===1?`-${d}`:`--${d}`,Object.keys(n).map(u=>u.length===1?`-${u}`:`--${u}`))}for(let[a,d]of Object.entries(n)){let u=o.options[a];u!==void 0&&(d.kind==="boolean"?s[a]=u:d.type==="array"?s[a]=(i.get(a)??[]).map(p=>d.coerce(p)):s[a]=d.coerce(String(u)))}return{values:s,positionals:o.rest}}var so=class extends Error{token;known;constructor(n,t){super(`unknown command '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownCommandError",this.token=n,this.known=t}};function Ll(e,n){let[t,...r]=e;if(t!==void 0){for(let[s,i]of Object.entries(n.commands))if(t===s||(i.aliases??[]).includes(t))return{command:s,args:r};if(n.errorOnUnknownCommand&&!t.startsWith("-"))throw new so(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as km,mkdirSync as Rm,readFileSync as Hl,statSync as bm}from"node:fs";import{dirname as Gl,join as _m}from"node:path";var Tl="RED_WORKER_SCOPE",$l="RED_WORKER_MEMORY_CEILING",Il="RED_WORKER_SCOPE_DEGRADATION",lo={scope:null,memory_ceiling:null,scope_degradation:null};function ao(e){return{scope:io(e[Tl]),memory_ceiling:io(e[$l]),scope_degradation:io(e[Il])}}function Mn(e){let n={};return e.scope!=null&&e.scope!==""&&(n[Tl]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[$l]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[Il]=e.scope_degradation),n}function io(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as cm,readdirSync as um,readFileSync as Wl,rmSync as pm,writeFileSync as fm}from"node:fs";import{basename as mm,join as an}from"node:path";import{isAbsolute as $x,join as $t,resolve as Ix}from"node:path";function am(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var Nl="deaths",Ml="deaths.toonl";function It(e){return $t(am(e),Nl)}function Cn(e){return $t(It(e),Ml)}var Wn="live",Cl="attributions.toonl";function Nt(e){return $t(It(e),Wn)}function co(e){return $t(It(e),Cl)}var po=an("sys","kernel","random","boot_id"),Bl=1;function fo(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:Bl,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:Fl(an(t,po)),cgroup:hm(t,r),last_phase:e.last_phase}}function Fl(e){try{let n=Wl(e,"utf8").trim();return n===""?null:n}catch{return null}}function hm(e,n){let t=Fl(an(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
42
- `),o=r.find(i=>i.startsWith("0::"));if(o)return o.slice(3)||null;let s=r[0]?.split(":").slice(2).join(":");return s===void 0||s===""?null:s}function mo(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function ho(e,n){let t=an(e,mo(n));try{return cm(e,{recursive:!0,mode:448}),fm(t,be({trailer:!1}).push(ym(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function Ne(e,n){try{pm(an(e,mo(n)),{force:!0})}catch{}}function go(e,n){let t;try{t=um(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=an(e,o);try{let l=ve(Wl(s,"utf8"))[0];if(l===void 0)throw new Error("anchor holds no record");r.push(gm(l))}catch(i){n?.(mm(s),i instanceof Error?i.message:String(i))}}return r}function gm(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:uo(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:uo(e.pid),ppid:uo(e.ppid),boot_id:e.boot_id==null?null:String(e.boot_id),cgroup:e.cgroup==null?null:String(e.cgroup),last_phase:String(e.last_phase)}}function uo(e){return typeof e=="number"?e:Number(e)}function ym(e){return{...e}}var wm=1,xm=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Sm(e){return typeof e=="string"&&xm.has(e)}var vm="startup";function Em(e,n){return{...e.scope??lo,version:wm,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,exit_path:e.exit_path,signal:e.signal??null,exit_code:e.exit_code??null,last_phase:e.last_phase,detail:e.detail??null,...n}}function Pm(e){let n=e.resourceUsage();return{uptime_s:Math.round(e.uptime()),rss_kb:Math.round(e.memoryUsage().rss/1024),max_rss_kb:n.maxRSS,user_cpu_us:n.userCPUTime,system_cpu_us:n.systemCPUTime,minor_page_faults:n.minorPageFault,major_page_faults:n.majorPageFault,voluntary_ctx_switches:n.voluntaryContextSwitches,involuntary_ctx_switches:n.involuntaryContextSwitches}}var ko={mkdir(e){Rm(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=bm(e).size}catch{return!0}if(n===0)return!0;try{return Hl(e,"utf8").endsWith(`
43
- `)}catch{return!0}},append(e,n){km(e,n,{encoding:"utf8",mode:384})},read(e){return Hl(e,"utf8")}};function Dm(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function jm(e,n,t=ko){let r=be({trailer:!1}).push(Dm(n));return t.mkdir(Gl(e)),t.endsClean(e)||t.append(e,`
44
- `),t.append(e,r),n}function Kl(e){let n=e.endsWith(`
21
+ `);return}if(t.every(ae)){ro(e,n,t.length,void 0,s.delimiter),e.push(" "),e.push(t.map(l=>F(l,s.delimiter)).join(s.delimiter)),e.push(`
22
+ `);return}let i=o?void 0:Dl(t,s,r+1);if(i!==void 0){ro(e,n,t.length,i.fields,s.delimiter),e.push(`
23
+ `);for(let l of t){un(e,r+1);let a=[];e.push(i.paths.map(d=>po(co(l,d.path),d,s.delimiter,s,a,r+2)).join(s.delimiter)),e.push(`
24
+ `),e.push(...a)}return}ro(e,n,t.length,void 0,s.delimiter),e.push(`
25
+ `);for(let l of t)un(e,r+1),Cf(e,l,r+1,s)}function Cf(e,n,t,r){if(de(t,0,r),Array.isArray(n)){e.push("- "),io(e,void 0,n,t,!0,r);return}if(T(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
26
+ `);return}e.push("- "),oo(e,o[0][0],o[0][1],t+1,r);for(let[s,i]of o.slice(1))un(e,t+1),oo(e,s,i,t+1,r);return}e.push("- ",F(n,r.delimiter),`
27
+ `)}function ro(e,n,t,r,o){n!==void 0&&e.push(M(n)),e.push("[",String(t),lo(o),"]"),r!==void 0&&e.push("{",r.map(s=>uo(s,o)).join(o),"}"),e.push(":")}function lo(e){return e===L?"":e}function Dl(e,n,t){let r=Hf(e,n);if(r!==void 0)return r;let o=so(e.map(s=>({value:s})),n,t);return o===void 0?void 0:{fields:o,paths:ao(o)}}function Wf(e,n,t){let r=Object.values(e);if(!(r.length<2))return Dl(r,n,t)}function so(e,n,t){de(t,0,n);let r=e[0]?.value;if(!T(r))return;let o=Object.keys(r).map(s=>({key:s}));if(o.length!==0){for(let{value:s}of e)if(!T(s)||Object.keys(s).length!==o.length||o.some(l=>!Object.prototype.hasOwnProperty.call(s,l.key)))return;for(let s of o){let i=e.map(({value:a})=>({value:a[s.key]}));if(i.every(({value:a})=>ae(a)))continue;if(n.primitiveArrayColumns&&i.every(({value:a})=>Array.isArray(a)&&a.every(ae))){s.listDelimiter=";";continue}if(n.objectArrayColumns&&i.every(({value:a})=>Array.isArray(a))){let a=jl(i.map(({value:u})=>u));if(a!==void 0){s.fixedLength=a.fixedLength,s.fixedDelimiter=n.delimiter;continue}let d=so(i.flatMap(({value:u})=>u.map(p=>({value:p}))),n,t+1);if(d!==void 0){s.children=d,s.childTable=!0;continue}}if(!n.nestedTabularHeaders)return;let l=so(i,n,t+1);if(l===void 0)return;s.children=l}return o}}function Hf(e,n){if(!n.objectArrayColumns)return;let t=jl(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:n.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function jl(e){let n=e[0]?.length;if(!(!Number.isInteger(n)||n===0)&&e.every(t=>Array.isArray(t)&&t.length===n&&t.every(ae)))return{fixedLength:n}}function ao(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.childTable===!0?[{path:r,childFields:t.children}]:t.fixedLength!==void 0?[{path:r,fixedLength:t.fixedLength}]:t.children===void 0?[{path:r,listDelimiter:t.listDelimiter}]:ao(t.children,r)})}function co(e,n){let t=e;for(let r of n)t=t[r];return t}function uo(e,n){return e.listDelimiter!==void 0?`${M(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${M(e.key)}[${e.fixedLength}${lo(n)}]`:e.children===void 0?M(e.key):`${M(e.key)}{${e.children.map(t=>uo(t,n)).join(n)}}`}function po(e,n,t,r,o,s){return n.childFields!==void 0?(Bf(o,e,n.childFields,r,s),String(e.length)):n.fixedLength!==void 0?e.map(i=>F(i,t)).join(t):n.listDelimiter===void 0?F(e,t):e.map(i=>Ff(i,t,n.listDelimiter)).join(n.listDelimiter)}function Bf(e,n,t,r,o){for(let s of n){un(e,o);let i=[];e.push(ao(t).map(l=>po(co(s,l.path),l,r.delimiter,r,i,o+1)).join(r.delimiter)),e.push(`
28
+ `),e.push(...i)}}function Ff(e,n,t){return typeof e!="string"?F(e,n):Jr(e,n)||e.includes(t)?Lt(e):e}var Ml=[L,"|"," "];var Cl=8,Wl=/^[A-Za-z0-9_-]+$/,Kx=new TextEncoder,Vx=new TextDecoder;function Vf(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw P(n,"invalid trailer count");return Number.parseInt(t,10)}function Hl(e,n){if(!Wl.test(e))throw P(n,"invalid tag")}function qf(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!Wl.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw P(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function Jf(e,n){if(!e.startsWith("["))return null;let t=e.slice(1),r=t.indexOf("]");if(r===-1)throw P(n,"invalid header");let o=t.slice(0,r),s=o.startsWith("~"),i=s?o.slice(1):o;if(!s&&i.startsWith("="))return null;if(!Ml.includes(i)&&i!=="")throw P(n,"invalid header delimiter");let l=i===""?L:i,a=t.slice(r+1),d=null;if(!s&&a.startsWith("<")){let f=a.indexOf(">");if(f===-1)throw P(n,"invalid tag");if(d=a.slice(1,f),Hl(d,n),i!=="")throw P(n,"invalid header delimiter");a=a.slice(f+1)}if(!a.startsWith("{")||!a.endsWith("}:"))throw P(n,"invalid header");let u=a.slice(1,-2),p;try{p=ne(u,l,n).map(f=>ee(f,n)[0])}catch(f){throw ln(f)}if(p.length===0||p.some(f=>f===""))throw P(n,"invalid header fields");return{delimiter:l,fields:p,fieldText:u,continuation:s,tag:d}}function Qf(e,n,t){if(e===null||e.delimiter===void 0)throw P(t,"continuation header before header");if(e.delimiter!==n.delimiter||e.fieldText!==n.fieldText)throw P(t,"continuation header mismatch")}function Ol(e,n,t,r){let o;try{o=ne(e,n,r)}catch(s){throw ln(s)}if(o.length!==t)throw P(r,"row arity mismatch");for(let s of o)try{z(s,r)}catch(i){throw ln(i)}return o}function zf(e,n,t){let r={};return e.forEach((o,s)=>{try{te(r,o,z(n[s],t))}catch(i){throw ln(i)}}),r}function Yf(e,n,t){if(e.startsWith("- "))throw P(n,"reserved line prefix");let r=Vf(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw P(n,"trailer without header");if(t.rowCount!==r)throw P(n,"trailer count mismatch");return{kind:"trailer"}}let o=Jf(e,n);if(o!==null)return o.continuation?(Qf(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=qf(e,n);if(s!==null){let i=t?.taggedLanes?.get(s.tag);if(i===void 0)throw P(n,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:Ol(s.cellsText,i.delimiter,i.fields.length,n)}}if(t===null||t.delimiter===void 0)throw P(n,"row before header");return{kind:"row",cells:Ol(e,t.delimiter,t.fields.length,n)}}function Xf(e,n={}){let t=[],r=new Map,o=[],s=[],i=null,l=!1,a=!1;function d(m,g){let _=s.at(-1);if(_!==void 0&&_.lane===m.lane&&_.delimiter===m.delimiter&&_.fieldText===m.fieldText){_.rows.push(g);return}s.push({lane:m.lane,delimiter:m.delimiter,fields:m.fields,fieldText:m.fieldText,rows:[g]})}function u(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function p(m,g,_){let k=r.get(m);if(k===void 0){if(r.size>=Cl)throw P(_,"too many tagged lanes");k={segments:[],current:null},r.set(m,k),t.push(m)}else k.current!==null&&k.segments.push(k.current);k.current={lane:m,delimiter:g.delimiter,fields:g.fields,fieldText:g.fieldText,rows:[]},k.delimiter=g.delimiter,k.fields=g.fields,k.fieldText=g.fieldText}if(At(e).forEach((m,g)=>{let _=g+1;if(m==="")return;let k=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},x=Yf(m,_,k);if(x.kind==="trailer"){u(),i=null;return}if(x.kind!=="continuation"){if(x.kind==="tag-header"){a=!0,p(x.header.tag,x.header,_);return}if(x.kind==="header"){u(),l||(t.push(null),l=!0),i={lane:null,delimiter:x.header.delimiter,fields:x.header.fields,fieldText:x.header.fieldText,rows:[]};return}if(x.kind==="tagged-row"){a=!0;let v=r.get(x.tag).current;v.rows.push(x.cells),d(v,x.cells);return}if(i===null)throw P(_,"row before header");i.rows.push(x.cells),d(i,x.cells)}}),!a)return u(),n.preserveInterleaving===!0,o;let f=[];u();for(let m of t){if(m===null){f.push(...o);continue}let g=r.get(m);f.push(...g.segments),g.current!==null&&f.push(g.current)}return n.preserveInterleaving===!0?s:f}function we(e){return Xf(e).flatMap(n=>n.rows.map(t=>zf(n.fields,t,0)))}function Zf(e){if(!Ml.includes(e))throw P(0,"invalid header delimiter")}function Al(e,n,t=!1){return`[${`${t?"~":""}${e===L?"":e}`}]{${n}}:
29
+ `}function Ll(e,n){return`[]<${e}>{${n}}:
30
+ `}function fo(e,n){return n.map(M).join(e)}function em(e){if(!Array.isArray(e)||e.length===0)throw P(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=ee(String(n),0)}catch(r){throw ln(r)}if(t==="")throw P(0,"TOONL header requires fields");return t})}function $l(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function Tl(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw P(0,"TOONL continuation cadence must be positive")}function nm(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function Il(e){if(e===null||typeof e!="object"||Array.isArray(e))throw P(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw P(0,"TOONL output requires object rows");if(n.some(t=>!ae(e[t])))throw P(0,"TOONL rows must be flat objects");return n}function tm(e){return JSON.stringify([...e].sort())}function Nl(e,n){let t=tm(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function ce({delimiter:e=L,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){Zf(e),Tl(t),Tl(r);let o=null,s="",i=new Map,l=0,a=0,d=0,u=new Map,p=!1,f={continuationEveryRows:t,continuationEveryBytes:r},m=()=>o===null||!n?"":`[=${l}]
31
+ `,g=()=>nm(f,a,d)?(a=0,d=0,Al(e,s,!0)):"",_=k=>{Hl(k,0);let x=u.get(k);if(x===void 0){if(u.size>=Cl)throw P(0,"too many tagged lanes");x={fields:null,fieldsByShape:new Map},u.set(k,x)}return x};return{push(k){if(p)throw P(0,"TOONL encoder is closed");let x=Nl(Il(k),i),v="";(o===null||o.length!==x.length||o.some((ke,Xe)=>ke!==x[Xe]))&&(v+=m(),o=x,s=fo(e,o),l=0,a=0,d=0,v+=Al(e,s));let G=o.map(ke=>F(k[ke],e));v+=g();let ye=`${G.join(e)}
32
+ `;return v+=ye,l+=1,a+=1,d+=ye.length,v},declareLane(k,x){if(p)throw P(0,"TOONL encoder is closed");let v=em(x),G=fo(L,v),ye=_(k);return $l(ye.fields,v)?"":(ye.fields=v,Ll(k,G))},pushTagged(k,x){if(p)throw P(0,"TOONL encoder is closed");let v=_(k),G=Nl(Il(x),v.fieldsByShape),ye=fo(L,G),ke=G.map(ft=>F(x[ft],L)),Xe="";return $l(v.fields,G)||(v.fields=G,Xe+=Ll(k,ye)),`${Xe}${k}:${ke.join(L)}
33
+ `},end(){return p?"":(p=!0,m())}}}function mo(e){let n={app:e,version:rm(pn("__RED_BUILD_VERSION__",()=>"3.4.2")??"0.0.0-dev"),gitSha:pn("__RED_BUILD_GIT_SHA__",()=>"15372f2fce172cf74ac5ca45cdcbde3d18536c54")??"unknown",buildTime:pn("__RED_BUILD_TIME__",()=>"2026-08-04T04:36:05Z")??"unknown",bundleAsset:pn("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=pn("__REDDB_SDK_VERSION__",()=>""),r=pn("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function rm(e){return e.startsWith("v")?e.slice(1):e}function Bl(e){return`${e.app} ${e.version} ${e.gitSha}`}function pn(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var Fl={"=":"data",":=":{to:"data",typed:!0},":":"meta"},om=/^[a-z][a-z0-9+.-]*:\/\//i;function sm(e,n){return typeof n=="string"?{separator:e,to:n,typed:!1,prefix:!1}:{separator:e,to:n.to,typed:n.typed??!1,prefix:n.prefix??!1}}function im(e=Fl){return Object.entries(e).map(([n,t])=>sm(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function lm(e){return/^-\d+(\.\d+)?$/.test(e)}function Bn(e){return!(!e||e.startsWith("-")&&!lm(e))}function Ct(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e}function Ul(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e.includes(",")?e.split(",").map(t=>Ul(t.trim())):e}function We(e,n){switch(n){case"boolean":return am(e);case"number":return dm(e);case"array":return e.split(",").map(t=>Ct(t.trim()));case"string":default:return e}}function am(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function dm(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let n=Number(e);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${e}" to number`);return n}function Oe(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function cm(e,n={}){return e.map(t=>{let r=n[t.type];return r?r(t.value):t.value}).join("")}function j(e,n){return{type:e,value:n}}function um(e){let n=[],t=fm(e);if(n.push(j("section-header","Usage:"),j("text"," "),j("usage-text",t),j("newline",`
34
+ `),j("newline",`
35
+ `)),e.positional&&e.positional.length>0){n.push(j("section-header","Arguments:"),j("newline",`
36
+ `));for(let r of e.positional)if(r.description){let o=r.variadic?`${r.name}...`:r.name;n.push(j("indent"," "),j("positional-name",`<${o}>`)),r.required||n.push(j("positional-optional"," (optional)")),n.push(j("newline",`
37
+ `),j("indent"," "),j("option-description",r.description),j("newline",`
38
+ `))}n.push(j("newline",`
39
+ `))}if(e.options&&Object.keys(e.options).length>0){n.push(j("section-header","Options:"),j("newline",`
40
+ `));let r=mm(e.options);n.push(...r)}return n}function pm(e,n){let t=um(e);return cm(t,n)}function fm(e){let n=["[options]"];if(e.positional)for(let t of e.positional)t.variadic?n.push(t.required?`<${t.name}...>`:`[${t.name}...]`):n.push(t.required?`<${t.name}>`:`[${t.name}]`);return n.join(" ")}function mm(e,n=!1){let t=[],r=[],o=n?"global-option-flag":"option-flag",s=n?"global-option-type":"option-type",i=n?"global-option-default":"option-default",l=n?"global-option-description":"option-description";for(let[d,u]of Object.entries(e)){if(u.hidden)continue;let p=[],f=_=>{p.includes(_)||p.push(_)};u.short&&f(`-${u.short}`),f(`--${d}`);for(let _ of u.aliases??[])_.length===1?f(`-${_}`):f(`--${_}`);let m=p.join(", "),g=u.type&&u.type!=="boolean"?`<${u.type}>`:void 0;r.push({flags:m,type:g,desc:u.description??"",default:u.default!==void 0?String(u.default):void 0})}let a=Math.max(...r.map(d=>d.flags.length+(d.type?d.type.length+1:0)),20);for(let d of r){let u=d.flags.length+(d.type?d.type.length+1:0),p=" ".repeat(a-u+2);t.push(j("indent"," ")),t.push(j(o,d.flags)),d.type&&(t.push(j("text"," ")),t.push(j(s,d.type))),t.push(j("text",p)),t.push(j(l,d.desc)),d.default!==void 0&&(t.push(j("text"," ")),t.push(j(i,`(default: ${d.default})`))),t.push(j("newline",`
41
+ `))}return t}function Gl(e){let n=_m(e.options??{},e.autoShort??!1),t=im(e.separators??Fl);return{schema:e,parse(r){return hm(r,e,n,t)},help(){return pm(e,e.formatter)}}}function hm(e,n,t,r){let o={positional:{},options:{},errors:[],rest:[]},s=new Set(r.map(u=>u.to));for(let u of s)o[u]={};let i=0,l=n.positional??[],a=0,d=!1;for(;a<e.length;){let u=e[a];if(n.stopEarly&&i>0){o.rest=e.slice(a);break}if(u==="--"&&!d){d=!0,a++;continue}if(d){if(i<l.length){let f=l[i];if(f.variadic){let m=[];for(;a<e.length;){let g=e[a];m.push(f.type?We(g,f.type):g),a++}o.positional[f.name]=m,i++}else{let m=f.type?We(u,f.type):u;o.positional[f.name]=m,i++,a++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(u)),a++;continue}if(u.startsWith("--")){a=Rm(u,a,e,o,t,n);continue}if(u.startsWith("-")&&u.length>1&&!Em(u)){a=bm(u,a,e,o,t,n);continue}let p=gm(u,r);if(p){let{key:f,value:m,config:g}=p,_=o,k=_[g.to]??(_[g.to]={});k[f]=g.typed?Ul(m):Oe(m),a++;continue}if(i<l.length){let f=l[i];if(f.variadic){let g=[];for(;a<e.length&&!e[a].startsWith("-");){let _=e[a];g.push(f.type?We(_,f.type):_),a++}o.positional[f.name]=g,i++;continue}let m=f.type?We(u,f.type):u;o.positional[f.name]=m,i++}else n.allowUnknown!==!1?o.rest.push(u):o.errors.push(`Unexpected positional argument: ${u}`);a++}return xm(o,n,t),Sm(o,n,l),vm(o,n,t),o}function gm(e,n){if(om.test(e))return null;for(let t of n){if(t.prefix&&e.startsWith(t.separator)){let o=e.slice(t.separator.length),s=o.indexOf(":");if(s>0){let i=o.slice(0,s),l=o.slice(s+1);if(ym(i))return{key:i,value:l,config:t}}continue}let r=e.indexOf(t.separator);if(r>0){let o=e.slice(0,r),s=e.slice(r+t.separator.length);if(km(o,s,t))return{key:o,value:s,config:t}}}return null}function ym(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function km(e,n,t){return e?t.separator===":"?e.includes("/")||e.includes(".")||/^\d+$/.test(n)?!1:/^[A-Z][a-zA-Z0-9-]*$/.test(e):!((t.separator==="="||t.separator===":=")&&e.includes("/")):!1}function Rm(e,n,t,r,o,s){let i=e.slice(2);if(i.startsWith("no-")){let a=i.slice(3),d=o.get(a);if(d?.negatable!==!1&&d?.type==="boolean")return r.options[d.name]=!1,n+1}if(i.includes("=")){let a=i.indexOf("="),d=i.slice(0,a),u=i.slice(a+1);return Wt(d,u,n+1,r,o,s)}let l=o.get(i);if(l){if(l.type!=="boolean"){let a=t[n+1];return Bn(a)?Wt(l.name,a,n+2,r,o,s):(r.errors.push(`Option --${i} requires a value`),n+1)}return r.options[l.name]=!0,n+1}return s.strict?r.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(r.options[i]=!0),n+1}function bm(e,n,t,r,o,s){let i=e.slice(1);if(i.includes("=")){let l=i.indexOf("="),a=i.slice(0,l),d=i.slice(l+1),u=ho(a,o);return u?Wt(u.name,d,n+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=Ct(Oe(d))),n+1)}if(i.length===1){let l=ho(i,o);if(l){if(l.type!=="boolean"){let a=t[n+1];return Bn(a)?Wt(l.name,a,n+2,r,o,s):(r.errors.push(`Option -${i} requires a value`),n+1)}return r.options[l.name]=!0,n+1}if(s.strict)r.errors.push(`Unknown option: -${i}`);else if(s.allowUnknown!==!1){let a=t[n+1];if(Bn(a))return r.options[i]=Ct(Oe(a)),n+2;r.options[i]=!0}return n+1}for(let l of i){let a=ho(l,o);a?a.type==="boolean"?r.options[a.name]=!0:r.errors.push(`Option -${l} requires a value`):s.strict?r.errors.push(`Unknown option: -${l}`):s.allowUnknown!==!1&&(r.options[l]=!0)}return n+1}function Wt(e,n,t,r,o,s){let i=o.get(e);if(i){if(i.choices){let a=i.type?We(Oe(n),i.type):Oe(n);if(!i.choices.includes(a))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${i.choices.join(", ")}`),t}let l=i.type?We(Oe(n),i.type):Oe(n);if(i.type==="array"){let a=r.options[e];Array.isArray(a)?a.push(...l):r.options[e]=l}else r.options[e]=l}else s.strict?r.errors.push(`Unknown option: --${e}`):s.allowUnknown!==!1&&(r.options[e]=Ct(Oe(n)));return t}function _m(e,n=!1){let t=new Map,r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i)),o=new Set;for(let[,s]of r)s.short&&o.add(s.short);for(let[s,i]of r){let l=i.short??"";n&&!l&&(l=wm(s,o),l&&o.add(l));let a={name:s,short:l,aliases:i.aliases??[],type:i.type??"string",description:i.description??"",required:i.required??!1,hidden:i.hidden??!1,negatable:i.negatable??!0,default:i.default,choices:i.choices,env:i.env,validate:i.validate};t.set(s,a);for(let d of a.aliases)t.set(d,a)}return t}function wm(e,n){for(let t of e){if(!/[a-zA-Z]/.test(t))continue;let r=t.toLowerCase();if(!n.has(r))return r;let o=t.toUpperCase();if(!n.has(o))return o}return""}function ho(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function xm(e,n,t){for(let r of t.values())if(e.options[r.name]===void 0)if(r.env&&process.env[r.env]!==void 0){let o=process.env[r.env];e.options[r.name]=r.type?We(o,r.type):o}else r.default!==void 0&&(e.options[r.name]=r.default);for(let r of n.positional??[])e.positional[r.name]===void 0&&r.default!==void 0&&(e.positional[r.name]=r.default)}function Sm(e,n,t){if(n.options)for(let[r,o]of Object.entries(n.options))o.required&&e.options[r]===void 0&&e.errors.push(`Missing required option: --${r}`);for(let r of t)r.required&&e.positional[r.name]===void 0&&e.errors.push(`Missing required argument: <${r.name}>`)}function vm(e,n,t){for(let r of t.values()){let o=e.options[r.name];if(r.validate&&o!==void 0){let s=r.validate(o);s!==!0&&e.errors.push(s)}}for(let r of n.positional??[]){let o=e.positional[r.name];if(r.validate&&o!==void 0){let s=r.validate(o);s!==!0&&e.errors.push(s)}}}function Em(e){return/^-\d+(\.\d+)?$/.test(e)}var go=class extends Error{flag;known;constructor(n,t){super(`unknown flag '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownFlagError",this.flag=n,this.known=t}};function Pm(e){let n={};for(let[t,r]of Object.entries(e))n[t]={type:r.kind==="boolean"?"boolean":"string",...t.length===1?{short:t}:{},...r.aliases===void 0?{}:{aliases:r.aliases}};return n}function Dm(e,n){let t=new Map;for(let[o,s]of Object.entries(n))if(!(s.kind!=="value"||s.type!=="array")){t.set(o,o);for(let i of s.aliases??[])t.set(i,o)}let r=new Map;for(let o=0;o<e.length;o+=1){let s=e[o];if(s==="--")break;let i=s.match(/^--([^=]+)(?:=(.*))?$/)??s.match(/^-([^=])(?:=(.*))?$/);if(i===null)continue;let l=t.get(i[1]);if(l===void 0)continue;let a=i[2];if(a===void 0&&Bn(e[o+1])&&(a=e[o+1],o+=1),a===void 0)continue;let d=r.get(l)??[];d.push(a),r.set(l,d)}return r}function He(e,n,t={}){let o=Gl({options:Pm(n),separators:{},allowUnknown:!0}).parse([...e]),s={},i=Dm(e,n),l=o.errors.find(a=>/^Option --?\S+ requires a value$/.test(a));if(l!==void 0)throw new Error(l.replace(/^Option /,""));if(o.errors.length>0)throw new Error(o.errors[0]);if(t.unknownFlags==="error"){let a=new Set(Object.keys(n));for(let d of Object.keys(o.options))if(!a.has(d))throw new go(d.length===1?`-${d}`:`--${d}`,Object.keys(n).map(u=>u.length===1?`-${u}`:`--${u}`))}for(let[a,d]of Object.entries(n)){let u=o.options[a];u!==void 0&&(d.kind==="boolean"?s[a]=u:d.type==="array"?s[a]=(i.get(a)??[]).map(p=>d.coerce(p)):s[a]=d.coerce(String(u)))}return{values:s,positionals:o.rest}}var yo=class extends Error{token;known;constructor(n,t){super(`unknown command '${n}'; expected one of: ${t.join(", ")}`),this.name="UnknownCommandError",this.token=n,this.known=t}};function Kl(e,n){let[t,...r]=e;if(t!==void 0){for(let[s,i]of Object.entries(n.commands))if(t===s||(i.aliases??[]).includes(t))return{command:s,args:r};if(n.errorOnUnknownCommand&&!t.startsWith("-"))throw new yo(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as Wm,mkdirSync as Hm,readFileSync as na,statSync as Bm}from"node:fs";import{dirname as ra,join as Fm}from"node:path";var Vl="RED_WORKER_SCOPE",ql="RED_WORKER_MEMORY_CEILING",Jl="RED_WORKER_SCOPE_DEGRADATION",Ro={scope:null,memory_ceiling:null,scope_degradation:null};function bo(e){return{scope:ko(e[Vl]),memory_ceiling:ko(e[ql]),scope_degradation:ko(e[Jl])}}function Fn(e){let n={};return e.scope!=null&&e.scope!==""&&(n[Vl]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[ql]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[Jl]=e.scope_degradation),n}function ko(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as Am,readdirSync as Lm,readFileSync as Xl,rmSync as $m,writeFileSync as Tm}from"node:fs";import{basename as Im,join as fn}from"node:path";import{isAbsolute as vS,join as Ht,resolve as ES}from"node:path";function jm(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var Ql="deaths",zl="deaths.toonl";function Bt(e){return Ht(jm(e),Ql)}function Un(e){return Ht(Bt(e),zl)}var Gn="live",Yl="attributions.toonl";function Ft(e){return Ht(Bt(e),Gn)}function _o(e){return Ht(Bt(e),Yl)}var xo=fn("sys","kernel","random","boot_id"),Zl=1;function So(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:Zl,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:ea(fn(t,xo)),cgroup:Nm(t,r),last_phase:e.last_phase}}function ea(e){try{let n=Xl(e,"utf8").trim();return n===""?null:n}catch{return null}}function Nm(e,n){let t=ea(fn(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
42
+ `),o=r.find(i=>i.startsWith("0::"));if(o)return o.slice(3)||null;let s=r[0]?.split(":").slice(2).join(":");return s===void 0||s===""?null:s}function vo(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function Eo(e,n){let t=fn(e,vo(n));try{return Am(e,{recursive:!0,mode:448}),Tm(t,ce({trailer:!1}).push(Cm(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function Be(e,n){try{$m(fn(e,vo(n)),{force:!0})}catch{}}function Po(e,n){let t;try{t=Lm(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=fn(e,o);try{let l=we(Xl(s,"utf8"))[0];if(l===void 0)throw new Error("anchor holds no record");r.push(Mm(l))}catch(i){n?.(Im(s),i instanceof Error?i.message:String(i))}}return r}function Mm(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:wo(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:wo(e.pid),ppid:wo(e.ppid),boot_id:e.boot_id==null?null:String(e.boot_id),cgroup:e.cgroup==null?null:String(e.cgroup),last_phase:String(e.last_phase)}}function wo(e){return typeof e=="number"?e:Number(e)}function Cm(e){return{...e}}var Um=1,Gm=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Km(e){return typeof e=="string"&&Gm.has(e)}var Vm="startup";function qm(e,n){return{...e.scope??Ro,version:Um,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,exit_path:e.exit_path,signal:e.signal??null,exit_code:e.exit_code??null,last_phase:e.last_phase,detail:e.detail??null,...n}}function Jm(e){let n=e.resourceUsage();return{uptime_s:Math.round(e.uptime()),rss_kb:Math.round(e.memoryUsage().rss/1024),max_rss_kb:n.maxRSS,user_cpu_us:n.userCPUTime,system_cpu_us:n.systemCPUTime,minor_page_faults:n.minorPageFault,major_page_faults:n.majorPageFault,voluntary_ctx_switches:n.voluntaryContextSwitches,involuntary_ctx_switches:n.involuntaryContextSwitches}}var jo={mkdir(e){Hm(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=Bm(e).size}catch{return!0}if(n===0)return!0;try{return na(e,"utf8").endsWith(`
43
+ `)}catch{return!0}},append(e,n){Wm(e,n,{encoding:"utf8",mode:384})},read(e){return na(e,"utf8")}};function Qm(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function zm(e,n,t=jo){let r=ce({trailer:!1}).push(Qm(n));return t.mkdir(ra(e)),t.endsClean(e)||t.append(e,`
44
+ `),t.append(e,r),n}function oa(e){let n=e.endsWith(`
45
45
  `)?e:e.slice(0,e.lastIndexOf(`
46
- `)+1);return n===""?[]:ve(n).map(Om)}function Om(e){let n=e.exit_path;if(!Sm(n))throw new Error(`death record has unknown exit_path ${JSON.stringify(n)}`);let t=e.kind;if(t!=="launcher"&&t!=="worker"&&t!=="daemon")throw new Error(`death record has unknown kind ${JSON.stringify(t)}`);return{version:z(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:z(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:z(e.exit_code),last_phase:String(e.last_phase),detail:e.detail==null?null:String(e.detail),scope:e.scope==null?null:String(e.scope),memory_ceiling:e.memory_ceiling==null?null:String(e.memory_ceiling),scope_degradation:e.scope_degradation==null?null:String(e.scope_degradation),uptime_s:z(e.uptime_s),rss_kb:z(e.rss_kb),max_rss_kb:z(e.max_rss_kb),user_cpu_us:z(e.user_cpu_us),system_cpu_us:z(e.system_cpu_us),minor_page_faults:z(e.minor_page_faults),major_page_faults:z(e.major_page_faults),voluntary_ctx_switches:z(e.voluntary_ctx_switches),involuntary_ctx_switches:z(e.involuntary_ctx_switches)}}function z(e){return typeof e=="number"?e:Number(e)}function Vl(e,n=ko){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return Kl(t)}var Am=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],yo=null;function ql(e){let n=e.host??process,t=e.io??ko,r=e.clock??(()=>new Date().toISOString()),o=n.pid,s=e.scope??ao(process.env),i=e.phase??vm,l=null,a=e.presenceDir===void 0?_m(Gl(e.lanePath),Wn):e.presenceDir,d=null,u=()=>{a!==null&&(d=fo({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),ho(a,d))},p=k=>{if(!l){try{l=jm(e.lanePath,Em({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...k},Pm(n)),t)}catch{}a!==null&&d!==null&&Ne(a,d)}},f={signal(k){p({exit_path:"signal",signal:k})},exit(k){p({exit_path:"exit",exit_code:k})},uncaughtException(k){p({exit_path:"uncaught-exception",detail:Ul(k)})},unhandledRejection(k){p({exit_path:"unhandled-rejection",detail:Ul(k)})}},g=[...(e.signals??Am).map(k=>{let w=()=>{if(f.signal(k),!(n.listenerCount?.(k)!==1||!n.kill)){n.off(k,w);try{n.kill(o,k)}catch{}}};return[k,w]}),["uncaughtException",(...k)=>f.uncaughtException(k[0])],["unhandledRejection",(...k)=>f.unhandledRejection(k[0])],["exit",(...k)=>f.exit(typeof k[0]=="number"?k[0]:null)]];for(let[k,w]of g)n.on(k,w);let _={lanePath:e.lanePath,phase(k){i=k,l||u()},currentPhase:()=>i,written:()=>l,uninstall(){for(let[k,w]of g)n.off(k,w);a!==null&&d!==null&&Ne(a,d),yo===_&&(yo=null)},handlers:f};return e.setActive!==!1&&(yo=_),u(),_}function Ul(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Lm,readdirSync as Tm,readFileSync as Mt,statSync as $m,writeFileSync as Im}from"node:fs";import{join as Yl}from"node:path";var Nm=1,Mm=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],Cm=512*1024;function Wm(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??Mm,r=[],o=Yl(n,po),s=null;try{let a=Mt(o,"utf8").trim();s=a===""?null:a,r.push({source:o,result:s?"read":"empty",detail:s})}catch(a){r.push({source:o,result:Ro(a),detail:null})}let i=new Set;try{for(let a of Tm(n))/^\d+$/.test(a)&&i.add(Number(a));r.push({source:n,result:"read",detail:`${i.size} live pids`})}catch(a){r.push({source:n,result:Ro(a),detail:null})}let l=[];for(let a of t)try{let u=Bm(a,e.tailBytes??Cm).split(`
47
- `).filter(p=>p.trim()!=="");l.push(...u),r.push({source:a,result:u.length===0?"empty":"read",detail:`${u.length} lines`})}catch(d){r.push({source:a,result:Ro(d),detail:null})}return{boot_id:s,live_pids:i,journal:l,probes:r}}function Ro(e){return e.code==="ENOENT"?"absent":"unreadable"}function Bm(e,n){let t=$m(e).size,r=Mt(e,"utf8");return t<=n?r:r.slice(r.length-n)}var Fm=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,Hm=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,Um=/Killed (\/\S*) due to memory pressure/,Gm=/\bopid=(\d+)\b/,Jl=/\bsig=(\d+)\b/,Km=/\buid=(\d+)\b/,Vm=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,qm={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function Jm(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,s=[...n.probes.map(p=>`${p.source}: ${p.result}${p.detail?` (${p.detail})`:""}`),`boot id: anchored under ${e.boot_id??"unknown"}, host now ${n.boot_id??"unknown"} (${o?"changed":"same"})`,`parent account: ppid ${e.ppid}`,`cgroup: ${e.cgroup??"unknown"}`],i=(p,f,m,g)=>({version:Nm,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:p,confidence:f,signal:m,host_boot_changed:o,evidence:g,checked:s}),l=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],a=n.journal.find(p=>Ql(p,e.pid,Fm)||Ql(p,e.pid,Hm));if(a!==void 0)return i("oomd",o?"medium":"high","SIGKILL",[a,...l]);if(e.cgroup!==null)for(let p of n.journal){let f=Um.exec(p)?.[1];if(f!==void 0){if(f===e.cgroup)return i("oomd",o?"medium":"high","SIGKILL",[p,...l]);if(e.cgroup.startsWith(`${f}/`))return i("oomd","medium","SIGKILL",[p,`the killed scope ${f} is an ancestor of this process's ${e.cgroup}`,...l])}}let d=n.journal.find(p=>Number(Gm.exec(p)?.[1])===e.pid&&Jl.test(p));if(d!==void 0){let p=Number(Jl.exec(d)?.[1]),f=Km.exec(d)?.[1];return i("user-signal",o?"medium":"high",qm[p]??null,[d,...f===void 0?[]:[`sent by uid ${f}`],...l])}let u=t.find(p=>p.pid===e.ppid);if(u!==void 0&&!n.live_pids.has(e.ppid))return i("parent-death","medium",null,[`parent pid ${e.ppid} (${u.kind} ${u.id}) recorded its own death at ${u.ts} via ${u.exit_path}${u.signal?` ${u.signal}`:""}`]);if(o){let p=n.journal.find(f=>Vm.test(f));return p!==void 0?i("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,p]):i("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,"no shutdown record on any journal read: the host stopped without announcing it (a freeze or a power loss, not an orderly teardown)"])}return i("unknown","none",null,[])}function Ql(e,n,t){return Number(t.exec(e)?.[1])===n}var Qm=" | ";function zl(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(Qm)}function zm(e){return{version:e.version,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.last_seen,last_phase:e.last_phase,sender_class:e.sender_class,confidence:e.confidence,signal:e.signal,host_boot_changed:e.host_boot_changed,evidence:zl(e.evidence),checked:zl(e.checked)}}function Ym(e){let n=be({trailer:!1});return e.map(t=>n.push(zm(t))).join("")}function Xl(e){let n=Nt(e.stateRoot),t=co(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??Wm({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=go(n,p=>s.push(p)),l=Vl(Cn(e.stateRoot)),a=[],d=[],u=[];for(let p of i){if(o.live_pids.has(p.pid)){d.push(p);continue}if(l.find(m=>m.pid===p.pid&&m.id===p.id)!==void 0){u.push(p),Ne(n,p);continue}a.push(Jm(p,o,l,r())),Ne(n,p)}return a.length>0&&Xm(t,a),{attributions:a,alive:d,self_recorded:u,skipped:s,laneText:()=>{try{return Mt(t,"utf8")}catch{return""}}}}function Zl(e){let n=e.skipped.length===0?"":` | unreadable anchors=${e.skipped.join(",")}`;if(e.attributions.length===0)return`death reaper: no un-recorded deaths (live=${e.alive.length} self-recorded=${e.self_recorded.length})${n}`;let t=e.attributions.map(r=>` | ${r.kind} ${r.id} pid=${r.pid} ${r.sender_class}/${r.confidence} phase=${r.last_phase}`+(r.evidence[0]?` evidence="${r.evidence[0]}"`:"")).join("");return`death reaper: attributed ${e.attributions.length}${t}${n}`}function Xm(e,n){try{Lm(Yl(e,".."),{recursive:!0,mode:448});let t=Zm(e),r=t===""||t.endsWith(`
46
+ `)+1);return n===""?[]:we(n).map(Ym)}function Ym(e){let n=e.exit_path;if(!Km(n))throw new Error(`death record has unknown exit_path ${JSON.stringify(n)}`);let t=e.kind;if(t!=="launcher"&&t!=="worker"&&t!=="daemon")throw new Error(`death record has unknown kind ${JSON.stringify(t)}`);return{version:X(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:X(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:X(e.exit_code),last_phase:String(e.last_phase),detail:e.detail==null?null:String(e.detail),scope:e.scope==null?null:String(e.scope),memory_ceiling:e.memory_ceiling==null?null:String(e.memory_ceiling),scope_degradation:e.scope_degradation==null?null:String(e.scope_degradation),uptime_s:X(e.uptime_s),rss_kb:X(e.rss_kb),max_rss_kb:X(e.max_rss_kb),user_cpu_us:X(e.user_cpu_us),system_cpu_us:X(e.system_cpu_us),minor_page_faults:X(e.minor_page_faults),major_page_faults:X(e.major_page_faults),voluntary_ctx_switches:X(e.voluntary_ctx_switches),involuntary_ctx_switches:X(e.involuntary_ctx_switches)}}function X(e){return typeof e=="number"?e:Number(e)}function sa(e,n=jo){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return oa(t)}var Xm=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],Do=null;function ia(e){let n=e.host??process,t=e.io??jo,r=e.clock??(()=>new Date().toISOString()),o=n.pid,s=e.scope??bo(process.env),i=e.phase??Vm,l=null,a=e.presenceDir===void 0?Fm(ra(e.lanePath),Gn):e.presenceDir,d=null,u=()=>{a!==null&&(d=So({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),Eo(a,d))},p=k=>{if(!l){try{l=zm(e.lanePath,qm({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...k},Jm(n)),t)}catch{}a!==null&&d!==null&&Be(a,d)}},f={signal(k){p({exit_path:"signal",signal:k})},exit(k){p({exit_path:"exit",exit_code:k})},uncaughtException(k){p({exit_path:"uncaught-exception",detail:ta(k)})},unhandledRejection(k){p({exit_path:"unhandled-rejection",detail:ta(k)})}},g=[...(e.signals??Xm).map(k=>{let x=()=>{if(f.signal(k),!(n.listenerCount?.(k)!==1||!n.kill)){n.off(k,x);try{n.kill(o,k)}catch{}}};return[k,x]}),["uncaughtException",(...k)=>f.uncaughtException(k[0])],["unhandledRejection",(...k)=>f.unhandledRejection(k[0])],["exit",(...k)=>f.exit(typeof k[0]=="number"?k[0]:null)]];for(let[k,x]of g)n.on(k,x);let _={lanePath:e.lanePath,phase(k){i=k,l||u()},currentPhase:()=>i,written:()=>l,uninstall(){for(let[k,x]of g)n.off(k,x);a!==null&&d!==null&&Be(a,d),Do===_&&(Do=null)},handlers:f};return e.setActive!==!1&&(Do=_),u(),_}function ta(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Zm,readdirSync as eh,readFileSync as Ut,statSync as nh,writeFileSync as th}from"node:fs";import{join as ca}from"node:path";var rh=1,oh=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],sh=512*1024;function ih(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??oh,r=[],o=ca(n,xo),s=null;try{let a=Ut(o,"utf8").trim();s=a===""?null:a,r.push({source:o,result:s?"read":"empty",detail:s})}catch(a){r.push({source:o,result:Oo(a),detail:null})}let i=new Set;try{for(let a of eh(n))/^\d+$/.test(a)&&i.add(Number(a));r.push({source:n,result:"read",detail:`${i.size} live pids`})}catch(a){r.push({source:n,result:Oo(a),detail:null})}let l=[];for(let a of t)try{let u=lh(a,e.tailBytes??sh).split(`
47
+ `).filter(p=>p.trim()!=="");l.push(...u),r.push({source:a,result:u.length===0?"empty":"read",detail:`${u.length} lines`})}catch(d){r.push({source:a,result:Oo(d),detail:null})}return{boot_id:s,live_pids:i,journal:l,probes:r}}function Oo(e){return e.code==="ENOENT"?"absent":"unreadable"}function lh(e,n){let t=nh(e).size,r=Ut(e,"utf8");return t<=n?r:r.slice(r.length-n)}var ah=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,dh=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,ch=/Killed (\/\S*) due to memory pressure/,uh=/\bopid=(\d+)\b/,la=/\bsig=(\d+)\b/,ph=/\buid=(\d+)\b/,fh=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,mh={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function hh(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,s=[...n.probes.map(p=>`${p.source}: ${p.result}${p.detail?` (${p.detail})`:""}`),`boot id: anchored under ${e.boot_id??"unknown"}, host now ${n.boot_id??"unknown"} (${o?"changed":"same"})`,`parent account: ppid ${e.ppid}`,`cgroup: ${e.cgroup??"unknown"}`],i=(p,f,m,g)=>({version:rh,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:p,confidence:f,signal:m,host_boot_changed:o,evidence:g,checked:s}),l=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],a=n.journal.find(p=>aa(p,e.pid,ah)||aa(p,e.pid,dh));if(a!==void 0)return i("oomd",o?"medium":"high","SIGKILL",[a,...l]);if(e.cgroup!==null)for(let p of n.journal){let f=ch.exec(p)?.[1];if(f!==void 0){if(f===e.cgroup)return i("oomd",o?"medium":"high","SIGKILL",[p,...l]);if(e.cgroup.startsWith(`${f}/`))return i("oomd","medium","SIGKILL",[p,`the killed scope ${f} is an ancestor of this process's ${e.cgroup}`,...l])}}let d=n.journal.find(p=>Number(uh.exec(p)?.[1])===e.pid&&la.test(p));if(d!==void 0){let p=Number(la.exec(d)?.[1]),f=ph.exec(d)?.[1];return i("user-signal",o?"medium":"high",mh[p]??null,[d,...f===void 0?[]:[`sent by uid ${f}`],...l])}let u=t.find(p=>p.pid===e.ppid);if(u!==void 0&&!n.live_pids.has(e.ppid))return i("parent-death","medium",null,[`parent pid ${e.ppid} (${u.kind} ${u.id}) recorded its own death at ${u.ts} via ${u.exit_path}${u.signal?` ${u.signal}`:""}`]);if(o){let p=n.journal.find(f=>fh.test(f));return p!==void 0?i("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,p]):i("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,"no shutdown record on any journal read: the host stopped without announcing it (a freeze or a power loss, not an orderly teardown)"])}return i("unknown","none",null,[])}function aa(e,n,t){return Number(t.exec(e)?.[1])===n}var gh=" | ";function da(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(gh)}function yh(e){return{version:e.version,ts:e.ts,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.last_seen,last_phase:e.last_phase,sender_class:e.sender_class,confidence:e.confidence,signal:e.signal,host_boot_changed:e.host_boot_changed,evidence:da(e.evidence),checked:da(e.checked)}}function kh(e){let n=ce({trailer:!1});return e.map(t=>n.push(yh(t))).join("")}function ua(e){let n=Ft(e.stateRoot),t=_o(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??ih({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=Po(n,p=>s.push(p)),l=sa(Un(e.stateRoot)),a=[],d=[],u=[];for(let p of i){if(o.live_pids.has(p.pid)){d.push(p);continue}if(l.find(m=>m.pid===p.pid&&m.id===p.id)!==void 0){u.push(p),Be(n,p);continue}a.push(hh(p,o,l,r())),Be(n,p)}return a.length>0&&Rh(t,a),{attributions:a,alive:d,self_recorded:u,skipped:s,laneText:()=>{try{return Ut(t,"utf8")}catch{return""}}}}function pa(e){let n=e.skipped.length===0?"":` | unreadable anchors=${e.skipped.join(",")}`;if(e.attributions.length===0)return`death reaper: no un-recorded deaths (live=${e.alive.length} self-recorded=${e.self_recorded.length})${n}`;let t=e.attributions.map(r=>` | ${r.kind} ${r.id} pid=${r.pid} ${r.sender_class}/${r.confidence} phase=${r.last_phase}`+(r.evidence[0]?` evidence="${r.evidence[0]}"`:"")).join("");return`death reaper: attributed ${e.attributions.length}${t}${n}`}function Rh(e,n){try{Zm(ca(e,".."),{recursive:!0,mode:448});let t=bh(e),r=t===""||t.endsWith(`
48
48
  `)?"":`
49
- `;Im(e,`${t}${r}${Ym(n)}`,{encoding:"utf8",mode:384})}catch{}}function Zm(e){try{return Mt(e,"utf8")}catch{return""}}import{join as eh}from"node:path";var nh=[".red","redskilled"],ae=448;function Me(e){return eh(e,...nh)}import{execFileSync as hh}from"node:child_process";import{readFileSync as gh}from"node:fs";import{dirname as ia,join as yh}from"node:path";import{existsSync as th,readFileSync as pS}from"node:fs";import{dirname as rh,join as oh}from"node:path";function ea(e,n){let t=e;for(let r=0;r<16;r++){let o=oh(t,n);if(th(o))return o;let s=rh(t);if(s===t)break;t=s}return null}function sh(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function dn(e,n){let t=[];for(let r of e.split(`
50
- `)){let o=r.replace(/\r$/,""),s=o.trim();if(!s||s.startsWith("#"))continue;let i=o.indexOf(":");if(i<0)continue;let l=o.length-o.trimStart().length,a=o.slice(0,i).trim();if(!a)continue;let d=o.slice(i+1).trim();for(;t.length&&t[t.length-1].indent>=l;)t.pop();if(t.push({indent:l,key:a}),d&&t.map(p=>p.key).join(".")===n)return sh(d)}}import{createHash as ih}from"node:crypto";var lh="project.name";function ta(e){let n=dn(e,lh)?.trim();return n===void 0||n===""?void 0:n}var ah=8,ra="project";function oa(e){let n=fh(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:dh(e.remoteUrl)??{name:ch(e.checkoutPath,n),source:"basename"},o=ph(n??bo(e.checkoutPath));return{name:r.name,slug:`${uh(r.name)}-${o}`,hash:o,source:r.source}}function sa(e){let n=(e??"").trim();if(n==="")return;let t=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),r=/^[^/]*?:(?!\d)(.+)$/.exec(t),s=(r?r[1]:t.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(i=>i.trim()).filter(i=>i!=="");if(s.length!==0)return s.slice(-2).join("/")}function dh(e){let n=sa(e);return n===void 0?void 0:{name:n,source:"remote"}}function ch(e,n){let t=n===void 0?"":na(mh(n));if(t!=="")return t;let r=na(bo(e));return r===""?ra:r}function uh(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?ra:t}function ph(e){return ih("sha256").update(e).digest("hex").slice(0,ah)}function fh(e){let n=bo(e??"");return n===""?void 0:n}function bo(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function na(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function mh(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var kh=2e3;function la(e){return Rh(e).name}function Rh(e){let n=wo(e),t=_o(e,["rev-parse","--absolute-git-dir"])??_o(e,["rev-parse","--git-common-dir"]),r=_o(e,["remote","get-url","origin"]);return oa({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function wo(e){let n=ea(e,yh(".red","config.yaml"));if(n==null)return{};let t;try{t=gh(n,"utf8")}catch{return{}}let r=ta(t),o=ia(ia(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function _o(e,n){try{let t=hh("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:kh}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as ku}from"node:crypto";import{spawn as Jb}from"node:child_process";import{mkdir as Qb}from"node:fs/promises";import{dirname as zb}from"node:path";import{createHash as wh}from"node:crypto";import{constants as Po}from"node:fs";import{mkdir as ga,open as xh,readFile as Sh,rm as ya,stat as vh}from"node:fs/promises";import{createConnection as Eh}from"node:net";import{tmpdir as Ph}from"node:os";import{dirname as ka,join as Bn}from"node:path";var bh="toon";function ca(e){return e.trimStart().startsWith("{")?"json":"toon"}function So(e){let n=0;for(;e[n]===`
51
- `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=ca(t);if(r==="json"){let s=t.indexOf(`
49
+ `;th(e,`${t}${r}${kh(n)}`,{encoding:"utf8",mode:384})}catch{}}function bh(e){try{return Ut(e,"utf8")}catch{return""}}import{join as _h}from"node:path";var wh=[".red","redskilled"],xe=448;function Fe(e){return _h(e,...wh)}import{execFileSync as Nh}from"node:child_process";import{readFileSync as Mh}from"node:fs";import{dirname as Ra,join as Ch}from"node:path";import{existsSync as xh,readFileSync as rv}from"node:fs";import{dirname as Sh,join as vh}from"node:path";function fa(e,n){let t=e;for(let r=0;r<16;r++){let o=vh(t,n);if(xh(o))return o;let s=Sh(t);if(s===t)break;t=s}return null}function Eh(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function mn(e,n){let t=[];for(let r of e.split(`
50
+ `)){let o=r.replace(/\r$/,""),s=o.trim();if(!s||s.startsWith("#"))continue;let i=o.indexOf(":");if(i<0)continue;let l=o.length-o.trimStart().length,a=o.slice(0,i).trim();if(!a)continue;let d=o.slice(i+1).trim();for(;t.length&&t[t.length-1].indent>=l;)t.pop();if(t.push({indent:l,key:a}),d&&t.map(p=>p.key).join(".")===n)return Eh(d)}}import{createHash as Ph}from"node:crypto";var Dh="project.name";function ha(e){let n=mn(e,Dh)?.trim();return n===void 0||n===""?void 0:n}var jh=8,ga="project";function ya(e){let n=Th(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:Oh(e.remoteUrl)??{name:Ah(e.checkoutPath,n),source:"basename"},o=$h(n??Ao(e.checkoutPath));return{name:r.name,slug:`${Lh(r.name)}-${o}`,hash:o,source:r.source}}function ka(e){let n=(e??"").trim();if(n==="")return;let t=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),r=/^[^/]*?:(?!\d)(.+)$/.exec(t),s=(r?r[1]:t.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(i=>i.trim()).filter(i=>i!=="");if(s.length!==0)return s.slice(-2).join("/")}function Oh(e){let n=ka(e);return n===void 0?void 0:{name:n,source:"remote"}}function Ah(e,n){let t=n===void 0?"":ma(Ih(n));if(t!=="")return t;let r=ma(Ao(e));return r===""?ga:r}function Lh(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?ga:t}function $h(e){return Ph("sha256").update(e).digest("hex").slice(0,jh)}function Th(e){let n=Ao(e??"");return n===""?void 0:n}function Ao(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function ma(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function Ih(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var Wh=2e3;function ba(e){return Hh(e).name}function Hh(e){let n=$o(e),t=Lo(e,["rev-parse","--absolute-git-dir"])??Lo(e,["rev-parse","--git-common-dir"]),r=Lo(e,["remote","get-url","origin"]);return ya({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function $o(e){let n=fa(e,Ch(".red","config.yaml"));if(n==null)return{};let t;try{t=Mh(n,"utf8")}catch{return{}}let r=ha(t),o=Ra(Ra(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function Lo(e,n){try{let t=Nh("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Wh}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as Tu}from"node:crypto";import{spawn as j_}from"node:child_process";import{mkdir as O_}from"node:fs/promises";import{dirname as A_}from"node:path";import{createHash as Uh}from"node:crypto";import{constants as Co}from"node:fs";import{mkdir as ja,open as Gh,readFile as Kh,rm as Oa,stat as Vh}from"node:fs/promises";import{createConnection as qh}from"node:net";import{tmpdir as Jh}from"node:os";import{dirname as Aa,join as Kn}from"node:path";var Bh="toon";function xa(e){return e.trimStart().startsWith("{")?"json":"toon"}function Io(e){let n=0;for(;e[n]===`
51
+ `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=xa(t);if(r==="json"){let s=t.indexOf(`
52
52
  `);return s<0?null:{frame:t.slice(0,s),dialect:r,rest:t.slice(s+1)}}let o=t.indexOf(`
53
53
 
54
- `);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function vo(e){let n=ca(e)==="json"?xo:aa,t=n===xo?aa:xo;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function xo(e){return JSON.parse(e)}function aa(e){return Q(e)}function Eo(e,n){if(n==="toon"){let t=_h(e);if(t!==null)return t.endsWith(`
54
+ `);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function No(e){let n=xa(e)==="json"?To:_a,t=n===To?_a:To;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function To(e){return JSON.parse(e)}function _a(e){return Y(e)}function Mo(e,n){if(n==="toon"){let t=Fh(e);if(t!==null)return t.endsWith(`
55
55
  `)?`${t}
56
56
  `:`${t}
57
57
 
58
58
  `}return`${JSON.stringify(e)}
59
- `}function _h(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=W(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function ua(e,n){return!da(e)||!da(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function da(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var pa=new Set;function fa(e){return pa.has(e)?"json":bh}function ma(e){pa.add(e)}var Dh=108;async function Ct(e,n,t="resident server"){let r=e.wire,o=r??fa(e.socketPath),s=await ha(e,n,t,o);return r||o==="json"||!ua(n,s)?s:(ma(e.socketPath),await ha(e,n,t,"json"))}async function ha(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=Eh(e.socketPath),a=!1,d="",u=setTimeout(()=>{p(()=>i(new Error(`${t} timed out`))),l.destroy()},o);function p(f){a||(a=!0,clearTimeout(u),f())}l.on("connect",()=>{l.write(Eo(n,r))}),l.on("data",f=>{d+=f.toString("utf8");let m=So(d);m&&(d=m.rest,p(()=>{try{s(vo(m.frame))}catch(g){i(g)}}),l.end())}),l.on("error",f=>p(()=>i(f))),l.on("close",()=>{a||p(()=>i(new Error(`${t} closed without response`)))})})}function Ra(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=So(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(Eo(l,s.dialect))}catch{}};(async()=>{let l;try{l=vo(s.frame),await n(l,i)}catch(a){t(a,l,i)}finally{e.end()}})()})}async function jh(e){await ga(ka(e),{recursive:!0,mode:448});try{return await xh(e,Po.O_CREAT|Po.O_EXCL|Po.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}var Oh=6e4,ba="resident-spawn-lock v1",Ah=3;async function _a(e,n={}){let t=n.maxAgeMs??Oh,r=n.now??Date.now,o=n.pid??process.pid,s=n.isPidAlive??B;await ga(ka(e),{recursive:!0,mode:448});let i=[];for(let l=0;;l+=1){let a=await jh(e);if(a)return await a.writeFile(`${ba} pid=${o} taken=${new Date(r()).toISOString()}
60
- `).catch(()=>{}),{acquired:!0,lockPath:e,handle:a,reaped:i};let d=await Th(e),u=await Ih(e,d,r());if(l>=Ah||u==null)return{acquired:!1,lockPath:e,holder:d,ageMs:u};let p=Lh(d,u,t,s);if(p==null)return{acquired:!1,lockPath:e,holder:d,ageMs:u};let f={lockPath:e,reason:p,holder:d,ageMs:u};await ya(e,{force:!0}),i.push(f),n.onReap?.(f)}}async function wa(e){await e.handle.close().catch(()=>{}),await ya(e.lockPath,{force:!0})}function Lh(e,n,t,r){return e==null?n>t?"unattributed":null:r(e.pid)?n>t?"aged-out":null:"holder-dead"}function xa(e){let n=e.ageMs==null?"of unknown age":`taken ${Math.round(e.ageMs/1e3)}s ago`,t=e.holder==null?"an owner it does not name":`pid ${e.holder.pid} (at ${e.holder.takenAt})`;return`no spawn was attempted: the spawn lock ${JSON.stringify(e.lockPath)} is held by ${t}, ${n}. If that process is gone, remove the file to clear it`}async function Th(e){try{return $h(await Sh(e,"utf8"))}catch{return null}}function $h(e){let n=e.split(`
61
- `,1)[0]?.trim()??"";if(!n.startsWith(ba))return null;let t=Number(/\bpid=(\d+)\b/.exec(n)?.[1]??""),r=/\btaken=(\S+)/.exec(n)?.[1]??"";return!Number.isInteger(t)||t<=0||!Number.isFinite(Date.parse(r))?null:{pid:t,takenAt:r}}async function Ih(e,n,t){let r=n==null?Number.NaN:Date.parse(n.takenAt);if(Number.isFinite(r))return Math.max(0,t-r);try{return Math.max(0,t-(await vh(e)).mtimeMs)}catch{return null}}function B(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var Nh="/tmp";function Wt(e){let n=e.env??process.env,t=wh("sha256").update(e.key).digest("hex").slice(0,20),r=a=>Bn(a,e.socketFileName).length<Dh,o=n.XDG_RUNTIME_DIR;if(o){let a=Bn(o,"red-skills",t);if(r(a))return a}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=Bn(`red-skills-${s}`,t),l=Bn(Ph(),i);return r(l)||process.platform==="win32"?l:Bn(Nh,i)}_e();import{homedir as sg}from"node:os";import{join as Wo}from"node:path";import{spawnSync as ig}from"node:child_process";import{createHash as lg}from"node:crypto";import{existsSync as ag,readdirSync as dg}from"node:fs";import{mkdir as Aa,readFile as cg,rename as ug,writeFile as pg}from"node:fs/promises";import{dirname as fg}from"node:path";var Be="@reddb-io/red-skills",qh="https://registry.npmjs.org",Jh="canary",We=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}},Qh=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;function $o(e){return typeof e=="string"&&Qh.test(e.trim())}function Pa(e){return`${e}-.bundle.min.mjs`}var zh=".unversioned";function Yh(e,n,t="stable"){if(t==="canary")return`${e}-canary.bundle.min.mjs`;if(!$o(n))throw new We("invalid-version",`refusing to key the ${e} bundle cache on ${JSON.stringify(n??"")}: it would mint ${Pa(e)}, a name no resolver prefers and one whose mere existence satisfies the cache-first test forever (#3153)`);return`${e}-${n.trim()}.bundle.min.mjs`}function Ut(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return Un(r,Yh(n,t,o))}function Xh(e){return e==="dev"?["rsp","redskilled"]:[]}function Zh(e){return`${e}.bundle.min.mjs`}function eg(e){return Un("dist",Zh(e))}function ng(e,n="stable"){return`${Be}@${n==="canary"?Jh:e}`}function Io(e=Be){return`${qh}/${e.replace("/","%2F")}`}async function No(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=Ut({plugin:t,version:r,cacheDir:o,channel:s}),l=Xh(t),a=l.map(f=>Ut({plugin:f,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await rg(e,a))return i;let d=ng(r,s),u=Un(o,`.staging-${t}-${s==="canary"?"canary":r}`),p;try{p=await e.materialize(d,u)}catch(f){throw Oa(f,d)}for(let f of[t,...l]){let m=eg(f),g=Un(p,m);if(!await e.exists(g))throw new We("bundle-missing",`npm package ${d} has no ${m}`);let _=f===t?i:Ut({plugin:f,version:r,cacheDir:o,channel:s});await e.writeFile(_,await e.readFile(g))}return await tg(e,o,[t,...l]),i}async function tg(e,n,t){if(e.rename)for(let r of t){let o=Un(n,Pa(r));try{if(!await e.exists(o))continue;await e.rename(o,`${o}${zh}`)}catch{}}}async function rg(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function Da(e,n,t=Be){let r;try{r=await e.fetchText(Io(t))}catch(s){throw Oa(s,t)}let o=Mo(r);return{sameMajor:og(o,n),newest:Co(o)}}function Mo(e){let n;try{n=JSON.parse(e)}catch{return[]}if(typeof n!="object"||n===null)return[];let t=n.versions;return typeof t!="object"||t===null?[]:Object.keys(t)}function og(e,n){let t=To(n);if(t===null)return null;let r=null;for(let o of e)To(o)===t&&(r===null||ja(o,r)>0)&&(r=o);return r}function Co(e){let n=null;for(let t of e){let r=String(t).trim();To(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||ja(r,n)>0)&&(n=r)}return n}function To(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function ja(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n.trim());return!t||!r?0:Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function Oa(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new We("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new We("package-missing",`npm could not resolve ${n}: ${t}`,e):new We("network",`failed to resolve ${n}: ${t}`,e)}function Un(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}_e();var La={async materialize(e,n){await Aa(n,{recursive:!0});let t=ig("npm",["install",e,"--prefix",n,"--no-save","--no-audit","--no-fund","--ignore-scripts","--loglevel=error"],{stdio:["ignore","ignore","pipe"],encoding:"utf8"});if(t.error)throw t.error;if(t.status!==0)throw new Error(`npm install ${e} -> ${t.status}: ${(t.stderr||"").trim()}`);return Wo(n,"node_modules",...Be.split("/"))},async readFile(e){return new Uint8Array(await cg(e))},async writeFile(e,n){await Aa(fg(e),{recursive:!0}),await pg(e,n)},async exists(e){return ag(e)},sha256(e){return lg("sha256").update(e).digest("hex")},async fetchText(e){let n=await fetch(e,{redirect:"follow"});if(!n.ok)throw new Error(`GET ${e} -> ${n.status}`);return await n.text()},async rename(e,n){await ug(e,n)}},mg="redskilled";function hg(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Wo(e.HOME||sg(),".cache");return Wo(n,"red-skills","bundles")}var gg=/^([a-z0-9-]+)-(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?)\.bundle\.min\.mjs$/;async function yg(e,n){if($o(e.version))return e.version.trim();let t=e.listCacheDir??bg,r=kg(t(n),"dev");if(r)return r;try{let s=await(e.bundleIO??La).fetchText(Io());return Co(Mo(s))}catch{return null}}function kg(e,n){let t=null;for(let r of e){let o=gg.exec(r);if(!o||o[1]!==n)continue;let s=o[2];(t===null||Rg(s,t)>0)&&(t=s)}return t}function Rg(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n);return Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function bg(e){try{return dg(e)}catch{return[]}}async function _g(e={},n={},t={}){let r=Pe(e,n);if(ce(r))return r;let o=t.env??n.env??process.env,s=hg(o),i=await yg(t,s);if(i===null)return r;try{await No(t.bundleIO??La,{plugin:mg,version:i,cacheDir:s})}catch{return r}return Pe(e,n)}async function Ta(e={},n={},t={}){let r=await _g(e,n,t);if(ce(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(_e(),Ea));throw new o(r)}import{randomUUID as ur}from"node:crypto";import{mkdir as Lb,rm as mu}from"node:fs/promises";import{connect as Tb,createServer as $b}from"node:net";import{dirname as Ib}from"node:path";import{totalmem as xg}from"node:os";function Gn(e){if(e.applied_budget!=null)return e.applied_budget;let n=e.budget??{};return n.memory_max==null&&n.memory_high==null&&e.memory_ceiling!=null?{...n,memory_max:e.memory_ceiling}:n}function $a(e,n={}){let t=0,r=0,o=0,s=[],i=[];for(let d of e){let u=Gn(d),p=!1;for(let[f,m]of[[u.memory_high,g=>t+=g],[u.memory_max,g=>r+=g]]){if(f==null)continue;let g=cn(f);g==null?p=!0:m(g)}u.cpu_weight!=null&&(o+=u.cpu_weight),p&&s.push(d.worker_id),d.isolated||i.push(d.worker_id)}let l=n.hostCeilingBytes??null,a=l==null?0:Math.max(0,r-l);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:r,cpu_weight_total:o,unaccounted_workers:s.sort(),unisolated_workers:i.sort(),memory_ceiling_bytes:l,over_committed_bytes:a,over_commitment_reason:a===0?null:wg(e.length,r,l,a)}}function wg(e,n,t,r){return`this host's ${e} Worker(s) carry ${n} bytes of applied MemoryMax against a host ceiling of ${t} bytes \u2014 ${r} bytes over. A per-Worker MemoryMax is a wall rather than a reservation, so the host stays safe only while the Workers do not all peak together; the ceiling is not enforced host-wide.`}function cn(e){let n=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!n)return null;let t={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[n[2].toLowerCase()];return Math.round(Number(n[1])*t)}function Ia(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&Number.isInteger(n.worker_count)&&typeof n.memory_high_bytes=="number"&&typeof n.memory_max_bytes=="number"&&typeof n.cpu_weight_total=="number"&&Array.isArray(n.unaccounted_workers)&&Array.isArray(n.unisolated_workers)}var Na="REDSKILLED_MEMORY_CEILING",Bo="REDSKILLED_WORKER_CEILING",Ma=.7;function Wa(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return cn(n)}function Gt(e){let n=0,t=[];for(let r of e){let o=Wa(r.budget);o===null?t.push(r.worker_id):o!==void 0&&(n+=o)}return{worker_count:e.length,memory_bytes:n,unaccounted_workers:t.sort()}}function Ba(e){let{ceiling:n}=e,t=Gt(e.workers),r=Wa(e.budget),o=r===void 0?null:r,s=t.memory_bytes+(r??0),i=t.worker_count+1,l=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",a=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,d=(u,p)=>({version:1,admitted:!1,verdict:u,reason:p,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s});return n.worker_count!=null&&i>n.worker_count?d("refused-over-worker-ceiling",`redskilled refused this Worker${l}: it would be Worker ${i} past a host ceiling of ${n.worker_count} Worker(s), and ${a}`):n.memory_bytes!=null&&r===null?d("refused-unaccountable-budget",`redskilled refused this Worker${l}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${n.memory_bytes} bytes, and ${a}`):n.memory_bytes!=null&&s>n.memory_bytes?d("refused-over-memory-ceiling",`redskilled refused this Worker${l}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${n.memory_bytes} bytes, and ${a}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${l}: ${s} bytes of declared Worker memory against a host ceiling of ${n.memory_bytes??"unbounded"} bytes, and ${a}`,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function Fa(e){let n=e.budget?.memory_max??e.budget?.memory_high;if(n!=null)return{memory_max:n,reason:`the client declared this Worker's memory ceiling (${n}), so the host derived none`};if(e.ceiling.memory_bytes==null)return{memory_max:null,reason:"this host admits Workers against no memory ceiling, so there is no accounting to derive a per-Worker ceiling from; the daemon's RSS sampling floor is the only remaining ceiling"};let t=Gt(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,s=o==null?r:Math.floor(e.ceiling.memory_bytes/o),i=Math.min(r,s);if(i<=0)return{memory_max:null,reason:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes is already fully committed to ${t.worker_count} Worker(s), so no positive per-Worker ceiling can be derived; the daemon's RSS sampling floor is the only remaining ceiling`};let l=o==null?`the headroom under this host's memory ceiling of ${e.ceiling.memory_bytes} bytes; this host declares no Worker slot count (${Bo} is unset), so this ceiling is a per-Worker wall and not memory the host sets aside \u2014 N Workers may carry N such walls, and the host ceiling is not enforced host-wide. Declare a slot count to make it divide into shares that sum to it`:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes shared across its ${o} Worker slot(s)`;return{memory_max:String(i),reason:`derived from ${l} (ceiling source: ${e.ceiling.source})`}}function Ha(e=process.env,n=xg()){let t=(e[Na]??"").trim(),r=(e[Bo]??"").trim(),o=Eg(r);if(t!==""){let s=vg(t,n);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"};Ca(`redskilled: ${Na}=${JSON.stringify(t)} is not a memory ceiling this host can read; using ${Ma*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return r!==""&&o===null&&!Sg(r)&&Ca(`redskilled: ${Bo}=${JSON.stringify(r)} is not a positive integer; this host admits an unbounded number of Workers instead.`),{memory_bytes:Math.floor(n*Ma),worker_count:o,source:"host-fraction"}}function Sg(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var Ca=e=>process.stderr.write(`${e}
62
- `);function vg(e,n){let t=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(t))return null;let r=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return r?Math.floor(n*(Number(r[1])/100)):cn(e)??void 0}function Eg(e){if(e===""||["infinity","none","off","unbounded"].includes(e.toLowerCase()))return null;let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:null}import{appendFile as Pg,mkdir as Dg,open as jg,readFile as Og,stat as Ag,truncate as Ua}from"node:fs/promises";import{dirname as Lg}from"node:path";var Ga="redskilled.events.toonl";function Tg(e){let n=e.worker.budget??{};return{version:1,ts:e.ts,event:e.event,worker_id:e.worker.worker_id,project_label:e.worker.project_label,pid:e.worker.pid,workspace_path:e.worker.workspace_path,log_path:e.worker.log_path??null,isolated:e.worker.isolated,unit:e.worker.unit??null,memory_high:n.memory_high??null,memory_max:n.memory_max??null,cpu_weight:n.cpu_weight??null,detail:e.detail??null,exit_code:e.exitCode??null,signal:e.signal??null,reason:e.reason??null}}var $g="daemon:";function Ig(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${$g}${e.pid}`,project_label:"",pid:e.pid,workspace_path:e.socketPath,log_path:null,isolated:!1,unit:null,memory_high:null,memory_max:null,cpu_weight:null,detail:e.detail,exit_code:null,signal:e.signal??null,reason:e.reason}}function Ka(e){let n=be({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await Dg(Lg(e),{recursive:!0,mode:448}),await Ng(e),await Pg(e,n.push(Bg(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(Tg(o)),recordDaemonStop:o=>r(Ig(o)),read:()=>Mg(e),flush:async()=>{await t}}}async function Ng(e){let n;try{n=(await Ag(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await jg(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let s=n;s>0;s-=t){let i=Math.min(t,s),l=Buffer.alloc(i);await r.read(l,0,i,s-i);let a=l.lastIndexOf(10);if(a>=0){await Ua(e,s-i+a+1);return}}await Ua(e,0)}finally{await r.close()}}async function Mg(e){let n;try{n=await Og(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return Cg(n)}function Cg(e){let n=e.split(`
63
- `);return n.pop(),n.length===0?[]:ve(`${n.join(`
59
+ `}function Fh(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=W(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function Sa(e,n){return!wa(e)||!wa(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function wa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var va=new Set;function Ea(e){return va.has(e)?"json":Bh}function Pa(e){va.add(e)}var Qh=108;async function Gt(e,n,t="resident server"){let r=e.wire,o=r??Ea(e.socketPath),s=await Da(e,n,t,o);return r||o==="json"||!Sa(n,s)?s:(Pa(e.socketPath),await Da(e,n,t,"json"))}async function Da(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=qh(e.socketPath),a=!1,d="",u=setTimeout(()=>{p(()=>i(new Error(`${t} timed out`))),l.destroy()},o);function p(f){a||(a=!0,clearTimeout(u),f())}l.on("connect",()=>{l.write(Mo(n,r))}),l.on("data",f=>{d+=f.toString("utf8");let m=Io(d);m&&(d=m.rest,p(()=>{try{s(No(m.frame))}catch(g){i(g)}}),l.end())}),l.on("error",f=>p(()=>i(f))),l.on("close",()=>{a||p(()=>i(new Error(`${t} closed without response`)))})})}function La(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=Io(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(Mo(l,s.dialect))}catch{}};(async()=>{let l;try{l=No(s.frame),await n(l,i)}catch(a){t(a,l,i)}finally{e.end()}})()})}async function zh(e){await ja(Aa(e),{recursive:!0,mode:448});try{return await Gh(e,Co.O_CREAT|Co.O_EXCL|Co.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}var Yh=6e4,$a="resident-spawn-lock v1",Xh=3;async function Ta(e,n={}){let t=n.maxAgeMs??Yh,r=n.now??Date.now,o=n.pid??process.pid,s=n.isPidAlive??H;await ja(Aa(e),{recursive:!0,mode:448});let i=[];for(let l=0;;l+=1){let a=await zh(e);if(a)return await a.writeFile(`${$a} pid=${o} taken=${new Date(r()).toISOString()}
60
+ `).catch(()=>{}),{acquired:!0,lockPath:e,handle:a,reaped:i};let d=await eg(e),u=await tg(e,d,r());if(l>=Xh||u==null)return{acquired:!1,lockPath:e,holder:d,ageMs:u};let p=Zh(d,u,t,s);if(p==null)return{acquired:!1,lockPath:e,holder:d,ageMs:u};let f={lockPath:e,reason:p,holder:d,ageMs:u};await Oa(e,{force:!0}),i.push(f),n.onReap?.(f)}}async function Ia(e){await e.handle.close().catch(()=>{}),await Oa(e.lockPath,{force:!0})}function Zh(e,n,t,r){return e==null?n>t?"unattributed":null:r(e.pid)?n>t?"aged-out":null:"holder-dead"}function Na(e){let n=e.ageMs==null?"of unknown age":`taken ${Math.round(e.ageMs/1e3)}s ago`,t=e.holder==null?"an owner it does not name":`pid ${e.holder.pid} (at ${e.holder.takenAt})`;return`no spawn was attempted: the spawn lock ${JSON.stringify(e.lockPath)} is held by ${t}, ${n}. If that process is gone, remove the file to clear it`}async function eg(e){try{return ng(await Kh(e,"utf8"))}catch{return null}}function ng(e){let n=e.split(`
61
+ `,1)[0]?.trim()??"";if(!n.startsWith($a))return null;let t=Number(/\bpid=(\d+)\b/.exec(n)?.[1]??""),r=/\btaken=(\S+)/.exec(n)?.[1]??"";return!Number.isInteger(t)||t<=0||!Number.isFinite(Date.parse(r))?null:{pid:t,takenAt:r}}async function tg(e,n,t){let r=n==null?Number.NaN:Date.parse(n.takenAt);if(Number.isFinite(r))return Math.max(0,t-r);try{return Math.max(0,t-(await Vh(e)).mtimeMs)}catch{return null}}function H(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var rg="/tmp";function Kt(e){let n=e.env??process.env,t=Uh("sha256").update(e.key).digest("hex").slice(0,20),r=a=>Kn(a,e.socketFileName).length<Qh,o=n.XDG_RUNTIME_DIR;if(o){let a=Kn(o,"red-skills",t);if(r(a))return a}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=Kn(`red-skills-${s}`,t),l=Kn(Jh(),i);return r(l)||process.platform==="win32"?l:Kn(rg,i)}Se();import{homedir as Eg}from"node:os";import{join as zo}from"node:path";import{spawnSync as Pg}from"node:child_process";import{createHash as Dg}from"node:crypto";import{existsSync as jg,readdirSync as Og}from"node:fs";import{mkdir as Ga,readFile as Ag,rename as Lg,writeFile as $g}from"node:fs/promises";import{dirname as Tg}from"node:path";var Ke="@reddb-io/red-skills",mg="https://registry.npmjs.org",hg="canary",Ge=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}},gg=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;function Ko(e){return typeof e=="string"&&gg.test(e.trim())}function Ha(e){return`${e}-.bundle.min.mjs`}var yg=".unversioned";function kg(e,n,t="stable"){if(t==="canary")return`${e}-canary.bundle.min.mjs`;if(!Ko(n))throw new Ge("invalid-version",`refusing to key the ${e} bundle cache on ${JSON.stringify(n??"")}: it would mint ${Ha(e)}, a name no resolver prefers and one whose mere existence satisfies the cache-first test forever (#3153)`);return`${e}-${n.trim()}.bundle.min.mjs`}function Qt(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return Jn(r,kg(n,t,o))}function Rg(e){return e==="dev"?["rsp","redskilled"]:[]}function bg(e){return`${e}.bundle.min.mjs`}function _g(e){return Jn("dist",bg(e))}function wg(e,n="stable"){return`${Ke}@${n==="canary"?hg:e}`}function Vo(e=Ke){return`${mg}/${e.replace("/","%2F")}`}async function qo(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=Qt({plugin:t,version:r,cacheDir:o,channel:s}),l=Rg(t),a=l.map(f=>Qt({plugin:f,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await Sg(e,a))return i;let d=wg(r,s),u=Jn(o,`.staging-${t}-${s==="canary"?"canary":r}`),p;try{p=await e.materialize(d,u)}catch(f){throw Ua(f,d)}for(let f of[t,...l]){let m=_g(f),g=Jn(p,m);if(!await e.exists(g))throw new Ge("bundle-missing",`npm package ${d} has no ${m}`);let _=f===t?i:Qt({plugin:f,version:r,cacheDir:o,channel:s});await e.writeFile(_,await e.readFile(g))}return await xg(e,o,[t,...l]),i}async function xg(e,n,t){if(e.rename)for(let r of t){let o=Jn(n,Ha(r));try{if(!await e.exists(o))continue;await e.rename(o,`${o}${yg}`)}catch{}}}async function Sg(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function Ba(e,n,t=Ke){let r;try{r=await e.fetchText(Vo(t))}catch(s){throw Ua(s,t)}let o=Jo(r);return{sameMajor:vg(o,n),newest:Qo(o)}}function Jo(e){let n;try{n=JSON.parse(e)}catch{return[]}if(typeof n!="object"||n===null)return[];let t=n.versions;return typeof t!="object"||t===null?[]:Object.keys(t)}function vg(e,n){let t=Go(n);if(t===null)return null;let r=null;for(let o of e)Go(o)===t&&(r===null||Fa(o,r)>0)&&(r=o);return r}function Qo(e){let n=null;for(let t of e){let r=String(t).trim();Go(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||Fa(r,n)>0)&&(n=r)}return n}function Go(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function Fa(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim()),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n.trim());return!t||!r?0:Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function Ua(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Ge("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Ge("package-missing",`npm could not resolve ${n}: ${t}`,e):new Ge("network",`failed to resolve ${n}: ${t}`,e)}function Jn(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}Se();var Ka={async materialize(e,n){await Ga(n,{recursive:!0});let t=Pg("npm",["install",e,"--prefix",n,"--no-save","--no-audit","--no-fund","--ignore-scripts","--loglevel=error"],{stdio:["ignore","ignore","pipe"],encoding:"utf8"});if(t.error)throw t.error;if(t.status!==0)throw new Error(`npm install ${e} -> ${t.status}: ${(t.stderr||"").trim()}`);return zo(n,"node_modules",...Ke.split("/"))},async readFile(e){return new Uint8Array(await Ag(e))},async writeFile(e,n){await Ga(Tg(e),{recursive:!0}),await $g(e,n)},async exists(e){return jg(e)},sha256(e){return Dg("sha256").update(e).digest("hex")},async fetchText(e){let n=await fetch(e,{redirect:"follow"});if(!n.ok)throw new Error(`GET ${e} -> ${n.status}`);return await n.text()},async rename(e,n){await Lg(e,n)}},Ig="redskilled";function Ng(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||zo(e.HOME||Eg(),".cache");return zo(n,"red-skills","bundles")}var Mg=/^([a-z0-9-]+)-(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?)\.bundle\.min\.mjs$/;async function Cg(e,n){if(Ko(e.version))return e.version.trim();let t=e.listCacheDir??Bg,r=Wg(t(n),"dev");if(r)return r;try{let s=await(e.bundleIO??Ka).fetchText(Vo());return Qo(Jo(s))}catch{return null}}function Wg(e,n){let t=null;for(let r of e){let o=Mg.exec(r);if(!o||o[1]!==n)continue;let s=o[2];(t===null||Hg(s,t)>0)&&(t=s)}return t}function Hg(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n);return Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function Bg(e){try{return Og(e)}catch{return[]}}async function Fg(e={},n={},t={}){let r=Ae(e,n);if(pe(r))return r;let o=t.env??n.env??process.env,s=Ng(o),i=await Cg(t,s);if(i===null)return r;try{await qo(t.bundleIO??Ka,{plugin:Ig,version:i,cacheDir:s})}catch{return r}return Ae(e,n)}async function Va(e={},n={},t={}){let r=await Fg(e,n,t);if(pe(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(Se(),Wa));throw new o(r)}import{randomUUID as Rr}from"node:crypto";import{mkdir as f_,rm as Ou}from"node:fs/promises";import{connect as m_,createServer as h_}from"node:net";import{dirname as g_}from"node:path";import{availableParallelism as Qa,totalmem as Gg}from"node:os";function Qn(e){if(e.applied_budget!=null)return e.applied_budget;let n=e.budget??{};return n.memory_max==null&&n.memory_high==null&&e.memory_ceiling!=null?{...n,memory_max:e.memory_ceiling}:n}function qa(e,n={}){let t=0,r=0,o=0,s=[],i=[];for(let d of e){let u=Qn(d),p=!1;for(let[f,m]of[[u.memory_high,g=>t+=g],[u.memory_max,g=>r+=g]]){if(f==null)continue;let g=hn(f);g==null?p=!0:m(g)}u.cpu_weight!=null&&(o+=u.cpu_weight),p&&s.push(d.worker_id),d.isolated||i.push(d.worker_id)}let l=n.hostCeilingBytes??null,a=l==null?0:Math.max(0,r-l);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:r,cpu_weight_total:o,unaccounted_workers:s.sort(),unisolated_workers:i.sort(),memory_ceiling_bytes:l,over_committed_bytes:a,over_commitment_reason:a===0?null:Ug(e.length,r,l,a)}}function Ug(e,n,t,r){return`this host's ${e} Worker(s) carry ${n} bytes of applied MemoryMax against a host ceiling of ${t} bytes \u2014 ${r} bytes over. A per-Worker MemoryMax is a wall rather than a reservation, so the host stays safe only while the Workers do not all peak together; the ceiling is not enforced host-wide.`}function hn(e){let n=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!n)return null;let t={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[n[2].toLowerCase()];return Math.round(Number(n[1])*t)}function Ja(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&Number.isInteger(n.worker_count)&&typeof n.memory_high_bytes=="number"&&typeof n.memory_max_bytes=="number"&&typeof n.cpu_weight_total=="number"&&Array.isArray(n.unaccounted_workers)&&Array.isArray(n.unisolated_workers)}var za="REDSKILLED_MEMORY_CEILING",Xo="REDSKILLED_WORKER_CEILING",ed="REDSKILLED_VALIDATION_CEILING",Ya="REDSKILLED_INTERACTIVE_RESERVATION",zn=1,Xa=.7,Kg=2*1024**3,Vg=2;function nd(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return hn(n)}function Yt(e){let n=0,t=[];for(let r of e){let o=nd(r.budget);o===null?t.push(r.worker_id):o!==void 0&&(n+=o)}return{worker_count:e.length,memory_bytes:n,unaccounted_workers:t.sort()}}function td(e){let{ceiling:n}=e,t=Yt(e.workers),r=nd(e.budget),o=r===void 0?null:r,s=t.memory_bytes+(r??0),i=t.worker_count+1,l=Math.max(0,n.interactive_reservation??zn),a=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",d=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,u=(m,g)=>({version:1,admitted:!1,verdict:m,reason:g,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}),p=n.worker_count==null?0:i-n.worker_count;if(p>0){if(e.reservation!=="interactive")return u("refused-over-worker-ceiling",`redskilled refused this Worker${a}: it would be Worker ${i} past a host ceiling of ${n.worker_count} Worker(s); ${l} extra slot(s) are reserved for interactive dispatches, and ${d}`);if(p>l)return u("refused-over-interactive-reservation",`redskilled refused this interactive Worker${a}: reserved slot ${p}/${l} is outside the bounded interactive reservation above the host ceiling of ${n.worker_count} Worker(s), and ${d}`)}if(n.memory_bytes!=null&&r===null)return u("refused-unaccountable-budget",`redskilled refused this Worker${a}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${n.memory_bytes} bytes, and ${d}`);if(n.memory_bytes!=null&&s>n.memory_bytes)return u("refused-over-memory-ceiling",`redskilled refused this Worker${a}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${n.memory_bytes} bytes, and ${d}`);let f=e.reservation==="interactive"&&p>0;return{version:1,admitted:!0,verdict:f?"admitted-interactive-reservation":"admitted",reason:f?`redskilled admitted this interactive Worker${a} into reserved interactive slot ${p}/${l} above the host ceiling of ${n.worker_count} Worker(s): ${s} bytes of declared Worker memory against a host ceiling of ${n.memory_bytes??"unbounded"} bytes, and ${d}`:`redskilled admitted this Worker${a}: ${s} bytes of declared Worker memory against a host ceiling of ${n.memory_bytes??"unbounded"} bytes, and ${d}`,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function rd(e){let n=e.budget?.memory_max??e.budget?.memory_high;if(n!=null)return{memory_max:n,reason:`the client declared this Worker's memory ceiling (${n}), so the host derived none`};if(e.ceiling.memory_bytes==null)return{memory_max:null,reason:"this host admits Workers against no memory ceiling, so there is no accounting to derive a per-Worker ceiling from; the daemon's RSS sampling floor is the only remaining ceiling"};let t=Yt(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,s=o==null?r:Math.floor(e.ceiling.memory_bytes/o),i=Math.min(r,s);if(i<=0)return{memory_max:null,reason:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes is already fully committed to ${t.worker_count} Worker(s), so no positive per-Worker ceiling can be derived; the daemon's RSS sampling floor is the only remaining ceiling`};let l=o==null?`the headroom under this host's memory ceiling of ${e.ceiling.memory_bytes} bytes; this host declares no Worker slot count (${Xo} is unset), so this ceiling is a per-Worker wall and not memory the host sets aside \u2014 N Workers may carry N such walls, and the host ceiling is not enforced host-wide. Declare a slot count to make it divide into shares that sum to it`:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes shared across its ${o} Worker slot(s)`;return{memory_max:String(i),reason:`derived from ${l} (ceiling source: ${e.ceiling.source})`}}function Xt(e=process.env,n=Gg(),t={}){let r=Yo(t.flags?.memoryCeiling,e[za],t.config?.memoryCeiling),o=Yo(t.flags?.workerCeiling,e[Xo],t.config?.workerCeiling),s=Yo(t.flags?.validationCeiling,e[ed],t.config?.validationCeiling),i=r?.value??"",l=o?.value??"",a=(e[Ya]??"").trim(),d=od(l),u=a===""?zn:Qg(a),p=o?.source??"derived-default";if(l!==""&&d===null&&!qg(l)&&(zt(`redskilled: ${Zo(o)} ${Xo}=${JSON.stringify(l)} is not a positive integer; this host admits an unbounded number of Workers instead.`),p="derived-default"),i!==""){let f=Jg(i,n);if(f!==void 0)return Za({memory_bytes:f,worker_count:d,interactive_reservation:u??zn,source:"declared",memory_source:r.source,worker_source:p},s,t.availableParallelism??Qa());zt(`redskilled: ${Zo(r)} ${za}=${JSON.stringify(i)} is not a memory ceiling this host can read; using ${Xa*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return a!==""&&u===void 0&&zt(`redskilled: ${Ya}=${JSON.stringify(a)} is not a non-negative integer; using the default reservation of ${zn} Worker(s) instead.`),Za({memory_bytes:Math.floor(n*Xa),worker_count:d,interactive_reservation:u??zn,memory_source:"derived-default",worker_source:p,source:"host-fraction"},s,t.availableParallelism??Qa())}function Za(e,n,t){if(n!==void 0){let i=od(n.value);if(i!==null)return{...e,validation_count:i,validation_source:n.source};zt(`redskilled: ${Zo(n)} ${ed}=${JSON.stringify(n.value)} is not a positive integer; deriving the validation ceiling from host CPU, memory, and Worker capacity instead.`)}let r=Math.max(1,Math.floor(Math.max(1,t)/Vg)),o=e.memory_bytes==null?Number.POSITIVE_INFINITY:Math.max(1,Math.floor(e.memory_bytes/Kg)),s=e.worker_count??Number.POSITIVE_INFINITY;return{...e,validation_count:Math.max(1,Math.min(r,o,s)),validation_source:"derived-default"}}function Yo(e,n,t){if(e?.trim())return{value:e.trim(),source:"flag"};if(n?.trim())return{value:n.trim(),source:"environment"};if(t?.trim())return{value:t.trim(),source:"home-config"}}function Zo(e){return e.source==="flag"?"serve flag":e.source==="environment"?"environment":e.source==="home-config"?"home config":"derived default"}function qg(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var zt=e=>process.stderr.write(`${e}
62
+ `);function Jg(e,n){let t=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(t))return null;let r=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return r?Math.floor(n*(Number(r[1])/100)):hn(e)??void 0}function od(e){if(e===""||["infinity","none","off","unbounded"].includes(e.toLowerCase()))return null;let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:null}function Qg(e){let n=Number(e);return Number.isSafeInteger(n)&&n>=0?n:void 0}import{appendFile as zg,mkdir as Yg,open as Xg,readFile as Zg,stat as ey,truncate as sd}from"node:fs/promises";import{dirname as ny}from"node:path";var id="redskilled.events.toonl";function ty(e){let n=e.worker.budget??{};return{version:1,ts:e.ts,event:e.event,worker_id:e.worker.worker_id,project_label:e.worker.project_label,pid:e.worker.pid,workspace_path:e.worker.workspace_path,log_path:e.worker.log_path??null,isolated:e.worker.isolated,unit:e.worker.unit??null,memory_high:n.memory_high??null,memory_max:n.memory_max??null,cpu_weight:n.cpu_weight??null,detail:e.detail??null,exit_code:e.exitCode??null,signal:e.signal??null,reason:e.reason??null}}var ry="daemon:";function oy(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${ry}${e.pid}`,project_label:"",pid:e.pid,workspace_path:e.socketPath,log_path:null,isolated:!1,unit:null,memory_high:null,memory_max:null,cpu_weight:null,detail:e.detail,exit_code:null,signal:e.signal??null,reason:e.reason}}function ld(e){let n=ce({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await Yg(ny(e),{recursive:!0,mode:448}),await sy(e),await zg(e,n.push(dy(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(ty(o)),recordDaemonStop:o=>r(oy(o)),read:()=>iy(e),flush:async()=>{await t}}}async function sy(e){let n;try{n=(await ey(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await Xg(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let s=n;s>0;s-=t){let i=Math.min(t,s),l=Buffer.alloc(i);await r.read(l,0,i,s-i);let a=l.lastIndexOf(10);if(a>=0){await sd(e,s-i+a+1);return}}await sd(e,0)}finally{await r.close()}}async function iy(e){let n;try{n=await Zg(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return ly(n)}function ly(e){let n=e.split(`
63
+ `);return n.pop(),n.length===0?[]:we(`${n.join(`
64
64
  `)}
65
- `).filter(Fg).map(Hg)}function Va(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,Wg(t)):n.delete(t.worker_id));return[...n.values()]}function Wg(e){let n={...e.memory_high!=null?{memory_high:e.memory_high}:{},...e.memory_max!=null?{memory_max:e.memory_max}:{},...e.cpu_weight!=null?{cpu_weight:e.cpu_weight}:{}};return{worker_id:e.worker_id,project_label:e.project_label,pid:e.pid,started_at:e.ts,workspace_path:e.workspace_path,...e.log_path!=null?{log_path:e.log_path}:{},isolated:e.isolated,...e.unit!=null?{unit:e.unit}:{},...Object.keys(n).length>0?{budget:n}:{},warnings:[]}}function Bg(e){return{...e}}function Fg(e){return e.version===1&&typeof e.ts=="string"&&typeof e.worker_id=="string"&&(e.event==="worker-birth"||e.event==="worker-death"||e.event==="worker-budget-kill"||e.event==="daemon-stop")}function Hg(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:we(e.project_label)??"",pid:Number(e.pid??0),workspace_path:we(e.workspace_path)??"",log_path:we(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:we(e.unit),memory_high:we(e.memory_high),memory_max:we(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:we(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:we(e.signal),reason:we(e.reason)}}function we(e){return e==null||e===""?null:String(e)}function qa(e){let n=[...e.projects].sort((i,l)=>i.project_label.localeCompare(l.project_label)),t=e.backoffUntilMs??null,r=t!=null&&e.nowMs<t,o=[],s=[];for(let i of n){let l=Math.max(0,e.live[i.project_label]??0),a=Object.prototype.hasOwnProperty.call(e.queue,i.project_label),d=a?e.queue[i.project_label]??null:null,u={project_label:i.project_label,queue_depth:d,target:i.target,live:l};if(r){o.push({...u,outcome:"backing-off",wanted:0,detail:`the host refused a Worker, so no project is asked for one again before ${new Date(t).toISOString()}`});continue}let p=e.birthHaltUntilMs?.[i.project_label];if(p!=null&&e.nowMs<p){o.push({...u,outcome:"birth-halted",wanted:0,detail:`project ${JSON.stringify(i.project_label)} lost 3 Workers in a row inside 60000ms of birth, so it is not asked for another before ${new Date(p).toISOString()} \u2014 a Worker that cannot survive boot will not survive the next one either, and every birth spends host quota shared with every project`});continue}if(d==null){o.push({...u,outcome:"queue-unknown",wanted:0,detail:a?`the last poll produced no depth for project ${JSON.stringify(i.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(i.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...u,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(i.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,i.target),d)-l);if(f===0){o.push({...u,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for none`});continue}o.push({...u,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for ${f} more`});for(let m=0;m<f;m+=1)(s[m]??(s[m]=[])).push({project_label:i.project_label,index:l+m,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function Ja(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}var Kt={shortLifeStreak:0,haltUntilMs:null};function Qa(e,n,t){if(n>=6e4)return Kt;let r=e.shortLifeStreak+1;return r<3?{shortLifeStreak:r,haltUntilMs:null}:{shortLifeStreak:r,haltUntilMs:t+6e5}}function za(e,n){let t={};for(let[r,o]of Object.entries(e))o.haltUntilMs!=null&&n<o.haltUntilMs&&(t[r]=o.haltUntilMs);return t}function Xa(e){let n=e.workers.map(Ug),t=[...new Set([...n.map(o=>o.project_label),...e.projects??[]])].filter(o=>o!=="").sort(),r=n.filter(o=>o.survives).map(o=>o.worker_id);return{version:1,running:!0,stopped:!0,reason:e.reason,socket_path:e.socketPath,daemon_version:e.daemonVersion,pid:e.pid,holding:{workers:n,projects:t},surviving:r,detail:Kg({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function Za(e){return{version:1,running:!1,stopped:!1,reason:"not-running",socket_path:e,daemon_version:null,pid:null,holding:{workers:[],projects:[]},surviving:[],detail:`no redskilled daemon is answering on ${JSON.stringify(e)}, so there was nothing to stop`}}function Ug(e){return{worker_id:e.worker_id,project_label:e.project_label,pid:e.pid,unit:e.unit??null,isolated:e.isolated,survives:!0}}function Gg(e){return e==="requested"?"an operator asked for it":e==="signal"?"the daemon was signalled":e==="idle"?"the daemon was idle and held nothing":e==="replaced"?"a newer published bundle is taking the session over":"no daemon was running"}function Kg(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Gg(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${Ya(e.held,"Worker")} across ${Ya(e.projects,"project")}, and ${e.surviving} of them survive it \u2014 a Worker is an init-system unit, so this is a restart and not an evacuation`}function Ya(e,n){return`${e} ${n}${e===1?"":"s"}`}function Fo(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.holding;return n.version===1&&typeof n.running=="boolean"&&typeof n.stopped=="boolean"&&typeof n.reason=="string"&&typeof n.socket_path=="string"&&typeof n.detail=="string"&&(n.daemon_version===null||typeof n.daemon_version=="string")&&(n.pid===null||typeof n.pid=="number")&&t!=null&&Array.isArray(t.workers)&&Array.isArray(t.projects)&&Array.isArray(n.surviving)}import{chmod as Vg,mkdir as qg,readFile as Jg,rm as Qg,writeFile as zg}from"node:fs/promises";import{dirname as ed,join as od}from"node:path";import{tmpdir as nd}from"node:os";var Yg="redskilled.machine.claim.toon",Xg="REDSKILLED_MACHINE_DIR",Zg=8,De=class extends Error{constructor(t,r,o){super(ny(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},td;function sd(){return td??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},td}function ey(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[Xg]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||nd():nd();return od(o,`redskilled-${e.machineIdHash}`)}function Vt(e){return od(ey(e),Yg)}function qt(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??B;async function s(){let a;try{a=await Jg(e,"utf8")}catch(u){if(u.code==="ENOENT"||Ho(u))return;throw u}let d=ry(a);return oy(d)?d:void 0}function i(a,d){return{version:1,scope:"machine",pid:a.pid,start_time:a.startTime,uid:a.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}async function l(){try{return await Qg(e,{force:!0}),!0}catch(a){if(Ho(a))return!1;throw a}}return{claimPath:e,read:s,async claim(a){await qg(ed(e),{recursive:!0,mode:1023})!=null&&await Vg(ed(e),1023).catch(()=>{});let u=!1;for(let p=0;p<Zg;p+=1){let f=i(a,r());try{return await zg(e,ty(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:u,claim:f}}catch(g){if(g.code!=="EEXIST"){if(Ho(g))return{claimed:!1,reason:"stale-claim-not-reapable"};throw g}}let m=await s();if(!m){if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable"};u=!0;continue}if(rd(m,a,n.socketPath))return{claimed:!0,reaped:u,claim:m};if(await o(m.pid))return{claimed:!1,reason:"held",claim:m};if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable",claim:m};u=!0}return{claimed:!1,reason:"contended"}},async release(a){let d=await s();return!d||!rd(d,a,n.socketPath)?!1:await l()}}}function id(e,n,t){return{kind:"machine",claim_path:e,owner_uid:t.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath}}function ld(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.kind==="machine"&&typeof n.claim_path=="string"&&typeof n.owner_uid=="number"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&typeof n.socket_path=="string"}function ny(e,n,t){let r=t==null?"":` \u2014 held by pid ${t.pid} (uid ${t.uid}) on socket ${JSON.stringify(t.socket_path)}`;return n==="held"?`this machine already has a redskilled daemon${r}; a second one would void the host budget, so none was started. Reach that daemon, or stop it before starting another.`:n==="stale-claim-not-reapable"?`the redskilled machine claim ${JSON.stringify(e)} is stale and cannot be removed by this user${r}; remove it as its owner, then start again. No second daemon was started.`:`the redskilled machine claim ${JSON.stringify(e)} changed hands repeatedly; no daemon was started.`}function Ho(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function rd(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function ty(e){return`${W(e,{keyedMapCollapse:!0})}
66
- `}function ry(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Q(n)}catch{return null}}}function oy(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||n.scope!=="machine"||!Number.isInteger(n.pid)||n.pid<=0||!Number.isInteger(n.uid))return!1;for(let t of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var sy=["worker_id","slot","workspace_path","log_path"],Uo=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${sy.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},iy=/\{\{([a-z_]+)\}\}/g;function ly(e,n){let t=(i,l)=>i.replace(iy,(a,d)=>{switch(d){case"worker_id":return n.worker_id;case"slot":return String(n.slot);case"workspace_path":return n.workspace_path;case"log_path":return n.log_path??"";default:throw new Uo(d,l)}}),r=e.argv.map((i,l)=>t(i,`argv word ${l}`)),o={};for(let[i,l]of Object.entries(e.env??{}))o[i]=t(l,`env entry ${JSON.stringify(i)}`);let s=e.log_path==null?void 0:t(e.log_path,"the log path");return{argv:r,env:o,...s==null||s===""?{}:{log_path:s}}}function ad(e,n,t){let r=ly(e,n),o=r.log_path??n.log_path,[s,...i]=r.argv;if(s===void 0||s==="")throw new Error(`redskilled cannot start a Worker for project ${JSON.stringify(t.project_label)}: its launch expanded to an argv with no command`);return{worker_id:n.worker_id,project_label:t.project_label,workspace_path:n.workspace_path,...o==null||o===""?{}:{log_path:o},command:s,args:i,env:r.env}}function Go(e,n){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(n)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((t,r)=>{if(typeof t!="string"||t==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${r} of project ${JSON.stringify(n)} is not`);return t})}function Ko(e,n){if(e!=null){if(typeof e!="string"||e.trim()==="")throw new Error(`redskilled needs a declared log path to be a non-empty string to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}: a project that declares an empty path states a Worker whose output no surface can ever show, which reads as a Worker with nothing to say`);return e}}function Vo(e,n){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error(`redskilled needs a launch env to be a map of strings to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}`);let t={};for(let[r,o]of Object.entries(e)){if(r==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(n)} to be named`);if(typeof o!="string")throw new Error(`redskilled needs every launch env value to be a string, and ${JSON.stringify(r)} of project ${JSON.stringify(n)} is ${JSON.stringify(o)}`);t[r]=o}return t}var ay=3e5,dy=.5,Jo=class extends Error{constructor(t){super(`redskilled already holds a registration for project ${JSON.stringify(t.project_label)}, registered at ${t.registered_at} for a target of ${t.target} and standing until ${t.renew_by}: a project contributes one registration, so a second one is refused rather than silently replacing the first`);this.held=t;this.name="RedskilledProjectRegisteredError"}};function dd(e,n){if(n.held!=null)throw new Jo(n.held);let t=qo(e.project_label,"a project label"),r=qo(e.selector,"a selector"),o=Go(e.argv,t),s=Vo(e.env,t),i=Ko(e.log_path,t),l=qo(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.target)}`);let a=e.renew_within_ms??ay;if(!Number.isFinite(a)||a<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let d=Date.parse(n.now);if(!Number.isFinite(d))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(n.now)}`);return{version:1,project_label:t,selector:r,argv:o,workspace_path:l,env:s,...i==null?{}:{log_path:i},target:e.target,registered_at:new Date(d).toISOString(),renew_within_ms:a,renew_by:new Date(d+a).toISOString(),renewed_at:new Date(d).toISOString(),renewals:0,session_renewals:0,launch_revision:0}}var Jt=class extends Error{constructor(t){super(`redskilled holds no registration for project ${JSON.stringify(t)} to renew: it lapsed or was never held, and a renewal never mints a record \u2014 register again, stating the selector, the argv and the target`);this.projectLabel=t;this.name="RedskilledProjectUnregisteredError"}};function cd(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(n.now)}`);let r=n.renew_within_ms??e.renew_within_ms;if(!Number.isFinite(r)||r<=0)throw new Error(`redskilled needs a positive renewal window to renew project ${JSON.stringify(e.project_label)}, not ${JSON.stringify(n.renew_within_ms)}`);let o=n.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:Go(n.launch.argv,e.project_label),env:Vo(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=n.launch==null?e.log_path:Ko(n.launch.log_path,e.project_label),{log_path:i,...l}=e;return{...l,...s==null?{}:{log_path:s},...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1,session_renewals:(e.session_renewals??e.renewals)+1}}function Qo(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(n.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,n.liveWorkers??0),s=n.queue,i=s!=null&&s.outcome==="counted"?s.depth:null,l=i!=null&&i>0?"open-work":o>0?"live-worker":null;if(l==null){let a=i===0?"drained":"uncounted";return{registration:e,verdict:a,detail:a==="drained"?`project ${r} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${r}, and an uncounted queue never sustains a registration \u2014 it stands on its own deadline of ${e.renew_by}`}}return{registration:{...e,renew_by:new Date(t+e.renew_within_ms).toISOString(),sustained_at:new Date(t).toISOString(),sustains:(e.sustains??0)+1,sustained_by:l,renewals:e.renewals+1,session_renewals:e.session_renewals??e.renewals},verdict:l,detail:l==="open-work"?`project ${r} has ${i} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function cy(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function ud(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*dy;if(r(t))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return r(o)?"self-renewing":"running-on"}function pd(e,n){let t=[],r=[];for(let o of e)(cy(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function zo(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.project_label=="string"&&typeof n.selector=="string"&&Array.isArray(n.argv)&&n.argv.every(t=>typeof t=="string")&&typeof n.workspace_path=="string"&&Number.isInteger(n.target)&&typeof n.registered_at=="string"&&typeof n.renew_within_ms=="number"&&typeof n.renew_by=="string"&&(n.renewed_at===void 0||typeof n.renewed_at=="string")&&(n.renewals===void 0||Number.isInteger(n.renewals))&&(n.session_renewals===void 0||Number.isInteger(n.session_renewals))&&(n.env===void 0||uy(n.env))&&(n.log_path===void 0||typeof n.log_path=="string")&&(n.launch_revision===void 0||Number.isInteger(n.launch_revision))&&(n.sustained_at===void 0||typeof n.sustained_at=="string")&&(n.sustains===void 0||Number.isInteger(n.sustains))&&(n.sustained_by===void 0||n.sustained_by==="open-work"||n.sustained_by==="live-worker")}function uy(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function qo(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var py={ping:"host-read","host-state":"host-read","statusline-payload":"host-read",shutdown:"daemon-life","worker-start":"project-write","worker-stop":"project-write","worker-recycle":"project-write","worker-steer":"project-write","worker-heartbeat":"project-write","project-register":"project-write","project-renew":"project-write","project-deregister":"project-write"};function fd(e){return`worker-${e}`}function md(e){let n=py[e.op]??"project-write",t=e.sessionProject??null,r=e.targetProject??null,o={version:1,op:e.op,reach:n,session_project:t,target_project:r};return n==="host-read"?{...o,permitted:!0,verdict:"permitted-host-read",reason:`redskilled permitted ${e.op}: a session reads the whole host, whichever project it was started in`}:n==="daemon-life"?{...o,permitted:!0,verdict:"permitted-daemon-life",reason:`redskilled permitted ${e.op}: it acts on the daemon's own process, not on any project's Workers`}:t==null||t===""?{...o,permitted:!0,verdict:"permitted-unattributed",reason:`redskilled permitted ${e.op}: the session named no project of its own, so there is nothing to refuse it against`}:r!=null&&r===t?{...o,permitted:!0,verdict:"permitted-own-project",reason:`redskilled permitted ${e.op}: the target belongs to project ${JSON.stringify(t)}, which is this session's own`}:{...o,permitted:!1,verdict:"refused-cross-project",reason:`redskilled refused ${e.op} from a session in project ${JSON.stringify(t)}: ${r==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(r)}`}. A session reads the whole host and writes only its own project.`}}function hd(e){return e==="single-object"?"rest":"graphql"}function $(e,n,t,r,o){return{key:e,kind:"read",cardinality:n,surface:o??hd(n),budget:t,...o?{only:o}:{},why:r}}function V(e,n,t,r){return{key:e,kind:"write",cardinality:"single-object",surface:n,budget:t,why:r}}var gd=[$("issue view","single-object","rest","one issue by number; REST answers it in one request against the idle pool"),$("pr view","single-object","rest","one pull request by number, polled per Worker per iteration"),$("repo view","single-object","rest","one repository's own metadata"),$("run view","single-object","rest","one Actions run; the Actions API has no GraphQL surface either way"),$("release view","single-object","rest","one release by tag"),$("pr diff","single-object","rest","one pull request's diff, served by a REST media type"),$("issue list","multi-node","graphql","a connection of issues; one GraphQL query beats N REST pages"),$("pr list","multi-node","graphql","a connection of pull requests; one GraphQL query beats N REST pages"),$("pr checks","multi-node","graphql","every check context on one commit, which is a connection, not an object"),$("release list","multi-node","rest","Releases have no GraphQL connection gh reads; REST pages them","rest"),$("run list","multi-node","rest","the Actions API has no GraphQL surface, so a listing draws the request pool","rest"),$("label list","multi-node","graphql","a connection of labels inside one repository"),$("issue list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),$("pr list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),$("search issues","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),$("search prs","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),$("search repos","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),$("api graphql","multi-node","graphql","the caller wrote the query; `gh api graphql` is GraphQL by construction"),$("api rest","single-object","rest","any `gh api <path>` that is not `graphql` is a REST request"),V("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),V("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),V("issue close","graphql","graphql","gh closes with the closeIssue mutation"),V("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),V("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),V("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),V("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),V("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),V("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),V("pr close","graphql","graphql","gh closes with a GraphQL mutation"),V("pr edit","graphql","graphql","gh edits with GraphQL mutations"),V("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),V("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),V("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],fy=new Map(gd.map(e=>[e.key,e]));function yd(e){let n=[],t=0;for(;t<e.length&&e[t].startsWith("-");)t+=e[t]==="-R"||e[t]==="--repo"?2:1;for(;t<e.length&&!e[t].startsWith("-")&&n.length<2;)n.push(e[t]),t+=1;return n}function Yo(e){let n=yd(e);if(n.length===0)return"";if(n[0]==="api")return n[1]==="graphql"?"api graphql":"api rest";let t=n.length===1?n[0]:`${n[0]} ${n[1]}`;return n[1]==="list"&&e.includes("--search")?`${t} (search)`:t}var Qt=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(n){let t=Yo(n);super(`unclassified GitHub operation ${JSON.stringify(t||"(empty argv)")}: add an entry to GITHUB_OPERATIONS in packages/github/surface.ts stating its cardinality. Defaulting to GraphQL is what sent every single-object poll to the node-point pool (ADR 0132 decision 4).`),this.operation=t,this.args=[...n]}};function kd(e){return fy.get(Yo(e))??null}function Rd(e){let n=kd(e);if(!n)throw new Qt(e);return n}function Xo(e){return Rd(e).surface}var _d="rate_limit",wd={rest:"core",graphql:"graphql",search:"search"},xe=["rest","graphql","search"];function Zt(e,n){return{version:1,origin:"asked",outcome:"unanswered",source:"GET /rate_limit",asked_at:e,request_count:0,pools:{rest:null,graphql:null,search:null},unreported_pools:[...xe],detail:n??"no balance has been asked for yet, so none is known"}}var es=15e3,un=.15,Yt=[{at_or_below_fraction:0,every_ms:es,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:un,every_ms:3e4,why:"inside the reserved band: the posture can change between two calls"},{at_or_below_fraction:.5,every_ms:12e4,why:"below half: tightening, because the band is now reachable inside one window"},{at_or_below_fraction:1,every_ms:6e5,why:"above half: rare, because nothing this balance decides is anywhere close"}],Zo=2;function xd(e,n){let t=bd(e),r=bd(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let l of xe){let a=wd[l],d=r[a],u=gy(l,a,d);o[l]=u,u==null&&s.push(l)}let i=xe.length-s.length;return{version:1,origin:"asked",outcome:i>0?"asked":"unanswered",source:"GET /rate_limit",asked_at:n.askedAt,request_count:1,pools:o,unreported_pools:s,detail:i>0?`the token's own answer for ${i} of ${xe.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function ns(e){try{let n=await e.transport();return xd(n,{askedAt:e.now})}catch(n){let t=n instanceof Error?n.message:String(n);return{...Zt(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function ts(e){let n=null;for(let t of xe){let r=e.pools[t];r!=null&&(n==null||r.fraction<n.fraction)&&(n=r)}return n}function er(e,n){let t=ts(e);if(t==null)return Xt(un).every_ms;let r=Xt(t.fraction);if(t.remaining>0)return r.every_ms;let o=vd(n.now,t.reset_at);return o==null?r.every_ms:Math.max(es,Math.min(r.every_ms,o))}function rs(e,n=un){return Math.ceil(e.limit*n)}function Sd(e,n,t=un){let r=e.pools[n];return r==null?"unknown":r.remaining<=0?"spent":r.remaining<rs(r,t)?"reserved":"open"}function os(e){let n=e.reservedFraction??un,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:Xt(n).every_ms*Zo,stale:!1,posture:"unknown",reserved_fraction:n,next_poll_ms:Xt(n).every_ms,pools:[],unreported_pools:[...xe],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let r=er(t,{now:e.now}),o=e.stalenessMs??r*Zo,s=vd(t.asked_at,e.now),i=t.outcome==="asked"&&(s==null||s>o),l=xe.map(u=>t.pools[u]).filter(u=>u!=null),a=hy(t,n),d=ts(t);return{version:1,origin:"asked",outcome:t.outcome,asked_at:t.asked_at,age_ms:s,threshold_ms:o,stale:i,posture:a,reserved_fraction:n,next_poll_ms:r,pools:l,unreported_pools:t.unreported_pools,reason:i?`this balance is stale: asked ${s==null?"at an unreadable instant":`${s}ms ago`}, past the ${o}ms window, so the posture below is the last one the token confirmed and not the current one`:my(a,d,t,n)}}function ss(e){if(!ls(e))return!1;let n=e;return n.version===1&&n.origin==="asked"&&(n.outcome==="asked"||n.outcome==="unanswered")&&(n.asked_at===null||typeof n.asked_at=="string")&&(n.age_ms===null||typeof n.age_ms=="number")&&typeof n.threshold_ms=="number"&&typeof n.stale=="boolean"&&typeof n.posture=="string"&&typeof n.reserved_fraction=="number"&&typeof n.next_poll_ms=="number"&&Array.isArray(n.pools)&&Array.isArray(n.unreported_pools)&&typeof n.reason=="string"}function my(e,n,t,r){if(n==null)return t.detail;let o=rs(n,r);switch(e){case"spent":return`the ${n.pool} pool is spent and resets at ${n.reset_at}: work is not queued, it is refused`;case"reserved":return`the ${n.pool} pool has ${n.remaining} of ${n.limit} left, inside the reserved band of ${o}: convenience reads are refused and the claim, a landing and a closing comment still pass`;default:return`the ${n.pool} pool is the tightest at ${n.remaining} of ${n.limit}, above the reserved band of ${o}`}}function hy(e,n){let t="unknown";for(let r of xe){if(e.pools[r]==null)continue;let o=Sd(e,r,n);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function Xt(e){for(let n of Yt)if(e<=n.at_or_below_fraction)return n;return Yt[Yt.length-1]}function gy(e,n,t){if(!ls(t))return null;let r=zt(t.limit),o=zt(t.remaining),s=zt(t.used),i=zt(t.reset);return r==null||r<=0||o==null?null:{pool:e,resource:n,limit:r,remaining:o,used:s??0,reset_at:i==null?"":new Date(i*1e3).toISOString(),fraction:o/r}}function is(e){let n=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let r=await t(`${n}/${_d}`,{method:"GET",headers:{authorization:`bearer ${e.token}`,accept:"application/vnd.github+json"}});if(!r.ok)throw new Error(`the balance ask was refused with HTTP ${r.status}`);return await r.json()}}function vd(e,n){let t=Date.parse(e),r=Date.parse(n);return!Number.isFinite(t)||!Number.isFinite(r)?null:Math.max(0,r-t)}function zt(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function bd(e){return ls(e)?e:{}}function ls(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ad(e){return{generated_at:e.now,hour:Ed("hour",36e5,e),day:Ed("day",864e5,e)}}function Vn(e,n,t){let r=Kn(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(l=>{let a=Kn(n(l));return a==null?!1:r==null||r-a<=o});return i.length<=s?i:i.slice(i.length-s)}function Ed(e,n,t){let r=Kn(t.now),o=r==null?null:r-n,s=e==="hour"?"1h":"24h",i=t.observations.map(p=>({observation:p,at:Kn(p.observed_at)})).filter(p=>p.at!=null&&jd(p.at,o,r)).sort((p,f)=>p.at-f.at),l=t.outcomes.map(p=>Kn(p.ts)).filter(p=>p!=null&&jd(p,o,r)),a=Pd(i,p=>p.tokens,"tokens",s),d=Pd(i,p=>p.tools,"tools",s),u=[];return i.length===0?u.push("worker-vitals"):(a.samples===0&&u.push("worker-vitals.tokens"),d.samples===0&&u.push("worker-vitals.tools")),l.length===0&&u.push("worker-outcomes"),{window:e,window_ms:n,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:a,tools_per_min:d,issues_per_hour:yy(l.length,n,s),runner_share:Dd("runner",i,p=>p.runner,s),model_share:Dd("model",i,p=>p.model,s),unavailable:u}}function Pd(e,n,t,r){let o=new Map,s=0;for(let d of e){let u=n(d.observation);if(u==null||!Number.isFinite(u))continue;s+=1;let p=o.get(d.observation.worker_id)??[];p.push({at:d.at,count:u}),o.set(d.observation.worker_id,p)}if(s===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${r}`,samples:0};let i=0,l=null,a=null;for(let d of o.values()){if(d.length<2)continue;for(let f=1;f<d.length;f++){let m=d[f-1],g=d[f];m==null||g==null||(i+=Math.max(0,g.count-m.count))}let u=d[0],p=d[d.length-1];u!=null&&(l=l==null?u.at:Math.min(l,u.at)),p!=null&&(a=a==null?p.at:Math.max(a,p.at))}return l==null||a==null||a<=l?{value:null,absent_reason:`the last ${r} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:s}:{value:i/((a-l)/6e4),absent_reason:null,samples:s}}function yy(e,n,t){return e===0?{value:null,absent_reason:`no Worker outcome was recorded in the last ${t}`,samples:0}:{value:e/(n/36e5),absent_reason:null,samples:e}}function Dd(e,n,t,r){let o=new Map;for(let d of n){let u=t(d.observation);u!=null?o.set(d.observation.worker_id,u):o.has(d.observation.worker_id)||o.set(d.observation.worker_id,null)}let s=new Map,i=0,l=0;for(let d of o.values()){if(d==null){l+=1;continue}i+=1,s.set(d,(s.get(d)??0)+1)}let a=[...s.entries()].map(([d,u])=>({key:d,worker_count:u,share:u/i})).sort((d,u)=>u.worker_count-d.worker_count||d.key.localeCompare(u.key));return{dimension:e,attributed_workers:i,unattributed_workers:l,shares:a,absent_reason:a.length>0?null:o.size===0?`no Worker was observed in the last ${r}`:`no Worker published a ${e} in the last ${r}`}}function jd(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function Kn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function Ld(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.generated_at=="string"&&Od(n.hour)&&Od(n.day)}function Od(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.window=="string"&&typeof n.window_ms=="number"&&as(n.tokens_per_min)&&as(n.tools_per_min)&&as(n.issues_per_hour)&&Array.isArray(n.unavailable)}function as(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return(n.value===null||typeof n.value=="number")&&(n.absent_reason===null||typeof n.absent_reason=="string")&&Number.isInteger(n.samples)}import{execFileSync as ky}from"node:child_process";import{existsSync as Ry,readFileSync as nr,readdirSync as by}from"node:fs";import{dirname as _y,join as Fe}from"node:path";function qn(e){let n=Gn(e),t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let s=cn(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function Td(e){let n=[],t=[];for(let r of e.workers){let o=qn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(Gn(r).memory_max??Gn(r).memory_high)==null?"this Worker declared no memory budget and the host derived no ceiling for it, so the sampler has none to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let s=e.rss[r.worker_id];if(typeof s!="number"||!Number.isFinite(s)){t.push({worker_id:r.worker_id,reason:"the host produced no RSS reading for this Worker on this tick, and an unmeasured Worker is never killed on suspicion"});continue}if(!(s<=o.bytes)){if(e.sources?.[r.worker_id]==="cgroup"&&o.name==="MemoryMax"){t.push({worker_id:r.worker_id,reason:`this Worker's ${o.name} of ${o.declared} is held by the kernel on its own cgroup, and the reading is memory.current \u2014 which counts reclaimable page cache the kernel drops before it kills anything, so the daemon does not duplicate an enforcement that can tell cache from anonymous memory`});continue}n.push(wy(r,o,s))}}return{terminations:n,unenforceable:t}}function wy(e,n,t){let r=`Worker ${JSON.stringify(e.worker_id)} of project ${JSON.stringify(e.project_label)}`;return{version:1,worker_id:e.worker_id,project_label:e.project_label,outcome:"terminated-over-memory-budget",classification:"budget-exceeded",stall:!1,budget_name:n.name,budget_declared:n.declared,budget_bytes:n.bytes,observed_rss_bytes:t,workspace_path:e.workspace_path,reason:`redskilled terminated ${r}: its tree RSS of ${t} bytes exceeded its ${n.name} budget of ${n.declared} (${n.bytes} bytes). This is a budget termination, not a stall, and the work in ${JSON.stringify(e.workspace_path)} is handed forward.`}}var xy=4096;function $d(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return r;let o={},s={},i={},l=vy(e,t,n);for(let[p,f]of l){let m=Dy(f);m!=null&&(o[p]=m.memoryBytes,m.cpuSeconds!=null&&(s[p]=m.cpuSeconds),i[p]="cgroup")}let a=e.filter(p=>i[p.worker_id]==null);if(a.length===0)return{rss:o,cpu_seconds:s,sources:i};let d=Ay(t,n);if(d.size===0)return{rss:o,cpu_seconds:s,sources:i};let u=new Map;for(let p of d.values()){let f=u.get(p.ppid);f?f.push(p.pid):u.set(p.ppid,[p.pid])}for(let p of a){if(!d.has(p.pid))continue;let f=0,m=0,g=[p.pid],_=new Set;for(;g.length>0;){let k=g.pop();if(_.has(k))continue;_.add(k);let w=d.get(k);if(w){f+=w.rssBytes,m+=w.cpuSeconds;for(let O of u.get(k)??[])g.push(O)}}o[p.worker_id]=f,s[p.worker_id]=m,i[p.worker_id]="process-tree"}return{rss:o,cpu_seconds:s,sources:i}}var Sy="/sys/fs/cgroup";function vy(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let s=t.cgroupRoot??Sy,i=e.filter(a=>a.unit!=null&&a.unit!=="");if(i.length===0)return r;let l=Ey(s,t);for(let a of i)for(let d of l){let u=Fe(d,a.unit);if(Ry(Fe(u,"memory.current"))){r.set(a.worker_id,u);break}}return r}function Ey(e,n){let t=n.selfCgroupPath??Py(),r=[],o=l=>{r.includes(l)||r.push(l)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(Fe(e,s));let l=_y(s);if(l===s)break;s=l}o(e);let i=n.uid??process.getuid?.();return i!=null&&o(Fe(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),r}function Py(){try{for(let e of nr("/proc/self/cgroup","utf8").split(`
67
- `))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function Dy(e){let n;try{n=nr(Fe(e,"memory.current"),"utf8")}catch{return null}let t=Number(n.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:jy(e)}}function jy(e){let n;try{n=nr(Fe(e,"cpu.stat"),"utf8")}catch{return null}return Oy(n)}function Oy(e){for(let n of e.split(`
68
- `)){let[t,r]=n.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(r);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function Ay(e,n){return n.procRoot!=null||e==="linux"?My(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?Iy(Ly(n.psTable)):new Map}function Ly(e){try{return(e??Ty)()}catch{return""}}function Ty(){return ky("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var $y=1024;function Iy(e){let n=new Map;for(let t of e.split(`
69
- `)){let r=t.trim().split(/\s+/);if(r.length!==4)continue;let[o,s,i]=r.slice(0,3).map(Number);if(![o,s,i].every(a=>a!=null&&Number.isSafeInteger(a)&&a>=0))continue;let l=Ny(r[3]);l!=null&&n.set(o,{pid:o,ppid:s,rssBytes:i*$y,cpuSeconds:l})}return n}function Ny(e){let n=e.indexOf("-"),t=n<0?0:Number(e.slice(0,n));if(!Number.isFinite(t)||t<0)return null;let r=e.slice(n+1).split(":"),o=t*86400,s=1;for(let i=r.length-1;i>=0;i--){let l=Number(r[i]);if(!Number.isFinite(l)||l<0||r[i]==="")return null;o+=l*s,s*=60}return o}function My(e){let n=new Map,t;try{t=by(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=nr(Fe(e,r,"stat"),"utf8")}catch{continue}let s=Wy(o);s&&n.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*xy,cpuSeconds:s.cpuTicks/Cy})}return n}var Cy=100;function Wy(e){let n=e.lastIndexOf(")");if(n<0)return null;let t=Number(e.slice(0,e.indexOf(" "))),r=e.slice(n+1).trim().split(/\s+/),o=Number(r[1]),s=Number(r[11]),i=Number(r[12]),l=Number(r[21]);return!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||!Number.isFinite(l)||!Number.isFinite(s)||!Number.isFinite(i)?null:{pid:t,ppid:o,rssPages:Math.max(0,l),cpuTicks:Math.max(0,s)+Math.max(0,i)}}var By=["api","graphql"],Fy=Xo(By);function Hy(e,n="https://api.github.com"){return e==="graphql"?`${n}/graphql`:n}var Id=100,us=6e4,Uy=2*us,Gy=7*24*60*60*1e3,ds=class extends Error{constructor(t,r,o){super(`redskilled polls every repository with one host token ${JSON.stringify(o)}, and project ${JSON.stringify(t)} declares its own credential ${JSON.stringify(r)}: a project needing its own credential invalidates the host-scoped poller (ADR 0130 Amendment 1) rather than bending it, so the poller returns to the projects instead of reaching this repository under the wrong identity`);this.projectLabel=t;this.tokenRef=r;this.hostTokenRef=o;this.name="RedskilledSplitCredentialError"}};function ps(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new ds(t.project_label,t.token_ref,n)}function Ky(e,n={now:new Date(0).toISOString()}){Jy(e);let t=n.closedWindowMs??Gy,r=Date.parse(n.now);if(!Number.isFinite(r))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(n.now)}`);let o=new Date(r-Math.max(0,t)).toISOString(),s=e.map((a,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:a}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { cost remaining resetAt }",...s.flatMap(({alias:a,search_alias:d,project:u})=>{let p=JSON.stringify(u.owner),f=JSON.stringify(u.name),m=JSON.stringify(`repo:${u.owner}/${u.name} is:closed closed:>=${o}`);return[` ${a}: repository(owner: ${p}, name: ${f}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${d}: search(query: ${m}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
70
- `),aliases:s,closed_since:o}}function Vy(e,n,t){let r=pn(n),o=pn(r.data),s=Array.isArray(r.errors)?r.errors.map(pn):[],i=Qy(o.rateLimit,s),l=e.aliases.map(({alias:a,search_alias:d,project:u})=>{let p=u.owner+"/"+u.name,f=o[a],m=s.find(g=>Nd(g.path,a)||Nd(g.path,d));if(tr(f)){let g=Md(f.open_pull_requests),_=Md(f.open_issues),k=zy(o[d]);if(g!=null&&_!=null&&k!=null)return{project_label:u.project_label,repository:p,outcome:"counted",counts:{open_pull_requests:g,open_issues:_,recently_closed:k},detail:`counted ${p} for project ${JSON.stringify(u.project_label)}`}}return i.exhausted||Hd(m)?{project_label:u.project_label,repository:p,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${p} answered, so this project has no counts rather than zero counts${i.reset_at==null?"":`; the quota resets at ${i.reset_at}`}`}:{project_label:u.project_label,repository:p,outcome:"unreachable",counts:null,detail:`${p} is not reachable with the host token: ${cs(m?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:l.length,rate_limit:i,projects:l}}function qy(e){return{version:1,fetched_at:e,request_count:0,project_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1,point_cost:null},projects:[]}}async function Cd(e){if(e.projects.length===0)return qy(e.now);ps(e.projects,e.hostTokenRef);let n=Ky(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return Vy(n,t,{fetchedAt:e.now})}catch(t){let r=t instanceof Error?t.message:String(t),o=/rate limit|secondary rate|429/i.test(r);return{version:1,fetched_at:e.now,request_count:1,project_count:e.projects.length,rate_limit:{remaining:null,reset_at:null,exhausted:o,point_cost:null},projects:e.projects.map(s=>({project_label:s.project_label,repository:`${s.owner}/${s.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${s.owner}/${s.name} answered: ${r}`}))}}}function Wd(e){let n=e.stalenessMs??Uy,t=e.activity;if(t==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:n,stale:!1,request_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1,point_cost:null},projects:[],reason:"the daemon polls no repository, so there are no counts to age"};let r=Date.parse(e.now),o=Date.parse(t.fetched_at),s=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,i=s==null||s>n;return{version:1,fetched_at:t.fetched_at,age_ms:s,threshold_ms:n,stale:t.projects.length>0&&i,request_count:t.request_count,rate_limit:t.rate_limit,projects:t.projects.map(l=>({...l,fetched_at:t.fetched_at,age_ms:s,stale:i})),reason:t.projects.length===0?"the daemon polls no repository, so there are no counts to age":s==null?"these counts carry no readable instant, so they cannot be presented as current":i?`these counts are ${s}ms old, past the ${n}ms window`:`fetched ${s}ms ago, within the ${n}ms window`}}function Bd(e){if(!tr(e))return!1;let n=e;return n.version===1&&(n.fetched_at===null||typeof n.fetched_at=="string")&&(n.age_ms===null||typeof n.age_ms=="number")&&typeof n.threshold_ms=="number"&&typeof n.stale=="boolean"&&Number.isInteger(n.request_count)&&tr(n.rate_limit)&&Array.isArray(n.projects)&&typeof n.reason=="string"}function Fd(e){let n=e.endpoint??Hy(Fy),t=e.fetchImpl??fetch;return async r=>{let o=await t(n,{method:"POST",headers:{authorization:`bearer ${e.token}`,"content-type":"application/json",accept:"application/vnd.github+json"},body:JSON.stringify({query:r})});if(!o.ok){let s=o.headers.get("x-ratelimit-remaining"),i=o.status===429||s==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(i?": the host token's rate limit is spent":""))}return await o.json()}}function Jy(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>Id)throw new Error(`redskilled activity fetch spans at most ${Id} repositories in one query`);let n=new Set;for(let t of e){if(t.project_label===""||t.owner===""||t.name==="")throw new Error("redskilled activity fetch needs a project label and an owner/name for every registered project");if(n.has(t.project_label))throw new Error(`redskilled holds one repository per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function Qy(e,n){let t=pn(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(Hd),i=typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:null;return{remaining:r,reset_at:o,exhausted:s||r===0,point_cost:i}}function Hd(e){if(e==null)return!1;let n=cs(e.type),t=cs(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function Nd(e,n){return Array.isArray(e)&&e.includes(n)}function Md(e){let n=pn(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function zy(e){let n=pn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function pn(e){return tr(e)?e:{}}function tr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cs(e){return typeof e=="string"?e:""}var Yy=3e4,Xy=4,Zy=["logs","vitals","display"];function Ud(e,n){if(n===void 0)return e;let t=Zy.filter(o=>n[o]!==!0);if(t.length===0)return e;let r=o=>n[o]===!0;return{...e,workers:e.workers.map(o=>({...o,...r("vitals")?{}:{vitals:ek,budget:{...o.budget,used_bytes:null,used_fraction:null}},...r("logs")?{}:{log:nk},...r("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var ek={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},nk={last_line:null,published_at:null,source:null};function Gd(e){let n=e.stalenessMs??Yy,t=Jn(e.now),r=e.sampledAt==null?null:Jn(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),s=o!=null&&o<=n,i=new Set(e.reattachedWorkerIds??[]),l=e.hostState.workers.map(f=>ok(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:i.has(f.worker_id)?"reattached":"running"})),a=l.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=l.length-a.length,u=l.reduce((f,m)=>f+(m.vitals.rss_bytes??0),0),p=Gt(e.hostState.workers);return{version:1,generated_at:e.now,daemon:{pid:e.hostState.pid,daemon_version:e.hostState.daemon_version,protocol_version:e.hostState.protocol_version,started_at:e.hostState.started_at,machine_id_hash:e.hostState.machine_id_hash,session_key_hash:e.hostState.session_key_hash},staleness:ak({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:l.length,measuredCount:d,unmeasured:a}),host:{worker_count:l.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:p,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:u,measured_worker_count:d,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:p.memory_bytes/e.ceiling.memory_bytes},projects:lk(l),known_projects:ik(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,m)=>f.localeCompare(m)),lapsed_projects:(e.hostState.lapsed_registrations??[]).map(f=>({project_label:f.project_label,at:f.at,reason:f.detail})),workers:l,github_balance:os({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:Wd({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:tk(e.deaths,e.recentDeathLimit??Xy)},engine:rk(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function tk(e,n){let t=[...e].sort((o,s)=>(Jn(s.ts)??0)-(Jn(o.ts)??0)),r=t.slice(0,Math.max(0,Math.floor(n))).map(o=>({kind:o.kind,id:o.id,pid:o.pid,ts:o.ts,last_seen:o.last_seen,last_phase:o.last_phase,sender_class:o.sender_class,confidence:o.confidence,signal:o.signal,evidence:o.evidence[0]??null}));return{count:t.length,recent:r,latest:r[0]??null,reaped_at:r[0]?.ts??null}}function rk(e){let n=e.upgrade,t=n?.running_version??e.daemon_version,r=n?.published_version??null,o=n?.newest_published_version??null,s=(n?.newer_published??0)>0,i=(n?.major_held??0)>0;return{running_version:t,published_version:r,newer_published:s,major_held:i,current:r==null&&o==null?null:!s&&!i}}function ok(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=qn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=Jn(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms:n.nowMs==null||i==null?null:Math.max(0,n.nowMs-i),state:n.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:r,sampled_at:r==null?null:n.sampledAt,age_ms:r==null?null:n.ageMs,fresh:r!=null&&n.sampleFresh,rss_source:r==null?null:e.rss_source??null},budget:{name:o?.name??null,declared:o?.declared??s,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:sk(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function sk(e){let n={last_line:null,published_at:null,source:null};return e==null||e.line.trim()===""?n:{last_line:e.line,published_at:e.published_at,source:e.source}}function ik(e){let n=new Set;for(let t of e.registrations??[])n.add(t.project_label);for(let t of e.projects)n.add(t.project_label);for(let t of e.lapsed_registrations??[])n.add(t.project_label);return[...n].sort((t,r)=>t.localeCompare(r))}function lk(e){let n=new Map;for(let t of e){let r=n.get(t.project_label)??{workers:0,declared:0,observed:0,measured:0};r.workers+=1,r.declared+=t.budget.bytes??0,r.observed+=t.vitals.rss_bytes??0,r.measured+=t.vitals.rss_bytes==null?0:1,n.set(t.project_label,r)}return[...n.entries()].map(([t,r])=>({project_label:t,worker_count:r.workers,declared_memory_bytes:r.declared,observed_rss_bytes:r.observed,measured_worker_count:r.measured})).sort((t,r)=>t.project_label.localeCompare(r.project_label))}function ak(e){let n={sampled_at:e.sampledAt,age_ms:e.ageMs,threshold_ms:e.threshold,measured_worker_count:e.measuredCount,unmeasured_workers:e.unmeasured};return e.workerCount===0?{...n,stale:!1,reason:"the host holds no Workers, so there is nothing to measure and nothing to age"}:e.sampledAt==null||e.ageMs==null?{...n,stale:!0,reason:`this answer is stale: the daemon has taken no measurement of its ${e.workerCount} live Worker(s) yet`}:e.ageMs>e.threshold?{...n,stale:!0,reason:`this answer is stale: its measurement is ${e.ageMs}ms old, past the ${e.threshold}ms staleness window`}:{...n,stale:!1,reason:`measured ${e.ageMs}ms ago, within the ${e.threshold}ms staleness window`}}function Jn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function fs(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.daemon,r=n.staleness,o=n.host;return n.version===1&&typeof n.generated_at=="string"&&t!=null&&typeof t=="object"&&Number.isInteger(t.pid)&&typeof t.daemon_version=="string"&&typeof t.protocol_version=="number"&&r!=null&&typeof r=="object"&&typeof r.stale=="boolean"&&typeof r.threshold_ms=="number"&&Array.isArray(r.unmeasured_workers)&&o!=null&&typeof o=="object"&&Number.isInteger(o.worker_count)&&Number.isInteger(o.project_count)&&typeof o.observed_rss_bytes=="number"&&Array.isArray(n.projects)&&Array.isArray(n.workers)&&(n.known_projects===void 0||Array.isArray(n.known_projects)&&n.known_projects.every(s=>typeof s=="string"))&&(n.registered_projects===void 0||Array.isArray(n.registered_projects)&&n.registered_projects.every(s=>typeof s=="string"))&&(n.lapsed_projects===void 0||Array.isArray(n.lapsed_projects)&&n.lapsed_projects.every(dk))&&(n.repository_activity===void 0||Bd(n.repository_activity))&&(n.github_balance===void 0||ss(n.github_balance))&&(n.deaths===void 0||ck(n.deaths))&&(n.engine===void 0||uk(n.engine))&&(n.metrics===void 0||Ld(n.metrics))}function dk(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.project_label=="string"&&typeof n.at=="string"&&typeof n.reason=="string"}function ck(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return Number.isInteger(n.count)&&Array.isArray(n.recent)}function uk(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")}var Kd={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,started_at:null,context:null,eta:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null};function ms(e,n){let t=e.display?.started_at;if(t!=null&&t!==""){let r=Date.parse(t),o=Date.parse(n);if(Number.isFinite(r)&&Number.isFinite(o))return Math.max(0,o-r)}return e.uptime_ms}var U=e=>`\x1B[${e}m`,pk=U("48;2;114;47;55"),fk=U("48;2;88;36;42"),mk=U("38;2;255;255;255"),hk=U("38;2;201;150;158"),hs=U("38;2;255;214;214"),gs=U("39"),Qn=U("38;2;224;138;148"),ys=U("38;2;240;110;120"),ks=U("38;2;255;214;214"),Rs=U("38;2;146;84;94"),bs=U("38;2;255;95;95"),_s=U("49"),fn=U("0"),ws=U("1"),xs=U("22");var gk=/\x1b\[[0-9;]*m/g,yk=/(\x1b\[[0-9;]*m)/,kk=/^\x1b\[[0-9;]*m$/;function Vd(e){return e.replace(gk,"")}function Rk(e){return e.slice(2,-1).split(";").every(t=>t===""||Number(t)===0)}function ue(e){return[...Vd(e)].length}function q(e,n){if(n<=0)return"";if(ue(e)<=n)return e;if(n===1)return"\u2026";let t=n-1,r=0,o=!1,s="";for(let i of e.split(yk))if(i!==""){if(kk.test(i)){s+=i,o=!Rk(i);continue}for(let l of i){if(r===t)return`${s}\u2026${o?fn:""}`;s+=l,r+=1}}return`${s}\u2026${o?fn:""}`}function zn(e,n){return e+" ".repeat(Math.max(0,n-ue(e)))}function Ss(e){let n=e.toLowerCase();for(let t of["opus","sonnet","haiku","fable"])if(n.includes(t))return t;return e}function te(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}function Yn(e){if(!Number.isFinite(e)||e<=0)return"0";let n=(t,r)=>{let o=(Math.round(t*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${r}`};return e>=1e9?n(e/1e9,"B"):e>=1e6?n(e/1e6,"M"):e>=1e3?n(e/1e3,"k"):String(Math.round(e))}function Xn(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return Yn(e);if(e<=0)return"0";let n=(Math.round(e*10)/10).toFixed(1);return n.endsWith(".0")?n.slice(0,-2):n}function Zn(e){if(e==null||!Number.isFinite(e)||e<0)return"\u2014";let n=Math.floor(e/1e3);if(n<60)return`${n}s`;let t=Math.floor(n/60);if(t<60)return`${t}m${n%60}s`;let r=Math.floor(t/60);return r<24?`${r}h${t%60}m`:`${Math.floor(r/24)}d${r%24}h`}function vs(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}var et="!unregistered",nt="!lapsed",tt="\u21E1",He="\u2020",mn="\u25D0",hn="\u25EF",Es="\u21B3",Ps="redskilled unreachable \u2014 Worker state unknown";function gn(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function rr(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function rt(e,n){return n==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(n)?e.registered_projects==null||e.registered_projects.includes(n)?"matched":e.lapsed_projects?.some(t=>t.project_label===n)===!0?"lapsed":"name-only":"unregistered"}function Ds(e){let n=[];return e.workers.length>0&&e.workers.length<=e.maxWorkers&&n.push("workers"),e.mode==="global"&&e.projects.length>0&&e.projects.length<=e.maxProjects&&n.push("projects"),n.push("host"),n}var je=["wid","run","org","iss","bar","phase","elapsed","eta","hb","loc","tks","ctx","tls","rsn","txt"],pe={mode:"local",project:null,maxWidth:200,maxRows:16},bk=" ",qd="\u2588",_k="\u25B6",wk="\u2717",xk="\u2591",Sk=new Set(["gate","push-pr","merge","cascade"]),vk=new Set(["requeue"]);function yn(e,n=pe){let t=rt(e,n.project),r=gn(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(p=>js(p,n,e.generated_at)),i=Lk(s),l=o.map((p,f)=>({worker_id:p.worker_id,project_label:p.project_label,mine:n.project!=null&&p.project_label===n.project,cells:s[f],line:q(Tk(s[f],i),n.maxWidth)})),a=Ek(e,n,r,t),d=r.length-o.length,u=[a.line,...l.map(p=>p.line)];return d>0&&u.push(q(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),u.push(...Dk(e,n)),u.push(...Pk(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:je,header:a,rows:l,lines:u,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function js(e,n,t){let r=e.display??Kd,o=[r.runner,r.model==null?null:Ss(r.model),r.effort].filter(l=>!!l).join(" "),s=r.phase!=null&&Sk.has(r.phase),i=s||r.origin!=null&&vk.has(r.origin);return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:o===""?"":`run=${o}`,org:s?"org=landing":r.origin==null?"":`org=${r.origin}`,iss:r.issue==null?"":`iss=${r.issue}`,bar:Jd(r),phase:[r.phase,r.step].filter(l=>!!l).join("\xB7"),elapsed:Zn(ms(e,t)),eta:r.eta==null?"":`eta=${Zn(r.eta*1e3)}`,hb:`hb=${r.heartbeat??"?"}`,loc:i?"":Ak(r.added,r.removed),tks:i||r.tokens==null?"":`tks=${Yn(r.tokens)}`,ctx:r.context==null?"":`ctx=${Yn(r.context)}`,tls:i||r.tools==null?"":`tls=${r.tools}`,rsn:i||r.reasoning==null?"":`rsn=${r.reasoning}`,txt:i||r.text==null?"":`txt=${r.text}`}}function Jd(e){let n=e.phase_total,t=e.phase_index;if(n==null||n<=0||t==null||t<0)return"";let r=Math.min(Math.floor(t),Math.floor(n));if(r>=n)return qd.repeat(Math.floor(n));let o=e.failed?wk:_k;return`${qd.repeat(r)}${o}${xk.repeat(Math.floor(n)-r-1)}`}function Ek(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(w=>w.project_label===n.project),s={open_pull_requests:o?.counts?.open_pull_requests??null,recently_closed:o?.counts?.recently_closed??null,open_issues:o?.counts?.open_issues??null,stale:o?.stale===!0},i={memory_used_fraction:e.host.ceiling_used_fraction,memory_used_bytes:e.host.consumption.memory_bytes,memory_ceiling_bytes:e.host.ceiling.memory_bytes,worker_count:e.host.worker_count,worker_ceiling:e.host.ceiling.worker_count},l=Ok(t),a=o?.repository??n.project,d=e.engine??null,u=d?.running_version??e.daemon.daemon_version,p=e.deaths??null,f=e.metrics??null,m=[`\xBB ${a??"host"} v${u}${d!=null&&d.current===!1?tt:""}`];(r==="unregistered"||r==="name-only")&&m.push(et),r==="lapsed"&&m.push(nt),l!=null&&m.push(l),m.push(`wrk=${t.length}/${e.host.worker_count}`),m.push(i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`),m.push(jk(i)),s.open_pull_requests!=null&&m.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&m.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&m.push(`iss=${s.open_issues}`),s.stale&&m.push("!counts stale");let g=f==null?null:Qd(f.hour);if(g!=null&&m.push(g),p!=null&&p.count>0&&p.latest!=null&&m.push(`${He}${p.count} ${p.latest.sender_class}`),e.staleness.stale){let w=e.staleness.age_ms;m.push(w==null?"!unmeasured":`!stale ${Math.round(w/1e3)}s`)}let _=m.join(" \xB7 "),k=g!=null&&ue(_)>n.maxWidth?m.filter(w=>w!==g).join(" \xB7 "):_;return{repo:a,project:n.project,project_match:r,version:u,engine:d,deaths:p,metrics:f,model:l,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:q(k,n.maxWidth)}}function Qd(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${Xn(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${Xn(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${Xn(e.issues_per_hour.value)}`);let t=e.runner_share.shares[0];return t!=null&&n.push(`${t.key}=${Math.round(t.share*100)}%`),n.length===0?null:n.join(" ")}function Pk(e,n){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let r=t.posture==="spent"?hn:mn,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[q(`${r} github budget ${t.posture}${o} \u2014 ${t.reason}`,n.maxWidth)]}function Dk(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(s=>q(`${He} ${s.kind} ${s.id} pid=${s.pid} ${s.sender_class}/${s.confidence} phase=${s.last_phase}`+(s.signal==null?"":` signal=${s.signal}`)+(s.evidence==null?"":` \u2014 ${s.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(q(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function jk(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${te(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${te(e.memory_used_bytes)}/${te(e.memory_ceiling_bytes)}${n}`}function Ok(e){for(let n of e){let t=n.display;if(t==null)continue;let r=[t.runner,t.model,t.effort].filter(o=>!!o);if(r.length>0)return r.join("\xB7")}return null}function Ak(e,n){if(e==null&&n==null)return"";let t=[];return e!=null&&e>0&&t.push(`+${e}`),n!=null&&n>0&&t.push(`-${n}`),`loc=${t.length>0?t.join(" "):"0"}`}function Lk(e){let n=Object.fromEntries(je.map(t=>[t,0]));for(let t of e)for(let r of je)n[r]=Math.max(n[r],ue(t[r]));return n}function Tk(e,n){return je.filter(r=>n[r]>0).map(r=>zn(e[r],n[r])).join(bk).replace(/\s+$/,"")}var j={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Ue(e,n=j){let t=rt(e,n.project),r=gn(e,n),o=rr(e,n),s=Ik(e,n,r,t),i=Ds({mode:n.mode,maxWorkers:n.maxWorkers,maxProjects:n.maxProjects,workers:r,projects:o}),l={detail:"host",line:s};for(let f of i){let m=f==="workers"?s:Vk(s,$k(f,o),n.separator);if(l={detail:f,line:m},f==="workers"||ue(m)<=n.maxWidth)break}let a=q(l.line,n.maxWidth),d=l.detail==="workers"?Hk(r,n,e.generated_at):{lines:[],degraded:!1},u=l.detail==="workers"?r.flatMap((f,m)=>{let g=n.verbose?Gk(f,n):null;return g==null?[d.lines[m]]:[d.lines[m],g]}):[],p=r.length>0?"workers":"host";return{version:1,line:a,lines:[a,...u],verbose:n.verbose,mode:n.mode,project:n.project,project_match:t,detail:l.detail,degraded:l.detail!==p||a!==l.line||d.degraded,stale:e.staleness.stale,generated_at:e.generated_at}}function As(e){let n=e.options??j,t=q(Ps,n.maxWidth);return{version:1,line:t,lines:[t],verbose:n.verbose,mode:n.mode,project:n.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}function $k(e,n){return e==="projects"?n.map(Kk):[]}function Ik(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(Os(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(Os(e,n)),t.length===0&&o.push("idle")):r==="name-only"||r==="lapsed"?(o.push(`${n.project} ${t.length}w`),o.push(Os(e,n)),o.push(r==="lapsed"?nt:et)):o.push(Wk(n.project,r)),o.push(Nk(e));let s=Mk(e);s!=null&&o.push(s);let i=Ck(e);return i!=null&&o.push(i),e.staleness.stale&&o.push(Bk(e)),o.join(" ")}function Nk(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${tt}`}function Mk(e){let n=e.github_balance;return n==null?null:n.posture==="spent"?`${hn} quota spent`:n.posture==="reserved"?`${mn} quota band`:null}function Ck(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${He}${n.count} ${n.latest.sender_class}`}function Wk(e,n){return n==="unregistered"?`project unknown \u2014 ${e} is not registered on this host`:"project unknown \u2014 this directory resolved to no project"}function Os(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,s)=>o+s.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${te(t)}/${te(r)}`:te(t)}function Bk(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function Fk(e,n,t,r){let o=t.map(s=>Uk(s,zn(e[s],n[s])));return q(`${_s}${Qn}${o.join(" ")}${fn}`,r)}function Hk(e,n,t){let r=e.map(l=>js(l,n,t)),o=je.filter(l=>r.some(a=>ue(a[l])>0)),s=[...o],i=zd(r,s);for(;s.length>1&&Yd(i,s)>n.maxWidth;)s.pop(),i=zd(r,s);return{lines:r.map(l=>Fk(l,i,s,n.maxWidth)),degraded:s.length<o.length||Yd(i,s)>n.maxWidth}}function zd(e,n){let t=Object.fromEntries(je.map(r=>[r,0]));for(let r of e)for(let o of n)t[o]=Math.max(t[o],ue(r[o]));return t}function Yd(e,n){return n.reduce((t,r)=>t+e[r],0)+Math.max(0,n.length-1)*2}function Uk(e,n){if(e==="wid")return`${ws}${n}${xs}`;if(e==="bar")return n.replace(/█+/g,r=>`${ys}${r}`).replace("\u25B6",`${ks}\u25B6`).replace("\u2717",`${bs}\u2717`).replace(/░+/g,r=>`${Rs}${r}`)+Qn;let t=n.indexOf("=");return t>0?`${hs}${n.slice(0,t+1)}${gs}${n.slice(t+1)}${Qn}`:n}function Gk(e,n){let t=vs(e.log.last_line);return t==null?null:q(` ${Es} ${Ls(e,n.mode)}: ${t}`,n.maxWidth)}function Ls(e,n){return n==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Kk(e){return`${e.project_label} ${e.worker_count}w ${te(e.observed_rss_bytes)}`}function Vk(e,n,t){return[e,...n].join(t)}var or=1;async function ot(e,n){return await Ct(e,n,"redskilled daemon")}function Zd(e){let n=[...e.workers??[]],t=new Map;for(let r of n)t.set(r.project_label,(t.get(r.project_label)??0)+1);return{version:1,protocol_version:or,daemon_version:e.daemonVersion,machine_id_hash:e.machineIdHash,session_key_hash:e.sessionKeyHash,pid:e.pid,started_at:e.startedAt,...e.scope==null?{}:{scope:e.scope},workers:n,projects:[...t.entries()].map(([r,o])=>({project_label:r,worker_count:o})).sort((r,o)=>r.project_label.localeCompare(o.project_label)),registrations:zk(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:$a(n,{hostCeilingBytes:e.hostCeilingBytes??null}),upgrade:Yk(e)}}function zk(e){let n=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(n),r=e.queue??null,o=new Map(r==null?[]:r.projects.map(s=>[s.project_label,s]));return[...e.registrations??[]].map(s=>{let i=o.get(s.project_label);return{...s,...t?{renewal:ud(s,n)}:{},...r==null||i==null?{}:{last_poll:{at:r.fetched_at,outcome:i.outcome,depth:i.depth,request_count:r.request_count,detail:i.detail}}}}).sort((s,i)=>s.project_label.localeCompare(i.project_label))}function Yk(e){let n=e.daemonVersion,t=e.published?.version??null,r=e.published?.majorHold??null;return{running_version:n,published_version:t,published_unknown:+(t===null),newer_published:+(e.published?.newer===!0),replacement:e.published?.replacement??"none",checked_at:e.published?.checkedAt??null,checks:e.published?.checks??0,hold_reason:e.published?.holdReason??null,newest_published_version:e.published?.newest??null,major_held:+(r!==null),major_hold:r}}function ec(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.protocol_version=="number"&&typeof n.daemon_version=="string"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&Number.isInteger(n.pid)&&typeof n.started_at=="string"&&Array.isArray(n.workers)&&Array.isArray(n.projects)&&Ia(n.budget_accounting)&&(n.scope===void 0||ld(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(zo))&&(n.upgrade===void 0||Xk(n.upgrade))}function Xk(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")&&typeof n.published_unknown=="number"&&typeof n.newer_published=="number"&&(n.replacement==="none"||n.replacement==="pending"||n.replacement==="in-progress")&&(n.checked_at===null||typeof n.checked_at=="string")&&(n.newest_published_version===void 0||n.newest_published_version===null||typeof n.newest_published_version=="string")&&(n.major_held===void 0||typeof n.major_held=="number")&&(n.checks===void 0||typeof n.checks=="number")&&(n.hold_reason===void 0||n.hold_reason===null||typeof n.hold_reason=="string")&&(n.major_hold===void 0||n.major_hold===null||Zk(n.major_hold))}function Zk(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.version=="string"&&Number.isInteger(n.running_major)&&Number.isInteger(n.held_major)&&typeof n.reason=="string"&&typeof n.action=="string"&&n.action.trim()!==""}import{spawnSync as lr}from"node:child_process";import{existsSync as Ms}from"node:fs";import{delimiter as aR,join as cc}from"node:path";import{join as nc}from"node:path";import{existsSync as eR}from"node:fs";import{createRequire as nR}from"node:module";var tc="redskilled-job-object.node",Ge=100;function kn(e){return{available:!1,reason:e}}function tR(e,n,t){return[nc(t,"prebuilds",`${e}-${n}`,tc),nc(t,"native","build","Release",tc)]}function rc(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return kn(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??oR(),o=e.exists??eR,s=tR(n,t,r),i=s.find(d=>o(d));if(i==null)return kn(`no Job Object addon was found for ${n}-${t} (looked in ${s.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let l=e.requireFn??nR(import.meta.url),a;try{a=l(i)}catch(d){return kn(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return rR(a)?{available:!0,binding:a}:kn(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function rR(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function oR(){return new URL("..",import.meta.url).pathname}function oc(e){let n=e??{},t=[],r=sR(n);r==null&&(n.memory_max??n.memory_high)!=null&&t.push("the declared memory budget could not be reduced to bytes, so the job carries no memory ceiling");let o;return n.cpu_weight!=null&&(n.cpu_weight<Ge?o=Math.max(1,Math.min(100,Math.round(n.cpu_weight))):t.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${Ge}, and Windows CPU rate control is an absolute cap rather than a share, so no rate limit is set`)),{...r!=null?{memory_limit_bytes:r.bytes,memory_budget_name:r.name,memory_budget_declared:r.declared}:{},...o!=null?{cpu_rate_percent:o}:{},kill_on_close:!0,...t.length>0?{note:t.join("; ")}:{}}}function sR(e){return qn({budget:e})}var sr=5,sc=19;function Ts(e){return{available:!1,reason:e}}var iR="an address-space rlimit is not a resident-memory ceiling: a runtime that reserves address space it never faults in would die under a limit it never used, so no memory rlimit is set and the daemon's RSS sampling floor is the ceiling that actually holds";function lc(e,n){let t=e??{},r=[],o;if(!n.canRenice)r.push("nice is not on this host, so no priority control was applied and the Worker competes with interactive work");else if(t.cpu_weight==null)o=sr;else if(t.cpu_weight<Ge){let l=Math.round(sc*(Ge-t.cpu_weight)/Ge);o=Math.min(sc,Math.max(sr,l))}else o=sr,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${Ge}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${sr}`);let s=ic(t.max_processes);s==null&&t.max_processes!=null&&r.push(`max_processes=${t.max_processes} is not a positive whole number, so no ulimit -u is set`);let i=ic(t.cpu_seconds);return i==null&&t.cpu_seconds!=null&&r.push(`cpu_seconds=${t.cpu_seconds} is not a positive whole number, so no ulimit -t is set`),{...o!=null?{nice:o}:{},...s!=null?{max_processes:s}:{},...i!=null?{cpu_seconds:i}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:iR,...r.length>0?{note:r.join("; ")}:{}}}function ac(e){let{limits:n}=e,t=[];return n.max_processes!=null&&t.push(`ulimit -u ${n.max_processes}`),n.cpu_seconds!=null&&t.push(`ulimit -t ${n.cpu_seconds}`),t.push(n.nice!=null&&e.nice!=null?`exec ${lR(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
71
- `),e.command,...e.args]}function dc(e){let n=[];return e.nice!=null?n.push(`the Worker runs at nice ${e.nice} so it yields to interactive work`):n.push("no priority control was applied"),e.max_processes!=null&&n.push(`its processes are capped at ${e.max_processes}`),e.cpu_seconds!=null&&n.push(`its CPU time is capped at ${e.cpu_seconds} seconds`),`macOS placement applied POSIX limits: ${n.join(", ")}. macOS has no resource-group equivalent, so the Worker is charged to the daemon's own resource group, and ${e.memory_ceiling_reason}`+(e.note!=null?` (${e.note})`:"")}function $s(e){let n=e??{},t=[n.max_processes!=null?"max_processes":null,n.cpu_seconds!=null?"cpu_seconds":null].filter(r=>r!=null);return t.length===0?null:`${t.join(" and ")} ${t.length===1?"is a POSIX rlimit":"are POSIX rlimits"} honoured only by the macOS placement backend, so this placement carries no equivalent`}function ic(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function lR(e){return`'${e.replace(/'/g,"'\\''")}'`}var uc="REDSKILLED_PLACEMENT",ir="red-worker",Is="/bin/sh";function pc(e=process.env,n=process.platform){let t=Ts(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:rc({platform:n}),posix:t};let r=kn(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);if(n==="darwin")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:dR(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Ms(cc(o,"systemd","private"));return{platform:n,systemdRun:gc("systemd-run",e),userSession:s,jobObjects:r,posix:t}}function dR(e){return Ms(Is)?{available:!0,shell:Is,nice:gc("nice",e)}:Ts(`no POSIX shell was found at ${Is}, so there is nothing to apply rlimits or priority in`)}function fc(e=process.env){let n=(e[uc]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function cR(e,n,t=ir){return mc(e,n,t).replace(/\.service$/,"")}function mc(e,n,t=ir){return`${Ns(t,"red-worker",24)}-${Ns(e,"project",32)}-${Ns(n,"worker",32)}.service`}function hc(e){let n=[...e.args??[]],t={...e.budget??{},...e.budget?.memory_max==null&&e.memoryCeiling?.memory_max!=null?{memory_max:e.memoryCeiling.memory_max}:{}},r=t.memory_max??t.memory_high??null,o=t.memory_high!=null||t.memory_max!=null||t.cpu_weight!=null,s=e.target??{isolation:"transient-unit"},i=p=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:p,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Mn({scope:null,memory_ceiling:r,scope_degradation:p}),...o?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(s.isolation==="inherit")return i("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return i(`worker isolation disabled by ${uc}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return pR(e,n,t,r,o,i);if(e.probes.platform==="darwin")return uR(e,n,t,r,i);if(e.probes.platform!=="linux")return i(`transient-unit placement is the Linux backend (platform=${e.probes.platform}): the Worker is charged to the daemon's own resource group`);if(!e.probes.systemdRun)return i("transient-unit placement unavailable: systemd-run is not on PATH; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");if(!e.probes.userSession)return i("transient-unit placement unavailable: no systemd --user session; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");let l=mc(e.projectLabel,e.workerId,s.unit_prefix),a=["--user","--collect","--quiet","--wait",`--unit=${l}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&a.push("--pipe"),t.memory_high!=null&&a.push(`--property=MemoryHigh=${t.memory_high}`),t.memory_max!=null&&a.push(`--property=MemoryMax=${t.memory_max}`),t.cpu_weight!=null&&a.push(`--property=CPUWeight=${t.cpu_weight}`);let d=Mn({scope:l,memory_ceiling:r,scope_degradation:null});for(let[p,f]of Object.entries({...e.env??{},...d}))a.push(`--setenv=${p}=${f}`);let u=$s(e.budget);return{isolated:!0,backend:"transient-unit",unit:l,command:e.probes.systemdRun,args:[...a,"--",e.command,...n],budget:t,...r!=null?{memoryCeiling:r}:{},environment:d,...u!=null?{budgetWarning:u}:{}}}function uR(e,n,t,r,o){let s=e.probes.posix;if(!s.available)return o(`POSIX limit placement unavailable: ${s.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let i=lc(t,{canRenice:s.nice!=null}),l=t.memory_high!=null||t.memory_max!=null,a=dc(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:ac({limits:i,nice:s.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:i,warning:a,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Mn({scope:null,memory_ceiling:r,scope_degradation:a}),...l?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+i.memory_ceiling_reason}:{}}}function pR(e,n,t,r,o,s){let i=e.probes.jobObjects;if(!i.available)return s(`Job Object placement unavailable: ${i.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let l=oc(t),a=cR(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...n],cwd:e.workspacePath,job:{name:a,limits:l},budget:t,...r!=null?{memoryCeiling:r}:{},environment:Mn({scope:a,memory_ceiling:r,scope_degradation:null}),...fR(o&&l.note!=null?`${l.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,$s(e.budget))}}function fR(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function gc(e,n){for(let t of(n.PATH??"").split(aR)){if(!t)continue;let r=cc(t,e);if(Ms(r))return r}return null}function Ns(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function Cs(e,n){let t=[],r=[];for(let o of e){let s=!1;try{s=await n(o)===!0}catch{s=!1}(s?t:r).push(o)}return{alive:t,dead:r}}var yc=3e4;function kc(e){return e.unit!=null&&e.unit!==""?mR(e.unit):B(e.pid)}function mR(e){let n=lr("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var hR="REDSKILLED_UNIT_DISCOVERY",Rc="(unowned)";function bc(e){let n=lr("systemctl",["--user","show","--property=MainPID","--value",e],{encoding:"utf8"});if(n.error!=null||n.status!==0)return null;let t=Number.parseInt((n.stdout??"").trim(),10);return Number.isInteger(t)&&t>0?t:null}function gR(e=process.env){let n=(e[hR]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function _c(e,n,t=process.env){return gR(t)&&e===n}function wc(e=ir){let n=lr("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return n.error!=null||n.status!==0?[]:(n.stdout??"").split(`
72
- `).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function xc(e){let n=new Set(e.held.map(o=>o.unit).filter(o=>o!=null&&o!=="")),t=new Set,r=[];for(let o of e.units)o===""||n.has(o)||t.has(o)||(t.add(o),r.push({worker_id:o.replace(/\.service$/,""),project_label:Rc,pid:e.mainPid?.(o)??0,started_at:e.now,workspace_path:"",isolated:!0,unit:o,warnings:[`adopted from active unit ${JSON.stringify(o)}, which has no birth on this host's event lane: its project, its Worker id and its budget belonged to a daemon that is gone, so they are reported as unknown rather than guessed \u2014 it is counted against the host budget from here on instead of running outside it`]}));return r}function Sc(e){return e.project_label.trim()!==""?e:{...e,project_label:Rc,warnings:[...e.warnings,"adopted at start with no owning project on the event lane: the daemon that birthed it recorded no project label, so it is held and counted under a stated placeholder rather than dropped"]}}function vc(e){if(e.unit!=null&&e.unit!==""){let n=lr("systemctl",["--user","stop",e.unit],{stdio:"ignore"});return n.error==null&&n.status===0}try{return process.kill(e.pid,"SIGTERM"),!0}catch{return!1}}function yR(e,n=50){if(jc(e),!Number.isInteger(n)||n<=0)throw new Error(`redskilled queue discovery needs a whole, positive batch size, not ${JSON.stringify(n)}`);let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}function kR(e,n={}){let t=n.batchSize??50;if(jc(e),e.length>t)throw new Error(`redskilled queue discovery spans at most ${t} selectors in one query, and this batch holds ${e.length}: split it with planQueueDiscoveryBatches rather than dropping the remainder`);let r=e.map((i,l)=>({alias:`q${l}`,project:i}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...r.map(({alias:i,project:l})=>` ${i}: search(query: ${JSON.stringify(l.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
73
- `),aliases:r}}function RR(e,n){let t=st(n),r=st(t.data),o=Array.isArray(t.errors)?t.errors.map(st):[],s=_R(r.rateLimit,o);return{projects:e.aliases.map(({alias:l,project:a})=>{let d=xR(r[l]);if(d!=null)return{project_label:a.project_label,outcome:"counted",depth:d,detail:`project ${JSON.stringify(a.project_label)} has ${d} item(s) matching its selector`};let u=o.find(p=>wR(p.path,l));return s.exhausted||Oc(u)?{project_label:a.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(a.project_label)} answered, so this queue has no depth rather than a depth of zero`+(s.reset_at==null?"":`; the quota resets at ${s.reset_at}`)}:{project_label:a.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(a.project_label)} could not be counted with the host token: ${Ws(u?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function bR(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function Pc(e,n,t){return{version:1,fetched_at:n,request_count:0,project_count:e.length,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:e.map(r=>({project_label:r.project_label,outcome:"unconfigured",depth:null,detail:`project ${JSON.stringify(r.project_label)} was not counted because this host polls no tracker: ${t}`}))}}async function Dc(e){if(e.projects.length===0)return bR(e.now);let n=e.batchSize??50,t=yR(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=kR(s,{batchSize:n});try{let l=await e.transport(i.query),a=RR(i,l);r.push(...a.projects),o=Ec(o,a.rate_limit)}catch(l){let a=l instanceof Error?l.message:String(l),d=/rate limit|secondary rate|429/i.test(a);o=Ec(o,{remaining:null,reset_at:null,exhausted:d});for(let u of s)r.push({project_label:u.project_label,outcome:d?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(u.project_label)} answered: ${a}`})}}return{version:1,fetched_at:e.now,request_count:t.length,project_count:r.length,batch_size:n,rate_limit:o,projects:r}}function jc(e){if(e.length===0)throw new Error("redskilled queue discovery needs at least one registered project");let n=new Set;for(let t of e){if(typeof t.project_label!="string"||t.project_label==="")throw new Error("redskilled queue discovery needs a project label for every registered project");if(typeof t.selector!="string"||t.selector==="")throw new Error(`redskilled queue discovery needs a selector for project ${JSON.stringify(t.project_label)}: a project that names no work has no queue to discover`);if(n.has(t.project_label))throw new Error(`redskilled holds one selector per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function Ec(e,n){return{remaining:n.remaining==null?e.remaining:e.remaining==null?n.remaining:Math.min(e.remaining,n.remaining),reset_at:n.reset_at??e.reset_at,exhausted:e.exhausted||n.exhausted}}function _R(e,n){let t=st(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null;return{remaining:r,reset_at:o,exhausted:n.some(Oc)||r===0}}function Oc(e){return e==null?!1:Ws(e.type)==="RATE_LIMITED"||/rate limit/i.test(Ws(e.message))}function wR(e,n){return Array.isArray(e)&&e.includes(n)}function xR(e){let n=st(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function st(e){return SR(e)?e:{}}function SR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ws(e){return typeof e=="string"?e:""}function Ac(e,n,t){let r=e?.rate_limit;if(r==null)return n;if(r.exhausted){let s=r.reset_at==null?Number.NaN:Date.parse(r.reset_at),i=Number.isFinite(s)?s-t+1e3:n*4;return Math.min(vR,Math.max(n,i))}let o=r.remaining;return o==null?n:o<=ER?Math.max(n,3e4):o<=PR?Math.max(n,2e4):n}var vR=1e5,ER=250,PR=1e3;var DR={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,started_at:null,context:null,eta:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},jR=["runner","model","effort","origin","issue","phase","step","heartbeat","started_at"],OR=["phase_index","phase_total","context","eta","added","removed","tokens","tools","reasoning","text"];function Lc(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...DR};for(let r of jR){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of OR){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}import{randomInt as $R}from"node:crypto";import{spawn as IR}from"node:child_process";import{closeSync as NR,mkdirSync as MR,openSync as CR}from"node:fs";import{dirname as WR}from"node:path";import{delimiter as Tc,dirname as AR}from"node:path";function LR(e,n=Tc){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function TR(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=AR(n);return t===""||t==="."?null:t}function $c(e,n=process.execPath,t=Tc){let r=LR(e,t),o=TR(n);return o==null?r.join(t):[o,...r.filter(s=>s!==o)].join(t)}var Rn=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},ar=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}},Bs="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",Nc=4,BR=Bs.length**Nc;function Fs(e,n=$R){let t=new Set(e);for(let r=0;r<BR;r+=1){let o="h";for(let s=0;s<Nc;s+=1)o+=Bs[n(Bs.length)];if(!t.has(o))return o}throw new Rn("redskilled exhausted the host Worker id space")}function FR(e){if(e==null||e.trim()==="")return null;try{return MR(WR(e),{recursive:!0}),CR(e,"a")}catch{return null}}function HR(e){try{NR(e)}catch{}}function UR(e){let n=[["project_label",e.project_label],["workspace_path",e.workspace_path],["command",e.command]];for(let[t,r]of n)if(typeof r!="string"||r.trim()==="")throw new Rn(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new Rn("redskilled worker spec args must be an array")}function GR(e){if(e==null)throw new ar("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new ar(e.reason,e)}function Mc(e){let{spec:n,admission:t}=e;GR(t),UR(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(n.worker_id??e.workerId)?.trim()||Fs(e.liveWorkerIds??[]),i=e.probes??pc(r),l=e.openLog===!1?null:FR(n.log_path),a={...n.env??{},PATH:$c(n.env?.PATH??r.PATH,e.execPath??process.execPath)},d=hc({workerId:s,projectLabel:n.project_label,workspacePath:n.workspace_path,command:n.command,args:n.args,budget:n.budget,...e.memoryCeiling!=null?{memoryCeiling:e.memoryCeiling}:{},target:n.placement,env:a,enabled:e.enabled??fc(r),probes:i,pipeOutput:l!==null}),p=(e.spawnFn??IR)(d.command,d.args,{...d.cwd!=null?{cwd:d.cwd}:{},detached:!0,stdio:l===null?"ignore":["ignore",l,l],env:d.backend==="transient-unit"?{...r}:{...r,...a,...d.environment}});if(l!==null&&HR(l),p.pid==null)throw p.once("error",()=>{}),new Rn(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${s}`);let f=d.job!=null?KR(d,i,p.pid):null;p.once("error",()=>{}),p.once("exit",(k,w)=>{try{f?.job?.close()}catch{}e.onExit?.(s,k,w)}),p.unref();let m=d.job!=null?f?.job!=null:d.isolated,g=[d.warning,f?.warning,d.budgetWarning].filter(k=>k!=null);return{worker:{worker_id:s,project_label:n.project_label,pid:p.pid,started_at:o(),workspace_path:n.workspace_path,...n.log_path!=null?{log_path:n.log_path}:{},isolated:m,...d.unit!=null?{unit:d.unit}:{},...n.budget!=null?{budget:n.budget}:{},...Object.keys(d.budget).length>0?{applied_budget:d.budget}:{},...d.memoryCeiling!=null?{memory_ceiling:d.memoryCeiling,memory_ceiling_reason:e.memoryCeiling?.reason??"this Worker's ceiling is the budget its client declared"}:{},warnings:g},admission:t,warnings:g,plan:d,child:p,...f?.job!=null?{job:f.job}:{}}}function KR(e,n,t){let r=e.job;if(r==null)return{};let o="the Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling";if(!n.jobObjects.available)return{warning:`Job Object placement unavailable: ${n.jobObjects.reason}. ${o}`};let s;try{s=n.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(i){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${Ic(i)}. ${o}`}}try{s.assign(t)}catch(i){try{s.close()}catch{}return{warning:`Worker pid ${t} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${Ic(i)}. ${o}`}}return{job:s}}function Ic(e){return e instanceof Error?e.message:String(e)}import{open as VR,stat as qR}from"node:fs/promises";var JR=16*1024;async function Cc(e,n=JR){let t;try{t=(await qR(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let s=await VR(e,"r");try{let i=Buffer.alloc(r);await s.read(i,0,r,t-r),o=i.toString("utf8")}finally{await s.close()}}catch{return null}return QR(o)}function QR(e){let n=e.split(`
74
- `);for(let t=n.length-1;t>=0;t-=1){let r=n[t].replace(/\r$/,"");if(r.trim()!=="")return r}return null}import{spawn as cb}from"node:child_process";import{existsSync as ub,readdirSync as pb}from"node:fs";import{dirname as fb,join as Gc,resolve as mb}from"node:path";var zR="<version>";function Oe(e,n=[],t){let r=t&&t.trim().length>0?t.trim():zR;return[`npx -y -p ${Be}@${r}`,e,...n].join(" ")}function re(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?{major:Number(n[1]),minor:Number(n[2]),patch:Number(n[3])}:null}function Hs(e,n){let t=re(e),r=re(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var CP=4*60*60*1e3;_e();_e();import{spawnSync as YR}from"node:child_process";import{mkdir as XR,rm as ZR,writeFile as eb}from"node:fs/promises";import{existsSync as nb}from"node:fs";import{homedir as tb}from"node:os";import{dirname as rb,join as Us}from"node:path";var bn="redskilled.service",Gs="REDSKILLED_SUPERVISED",ob="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function sb(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||Us(e.HOME?.trim()||tb(),".config");return Us(n,"systemd","user")}function Ks(e=process.env){return Us(sb(e),bn)}function Wc(e,n={}){let t=n.env??process.env,r=Ht(n.override??{},n.entryLookup??{}),o=[...r.args,...Ce(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:bn,unitPath:Ks(t),command:r.command,args:o,text:ib(r.command,o,e)}}function ib(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${ob}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(lb).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Gs}=1"`,`Environment="REDSKILLED_SESSION=${Bc(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
75
- `)}function lb(e){return/[\s"'\\$%]/.test(e)?`"${Bc(e)}"`:e}function Bc(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function Fc(e,n={}){let t=n.writeFile??ab,r=n.run??Vs,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(dr("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(dr("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function Hc(e={}){let n=e.removeFile??db,t=e.run??Vs,r=Ks(e.env??process.env),o=[dr("disable",t,["systemctl","--user","disable","--now",bn])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(dr("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function Uc(e={}){let n=e.exists??nb,t=e.run??Vs,r=Ks(e.env??process.env),o=n(r);return{unitName:bn,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",bn]).status===0,active:o&&t(["systemctl","--user","is-active",bn]).status===0,floor:"auto-spawn"}}function dr(e,n,t){let r=n(t),o=(r.stderr??r.stdout??"").trim();return{step:e,argv:t,ok:r.status===0,...o?{detail:o}:{}}}async function ab(e,n){await XR(rb(e),{recursive:!0}),await eb(e,n,{encoding:"utf8",mode:420})}async function db(e){await ZR(e,{force:!0})}function Vs(e){let n=YR(e[0],[...e.slice(1)],{encoding:"utf8"});return n.error!=null?{status:null,stderr:n.error.message}:{status:n.status,stdout:n.stdout??"",stderr:n.stderr??""}}var Kc=75,qc=9e5,Vc="redskilled-replacement-entry-unresolved",hb="REDSKILLED_NO_REGISTRY_PROBE",Jc="REDSKILLED_BORN_BY_REPLACEMENT";function Qc(e=process.env){return e[Jc]==="1"}function zc(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function Yc(e){let n=e.running.trim();if(it(n))return null;let t=e.newest?.trim()??"",r=re(t),o=re(n);return r===null||o===null||r.major<=o.major?null:{version:t,running_major:o.major,held_major:r.major,reason:`redskilled ${t} is published and this daemon runs ${n}; a major version is deliberately never adopted by the background check, because a breaking change must not arrive on a machine that is holding Workers`,action:gb(r.major,e.supervised)}}function gb(e,n){let t=`install the ${e}.x bundle (update this machine's plugin pin), then `;return n?`${t}re-point the unit and restart it: ${Oe("red-skills-redskilled",["unit","install"])} && systemctl --user restart redskilled.service`:`${t}stop this daemon \u2014 the next client start resolves the newly installed bundle`}function Xc(e){let n=e.running.trim();if(it(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||re(t)===null?{act:"hold",reason:"published-unknown"}:Hs(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function it(e){let n=e.trim();return re(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function Zc(e=process.env){return e[Gs]==="1"}var qs=class extends Error{code=Vc;searched;constructor(n,t){super(`${Vc}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
65
+ `).filter(cy).map(uy)}function ad(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,ay(t)):n.delete(t.worker_id));return[...n.values()]}function ay(e){let n={...e.memory_high!=null?{memory_high:e.memory_high}:{},...e.memory_max!=null?{memory_max:e.memory_max}:{},...e.cpu_weight!=null?{cpu_weight:e.cpu_weight}:{}};return{worker_id:e.worker_id,project_label:e.project_label,pid:e.pid,started_at:e.ts,workspace_path:e.workspace_path,...e.log_path!=null?{log_path:e.log_path}:{},isolated:e.isolated,...e.unit!=null?{unit:e.unit}:{},...Object.keys(n).length>0?{budget:n}:{},warnings:[]}}function dy(e){return{...e}}function cy(e){return e.version===1&&typeof e.ts=="string"&&typeof e.worker_id=="string"&&(e.event==="worker-birth"||e.event==="worker-death"||e.event==="worker-budget-kill"||e.event==="daemon-stop")}function uy(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:ve(e.project_label)??"",pid:Number(e.pid??0),workspace_path:ve(e.workspace_path)??"",log_path:ve(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:ve(e.unit),memory_high:ve(e.memory_high),memory_max:ve(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:ve(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:ve(e.signal),reason:ve(e.reason)}}function ve(e){return e==null||e===""?null:String(e)}function dd(e){let n=[...e.projects].sort((i,l)=>i.project_label.localeCompare(l.project_label)),t=e.backoffUntilMs??null,r=t!=null&&e.nowMs<t,o=[],s=[];for(let i of n){let l=Math.max(0,e.live[i.project_label]??0),a=Object.prototype.hasOwnProperty.call(e.queue,i.project_label),d=a?e.queue[i.project_label]??null:null,u={project_label:i.project_label,queue_depth:d,target:i.target,live:l};if(r){o.push({...u,outcome:"backing-off",wanted:0,detail:`the host refused a Worker, so no project is asked for one again before ${new Date(t).toISOString()}`});continue}let p=e.birthHaltUntilMs?.[i.project_label];if(p!=null&&e.nowMs<p){o.push({...u,outcome:"birth-halted",wanted:0,detail:`project ${JSON.stringify(i.project_label)} lost 3 Workers in a row inside 60000ms of birth, so it is not asked for another before ${new Date(p).toISOString()} \u2014 a Worker that cannot survive boot will not survive the next one either, and every birth spends host quota shared with every project`});continue}if(d==null){o.push({...u,outcome:"queue-unknown",wanted:0,detail:a?`the last poll produced no depth for project ${JSON.stringify(i.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(i.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...u,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(i.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,i.target),d)-l);if(f===0){o.push({...u,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for none`});continue}o.push({...u,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for ${f} more`});for(let m=0;m<f;m+=1)(s[m]??(s[m]=[])).push({project_label:i.project_label,index:l+m,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function cd(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}var Zt={shortLifeStreak:0,haltUntilMs:null};function ud(e,n,t){if(n>=6e4)return Zt;let r=e.shortLifeStreak+1;return r<3?{shortLifeStreak:r,haltUntilMs:null}:{shortLifeStreak:r,haltUntilMs:t+6e5}}function pd(e,n){let t={};for(let[r,o]of Object.entries(e))o.haltUntilMs!=null&&n<o.haltUntilMs&&(t[r]=o.haltUntilMs);return t}function md(e){let n=e.workers.map(py),t=[...new Set([...n.map(o=>o.project_label),...e.projects??[]])].filter(o=>o!=="").sort(),r=n.filter(o=>o.survives).map(o=>o.worker_id);return{version:1,running:!0,stopped:!0,reason:e.reason,socket_path:e.socketPath,daemon_version:e.daemonVersion,pid:e.pid,holding:{workers:n,projects:t},surviving:r,detail:my({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function hd(e){return{version:1,running:!1,stopped:!1,reason:"not-running",socket_path:e,daemon_version:null,pid:null,holding:{workers:[],projects:[]},surviving:[],detail:`no redskilled daemon is answering on ${JSON.stringify(e)}, so there was nothing to stop`}}function py(e){return{worker_id:e.worker_id,project_label:e.project_label,pid:e.pid,unit:e.unit??null,isolated:e.isolated,survives:!0}}function fy(e){return e==="requested"?"an operator asked for it":e==="signal"?"the daemon was signalled":e==="idle"?"the daemon was idle and held nothing":e==="replaced"?"a newer published bundle is taking the session over":"no daemon was running"}function my(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${fy(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${fd(e.held,"Worker")} across ${fd(e.projects,"project")}, and ${e.surviving} of them survive it \u2014 a Worker is an init-system unit, so this is a restart and not an evacuation`}function fd(e,n){return`${e} ${n}${e===1?"":"s"}`}function es(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.holding;return n.version===1&&typeof n.running=="boolean"&&typeof n.stopped=="boolean"&&typeof n.reason=="string"&&typeof n.socket_path=="string"&&typeof n.detail=="string"&&(n.daemon_version===null||typeof n.daemon_version=="string")&&(n.pid===null||typeof n.pid=="number")&&t!=null&&Array.isArray(t.workers)&&Array.isArray(t.projects)&&Array.isArray(n.surviving)}import{chmod as hy,mkdir as gy,readFile as yy,rm as ky,writeFile as Ry}from"node:fs/promises";import{dirname as gd,join as bd}from"node:path";import{tmpdir as yd}from"node:os";var by="redskilled.machine.claim.toon",_y="REDSKILLED_MACHINE_DIR",wy=8,Le=class extends Error{constructor(t,r,o){super(Sy(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},kd;function _d(){return kd??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},kd}function xy(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[_y]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||yd():yd();return bd(o,`redskilled-${e.machineIdHash}`)}function er(e){return bd(xy(e),by)}function nr(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??H;async function s(){let a;try{a=await yy(e,"utf8")}catch(u){if(u.code==="ENOENT"||ns(u))return;throw u}let d=Ey(a);return Py(d)?d:void 0}function i(a,d){return{version:1,scope:"machine",pid:a.pid,start_time:a.startTime,uid:a.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}async function l(){try{return await ky(e,{force:!0}),!0}catch(a){if(ns(a))return!1;throw a}}return{claimPath:e,read:s,async claim(a){await gy(gd(e),{recursive:!0,mode:1023})!=null&&await hy(gd(e),1023).catch(()=>{});let u=!1;for(let p=0;p<wy;p+=1){let f=i(a,r());try{return await Ry(e,vy(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:u,claim:f}}catch(g){if(g.code!=="EEXIST"){if(ns(g))return{claimed:!1,reason:"stale-claim-not-reapable"};throw g}}let m=await s();if(!m){if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable"};u=!0;continue}if(Rd(m,a,n.socketPath))return{claimed:!0,reaped:u,claim:m};if(await o(m.pid))return{claimed:!1,reason:"held",claim:m};if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable",claim:m};u=!0}return{claimed:!1,reason:"contended"}},async release(a){let d=await s();return!d||!Rd(d,a,n.socketPath)?!1:await l()}}}function wd(e,n,t){return{kind:"machine",claim_path:e,owner_uid:t.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath}}function xd(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.kind==="machine"&&typeof n.claim_path=="string"&&typeof n.owner_uid=="number"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&typeof n.socket_path=="string"}function Sy(e,n,t){let r=t==null?"":` \u2014 held by pid ${t.pid} (uid ${t.uid}) on socket ${JSON.stringify(t.socket_path)}`;return n==="held"?`this machine already has a redskilled daemon${r}; a second one would void the host budget, so none was started. Reach that daemon, or stop it before starting another.`:n==="stale-claim-not-reapable"?`the redskilled machine claim ${JSON.stringify(e)} is stale and cannot be removed by this user${r}; remove it as its owner, then start again. No second daemon was started.`:`the redskilled machine claim ${JSON.stringify(e)} changed hands repeatedly; no daemon was started.`}function ns(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function Rd(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function vy(e){return`${W(e,{keyedMapCollapse:!0})}
66
+ `}function Ey(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Y(n)}catch{return null}}}function Py(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||n.scope!=="machine"||!Number.isInteger(n.pid)||n.pid<=0||!Number.isInteger(n.uid))return!1;for(let t of["start_time","machine_id_hash","session_key_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var Dy=["worker_id","slot","workspace_path","log_path"],ts=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${Dy.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},jy=/\{\{([a-z_]+)\}\}/g;function Oy(e,n){let t=(i,l)=>i.replace(jy,(a,d)=>{switch(d){case"worker_id":return n.worker_id;case"slot":return String(n.slot);case"workspace_path":return n.workspace_path;case"log_path":return n.log_path??"";default:throw new ts(d,l)}}),r=e.argv.map((i,l)=>t(i,`argv word ${l}`)),o={};for(let[i,l]of Object.entries(e.env??{}))o[i]=t(l,`env entry ${JSON.stringify(i)}`);let s=e.log_path==null?void 0:t(e.log_path,"the log path");return{argv:r,env:o,...s==null||s===""?{}:{log_path:s}}}function Sd(e,n,t){let r=Oy(e,n),o=r.log_path??n.log_path,[s,...i]=r.argv;if(s===void 0||s==="")throw new Error(`redskilled cannot start a Worker for project ${JSON.stringify(t.project_label)}: its launch expanded to an argv with no command`);return{worker_id:n.worker_id,project_label:t.project_label,workspace_path:n.workspace_path,...o==null||o===""?{}:{log_path:o},command:s,args:i,env:r.env}}function rs(e,n){if(!Array.isArray(e)||e.length===0)throw new Error(`redskilled needs an argv to register project ${JSON.stringify(n)}: a registration with nothing to run is a project the host could never start a Worker for`);return e.map((t,r)=>{if(typeof t!="string"||t==="")throw new Error(`redskilled needs every word of an argv to be a non-empty string, and word ${r} of project ${JSON.stringify(n)} is not`);return t})}function os(e,n){if(e!=null){if(typeof e!="string"||e.trim()==="")throw new Error(`redskilled needs a declared log path to be a non-empty string to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}: a project that declares an empty path states a Worker whose output no surface can ever show, which reads as a Worker with nothing to say`);return e}}function ss(e,n){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error(`redskilled needs a launch env to be a map of strings to register project ${JSON.stringify(n)}, not ${JSON.stringify(e)}`);let t={};for(let[r,o]of Object.entries(e)){if(r==="")throw new Error(`redskilled needs every launch env name of project ${JSON.stringify(n)} to be named`);if(typeof o!="string")throw new Error(`redskilled needs every launch env value to be a string, and ${JSON.stringify(r)} of project ${JSON.stringify(n)} is ${JSON.stringify(o)}`);t[r]=o}return t}var Ay=3e5,Ly=.5,ls=class extends Error{constructor(t){super(`redskilled already holds a registration for project ${JSON.stringify(t.project_label)}, registered at ${t.registered_at} for a target of ${t.target} and standing until ${t.renew_by}: a project contributes one registration, so a second one is refused rather than silently replacing the first`);this.held=t;this.name="RedskilledProjectRegisteredError"}};function vd(e,n){if(n.held!=null)throw new ls(n.held);let t=is(e.project_label,"a project label"),r=is(e.selector,"a selector"),o=rs(e.argv,t),s=ss(e.env,t),i=os(e.log_path,t),l=is(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.target)}`);let a=e.renew_within_ms??Ay;if(!Number.isFinite(a)||a<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let d=Date.parse(n.now);if(!Number.isFinite(d))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(n.now)}`);return{version:1,project_label:t,selector:r,argv:o,workspace_path:l,env:s,...i==null?{}:{log_path:i},target:e.target,registered_at:new Date(d).toISOString(),renew_within_ms:a,renew_by:new Date(d+a).toISOString(),renewed_at:new Date(d).toISOString(),renewals:0,session_renewals:0,launch_revision:0}}var Ve=class extends Error{constructor(t,r={kind:"never"}){super($y(t,r));this.projectLabel=t;this.absence=r;this.name="RedskilledProjectUnregisteredError"}};function $y(e,n){let t=JSON.stringify(e);if(n.kind==="lapsed"){let r=n.registered_at==null?"":` (registered ${n.registered_at})`;return`redskilled holds no registration for project ${t} to renew: it lapsed at ${n.at}${r}; renewal stopped \u2014 find why before registering it again`}return n.kind==="stopped"?`redskilled holds no registration for project ${t} to renew: it was stopped at ${n.at}; this is the requested state, so there is nothing to renew`:n.kind==="orphaned"?`redskilled holds no registration for project ${t} to renew: it is registered on a daemon this socket does not reach \u2014 do not register it again`:`redskilled holds no registration for project ${t} to renew: it was never registered on this host; register it first, stating the selector, the argv and the target`}function Ed(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to date a renewal, not ${JSON.stringify(n.now)}`);let r=n.renew_within_ms??e.renew_within_ms;if(!Number.isFinite(r)||r<=0)throw new Error(`redskilled needs a positive renewal window to renew project ${JSON.stringify(e.project_label)}, not ${JSON.stringify(n.renew_within_ms)}`);let o=n.launch==null?{env:e.env??{},launch_revision:e.launch_revision??0}:{argv:rs(n.launch.argv,e.project_label),env:ss(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=n.launch==null?e.log_path:os(n.launch.log_path,e.project_label),{log_path:i,...l}=e;return{...l,...s==null?{}:{log_path:s},...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1,session_renewals:(e.session_renewals??e.renewals)+1}}function as(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(n.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,n.liveWorkers??0),s=n.queue,i=s!=null&&s.outcome==="counted"?s.depth:null,l=i!=null&&i>0?"open-work":o>0?"live-worker":null;if(l==null){let a=i===0?"drained":"uncounted";return{registration:e,verdict:a,detail:a==="drained"?`project ${r} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${r}, and an uncounted queue never sustains a registration \u2014 it stands on its own deadline of ${e.renew_by}`}}return{registration:{...e,renew_by:new Date(t+e.renew_within_ms).toISOString(),sustained_at:new Date(t).toISOString(),sustains:(e.sustains??0)+1,sustained_by:l,renewals:e.renewals+1,session_renewals:e.session_renewals??e.renewals},verdict:l,detail:l==="open-work"?`project ${r} has ${i} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function Ty(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function Pd(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*Ly;if(r(t))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return r(o)?"self-renewing":"running-on"}function Dd(e,n){let t=[],r=[];for(let o of e)(Ty(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function ds(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.project_label=="string"&&typeof n.selector=="string"&&Array.isArray(n.argv)&&n.argv.every(t=>typeof t=="string")&&typeof n.workspace_path=="string"&&Number.isInteger(n.target)&&typeof n.registered_at=="string"&&typeof n.renew_within_ms=="number"&&typeof n.renew_by=="string"&&(n.renewed_at===void 0||typeof n.renewed_at=="string")&&(n.renewals===void 0||Number.isInteger(n.renewals))&&(n.session_renewals===void 0||Number.isInteger(n.session_renewals))&&(n.env===void 0||Iy(n.env))&&(n.log_path===void 0||typeof n.log_path=="string")&&(n.launch_revision===void 0||Number.isInteger(n.launch_revision))&&(n.sustained_at===void 0||typeof n.sustained_at=="string")&&(n.sustains===void 0||Number.isInteger(n.sustains))&&(n.sustained_by===void 0||n.sustained_by==="open-work"||n.sustained_by==="live-worker")}function Iy(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function is(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var Ny={ping:"host-read","host-state":"host-read","statusline-payload":"host-read",shutdown:"daemon-life","worker-start":"project-write","worker-stop":"project-write","worker-recycle":"project-write","worker-steer":"project-write","worker-heartbeat":"project-write","project-register":"project-write","project-renew":"project-write","project-deregister":"project-write"};function jd(e){return`worker-${e}`}function Od(e){let n=Ny[e.op]??"project-write",t=e.sessionProject??null,r=e.targetProject??null,o={version:1,op:e.op,reach:n,session_project:t,target_project:r};return n==="host-read"?{...o,permitted:!0,verdict:"permitted-host-read",reason:`redskilled permitted ${e.op}: a session reads the whole host, whichever project it was started in`}:n==="daemon-life"?{...o,permitted:!0,verdict:"permitted-daemon-life",reason:`redskilled permitted ${e.op}: it acts on the daemon's own process, not on any project's Workers`}:t==null||t===""?{...o,permitted:!0,verdict:"permitted-unattributed",reason:`redskilled permitted ${e.op}: the session named no project of its own, so there is nothing to refuse it against`}:r!=null&&r===t?{...o,permitted:!0,verdict:"permitted-own-project",reason:`redskilled permitted ${e.op}: the target belongs to project ${JSON.stringify(t)}, which is this session's own`}:{...o,permitted:!1,verdict:"refused-cross-project",reason:`redskilled refused ${e.op} from a session in project ${JSON.stringify(t)}: ${r==null?"it names no Worker of that project":`the target belongs to project ${JSON.stringify(r)}`}. A session reads the whole host and writes only its own project.`}}function Ad(e){return e==="single-object"?"rest":"graphql"}function I(e,n,t,r,o,s){return{key:e,kind:"read",cardinality:n,volatility:t,surface:s??Ad(n),budget:r,...s?{only:s}:{},why:o}}function q(e,n,t,r){return{key:e,kind:"write",cardinality:"single-object",surface:n,budget:t,why:r}}var Ld=[I("issue view","single-object","stable-poll","rest","one issue by number, repeatedly polled while usually unchanged; REST answers in one request"),I("pr view","single-object","stable-poll","rest","one pull request by number, polled per Worker per iteration"),I("repo view","single-object","stable-poll","rest","one repository's own metadata, repeatedly read while usually unchanged"),I("run view","single-object","stable-poll","rest","one Actions run repeatedly polled to terminal; Actions has no GraphQL surface"),I("release view","single-object","stable-poll","rest","one release by tag, repeatedly checked while usually absent or unchanged"),I("pr diff","single-object","one-shot","rest","one pull request's diff, read once for review and served by a REST media type"),I("issue list","multi-node","stable-poll","graphql","a repeatedly polled, usually-unchanged issue connection; GraphQL avoids N REST pages"),I("pr list","multi-node","stable-poll","graphql","a repeatedly polled, usually-unchanged pull-request connection; GraphQL avoids N REST pages"),I("pr checks","multi-node","stable-poll","graphql","check contexts form a connection repeatedly polled while awaiting terminal state"),I("release list","multi-node","stable-poll","rest","release waits poll a usually-unchanged list; Releases has no GraphQL connection gh reads","rest"),I("run list","multi-node","stable-poll","rest","run waits poll a usually-unchanged list; Actions has no GraphQL surface","rest"),I("label list","multi-node","one-shot","graphql","a label connection loaded once for the current operation"),I("issue list (search)","multi-node","stable-poll","search","queue discovery polls usually-unchanged search results through the 30/min search connection"),I("pr list (search)","multi-node","stable-poll","search","PR discovery polls usually-unchanged search results through the 30/min search connection"),I("search issues","multi-repository","one-shot","search","a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),I("search prs","multi-repository","one-shot","search","a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),I("search repos","multi-repository","one-shot","search","a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),I("api graphql","multi-node","one-shot","graphql","the caller supplies one explicit GraphQL query rather than a routed poll"),I("api rest","single-object","one-shot","rest","the caller supplies one explicit REST path rather than a routed poll"),q("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),q("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),q("issue close","graphql","graphql","gh closes with the closeIssue mutation"),q("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),q("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),q("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),q("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),q("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),q("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),q("pr close","graphql","graphql","gh closes with a GraphQL mutation"),q("pr edit","graphql","graphql","gh edits with GraphQL mutations"),q("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),q("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),q("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],My=new Map(Ld.map(e=>[e.key,e]));function $d(e){let n=[],t=0;for(;t<e.length&&e[t].startsWith("-");)t+=e[t]==="-R"||e[t]==="--repo"?2:1;for(;t<e.length&&!e[t].startsWith("-")&&n.length<2;)n.push(e[t]),t+=1;return n}function cs(e){let n=$d(e);if(n.length===0)return"";if(n[0]==="api")return n[1]==="graphql"?"api graphql":"api rest";let t=n.length===1?n[0]:`${n[0]} ${n[1]}`;return n[1]==="list"&&e.includes("--search")?`${t} (search)`:t}var tr=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(n){let t=cs(n);super(`unclassified GitHub operation ${JSON.stringify(t||"(empty argv)")}: add an entry to GITHUB_OPERATIONS in packages/github/surface.ts stating its cardinality. Defaulting to GraphQL is what sent every single-object poll to the node-point pool (ADR 0132 decision 4).`),this.operation=t,this.args=[...n]}};function Td(e){return My.get(cs(e))??null}function Id(e){let n=Td(e);if(!n)throw new tr(e);return n}function us(e){return Id(e).surface}var Md="rate_limit",Cd={rest:"core",graphql:"graphql",search:"search"},Ee=["rest","graphql","search"];function ir(e,n){return{version:1,origin:"asked",outcome:"unanswered",source:"GET /rate_limit",asked_at:e,request_count:0,pools:{rest:null,graphql:null,search:null},unreported_pools:[...Ee],detail:n??"no balance has been asked for yet, so none is known"}}var fs=15e3,gn=.15,or=[{at_or_below_fraction:0,every_ms:fs,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:gn,every_ms:3e4,why:"inside the reserved band: the posture can change between two calls"},{at_or_below_fraction:.5,every_ms:12e4,why:"below half: tightening, because the band is now reachable inside one window"},{at_or_below_fraction:1,every_ms:6e5,why:"above half: rare, because nothing this balance decides is anywhere close"}],ps=2;function Wd(e,n){let t=Nd(e),r=Nd(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let l of Ee){let a=Cd[l],d=r[a],u=Hy(l,a,d);o[l]=u,u==null&&s.push(l)}let i=Ee.length-s.length;return{version:1,origin:"asked",outcome:i>0?"asked":"unanswered",source:"GET /rate_limit",asked_at:n.askedAt,request_count:1,pools:o,unreported_pools:s,detail:i>0?`the token's own answer for ${i} of ${Ee.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function ms(e){try{let n=await e.transport();return Wd(n,{askedAt:e.now})}catch(n){let t=n instanceof Error?n.message:String(n);return{...ir(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function hs(e){let n=null;for(let t of Ee){let r=e.pools[t];r!=null&&(n==null||r.fraction<n.fraction)&&(n=r)}return n}function lr(e,n){let t=hs(e);if(t==null)return sr(gn).every_ms;let r=sr(t.fraction);if(t.remaining>0)return r.every_ms;let o=Bd(n.now,t.reset_at);return o==null?r.every_ms:Math.max(fs,Math.min(r.every_ms,o))}function gs(e,n=gn){return Math.ceil(e.limit*n)}function Hd(e,n,t=gn){let r=e.pools[n];return r==null?"unknown":r.remaining<=0?"spent":r.remaining<gs(r,t)?"reserved":"open"}function ys(e){let n=e.reservedFraction??gn,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:sr(n).every_ms*ps,stale:!1,posture:"unknown",reserved_fraction:n,next_poll_ms:sr(n).every_ms,pools:[],unreported_pools:[...Ee],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let r=lr(t,{now:e.now}),o=e.stalenessMs??r*ps,s=Bd(t.asked_at,e.now),i=t.outcome==="asked"&&(s==null||s>o),l=Ee.map(u=>t.pools[u]).filter(u=>u!=null),a=Wy(t,n),d=hs(t);return{version:1,origin:"asked",outcome:t.outcome,asked_at:t.asked_at,age_ms:s,threshold_ms:o,stale:i,posture:a,reserved_fraction:n,next_poll_ms:r,pools:l,unreported_pools:t.unreported_pools,reason:i?`this balance is stale: asked ${s==null?"at an unreadable instant":`${s}ms ago`}, past the ${o}ms window, so the posture below is the last one the token confirmed and not the current one`:Cy(a,d,t,n)}}function ks(e){if(!bs(e))return!1;let n=e;return n.version===1&&n.origin==="asked"&&(n.outcome==="asked"||n.outcome==="unanswered")&&(n.asked_at===null||typeof n.asked_at=="string")&&(n.age_ms===null||typeof n.age_ms=="number")&&typeof n.threshold_ms=="number"&&typeof n.stale=="boolean"&&typeof n.posture=="string"&&typeof n.reserved_fraction=="number"&&typeof n.next_poll_ms=="number"&&Array.isArray(n.pools)&&Array.isArray(n.unreported_pools)&&typeof n.reason=="string"}function Cy(e,n,t,r){if(n==null)return t.detail;let o=gs(n,r);switch(e){case"spent":return`the ${n.pool} pool is spent and resets at ${n.reset_at}: work is not queued, it is refused`;case"reserved":return`the ${n.pool} pool has ${n.remaining} of ${n.limit} left, inside the reserved band of ${o}: convenience reads are refused and the claim, a landing and a closing comment still pass`;default:return`the ${n.pool} pool is the tightest at ${n.remaining} of ${n.limit}, above the reserved band of ${o}`}}function Wy(e,n){let t="unknown";for(let r of Ee){if(e.pools[r]==null)continue;let o=Hd(e,r,n);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function sr(e){for(let n of or)if(e<=n.at_or_below_fraction)return n;return or[or.length-1]}function Hy(e,n,t){if(!bs(t))return null;let r=rr(t.limit),o=rr(t.remaining),s=rr(t.used),i=rr(t.reset);return r==null||r<=0||o==null?null:{pool:e,resource:n,limit:r,remaining:o,used:s??0,reset_at:i==null?"":new Date(i*1e3).toISOString(),fraction:o/r}}function Rs(e){let n=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let r=await t(`${n}/${Md}`,{method:"GET",headers:{authorization:`bearer ${e.token}`,accept:"application/vnd.github+json"}});if(!r.ok)throw new Error(`the balance ask was refused with HTTP ${r.status}`);return await r.json()}}function Bd(e,n){let t=Date.parse(e),r=Date.parse(n);return!Number.isFinite(t)||!Number.isFinite(r)?null:Math.max(0,r-t)}function rr(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function Nd(e){return bs(e)?e:{}}function bs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qd(e){return{generated_at:e.now,hour:Fd("hour",36e5,e),day:Fd("day",864e5,e)}}function Xn(e,n,t){let r=Yn(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(l=>{let a=Yn(n(l));return a==null?!1:r==null||r-a<=o});return i.length<=s?i:i.slice(i.length-s)}function Fd(e,n,t){let r=Yn(t.now),o=r==null?null:r-n,s=e==="hour"?"1h":"24h",i=t.observations.map(p=>({observation:p,at:Yn(p.observed_at)})).filter(p=>p.at!=null&&Kd(p.at,o,r)).sort((p,f)=>p.at-f.at),l=t.outcomes.map(p=>Yn(p.ts)).filter(p=>p!=null&&Kd(p,o,r)),a=Ud(i,p=>p.tokens,"tokens",s),d=Ud(i,p=>p.tools,"tools",s),u=[];return i.length===0?u.push("worker-vitals"):(a.samples===0&&u.push("worker-vitals.tokens"),d.samples===0&&u.push("worker-vitals.tools")),l.length===0&&u.push("worker-outcomes"),{window:e,window_ms:n,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:a,tools_per_min:d,issues_per_hour:By(l.length,n,s),runner_share:Gd("runner",i,p=>p.runner,s),model_share:Gd("model",i,p=>p.model,s),unavailable:u}}function Ud(e,n,t,r){let o=new Map,s=0;for(let d of e){let u=n(d.observation);if(u==null||!Number.isFinite(u))continue;s+=1;let p=o.get(d.observation.worker_id)??[];p.push({at:d.at,count:u}),o.set(d.observation.worker_id,p)}if(s===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${r}`,samples:0};let i=0,l=null,a=null;for(let d of o.values()){if(d.length<2)continue;for(let f=1;f<d.length;f++){let m=d[f-1],g=d[f];m==null||g==null||(i+=Math.max(0,g.count-m.count))}let u=d[0],p=d[d.length-1];u!=null&&(l=l==null?u.at:Math.min(l,u.at)),p!=null&&(a=a==null?p.at:Math.max(a,p.at))}return l==null||a==null||a<=l?{value:null,absent_reason:`the last ${r} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:s}:{value:i/((a-l)/6e4),absent_reason:null,samples:s}}function By(e,n,t){return e===0?{value:null,absent_reason:`no Worker outcome was recorded in the last ${t}`,samples:0}:{value:e/(n/36e5),absent_reason:null,samples:e}}function Gd(e,n,t,r){let o=new Map;for(let d of n){let u=t(d.observation);u!=null?o.set(d.observation.worker_id,u):o.has(d.observation.worker_id)||o.set(d.observation.worker_id,null)}let s=new Map,i=0,l=0;for(let d of o.values()){if(d==null){l+=1;continue}i+=1,s.set(d,(s.get(d)??0)+1)}let a=[...s.entries()].map(([d,u])=>({key:d,worker_count:u,share:u/i})).sort((d,u)=>u.worker_count-d.worker_count||d.key.localeCompare(u.key));return{dimension:e,attributed_workers:i,unattributed_workers:l,shares:a,absent_reason:a.length>0?null:o.size===0?`no Worker was observed in the last ${r}`:`no Worker published a ${e} in the last ${r}`}}function Kd(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function Yn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function Jd(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.generated_at=="string"&&Vd(n.hour)&&Vd(n.day)}function Vd(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.window=="string"&&typeof n.window_ms=="number"&&_s(n.tokens_per_min)&&_s(n.tools_per_min)&&_s(n.issues_per_hour)&&Array.isArray(n.unavailable)}function _s(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return(n.value===null||typeof n.value=="number")&&(n.absent_reason===null||typeof n.absent_reason=="string")&&Number.isInteger(n.samples)}import{execFileSync as Fy}from"node:child_process";import{existsSync as Uy,readFileSync as ar,readdirSync as Gy}from"node:fs";import{dirname as Ky,join as qe}from"node:path";function Zn(e){let n=Qn(e),t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let s=hn(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function Qd(e){let n=[],t=[];for(let r of e.workers){let o=Zn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(Qn(r).memory_max??Qn(r).memory_high)==null?"this Worker declared no memory budget and the host derived no ceiling for it, so the sampler has none to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let s=e.rss[r.worker_id];if(typeof s!="number"||!Number.isFinite(s)){t.push({worker_id:r.worker_id,reason:"the host produced no RSS reading for this Worker on this tick, and an unmeasured Worker is never killed on suspicion"});continue}if(!(s<=o.bytes)){if(e.sources?.[r.worker_id]==="cgroup"&&o.name==="MemoryMax"){t.push({worker_id:r.worker_id,reason:`this Worker's ${o.name} of ${o.declared} is held by the kernel on its own cgroup, and the reading is memory.current \u2014 which counts reclaimable page cache the kernel drops before it kills anything, so the daemon does not duplicate an enforcement that can tell cache from anonymous memory`});continue}n.push(Vy(r,o,s))}}return{terminations:n,unenforceable:t}}function Vy(e,n,t){let r=`Worker ${JSON.stringify(e.worker_id)} of project ${JSON.stringify(e.project_label)}`;return{version:1,worker_id:e.worker_id,project_label:e.project_label,outcome:"terminated-over-memory-budget",classification:"budget-exceeded",stall:!1,budget_name:n.name,budget_declared:n.declared,budget_bytes:n.bytes,observed_rss_bytes:t,workspace_path:e.workspace_path,reason:`redskilled terminated ${r}: its tree RSS of ${t} bytes exceeded its ${n.name} budget of ${n.declared} (${n.bytes} bytes). This is a budget termination, not a stall, and the work in ${JSON.stringify(e.workspace_path)} is handed forward.`}}var qy=4096;function zd(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return r;let o={},s={},i={},l=Qy(e,t,n);for(let[p,f]of l){let m=Xy(f);m!=null&&(o[p]=m.memoryBytes,m.cpuSeconds!=null&&(s[p]=m.cpuSeconds),i[p]="cgroup")}let a=e.filter(p=>i[p.worker_id]==null);if(a.length===0)return{rss:o,cpu_seconds:s,sources:i};let d=nk(t,n);if(d.size===0)return{rss:o,cpu_seconds:s,sources:i};let u=new Map;for(let p of d.values()){let f=u.get(p.ppid);f?f.push(p.pid):u.set(p.ppid,[p.pid])}for(let p of a){if(!d.has(p.pid))continue;let f=0,m=0,g=[p.pid],_=new Set;for(;g.length>0;){let k=g.pop();if(_.has(k))continue;_.add(k);let x=d.get(k);if(x){f+=x.rssBytes,m+=x.cpuSeconds;for(let v of u.get(k)??[])g.push(v)}}o[p.worker_id]=f,s[p.worker_id]=m,i[p.worker_id]="process-tree"}return{rss:o,cpu_seconds:s,sources:i}}var Jy="/sys/fs/cgroup";function Qy(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let s=t.cgroupRoot??Jy,i=e.filter(a=>a.unit!=null&&a.unit!=="");if(i.length===0)return r;let l=zy(s,t);for(let a of i)for(let d of l){let u=qe(d,a.unit);if(Uy(qe(u,"memory.current"))){r.set(a.worker_id,u);break}}return r}function zy(e,n){let t=n.selfCgroupPath??Yy(),r=[],o=l=>{r.includes(l)||r.push(l)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(qe(e,s));let l=Ky(s);if(l===s)break;s=l}o(e);let i=n.uid??process.getuid?.();return i!=null&&o(qe(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),r}function Yy(){try{for(let e of ar("/proc/self/cgroup","utf8").split(`
67
+ `))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function Xy(e){let n;try{n=ar(qe(e,"memory.current"),"utf8")}catch{return null}let t=Number(n.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:Zy(e)}}function Zy(e){let n;try{n=ar(qe(e,"cpu.stat"),"utf8")}catch{return null}return ek(n)}function ek(e){for(let n of e.split(`
68
+ `)){let[t,r]=n.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(r);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function nk(e,n){return n.procRoot!=null||e==="linux"?lk(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?sk(tk(n.psTable)):new Map}function tk(e){try{return(e??rk)()}catch{return""}}function rk(){return Fy("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var ok=1024;function sk(e){let n=new Map;for(let t of e.split(`
69
+ `)){let r=t.trim().split(/\s+/);if(r.length!==4)continue;let[o,s,i]=r.slice(0,3).map(Number);if(![o,s,i].every(a=>a!=null&&Number.isSafeInteger(a)&&a>=0))continue;let l=ik(r[3]);l!=null&&n.set(o,{pid:o,ppid:s,rssBytes:i*ok,cpuSeconds:l})}return n}function ik(e){let n=e.indexOf("-"),t=n<0?0:Number(e.slice(0,n));if(!Number.isFinite(t)||t<0)return null;let r=e.slice(n+1).split(":"),o=t*86400,s=1;for(let i=r.length-1;i>=0;i--){let l=Number(r[i]);if(!Number.isFinite(l)||l<0||r[i]==="")return null;o+=l*s,s*=60}return o}function lk(e){let n=new Map,t;try{t=Gy(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=ar(qe(e,r,"stat"),"utf8")}catch{continue}let s=dk(o);s&&n.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*qy,cpuSeconds:s.cpuTicks/ak})}return n}var ak=100;function dk(e){let n=e.lastIndexOf(")");if(n<0)return null;let t=Number(e.slice(0,e.indexOf(" "))),r=e.slice(n+1).trim().split(/\s+/),o=Number(r[1]),s=Number(r[11]),i=Number(r[12]),l=Number(r[21]);return!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||!Number.isFinite(l)||!Number.isFinite(s)||!Number.isFinite(i)?null:{pid:t,ppid:o,rssPages:Math.max(0,l),cpuTicks:Math.max(0,s)+Math.max(0,i)}}var ck=["api","graphql"],uk=us(ck);function pk(e,n="https://api.github.com"){return e==="graphql"?`${n}/graphql`:n}var Yd=100,Ss=6e4,fk=2*Ss,mk=7*24*60*60*1e3,ws=class extends Error{constructor(t,r,o){super(`redskilled polls every repository with one host token ${JSON.stringify(o)}, and project ${JSON.stringify(t)} declares its own credential ${JSON.stringify(r)}: a project needing its own credential invalidates the host-scoped poller (ADR 0130 Amendment 1) rather than bending it, so the poller returns to the projects instead of reaching this repository under the wrong identity`);this.projectLabel=t;this.tokenRef=r;this.hostTokenRef=o;this.name="RedskilledSplitCredentialError"}};function vs(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new ws(t.project_label,t.token_ref,n)}function hk(e,n={now:new Date(0).toISOString()}){kk(e);let t=n.closedWindowMs??mk,r=Date.parse(n.now);if(!Number.isFinite(r))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(n.now)}`);let o=new Date(r-Math.max(0,t)).toISOString(),s=e.map((a,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:a}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { cost remaining resetAt }",...s.flatMap(({alias:a,search_alias:d,project:u})=>{let p=JSON.stringify(u.owner),f=JSON.stringify(u.name),m=JSON.stringify(`repo:${u.owner}/${u.name} is:closed closed:>=${o}`);return[` ${a}: repository(owner: ${p}, name: ${f}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${d}: search(query: ${m}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
70
+ `),aliases:s,closed_since:o}}function gk(e,n,t){let r=yn(n),o=yn(r.data),s=Array.isArray(r.errors)?r.errors.map(yn):[],i=Rk(o.rateLimit,s),l=e.aliases.map(({alias:a,search_alias:d,project:u})=>{let p=u.owner+"/"+u.name,f=o[a],m=s.find(g=>Xd(g.path,a)||Xd(g.path,d));if(dr(f)){let g=Zd(f.open_pull_requests),_=Zd(f.open_issues),k=bk(o[d]);if(g!=null&&_!=null&&k!=null)return{project_label:u.project_label,repository:p,outcome:"counted",counts:{open_pull_requests:g,open_issues:_,recently_closed:k},detail:`counted ${p} for project ${JSON.stringify(u.project_label)}`}}return i.exhausted||oc(m)?{project_label:u.project_label,repository:p,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${p} answered, so this project has no counts rather than zero counts${i.reset_at==null?"":`; the quota resets at ${i.reset_at}`}`}:{project_label:u.project_label,repository:p,outcome:"unreachable",counts:null,detail:`${p} is not reachable with the host token: ${xs(m?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:l.length,rate_limit:i,projects:l}}function yk(e){return{version:1,fetched_at:e,request_count:0,project_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1,point_cost:null},projects:[]}}async function ec(e){if(e.projects.length===0)return yk(e.now);vs(e.projects,e.hostTokenRef);let n=hk(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return gk(n,t,{fetchedAt:e.now})}catch(t){let r=t instanceof Error?t.message:String(t),o=/rate limit|secondary rate|429/i.test(r);return{version:1,fetched_at:e.now,request_count:1,project_count:e.projects.length,rate_limit:{remaining:null,reset_at:null,exhausted:o,point_cost:null},projects:e.projects.map(s=>({project_label:s.project_label,repository:`${s.owner}/${s.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${s.owner}/${s.name} answered: ${r}`}))}}}function nc(e){let n=e.stalenessMs??fk,t=e.activity;if(t==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:n,stale:!1,request_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1,point_cost:null},projects:[],reason:"the daemon polls no repository, so there are no counts to age"};let r=Date.parse(e.now),o=Date.parse(t.fetched_at),s=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,i=s==null||s>n;return{version:1,fetched_at:t.fetched_at,age_ms:s,threshold_ms:n,stale:t.projects.length>0&&i,request_count:t.request_count,rate_limit:t.rate_limit,projects:t.projects.map(l=>({...l,fetched_at:t.fetched_at,age_ms:s,stale:i})),reason:t.projects.length===0?"the daemon polls no repository, so there are no counts to age":s==null?"these counts carry no readable instant, so they cannot be presented as current":i?`these counts are ${s}ms old, past the ${n}ms window`:`fetched ${s}ms ago, within the ${n}ms window`}}function tc(e){if(!dr(e))return!1;let n=e;return n.version===1&&(n.fetched_at===null||typeof n.fetched_at=="string")&&(n.age_ms===null||typeof n.age_ms=="number")&&typeof n.threshold_ms=="number"&&typeof n.stale=="boolean"&&Number.isInteger(n.request_count)&&dr(n.rate_limit)&&Array.isArray(n.projects)&&typeof n.reason=="string"}function rc(e){let n=e.endpoint??pk(uk),t=e.fetchImpl??fetch;return async r=>{let o=await t(n,{method:"POST",headers:{authorization:`bearer ${e.token}`,"content-type":"application/json",accept:"application/vnd.github+json"},body:JSON.stringify({query:r})});if(!o.ok){let s=o.headers.get("x-ratelimit-remaining"),i=o.status===429||s==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(i?": the host token's rate limit is spent":""))}return await o.json()}}function kk(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>Yd)throw new Error(`redskilled activity fetch spans at most ${Yd} repositories in one query`);let n=new Set;for(let t of e){if(t.project_label===""||t.owner===""||t.name==="")throw new Error("redskilled activity fetch needs a project label and an owner/name for every registered project");if(n.has(t.project_label))throw new Error(`redskilled holds one repository per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function Rk(e,n){let t=yn(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(oc),i=typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:null;return{remaining:r,reset_at:o,exhausted:s||r===0,point_cost:i}}function oc(e){if(e==null)return!1;let n=xs(e.type),t=xs(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function Xd(e,n){return Array.isArray(e)&&e.includes(n)}function Zd(e){let n=yn(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function bk(e){let n=yn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function yn(e){return dr(e)?e:{}}function dr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xs(e){return typeof e=="string"?e:""}var _k=3e4,wk=2,xk=3,Sk=4,vk=["logs","vitals","display"];function sc(e,n){if(n===void 0)return e;let t=vk.filter(o=>n[o]!==!0);if(t.length===0)return e;let r=o=>n[o]===!0;return{...e,workers:e.workers.map(o=>({...o,...r("vitals")?{}:{vitals:Ek,budget:{...o.budget,used_bytes:null,used_fraction:null}},...r("logs")?{}:{log:Pk},...r("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var Ek={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},Pk={last_line:null,published_at:null,source:null};function ic(e){let n=e.stalenessMs??_k,t=$e(e.now),r=e.sampledAt==null?null:$e(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),s=o!=null&&o<=n,i=new Set(e.reattachedWorkerIds??[]),l=e.hostState.workers.map(f=>Ak(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:i.has(f.worker_id)?"reattached":"running"})),a=l.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=l.length-a.length,u=l.reduce((f,m)=>f+(m.vitals.rss_bytes??0),0),p=Yt(e.hostState.workers);return{version:1,generated_at:e.now,daemon:{pid:e.hostState.pid,daemon_version:e.hostState.daemon_version,protocol_version:e.hostState.protocol_version,started_at:e.hostState.started_at,machine_id_hash:e.hostState.machine_id_hash,session_key_hash:e.hostState.session_key_hash},staleness:Ik({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:l.length,measuredCount:d,unmeasured:a}),host:{worker_count:l.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:p,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:u,measured_worker_count:d,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:p.memory_bytes/e.ceiling.memory_bytes},projects:Tk(l),known_projects:$k(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,m)=>f.localeCompare(m)),lapsed_projects:(e.hostState.lapsed_registrations??[]).map(f=>({project_label:f.project_label,at:f.at,...f.registered_at==null?{}:{registered_at:f.registered_at},reason:f.detail})),stopped_projects:(e.hostState.stopped_registrations??[]).map(f=>({project_label:f.project_label,at:f.at})),orphaned_projects:(e.hostState.orphaned_registrations??[]).map(f=>f.project_label),workers:l,github_balance:ys({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:nc({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:Dk(e.deaths,e.recentDeathLimit??Sk)},engine:Ok(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function Dk(e,n){let t=[...e].sort((s,i)=>($e(i.ts)??0)-($e(s.ts)??0)),r=t.slice(0,Math.max(0,Math.floor(n))).map(s=>({kind:s.kind,id:s.id,pid:s.pid,ts:s.ts,last_seen:s.last_seen,last_phase:s.last_phase,sender_class:s.sender_class,confidence:s.confidence,signal:s.signal,evidence:s.evidence[0]??null})),o=jk(t);return{count:t.length,recent:r,latest:r[0]??null,reaped_at:r[0]?.ts??null,...o==null?{}:{boot_loop:o}}}function jk(e){let n=new Map;for(let r of e){if(r.sender_class!=="boot-refused"||r.uptime_s==null||r.uptime_s>wk||r.project_label==null||r.project_label===""||$e(r.ts)==null)continue;let o=n.get(r.project_label)??[];o.push(r),n.set(r.project_label,o)}return[...n.entries()].filter(([,r])=>r.length>=xk).map(([r,o])=>{let s=o[0],i=$e(s.ts),l=Math.min(...o.map(d=>$e(d.ts))),a=s.detail?.trim()||s.evidence[0]?.trim();return a==null||a===""?null:{project_label:r,count:o.length,span_ms:Math.max(0,i-l),latest_refusal:a}}).filter(r=>r!=null).sort((r,o)=>o.count-r.count||o.span_ms-r.span_ms)[0]??null}function Ok(e){let n=e.upgrade,t=n?.running_version??e.daemon_version,r=n?.published_version??null,o=n?.newest_published_version??null,s=(n?.newer_published??0)>0,i=(n?.major_held??0)>0;return{running_version:t,published_version:r,newer_published:s,major_held:i,current:r==null&&o==null?null:!s&&!i}}function Ak(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=Zn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=$e(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms:n.nowMs==null||i==null?null:Math.max(0,n.nowMs-i),state:n.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:r,sampled_at:r==null?null:n.sampledAt,age_ms:r==null?null:n.ageMs,fresh:r!=null&&n.sampleFresh,rss_source:r==null?null:e.rss_source??null},budget:{name:o?.name??null,declared:o?.declared??s,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:Lk(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function Lk(e){let n={last_line:null,published_at:null,source:null};return e==null||e.line.trim()===""?n:{last_line:e.line,published_at:e.published_at,source:e.source}}function $k(e){let n=new Set;for(let t of e.registrations??[])n.add(t.project_label);for(let t of e.projects)n.add(t.project_label);for(let t of e.lapsed_registrations??[])n.add(t.project_label);for(let t of e.stopped_registrations??[])n.add(t.project_label);for(let t of e.orphaned_registrations??[])n.add(t.project_label);return[...n].sort((t,r)=>t.localeCompare(r))}function Tk(e){let n=new Map;for(let t of e){let r=n.get(t.project_label)??{workers:0,declared:0,observed:0,measured:0};r.workers+=1,r.declared+=t.budget.bytes??0,r.observed+=t.vitals.rss_bytes??0,r.measured+=t.vitals.rss_bytes==null?0:1,n.set(t.project_label,r)}return[...n.entries()].map(([t,r])=>({project_label:t,worker_count:r.workers,declared_memory_bytes:r.declared,observed_rss_bytes:r.observed,measured_worker_count:r.measured})).sort((t,r)=>t.project_label.localeCompare(r.project_label))}function Ik(e){let n={sampled_at:e.sampledAt,age_ms:e.ageMs,threshold_ms:e.threshold,measured_worker_count:e.measuredCount,unmeasured_workers:e.unmeasured};return e.workerCount===0?{...n,stale:!1,reason:"the host holds no Workers, so there is nothing to measure and nothing to age"}:e.sampledAt==null||e.ageMs==null?{...n,stale:!0,reason:`this answer is stale: the daemon has taken no measurement of its ${e.workerCount} live Worker(s) yet`}:e.ageMs>e.threshold?{...n,stale:!0,reason:`this answer is stale: its measurement is ${e.ageMs}ms old, past the ${e.threshold}ms staleness window`}:{...n,stale:!1,reason:`measured ${e.ageMs}ms ago, within the ${e.threshold}ms staleness window`}}function $e(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function Es(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.daemon,r=n.staleness,o=n.host;return n.version===1&&typeof n.generated_at=="string"&&t!=null&&typeof t=="object"&&Number.isInteger(t.pid)&&typeof t.daemon_version=="string"&&typeof t.protocol_version=="number"&&r!=null&&typeof r=="object"&&typeof r.stale=="boolean"&&typeof r.threshold_ms=="number"&&Array.isArray(r.unmeasured_workers)&&o!=null&&typeof o=="object"&&Number.isInteger(o.worker_count)&&Number.isInteger(o.project_count)&&typeof o.observed_rss_bytes=="number"&&Array.isArray(n.projects)&&Array.isArray(n.workers)&&(n.known_projects===void 0||Array.isArray(n.known_projects)&&n.known_projects.every(s=>typeof s=="string"))&&(n.registered_projects===void 0||Array.isArray(n.registered_projects)&&n.registered_projects.every(s=>typeof s=="string"))&&(n.lapsed_projects===void 0||Array.isArray(n.lapsed_projects)&&n.lapsed_projects.every(Nk))&&(n.stopped_projects===void 0||Array.isArray(n.stopped_projects)&&n.stopped_projects.every(Mk))&&(n.orphaned_projects===void 0||Array.isArray(n.orphaned_projects)&&n.orphaned_projects.every(s=>typeof s=="string"))&&(n.repository_activity===void 0||tc(n.repository_activity))&&(n.github_balance===void 0||ks(n.github_balance))&&(n.deaths===void 0||Ck(n.deaths))&&(n.engine===void 0||Wk(n.engine))&&(n.metrics===void 0||Jd(n.metrics))}function Nk(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.project_label=="string"&&typeof n.at=="string"&&(n.registered_at===void 0||typeof n.registered_at=="string")&&typeof n.reason=="string"}function Mk(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.project_label=="string"&&typeof n.at=="string"}function Ck(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return Number.isInteger(n.count)&&Array.isArray(n.recent)}function Wk(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")}var lc={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,wait_kind:null,wait_subject:null,wait_pid:null,wait_started_at:null,wait_deadline:null,wait_escalation:null,started_at:null,context:null,eta:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null};function Ps(e,n){let t=e.display?.started_at;if(t!=null&&t!==""){let r=Date.parse(t),o=Date.parse(n);if(Number.isFinite(r)&&Number.isFinite(o))return Math.max(0,o-r)}return e.uptime_ms}var U=e=>`\x1B[${e}m`,Hk=U("48;2;114;47;55"),Bk=U("48;2;88;36;42"),Fk=U("38;2;255;255;255"),Uk=U("38;2;201;150;158"),Ds=U("38;2;255;214;214"),js=U("39"),et=U("38;2;224;138;148"),Os=U("38;2;240;110;120"),As=U("38;2;255;214;214"),Ls=U("38;2;146;84;94"),$s=U("38;2;255;95;95"),Ts=U("49"),kn=U("0"),Is=U("1"),Ns=U("22");var Gk=/\x1b\[[0-9;]*m/g,Kk=/(\x1b\[[0-9;]*m)/,Vk=/^\x1b\[[0-9;]*m$/;function ac(e){return e.replace(Gk,"")}function qk(e){return e.slice(2,-1).split(";").every(t=>t===""||Number(t)===0)}function fe(e){return[...ac(e)].length}function J(e,n){if(n<=0)return"";if(fe(e)<=n)return e;if(n===1)return"\u2026";let t=n-1,r=0,o=!1,s="";for(let i of e.split(Kk))if(i!==""){if(Vk.test(i)){s+=i,o=!qk(i);continue}for(let l of i){if(r===t)return`${s}\u2026${o?kn:""}`;s+=l,r+=1}}return`${s}\u2026${o?kn:""}`}function nt(e,n){return e+" ".repeat(Math.max(0,n-fe(e)))}function Ms(e){let n=e.toLowerCase();for(let t of["opus","sonnet","haiku","fable"]){let r=n.indexOf(t);if(r===-1)continue;let s=n.slice(r+t.length).match(/^-(\d+(?:[-.]\d+)*)/)?.[1]?.split(/[-.]/)??[];return/^\d{8}$/.test(s.at(-1)??"")&&s.pop(),s.length===0?t:`${t}-${s.join(".")}`}return e}function re(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}function tt(e){if(!Number.isFinite(e)||e<=0)return"0";let n=(t,r)=>{let o=(Math.round(t*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${r}`};return e>=1e9?n(e/1e9,"B"):e>=1e6?n(e/1e6,"M"):e>=1e3?n(e/1e3,"k"):String(Math.round(e))}function rt(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return tt(e);if(e<=0)return"0";let n=(Math.round(e*10)/10).toFixed(1);return n.endsWith(".0")?n.slice(0,-2):n}function Pe(e){if(e==null||!Number.isFinite(e)||e<0)return"\u2014";let n=Math.floor(e/1e3);if(n<60)return`${n}s`;let t=Math.floor(n/60);if(t<60)return`${t}m${n%60}s`;let r=Math.floor(t/60);return r<24?`${r}h${t%60}m`:`${Math.floor(r/24)}d${r%24}h`}function Rn(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}var ot="!unregistered",Cs="!lapsed",st="\u21E1",De="\u2020",bn="\u25D0",_n="\u25EF",Ws="\u21B3",Hs="redskilled unreachable \u2014 Worker state unknown";function wn(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function cr(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function it(e,n){return n==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(n)?e.registered_projects==null||e.registered_projects.includes(n)?"matched":e.orphaned_projects?.includes(n)===!0?"orphaned":e.stopped_projects?.some(t=>t.project_label===n)===!0?"stopped":e.lapsed_projects?.some(t=>t.project_label===n)===!0?"lapsed":"name-only":"unregistered"}function Bs(e){let n=[];return e.workers.length>0&&e.workers.length<=e.maxWorkers&&n.push("workers"),e.mode==="global"&&e.projects.length>0&&e.projects.length<=e.maxProjects&&n.push("projects"),n.push("host"),n}var Te=["wid","run","org","iss","bar","phase","elapsed","eta","hb","loc","tks","ctx","tls","rsn","txt"],me={mode:"local",project:null,maxWidth:200,maxRows:16},Jk=" ",dc="\u2588",Qk="\u25B6",zk="\u2717",Yk="\u2591",Xk=new Set(["gate","push-pr","merge","cascade"]),Zk=new Set(["requeue"]);function xn(e,n=me){let t=it(e,n.project),r=wn(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(p=>Fs(p,n,e.generated_at)),i=aR(s),l=o.map((p,f)=>({worker_id:p.worker_id,project_label:p.project_label,mine:n.project!=null&&p.project_label===n.project,cells:s[f],line:J(dR(s[f],i),n.maxWidth)})),a=nR(e,n,r,t),d=r.length-o.length,u=[a.line,...l.map(p=>p.line)];return d>0&&u.push(J(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),u.push(...oR(e,n)),u.push(...rR(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Te,header:a,rows:l,lines:u,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Fs(e,n,t){let r=e.display??lc,o=[r.runner,r.model==null?null:Ms(r.model),r.effort].filter(l=>!!l).join(" "),s=r.phase!=null&&Xk.has(r.phase),i=s||r.origin!=null&&Zk.has(r.origin);return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:o===""?"":`run=${o}`,org:s?"org=landing":r.origin==null?"":`org=${r.origin}`,iss:r.issue==null?"":`iss=${r.issue}`,bar:cc(r),phase:[r.phase,r.step].filter(l=>!!l).join("\xB7"),elapsed:Pe(Ps(e,t)),eta:r.eta==null?"":`eta=${Pe(r.eta*1e3)}`,hb:eR(r,t)??`hb=${r.heartbeat??"?"}`,loc:i?"":lR(r.added,r.removed),tks:i||r.tokens==null?"":`tks=${tt(r.tokens)}`,ctx:r.context==null?"":`ctx=${tt(r.context)}`,tls:i||r.tools==null?"":`tls=${r.tools}`,rsn:i||r.reasoning==null?"":`rsn=${r.reasoning}`,txt:i||r.text==null?"":`txt=${r.text}`}}function eR(e,n){if(e.wait_kind==null||e.wait_subject==null||e.wait_pid==null||e.wait_pid<=0||e.wait_started_at==null)return null;let t=Date.parse(e.wait_started_at),r=Date.parse(n);return!Number.isFinite(t)||!Number.isFinite(r)?null:`${e.wait_kind}=${e.wait_subject} ${Pe(Math.max(0,r-t))}`}function cc(e){let n=e.phase_total,t=e.phase_index;if(n==null||n<=0||t==null||t<0)return"";let r=Math.min(Math.floor(t),Math.floor(n));if(r>=n)return dc.repeat(Math.floor(n));let o=e.failed?zk:Qk;return`${dc.repeat(r)}${o}${Yk.repeat(Math.floor(n)-r-1)}`}function nR(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(v=>v.project_label===n.project),s={open_pull_requests:o?.counts?.open_pull_requests??null,recently_closed:o?.counts?.recently_closed??null,open_issues:o?.counts?.open_issues??null,stale:o?.stale===!0},i={memory_used_fraction:e.host.ceiling_used_fraction,memory_used_bytes:e.host.consumption.memory_bytes,memory_ceiling_bytes:e.host.ceiling.memory_bytes,worker_count:e.host.worker_count,worker_ceiling:e.host.ceiling.worker_count,interactive_reservation:e.host.ceiling.interactive_reservation??0},l=iR(t),a=o?.repository??n.project,d=e.engine??null,u=d?.running_version??e.daemon.daemon_version,p=e.deaths??null,f=e.metrics??null,m=[`\xBB ${a??"host"} v${u}${d!=null&&d.current===!1?st:""}`];(r==="unregistered"||r==="name-only")&&m.push(ot),r==="lapsed"&&m.push(Cs),l!=null&&m.push(l),m.push(`wrk=${t.length}/${e.host.worker_count}`);let g=i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`;m.push(`${g} reserve=${i.interactive_reservation} interactive`),m.push(sR(i)),s.open_pull_requests!=null&&m.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&m.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&m.push(`iss=${s.open_issues}`),s.stale&&m.push("!counts stale");let _=f==null?null:uc(f.hour);if(_!=null&&m.push(_),p!=null&&p.count>0&&p.latest!=null){let v=p.boot_loop,G=Rn(v?.latest_refusal);m.push(v==null?`${De}${p.count} ${p.latest.sender_class}`:`${De}${p.count} boot-refused \xD7${v.count} in ${tR(v.span_ms)}`+(G==null?"":` \u2014 ${G}`))}if(e.staleness.stale){let v=e.staleness.age_ms;m.push(v==null?"!unmeasured":`!stale ${Math.round(v/1e3)}s`)}let k=m.join(" \xB7 "),x=_!=null&&fe(k)>n.maxWidth?m.filter(v=>v!==_).join(" \xB7 "):k;return{repo:a,project:n.project,project_match:r,version:u,engine:d,deaths:p,metrics:f,model:l,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:J(x,n.maxWidth)}}function tR(e){return Pe(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function uc(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${rt(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${rt(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${rt(e.issues_per_hour.value)}`);let t=e.runner_share.shares[0];return t!=null&&n.push(`${t.key}=${Math.round(t.share*100)}%`),n.length===0?null:n.join(" ")}function rR(e,n){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let r=t.posture==="spent"?_n:bn,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[J(`${r} github budget ${t.posture}${o} \u2014 ${t.reason}`,n.maxWidth)]}function oR(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(s=>J(`${De} ${s.kind} ${s.id} pid=${s.pid} ${s.sender_class}/${s.confidence} phase=${s.last_phase}`+(s.signal==null?"":` signal=${s.signal}`)+(s.evidence==null?"":` \u2014 ${s.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(J(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function sR(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${re(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${re(e.memory_used_bytes)}/${re(e.memory_ceiling_bytes)}${n}`}function iR(e){for(let n of e){let t=n.display;if(t==null)continue;let r=[t.runner,t.model,t.effort].filter(o=>!!o);if(r.length>0)return r.join("\xB7")}return null}function lR(e,n){if(e==null&&n==null)return"";let t=[];return e!=null&&e>0&&t.push(`+${e}`),n!=null&&n>0&&t.push(`-${n}`),`loc=${t.length>0?t.join(" "):"0"}`}function aR(e){let n=Object.fromEntries(Te.map(t=>[t,0]));for(let t of e)for(let r of Te)n[r]=Math.max(n[r],fe(t[r]));return n}function dR(e,n){return Te.filter(r=>n[r]>0).map(r=>nt(e[r],n[r])).join(Jk).replace(/\s+$/,"")}var A={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Je(e,n=A){let t=it(e,n.project),r=wn(e,n),o=cr(e,n),s=uR(e,n,r,t),i=Bs({mode:n.mode,maxWorkers:n.maxWorkers,maxProjects:n.maxProjects,workers:r,projects:o}),l={detail:"host",line:s};for(let f of i){let m=f==="workers"?s:xR(s,cR(f,o),n.separator);if(l={detail:f,line:m},f==="workers"||fe(m)<=n.maxWidth)break}let a=J(l.line,n.maxWidth),d=l.detail==="workers"?RR(r,n,e.generated_at):{lines:[],degraded:!1},u=l.detail==="workers"?r.flatMap((f,m)=>{let g=n.verbose?_R(f,n):null;return g==null?[d.lines[m]]:[d.lines[m],g]}):[],p=r.length>0?"workers":"host";return{version:1,line:a,lines:[a,...u],verbose:n.verbose,mode:n.mode,project:n.project,project_match:t,detail:l.detail,degraded:l.detail!==p||a!==l.line||d.degraded,stale:e.staleness.stale,generated_at:e.generated_at}}function Ks(e){let n=e.options??A,t=J(Hs,n.maxWidth);return{version:1,line:t,lines:[t],verbose:n.verbose,mode:n.mode,project:n.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}function cR(e,n){return e==="projects"?n.map(wR):[]}function uR(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(Gs(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(Gs(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(Gs(e,n)),o.push(ot)):o.push(gR(e,n.project,r)),o.push(pR(e));let s=fR(e);s!=null&&o.push(s);let i=mR(e);return i!=null&&o.push(i),e.staleness.stale&&o.push(yR(e)),o.join(" ")}function pR(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${st}`}function fR(e){let n=e.github_balance;return n==null?null:n.posture==="spent"?`${_n} quota spent`:n.posture==="reserved"?`${bn} quota band`:null}function mR(e){let n=e.deaths;if(n==null||n.count<=0||n.latest==null)return null;let t=n.boot_loop;if(t!=null){let r=Rn(t.latest_refusal);return`${De}${n.count} boot-refused \xD7${t.count} in ${hR(t.span_ms)}`+(r==null?"":` \u2014 ${r}`)}return`${De}${n.count} ${n.latest.sender_class}`}function hR(e){return Pe(e).replace(/m0s$/,"m").replace(/h0m$/,"h").replace(/d0h$/,"d")}function gR(e,n,t){if(t==="unregistered")return`project unknown \u2014 ${n} was never registered on this host`;if(t==="orphaned")return`project unknown \u2014 ${n} is registered on a daemon this socket does not reach`;if(t==="stopped"){let r=e.stopped_projects?.find(o=>o.project_label===n);return`project unknown \u2014 ${n} was stopped${r==null?"":` at ${Us(r.at)}`}`}if(t==="lapsed"){let r=e.lapsed_projects?.find(o=>o.project_label===n);if(r!=null){let o=r.registered_at==null?"":` (registered ${Us(r.registered_at)})`;return`project unknown \u2014 ${n} lapsed at ${Us(r.at)}${o}`}return`project unknown \u2014 ${n} lapsed`}return"project unknown \u2014 this directory resolved to no project"}function Us(e){return/^\d{4}-\d{2}-\d{2}T(\d{2}:\d{2}:\d{2})/.exec(e)?.[1]??e}function Gs(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,s)=>o+s.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${re(t)}/${re(r)}`:re(t)}function yR(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function kR(e,n,t,r){let o=t.map(s=>bR(s,nt(e[s],n[s])));return J(`${Ts}${et}${o.join(" ")}${kn}`,r)}function RR(e,n,t){let r=e.map(l=>Fs(l,n,t)),o=Te.filter(l=>r.some(a=>fe(a[l])>0)),s=[...o],i=pc(r,s);for(;s.length>1&&fc(i,s)>n.maxWidth;)s.pop(),i=pc(r,s);return{lines:r.map(l=>kR(l,i,s,n.maxWidth)),degraded:s.length<o.length||fc(i,s)>n.maxWidth}}function pc(e,n){let t=Object.fromEntries(Te.map(r=>[r,0]));for(let r of e)for(let o of n)t[o]=Math.max(t[o],fe(r[o]));return t}function fc(e,n){return n.reduce((t,r)=>t+e[r],0)+Math.max(0,n.length-1)*2}function bR(e,n){if(e==="wid")return`${Is}${n}${Ns}`;if(e==="bar")return n.replace(/█+/g,r=>`${Os}${r}`).replace("\u25B6",`${As}\u25B6`).replace("\u2717",`${$s}\u2717`).replace(/░+/g,r=>`${Ls}${r}`)+et;let t=n.indexOf("=");return t>0?`${Ds}${n.slice(0,t+1)}${js}${n.slice(t+1)}${et}`:n}function _R(e,n){let t=Rn(e.log.last_line);return t==null?null:J(` ${Ws} ${Vs(e,n.mode)}: ${t}`,n.maxWidth)}function Vs(e,n){return n==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function wR(e){return`${e.project_label} ${e.worker_count}w ${re(e.observed_rss_bytes)}`}function xR(e,n,t){return[e,...n].join(t)}var ur=1;async function lt(e,n){return await Gt(e,n,"redskilled daemon")}function hc(e){let n=[...e.workers??[]],t=new Map;for(let r of n)t.set(r.project_label,(t.get(r.project_label)??0)+1);return{version:1,protocol_version:ur,daemon_version:e.daemonVersion,machine_id_hash:e.machineIdHash,session_key_hash:e.sessionKeyHash,pid:e.pid,started_at:e.startedAt,...e.ceiling==null?{}:{ceiling:e.ceiling},...e.scope==null?{}:{scope:e.scope},workers:n,projects:[...t.entries()].map(([r,o])=>({project_label:r,worker_count:o})).sort((r,o)=>r.project_label.localeCompare(o.project_label)),registrations:PR(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},...e.stops==null||e.stops.length===0?{}:{stopped_registrations:[...e.stops]},...e.orphanedRegistrations==null||e.orphanedRegistrations.length===0?{}:{orphaned_registrations:[...e.orphanedRegistrations]},budget_accounting:qa(n,{hostCeilingBytes:e.ceiling?.memory_bytes??e.hostCeilingBytes??null}),upgrade:DR(e)}}function PR(e){let n=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(n),r=e.queue??null,o=new Map(r==null?[]:r.projects.map(s=>[s.project_label,s]));return[...e.registrations??[]].map(s=>{let i=o.get(s.project_label);return{...s,...t?{renewal:Pd(s,n)}:{},...r==null||i==null?{}:{last_poll:{at:r.fetched_at,outcome:i.outcome,depth:i.depth,request_count:r.request_count,detail:i.detail}}}}).sort((s,i)=>s.project_label.localeCompare(i.project_label))}function DR(e){let n=e.daemonVersion,t=e.published?.version??null,r=e.published?.majorHold??null;return{running_version:n,published_version:t,published_unknown:+(t===null),newer_published:+(e.published?.newer===!0),replacement:e.published?.replacement??"none",checked_at:e.published?.checkedAt??null,checks:e.published?.checks??0,hold_reason:e.published?.holdReason??null,newest_published_version:e.published?.newest??null,major_held:+(r!==null),major_hold:r}}function gc(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.protocol_version=="number"&&typeof n.daemon_version=="string"&&typeof n.machine_id_hash=="string"&&typeof n.session_key_hash=="string"&&Number.isInteger(n.pid)&&typeof n.started_at=="string"&&(n.ceiling===void 0||LR(n.ceiling))&&Array.isArray(n.workers)&&Array.isArray(n.projects)&&Ja(n.budget_accounting)&&(n.scope===void 0||xd(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(ds))&&(n.lapsed_registrations===void 0||Array.isArray(n.lapsed_registrations)&&n.lapsed_registrations.every(jR))&&(n.stopped_registrations===void 0||Array.isArray(n.stopped_registrations)&&n.stopped_registrations.every(OR))&&(n.orphaned_registrations===void 0||Array.isArray(n.orphaned_registrations)&&n.orphaned_registrations.every(AR))&&(n.upgrade===void 0||$R(n.upgrade))}function jR(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.project_label=="string"&&(n.registered_at===void 0||typeof n.registered_at=="string")&&typeof n.at=="string"&&typeof n.renew_by=="string"&&Number.isInteger(n.renewals)&&Number.isInteger(n.sustains)&&typeof n.detail=="string"}function OR(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.project_label=="string"&&typeof n.registered_at=="string"&&typeof n.at=="string"&&typeof n.detail=="string"}function AR(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.project_label=="string"&&(n.registered_at===void 0||typeof n.registered_at=="string")}function LR(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=new Set(["flag","environment","home-config","derived-default"]);return(n.memory_bytes===null||typeof n.memory_bytes=="number")&&(n.worker_count===null||typeof n.worker_count=="number")&&(n.validation_count===void 0||Number.isInteger(n.validation_count)&&Number(n.validation_count)>0)&&(n.source==="declared"||n.source==="host-fraction")&&(n.memory_source===void 0||t.has(String(n.memory_source)))&&(n.worker_source===void 0||t.has(String(n.worker_source)))&&(n.validation_source===void 0||t.has(String(n.validation_source)))}function $R(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")&&typeof n.published_unknown=="number"&&typeof n.newer_published=="number"&&(n.replacement==="none"||n.replacement==="pending"||n.replacement==="in-progress")&&(n.checked_at===null||typeof n.checked_at=="string")&&(n.newest_published_version===void 0||n.newest_published_version===null||typeof n.newest_published_version=="string")&&(n.major_held===void 0||typeof n.major_held=="number")&&(n.checks===void 0||typeof n.checks=="number")&&(n.hold_reason===void 0||n.hold_reason===null||typeof n.hold_reason=="string")&&(n.major_hold===void 0||n.major_hold===null||TR(n.major_hold))}function TR(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.version=="string"&&Number.isInteger(n.running_major)&&Number.isInteger(n.held_major)&&typeof n.reason=="string"&&typeof n.action=="string"&&n.action.trim()!==""}import{spawnSync as mr}from"node:child_process";import{existsSync as Ys}from"node:fs";import{delimiter as UR,join as Ec}from"node:path";import{join as yc}from"node:path";import{existsSync as IR}from"node:fs";import{createRequire as NR}from"node:module";var kc="redskilled-job-object.node",Qe=100;function Sn(e){return{available:!1,reason:e}}function MR(e,n,t){return[yc(t,"prebuilds",`${e}-${n}`,kc),yc(t,"native","build","Release",kc)]}function Rc(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return Sn(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??WR(),o=e.exists??IR,s=MR(n,t,r),i=s.find(d=>o(d));if(i==null)return Sn(`no Job Object addon was found for ${n}-${t} (looked in ${s.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let l=e.requireFn??NR(import.meta.url),a;try{a=l(i)}catch(d){return Sn(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return CR(a)?{available:!0,binding:a}:Sn(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function CR(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function WR(){return new URL("..",import.meta.url).pathname}function bc(e){let n=e??{},t=[],r=HR(n);r==null&&(n.memory_max??n.memory_high)!=null&&t.push("the declared memory budget could not be reduced to bytes, so the job carries no memory ceiling");let o;return n.cpu_weight!=null&&(n.cpu_weight<Qe?o=Math.max(1,Math.min(100,Math.round(n.cpu_weight))):t.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${Qe}, and Windows CPU rate control is an absolute cap rather than a share, so no rate limit is set`)),{...r!=null?{memory_limit_bytes:r.bytes,memory_budget_name:r.name,memory_budget_declared:r.declared}:{},...o!=null?{cpu_rate_percent:o}:{},kill_on_close:!0,...t.length>0?{note:t.join("; ")}:{}}}function HR(e){return Zn({budget:e})}var pr=5,_c=19;function qs(e){return{available:!1,reason:e}}var BR="an address-space rlimit is not a resident-memory ceiling: a runtime that reserves address space it never faults in would die under a limit it never used, so no memory rlimit is set and the daemon's RSS sampling floor is the ceiling that actually holds";function xc(e,n){let t=e??{},r=[],o;if(!n.canRenice)r.push("nice is not on this host, so no priority control was applied and the Worker competes with interactive work");else if(t.cpu_weight==null)o=pr;else if(t.cpu_weight<Qe){let l=Math.round(_c*(Qe-t.cpu_weight)/Qe);o=Math.min(_c,Math.max(pr,l))}else o=pr,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${Qe}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${pr}`);let s=wc(t.max_processes);s==null&&t.max_processes!=null&&r.push(`max_processes=${t.max_processes} is not a positive whole number, so no ulimit -u is set`);let i=wc(t.cpu_seconds);return i==null&&t.cpu_seconds!=null&&r.push(`cpu_seconds=${t.cpu_seconds} is not a positive whole number, so no ulimit -t is set`),{...o!=null?{nice:o}:{},...s!=null?{max_processes:s}:{},...i!=null?{cpu_seconds:i}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:BR,...r.length>0?{note:r.join("; ")}:{}}}function Sc(e){let{limits:n}=e,t=[];return n.max_processes!=null&&t.push(`ulimit -u ${n.max_processes}`),n.cpu_seconds!=null&&t.push(`ulimit -t ${n.cpu_seconds}`),t.push(n.nice!=null&&e.nice!=null?`exec ${FR(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
71
+ `),e.command,...e.args]}function vc(e){let n=[];return e.nice!=null?n.push(`the Worker runs at nice ${e.nice} so it yields to interactive work`):n.push("no priority control was applied"),e.max_processes!=null&&n.push(`its processes are capped at ${e.max_processes}`),e.cpu_seconds!=null&&n.push(`its CPU time is capped at ${e.cpu_seconds} seconds`),`macOS placement applied POSIX limits: ${n.join(", ")}. macOS has no resource-group equivalent, so the Worker is charged to the daemon's own resource group, and ${e.memory_ceiling_reason}`+(e.note!=null?` (${e.note})`:"")}function Js(e){let n=e??{},t=[n.max_processes!=null?"max_processes":null,n.cpu_seconds!=null?"cpu_seconds":null].filter(r=>r!=null);return t.length===0?null:`${t.join(" and ")} ${t.length===1?"is a POSIX rlimit":"are POSIX rlimits"} honoured only by the macOS placement backend, so this placement carries no equivalent`}function wc(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function FR(e){return`'${e.replace(/'/g,"'\\''")}'`}var Pc="REDSKILLED_PLACEMENT",fr="red-worker",Qs="/bin/sh";function Dc(e=process.env,n=process.platform){let t=qs(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:Rc({platform:n}),posix:t};let r=Sn(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);if(n==="darwin")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:GR(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Ys(Ec(o,"systemd","private"));return{platform:n,systemdRun:Lc("systemd-run",e),userSession:s,jobObjects:r,posix:t}}function GR(e){return Ys(Qs)?{available:!0,shell:Qs,nice:Lc("nice",e)}:qs(`no POSIX shell was found at ${Qs}, so there is nothing to apply rlimits or priority in`)}function jc(e=process.env){let n=(e[Pc]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function KR(e,n,t=fr){return Oc(e,n,t).replace(/\.service$/,"")}function Oc(e,n,t=fr){return`${zs(t,"red-worker",24)}-${zs(e,"project",32)}-${zs(n,"worker",32)}.service`}function Ac(e){let n=[...e.args??[]],t={...e.budget??{},...e.budget?.memory_max==null&&e.memoryCeiling?.memory_max!=null?{memory_max:e.memoryCeiling.memory_max}:{}},r=t.memory_max??t.memory_high??null,o=t.memory_high!=null||t.memory_max!=null||t.cpu_weight!=null,s=e.target??{isolation:"transient-unit"},i=p=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:p,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Fn({scope:null,memory_ceiling:r,scope_degradation:p}),...o?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(s.isolation==="inherit")return i("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return i(`worker isolation disabled by ${Pc}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return qR(e,n,t,r,o,i);if(e.probes.platform==="darwin")return VR(e,n,t,r,i);if(e.probes.platform!=="linux")return i(`transient-unit placement is the Linux backend (platform=${e.probes.platform}): the Worker is charged to the daemon's own resource group`);if(!e.probes.systemdRun)return i("transient-unit placement unavailable: systemd-run is not on PATH; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");if(!e.probes.userSession)return i("transient-unit placement unavailable: no systemd --user session; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");let l=Oc(e.projectLabel,e.workerId,s.unit_prefix),a=["--user","--collect","--quiet","--wait",`--unit=${l}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&a.push("--pipe"),t.memory_high!=null&&a.push(`--property=MemoryHigh=${t.memory_high}`),t.memory_max!=null&&a.push(`--property=MemoryMax=${t.memory_max}`),t.cpu_weight!=null&&a.push(`--property=CPUWeight=${t.cpu_weight}`);let d=Fn({scope:l,memory_ceiling:r,scope_degradation:null});for(let[p,f]of Object.entries({...e.env??{},...d}))a.push(`--setenv=${p}=${f}`);let u=Js(e.budget);return{isolated:!0,backend:"transient-unit",unit:l,command:e.probes.systemdRun,args:[...a,"--",e.command,...n],budget:t,...r!=null?{memoryCeiling:r}:{},environment:d,...u!=null?{budgetWarning:u}:{}}}function VR(e,n,t,r,o){let s=e.probes.posix;if(!s.available)return o(`POSIX limit placement unavailable: ${s.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let i=xc(t,{canRenice:s.nice!=null}),l=t.memory_high!=null||t.memory_max!=null,a=vc(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:Sc({limits:i,nice:s.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:i,warning:a,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Fn({scope:null,memory_ceiling:r,scope_degradation:a}),...l?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+i.memory_ceiling_reason}:{}}}function qR(e,n,t,r,o,s){let i=e.probes.jobObjects;if(!i.available)return s(`Job Object placement unavailable: ${i.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let l=bc(t),a=KR(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...n],cwd:e.workspacePath,job:{name:a,limits:l},budget:t,...r!=null?{memoryCeiling:r}:{},environment:Fn({scope:a,memory_ceiling:r,scope_degradation:null}),...JR(o&&l.note!=null?`${l.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,Js(e.budget))}}function JR(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function Lc(e,n){for(let t of(n.PATH??"").split(UR)){if(!t)continue;let r=Ec(t,e);if(Ys(r))return r}return null}function zs(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function Xs(e,n){let t=[],r=[];for(let o of e){let s=!1;try{s=await n(o)===!0}catch{s=!1}(s?t:r).push(o)}return{alive:t,dead:r}}var $c=3e4;function Tc(e){return e.unit!=null&&e.unit!==""?QR(e.unit):H(e.pid)}function QR(e){let n=mr("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var zR="REDSKILLED_UNIT_DISCOVERY",Ic="(unowned)";function Nc(e){let n=mr("systemctl",["--user","show","--property=MainPID","--value",e],{encoding:"utf8"});if(n.error!=null||n.status!==0)return null;let t=Number.parseInt((n.stdout??"").trim(),10);return Number.isInteger(t)&&t>0?t:null}function YR(e=process.env){let n=(e[zR]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Mc(e,n,t=process.env){return YR(t)&&e===n}function Cc(e=fr){let n=mr("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return n.error!=null||n.status!==0?[]:(n.stdout??"").split(`
72
+ `).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function Wc(e){let n=new Set(e.held.map(o=>o.unit).filter(o=>o!=null&&o!=="")),t=new Set,r=[];for(let o of e.units)o===""||n.has(o)||t.has(o)||(t.add(o),r.push({worker_id:o.replace(/\.service$/,""),project_label:Ic,pid:e.mainPid?.(o)??0,started_at:e.now,workspace_path:"",isolated:!0,unit:o,warnings:[`adopted from active unit ${JSON.stringify(o)}, which has no birth on this host's event lane: its project, its Worker id and its budget belonged to a daemon that is gone, so they are reported as unknown rather than guessed \u2014 it is counted against the host budget from here on instead of running outside it`]}));return r}function Hc(e){return e.project_label.trim()!==""?e:{...e,project_label:Ic,warnings:[...e.warnings,"adopted at start with no owning project on the event lane: the daemon that birthed it recorded no project label, so it is held and counted under a stated placeholder rather than dropped"]}}function Bc(e){if(e.unit!=null&&e.unit!==""){let n=mr("systemctl",["--user","stop",e.unit],{stdio:"ignore"});return n.error==null&&n.status===0}try{return process.kill(e.pid,"SIGTERM"),!0}catch{return!1}}function XR(e,n=50){if(Kc(e),!Number.isInteger(n)||n<=0)throw new Error(`redskilled queue discovery needs a whole, positive batch size, not ${JSON.stringify(n)}`);let t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}function ZR(e,n={}){let t=n.batchSize??50;if(Kc(e),e.length>t)throw new Error(`redskilled queue discovery spans at most ${t} selectors in one query, and this batch holds ${e.length}: split it with planQueueDiscoveryBatches rather than dropping the remainder`);let r=e.map((i,l)=>({alias:`q${l}`,project:i}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...r.map(({alias:i,project:l})=>` ${i}: search(query: ${JSON.stringify(l.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
73
+ `),aliases:r}}function eb(e,n){let t=at(n),r=at(t.data),o=Array.isArray(t.errors)?t.errors.map(at):[],s=tb(r.rateLimit,o);return{projects:e.aliases.map(({alias:l,project:a})=>{let d=ob(r[l]);if(d!=null)return{project_label:a.project_label,outcome:"counted",depth:d,detail:`project ${JSON.stringify(a.project_label)} has ${d} item(s) matching its selector`};let u=o.find(p=>rb(p.path,l));return s.exhausted||Vc(u)?{project_label:a.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(a.project_label)} answered, so this queue has no depth rather than a depth of zero`+(s.reset_at==null?"":`; the quota resets at ${s.reset_at}`)}:{project_label:a.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(a.project_label)} could not be counted with the host token: ${Zs(u?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function nb(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function Uc(e,n,t){return{version:1,fetched_at:n,request_count:0,project_count:e.length,batch_size:50,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:e.map(r=>({project_label:r.project_label,outcome:"unconfigured",depth:null,detail:`project ${JSON.stringify(r.project_label)} was not counted because this host polls no tracker: ${t}`}))}}async function Gc(e){if(e.projects.length===0)return nb(e.now);let n=e.batchSize??50,t=XR(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=ZR(s,{batchSize:n});try{let l=await e.transport(i.query),a=eb(i,l);r.push(...a.projects),o=Fc(o,a.rate_limit)}catch(l){let a=l instanceof Error?l.message:String(l),d=/rate limit|secondary rate|429/i.test(a);o=Fc(o,{remaining:null,reset_at:null,exhausted:d});for(let u of s)r.push({project_label:u.project_label,outcome:d?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(u.project_label)} answered: ${a}`})}}return{version:1,fetched_at:e.now,request_count:t.length,project_count:r.length,batch_size:n,rate_limit:o,projects:r}}function Kc(e){if(e.length===0)throw new Error("redskilled queue discovery needs at least one registered project");let n=new Set;for(let t of e){if(typeof t.project_label!="string"||t.project_label==="")throw new Error("redskilled queue discovery needs a project label for every registered project");if(typeof t.selector!="string"||t.selector==="")throw new Error(`redskilled queue discovery needs a selector for project ${JSON.stringify(t.project_label)}: a project that names no work has no queue to discover`);if(n.has(t.project_label))throw new Error(`redskilled holds one selector per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function Fc(e,n){return{remaining:n.remaining==null?e.remaining:e.remaining==null?n.remaining:Math.min(e.remaining,n.remaining),reset_at:n.reset_at??e.reset_at,exhausted:e.exhausted||n.exhausted}}function tb(e,n){let t=at(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null;return{remaining:r,reset_at:o,exhausted:n.some(Vc)||r===0}}function Vc(e){return e==null?!1:Zs(e.type)==="RATE_LIMITED"||/rate limit/i.test(Zs(e.message))}function rb(e,n){return Array.isArray(e)&&e.includes(n)}function ob(e){let n=at(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function at(e){return sb(e)?e:{}}function sb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zs(e){return typeof e=="string"?e:""}function qc(e,n,t){let r=e?.rate_limit;if(r==null)return n;if(r.exhausted){let s=r.reset_at==null?Number.NaN:Date.parse(r.reset_at),i=Number.isFinite(s)?s-t+1e3:n*4;return Math.min(ib,Math.max(n,i))}let o=r.remaining;return o==null?n:o<=lb?Math.max(n,3e4):o<=ab?Math.max(n,2e4):n}var ib=1e5,lb=250,ab=1e3;var db={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,wait_kind:null,wait_subject:null,wait_pid:null,wait_started_at:null,wait_deadline:null,wait_escalation:null,started_at:null,context:null,eta:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},cb=["runner","model","effort","origin","issue","phase","step","heartbeat","wait_kind","wait_subject","wait_started_at","wait_deadline","wait_escalation","started_at"],ub=["phase_index","phase_total","wait_pid","context","eta","added","removed","tokens","tools","reasoning","text"];function Jc(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...db};for(let r of cb){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of ub){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}import{randomInt as hb}from"node:crypto";import{spawn as gb}from"node:child_process";import{closeSync as yb,mkdirSync as kb,openSync as Rb}from"node:fs";import{dirname as bb}from"node:path";import{delimiter as Qc,dirname as pb}from"node:path";function fb(e,n=Qc){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function mb(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=pb(n);return t===""||t==="."?null:t}function zc(e,n=process.execPath,t=Qc){let r=fb(e,t),o=mb(n);return o==null?r.join(t):[o,...r.filter(s=>s!==o)].join(t)}var vn=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},hr=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}},ei="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",Xc=4,_b=ei.length**Xc;function ni(e,n=hb){let t=new Set(e);for(let r=0;r<_b;r+=1){let o="h";for(let s=0;s<Xc;s+=1)o+=ei[n(ei.length)];if(!t.has(o))return o}throw new vn("redskilled exhausted the host Worker id space")}function wb(e){if(e==null||e.trim()==="")return null;try{return kb(bb(e),{recursive:!0}),Rb(e,"a")}catch{return null}}function xb(e){try{yb(e)}catch{}}function Sb(e){let n=[["project_label",e.project_label],["workspace_path",e.workspace_path],["command",e.command]];for(let[t,r]of n)if(typeof r!="string"||r.trim()==="")throw new vn(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new vn("redskilled worker spec args must be an array")}function vb(e){if(e==null)throw new hr("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new hr(e.reason,e)}function Zc(e){let{spec:n,admission:t}=e;vb(t),Sb(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(n.worker_id??e.workerId)?.trim()||ni(e.liveWorkerIds??[]),i=e.probes??Dc(r),l=e.openLog===!1?null:wb(n.log_path),a={...n.env??{},PATH:zc(n.env?.PATH??r.PATH,e.execPath??process.execPath)},d=Ac({workerId:s,projectLabel:n.project_label,workspacePath:n.workspace_path,command:n.command,args:n.args,budget:n.budget,...e.memoryCeiling!=null?{memoryCeiling:e.memoryCeiling}:{},target:n.placement,env:a,enabled:e.enabled??jc(r),probes:i,pipeOutput:l!==null}),p=(e.spawnFn??gb)(d.command,d.args,{...d.cwd!=null?{cwd:d.cwd}:{},detached:!0,stdio:l===null?"ignore":["ignore",l,l],env:d.backend==="transient-unit"?{...r}:{...r,...a,...d.environment}});if(l!==null&&xb(l),p.pid==null)throw p.once("error",()=>{}),new vn(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${s}`);let f=d.job!=null?Eb(d,i,p.pid):null;p.once("error",()=>{}),p.once("exit",(k,x)=>{try{f?.job?.close()}catch{}e.onExit?.(s,k,x)}),p.unref();let m=d.job!=null?f?.job!=null:d.isolated,g=[d.warning,f?.warning,d.budgetWarning].filter(k=>k!=null);return{worker:{worker_id:s,project_label:n.project_label,pid:p.pid,started_at:o(),workspace_path:n.workspace_path,...n.log_path!=null?{log_path:n.log_path}:{},isolated:m,...d.unit!=null?{unit:d.unit}:{},...n.budget!=null?{budget:n.budget}:{},...Object.keys(d.budget).length>0?{applied_budget:d.budget}:{},...d.memoryCeiling!=null?{memory_ceiling:d.memoryCeiling,memory_ceiling_reason:e.memoryCeiling?.reason??"this Worker's ceiling is the budget its client declared"}:{},warnings:g},admission:t,warnings:g,plan:d,child:p,...f?.job!=null?{job:f.job}:{}}}function Eb(e,n,t){let r=e.job;if(r==null)return{};let o="the Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling";if(!n.jobObjects.available)return{warning:`Job Object placement unavailable: ${n.jobObjects.reason}. ${o}`};let s;try{s=n.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(i){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${Yc(i)}. ${o}`}}try{s.assign(t)}catch(i){try{s.close()}catch{}return{warning:`Worker pid ${t} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${Yc(i)}. ${o}`}}return{job:s}}function Yc(e){return e instanceof Error?e.message:String(e)}import{open as Pb,stat as Db}from"node:fs/promises";var jb=16*1024;async function eu(e,n=jb){let t;try{t=(await Db(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let s=await Pb(e,"r");try{let i=Buffer.alloc(r);await s.read(i,0,r,t-r),o=i.toString("utf8")}finally{await s.close()}}catch{return null}return Ob(o)}function Ob(e){let n=e.split(`
74
+ `);for(let t=n.length-1;t>=0;t-=1){let r=n[t].replace(/\r$/,"");if(r.trim()!=="")return r}return null}import{spawn as Kb}from"node:child_process";import{existsSync as Vb,readdirSync as qb}from"node:fs";import{dirname as Jb,join as iu,resolve as Qb}from"node:path";var Ab="<version>";function Ie(e,n=[],t){let r=t&&t.trim().length>0?t.trim():Ab;return[`npx -y -p ${Ke}@${r}`,e,...n].join(" ")}function oe(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?{major:Number(n[1]),minor:Number(n[2]),patch:Number(n[3])}:null}function ti(e,n){let t=oe(e),r=oe(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var $D=4*60*60*1e3;Se();Se();import{spawnSync as Lb}from"node:child_process";import{mkdir as $b,rm as Tb,writeFile as Ib}from"node:fs/promises";import{existsSync as Nb}from"node:fs";import{homedir as Mb}from"node:os";import{dirname as Cb,join as ri}from"node:path";var En="redskilled.service",oi="REDSKILLED_SUPERVISED",Wb="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function Hb(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||ri(e.HOME?.trim()||Mb(),".config");return ri(n,"systemd","user")}function si(e=process.env){return ri(Hb(e),En)}function nu(e,n={}){let t=n.env??process.env,r=Jt(n.override??{},n.entryLookup??{}),o=[...r.args,...Ue(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:En,unitPath:si(t),command:r.command,args:o,text:Bb(r.command,o,e)}}function Bb(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${Wb}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(Fb).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${oi}=1"`,`Environment="REDSKILLED_SESSION=${tu(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
75
+ `)}function Fb(e){return/[\s"'\\$%]/.test(e)?`"${tu(e)}"`:e}function tu(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function ru(e,n={}){let t=n.writeFile??Ub,r=n.run??ii,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(gr("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(gr("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function ou(e={}){let n=e.removeFile??Gb,t=e.run??ii,r=si(e.env??process.env),o=[gr("disable",t,["systemctl","--user","disable","--now",En])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(gr("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function su(e={}){let n=e.exists??Nb,t=e.run??ii,r=si(e.env??process.env),o=n(r);return{unitName:En,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",En]).status===0,active:o&&t(["systemctl","--user","is-active",En]).status===0,floor:"auto-spawn"}}function gr(e,n,t){let r=n(t),o=(r.stderr??r.stdout??"").trim();return{step:e,argv:t,ok:r.status===0,...o?{detail:o}:{}}}async function Ub(e,n){await $b(Cb(e),{recursive:!0}),await Ib(e,n,{encoding:"utf8",mode:420})}async function Gb(e){await Tb(e,{force:!0})}function ii(e){let n=Lb(e[0],[...e.slice(1)],{encoding:"utf8"});return n.error!=null?{status:null,stderr:n.error.message}:{status:n.status,stdout:n.stdout??"",stderr:n.stderr??""}}var lu=75,du=9e5,au="redskilled-replacement-entry-unresolved",zb="REDSKILLED_NO_REGISTRY_PROBE",cu="REDSKILLED_BORN_BY_REPLACEMENT";function uu(e=process.env){return e[cu]==="1"}function pu(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function fu(e){let n=e.running.trim();if(dt(n))return null;let t=e.newest?.trim()??"",r=oe(t),o=oe(n);return r===null||o===null||r.major<=o.major?null:{version:t,running_major:o.major,held_major:r.major,reason:`redskilled ${t} is published and this daemon runs ${n}; a major version is deliberately never adopted by the background check, because a breaking change must not arrive on a machine that is holding Workers`,action:Yb(r.major,e.supervised)}}function Yb(e,n){let t=`install the ${e}.x bundle (update this machine's plugin pin), then `;return n?`${t}re-point the unit and restart it: ${Ie("red-skills-redskilled",["unit","install"])} && systemctl --user restart redskilled.service`:`${t}stop this daemon \u2014 the next client start resolves the newly installed bundle`}function mu(e){let n=e.running.trim();if(dt(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||oe(t)===null?{act:"hold",reason:"published-unknown"}:ti(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function dt(e){let n=e.trim();return oe(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function hu(e=process.env){return e[oi]==="1"}var li=class extends Error{code=au;searched;constructor(n,t){super(`${au}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
76
76
  searched:
77
77
  ${t.map(r=>` ${r}`).join(`
78
- `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function yb(e,n={}){let t=n.env??process.env,r=n.exists??ub,o=n.execPath??process.execPath,s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,l=[],a=[[Gc(Ft(t),i),"bundle-cache"]];s&&a.push([Gc(fb(mb(s)),i),"caller-sibling-bundle"]);for(let[d,u]of a)if(l.push(d),r(d))return{command:o,args:[d],version:e,source:u,searched:l};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new qs(e,l);return{command:t.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:l}}function eu(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>yb(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function nu(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??Rb)(Kc),{...e,exitCode:Kc};let o=[...e.entry.args,...Ce(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??kb(r.env))(e.entry,o),e}function kb(e){return(n,t)=>{let r=cb(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[Jc]:"1"}});r.on("error",()=>{}),r.unref()}}function Rb(e){process.exitCode=e,process.exit(e)}async function tu(e,n=process.env,t=bb){let r=ou(n),o=su(e,n);if(n[hb]==="1")return{version:o,newest:r};let s=re(e)===null?"0.0.0":e;try{let i=await Da({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function ru(e,n=process.env,t){let r=t??Js;return{version:su(e,n,r),newest:ou(n,r)}}function ou(e=process.env,n=Js){return lu(iu(e,n))}function su(e,n=process.env,t=Js){let r=re(e.trim())?.major;return r===void 0?null:lu(iu(n,t).filter(o=>re(o)?.major===r))}function iu(e,n){let t=[];for(let r of n(Ft(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||re(o)===null||t.push(o)}return t}function lu(e){let n=null;for(let t of e)(n===null||Hs(t,n)>0)&&(n=t);return n}function Js(e){try{return pb(e)}catch{return[]}}async function bb(e){let n=await fetch(e,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`registry read failed with HTTP ${n.status}`);return await n.text()}import{mkdir as _b,readFile as wb,rename as xb,rm as Qs,writeFile as au}from"node:fs/promises";import{randomUUID as Sb}from"node:crypto";import{dirname as vb}from"node:path";var cr=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function lt(e){let n;try{n=await wb(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=Eb(n);return Pb(t)?t:void 0}var du;function uu(){return du??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},du}function pu(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??B;async function s(){return await lt(e)}async function i(a){let d=`${e}.${a.pid}.${Sb()}.tmp`;await au(d,cu(a),{encoding:"utf8",mode:384}),await xb(d,e)}function l(a,d){return{version:1,pid:a.pid,start_time:a.startTime,session_key_hash:n.sessionKeyHash,machine_id_hash:n.machineIdHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}return{read:s,async acquire(a){await _b(vb(e),{recursive:!0,mode:448});let d=!1;for(;;){let u=r(),p=l(a,u);try{return await au(e,cu(p),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:p}}catch(m){if(m.code!=="EEXIST")throw m}let f=await s();if(!f){await Qs(e,{force:!0}),d=!0;continue}if(zs(f,a))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await Qs(e,{force:!0}),d=!0}},async renew(a){let d=await s();if(!d||!zs(d,a))throw new cr(e);let u={...d,renewed_at:r()};return await i(u),u},async release(a){let d=await s();if(!d)return!1;if(!zs(d,a))throw new cr(e);return await Qs(e,{force:!0}),!0}}}function zs(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function cu(e){return`${W(e,{keyedMapCollapse:!0})}
79
- `}function Eb(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Q(n)}catch{return null}}}function Pb(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||!Number.isInteger(n.pid)||n.pid<=0)return!1;for(let t of["start_time","session_key_hash","machine_id_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var Ys=3e5,Nb=1e4,Mb=6e4,Cb=15e3,Wb=3e4,Bb=6e4,fu=16;function Fb(e){if(e.event!=="worker-death"&&e.event!=="worker-budget-kill")return null;let n=e.event==="worker-budget-kill",t=e.detail??`redskilled observed exit code=${e.exit_code??"null"} signal=${e.signal??"null"}`;return{version:1,ts:e.ts,kind:"worker",id:e.worker_id,pid:e.pid,last_seen:e.ts,last_phase:"unreported",sender_class:n?"teardown":"unknown",confidence:n?"high":"none",signal:e.signal,host_boot_changed:!1,evidence:n?[t]:[],checked:[`redskilled host event: ${t}`]}}var Ke=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},Hb="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function hu(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??Ys,o=e.clock??(()=>new Date().toISOString()),s=e.launch??Mc,i=e.ceiling??Ha();e.repositoryActivity!=null&&ps(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??uu(),a=e.leaseStore??pu(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??sd(),u={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},p=e.machineClaimStore??qt(n.machineClaimPath,u,{clock:o});await Lb(Ib(n.socketPath),{recursive:!0,mode:448});let f=await p.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new Ke(n.socketPath):new De(p.claimPath,f.reason,f.claim);let m=await a.acquire(l);if(!m.acquired)throw await p.release(d).catch(()=>{}),new Ke(n.socketPath,m.lease);let g;try{g=await Gb(n.socketPath,async()=>{let[c,h]=await Promise.all([a.read().catch(()=>{}),p.read().catch(()=>{})]);return c!=null&&c.pid!==l.pid&&B(c.pid)?!0:h!=null&&h.socket_path===n.socketPath&&h.pid!==d.pid&&B(h.pid)})}catch(c){throw await a.release(l).catch(()=>{}),await p.release(d).catch(()=>{}),c}let _=o(),k=e.eventLane??Ka(n.eventLanePath),w=e.liveness??kc,O=e.livenessGraceMs??yc,X=e.stopWorker??vc,he=e.unitInventory??(()=>_c(n.machineClaimPath,Vt({machineIdHash:n.machineIdHash}))?wc():[]),ge=e.unitMainPid??bc,qe=e.treeSampler??$d,gr=e.readLogTail??Cc,pi=e.sampleMs??Cb,fi=e.leaseRenewMs??Wb,mi=e.registrationSustainMs??Bb,hi=e.publishedVersion??(c=>tu(c)),gi=e.replaceCheckMs??qc,yi=e.publishedProbeTimeoutMs??Nb,Xu=e.localPublishedEvidence??(c=>ru(c,e.replacementIO?.env??process.env)),Zu=e.bornByReplacement??Qc(),ki=e.replaceBootCheckMs??Mb,Ri=e.supervised??Zc(),bi=e.replacementIO??{},oe=e.repositoryActivity,_i=oe?.intervalMs??us,dt=e.githubBalance,Ae=e.queueDiscovery,ct=Ae?.transport??oe?.transport,yr=Ae?.unconfiguredReason??Hb,kr=Ae?.intervalMs??15e3,wi=e.demandMs??15e3,ep=e.demandBackoffMs??3e4,v=new Map,Se=new Set,Je=new Map,ut=new Map,Rr=[],pt=[],ft=e.deaths===void 0?void 0:[...e.deaths],I=new Map,ye=new Map,br=new Set,xi={},_r=null,Si=null,wr=null,vi=!1,xr=0,Sr=null,wn="none",vr=null,Ei=null,Er=null,xn=null,G=null,mt=null,Sn=[],vn=null,ht={},Pr=!1,Qe,En,Pn,Dn,jn,On,gt,An,ze,Ye,K=!1,Dr=!1,yt=null,Pi,jr=new Promise(c=>{Pi=c});function Xe(c){Di(c);let h=Date.parse(c),y=pd(I.values(),h);for(let R of y.lapsed){I.delete(R.project_label);let x=G?.projects.find(A=>A.project_label===R.project_label),S=[...v.values()].some(A=>A.project_label===R.project_label);(x?.outcome==="counted"&&(x.depth??0)>0||S)&&ye.set(R.project_label,R),np(R,h)}return y.lapsed}function np(c,h){let y=Number.isFinite(h)?new Date(h).toISOString():c.renew_by;Sn.push({project_label:c.project_label,at:y,renew_by:c.renew_by,renewals:c.renewals,sustains:c.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(c.project_label)}: it stood until ${c.renew_by} and nothing renewed it \u2014 no session spoke for it, and no poll found it work or a Worker to hold it up`}),Sn.length>fu&&Sn.splice(0,Sn.length-fu)}function Di(c){if(I.size===0)return;let h=Date.parse(c);if(!Number.isFinite(h))return;let y={};for(let S of v.values())y[S.project_label]=(y[S.project_label]??0)+1;let R=G==null?Number.NaN:Date.parse(G.fetched_at),x=new Map((G?.projects??[]).map(S=>[S.project_label,S]));for(let S of[...I.values()]){let D=Number.isFinite(R)&&h-R<=S.renew_within_ms?x.get(S.project_label):void 0,Re=Qo(S,{now:c,...D==null?{}:{queue:{outcome:D.outcome,depth:D.depth}},liveWorkers:y[S.project_label]??0});Re.registration!==S&&I.set(S.project_label,Re.registration)}}function tp(c){if(ye.size===0||G==null)return;let h=Date.parse(c);if(!Number.isFinite(h))return;let y=new Map(G.projects.map(R=>[R.project_label,R]));for(let[R,x]of[...ye]){if(h-Date.parse(x.renew_by)>x.renew_within_ms){ye.delete(R);continue}let S=y.get(R);if(S==null)continue;let A=Qo(x,{now:c,queue:{outcome:S.outcome,depth:S.depth},liveWorkers:[...v.values()].filter(D=>D.project_label===R).length});A.verdict==="open-work"||A.verdict==="live-worker"?(I.set(R,A.registration),ye.delete(R)):A.verdict==="drained"&&ye.delete(R)}}function kt(){let c=o();return Xe(c),Zd({now:c,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:l.pid,startedAt:_,scope:id(p.claimPath,u,d),workers:[...v.values()],registrations:[...I.values()],lapses:Sn,queue:G,published:{version:Si,checkedAt:wr,newer:vi,replacement:wn,newest:vr,majorHold:Ei,checks:xr,holdReason:Sr}})}function Rt(){return Gd({hostState:kt(),ceiling:i,rss:xi,sampledAt:_r,logLines:Object.fromEntries(Je),displays:Object.fromEntries(ut),now:o(),reattachedWorkerIds:[...Se],repositoryActivity:Er,githubBalance:xn,...ft===void 0?{}:{deaths:ft},metrics:Ad({observations:Rr,outcomes:pt,now:o()})})}function rp(c,h){Rr=Vn([...Rr,{worker_id:h,observed_at:c.published_at,tokens:c.display.tokens,tools:c.display.tools,runner:c.display.runner,model:c.display.model}],y=>y.observed_at,{now:o()})}function op(c){pt=Vn([...pt,c],h=>h.ts,{now:o()})}async function Or(){return oe==null||oe.projects.length===0?null:(Er=await Cd({projects:oe.projects,hostTokenRef:oe.hostTokenRef,transport:oe.transport,closedWindowMs:oe.closedWindowMs,now:o()}),Er)}async function ji(){return dt==null?null:(xn=await ns({transport:dt.transport,now:o()}),xn)}function sp(){if(K||ze!=null||dt==null)return;let c=()=>{ze=void 0,ji().catch(()=>{}).then(()=>{if(K)return;let h=dt.intervalMsOverride??er(xn??ip(),{now:o()});ze=setTimeout(c,h),ze.unref()})};c()}function ip(){return Zt(o())}function lp(){if(!(ct!=null||Ae?.armTransport==null))try{let c=Ae.armTransport();if(c.transport!=null){ct=c.transport;return}c.unconfiguredReason!=null&&(yr=c.unconfiguredReason)}catch(c){yr=`this host could not resolve a tracker credential: ${c instanceof Error?c.message:String(c)}`}}async function Oi(){let c=o();Xe(c);let h=Date.parse(c);for(let[S,A]of[...ye])Number.isFinite(h)&&h-Date.parse(A.renew_by)>A.renew_within_ms&&ye.delete(S);let R=[...new Map([...ye,...I]).values()].map(S=>({project_label:S.project_label,selector:S.selector})).sort((S,A)=>S.project_label.localeCompare(A.project_label));if(R.length===0)return null;if(lp(),ct==null)return G=Pc(R,c,yr),G;G=await Dc({projects:R,transport:ct,now:c,...Ae?.batchSize==null?{}:{batchSize:Ae.batchSize}});let x=o();return tp(x),Di(x),G}async function Ai(){let c=o();if(Pr)return mt??Ja(c);Pr=!0;try{await Lr().catch(()=>{});let h={};for(let D of v.values())h[D.project_label]=(h[D.project_label]??0)+1;let y={};for(let D of G?.projects??[])y[D.project_label]=D.depth;let R=Date.parse(c),x=qa({projects:[...I.values()].map(D=>({project_label:D.project_label,selector:D.selector,argv:D.argv,workspace_path:D.workspace_path,target:D.target})),queue:y,live:h,nowMs:Number.isFinite(R)?R:0,backoffUntilMs:vn,birthHaltUntilMs:za(ht,Number.isFinite(R)?R:0)}),S=[],A=null;for(let D of x.births){let Re,jp=Fs(v.keys()),St=I.get(D.project_label),Gi=ad({argv:D.argv,...St?.env==null?{}:{env:St.env},...St?.log_path==null?{}:{log_path:St.log_path}},{worker_id:jp,slot:D.index,workspace_path:D.workspace_path},{project_label:D.project_label});try{Re=Ar(Gi)}catch(Nr){A=Nr instanceof Error?Nr.message:String(Nr),vn=(Number.isFinite(R)?R:Date.now())+ep;break}S.push({project_label:D.project_label,worker_id:Re.worker.worker_id,pid:Re.worker.pid,warnings:Gi.log_path==null?[...Re.warnings,`project ${JSON.stringify(D.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(Re.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:Re.warnings})}return A==null&&x.births.length>0&&(vn=null),mt={version:1,at:c,requested:x.births.length,granted:S,shortfall:x.births.length-S.length,refusal:A,retry_after:vn==null?null:new Date(vn).toISOString(),projects:x.intents},mt}finally{Pr=!1}}function ap(c){return Ue(Rt(),{...j,mode:c?.mode??j.mode,project:c?.project??j.project,maxWorkers:c?.max_workers??j.maxWorkers,maxProjects:c?.max_projects??j.maxProjects,maxWidth:c?.max_width??j.maxWidth,verbose:c?.verbose??j.verbose})}function dp(c){return yn(Rt(),{mode:c?.mode??pe.mode,project:c?.project??pe.project,maxWidth:c?.max_width??pe.maxWidth,maxRows:c?.max_rows??pe.maxRows})}function Ze(c,h,y){return md({op:c,sessionProject:h??null,targetProject:y})}async function cp(c){let h=v.get(c.worker_id),y=Ze(fd(c.command),c.session_project,h?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(c.command!=="stop")throw new Error(`redskilled does not implement ${c.command}: it owns birth, death and limits, and ${c.command} is a work decision the project's own bundle makes on top of them`);let R=h!=null&&await hp(h,c.detail??"stopped by its own project");return{version:1,command:c.command,worker_id:c.worker_id,applied:R,reach:y,detail:R?`redskilled stopped Worker ${JSON.stringify(c.worker_id)} of project ${JSON.stringify(h.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function bt(c){v.delete(c),Se.delete(c),Je.delete(c),ut.delete(c)}function Li(c){let h=v.get(c.worker_id),y=Ze("worker-heartbeat",c.session_project,h?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(typeof c.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(h==null)return{version:1,worker_id:c.worker_id,accepted:!1,reach:y,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to publish a line for`};let R=o();Je.set(c.worker_id,{line:c.last_log_line,published_at:R,source:"heartbeat"});let x=c.display===void 0?null:Lc(c.display);if(x!=null){let S={display:x,published_at:R};ut.set(c.worker_id,S),rp(S,c.worker_id)}return{version:1,worker_id:c.worker_id,accepted:!0,reach:y,published_at:R,detail:`redskilled stored a line for Worker ${JSON.stringify(c.worker_id)} without reading it`}}async function up(c,h,y){let R=`exit code=${h??"null"} signal=${y??"null"}`;if(c.unit!=null&&c.unit!==""&&await fp(c)){mp(c,`its launch client ended (${R}) while unit ${JSON.stringify(c.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}bt(c.worker_id),ke("worker-death",c,R,{exitCode:h,signal:y}),N()}function pp(c,h){if(!Number.isFinite(h)||h<0){ht[c]=Kt;return}let y=ht[c]??Kt,R=Qa(y,h,Date.parse(o()));ht[c]=R,R.haltUntilMs!=null&&y.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(c)} lost ${R.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(R.haltUntilMs).toISOString()}
80
- `)}async function fp(c){try{return await w(c)===!0}catch{return!1}}function mp(c,h){let y=c.unit==null?null:ge(c.unit);v.set(c.worker_id,{...c,...y!=null&&y>0?{pid:y}:{},warnings:[...c.warnings,h]}),Se.add(c.worker_id),N()}function Ti(c,h){let y=Ze("project-register",h,c.project_label);if(!y.permitted)throw new Error(y.reason);let R=o();Xe(R);let x=dd(c,{now:R,held:I.get(c.project_label)});return I.set(x.project_label,x),N(),{version:1,registration:x,reach:y,detail:`redskilled holds a registration for project ${JSON.stringify(x.project_label)} at a target of ${x.target} until ${x.renew_by}, and has read neither its selector nor its argv`}}function $i(c,h={}){let y=Ze("project-renew",h.sessionProject,c);if(!y.permitted)throw new Error(y.reason);let R=o();Xe(R);let x=I.get(c);if(x==null)throw new Jt(c);let S=cd(x,{now:R,...h.renewWithinMs==null?{}:{renew_within_ms:h.renewWithinMs},...h.launch==null?{}:{launch:h.launch}});return I.set(S.project_label,S),N(),{version:1,registration:S,reach:y,detail:`redskilled renewed the registration for project ${JSON.stringify(S.project_label)}, which now stands until ${S.renew_by} after renewal ${S.renewals}`+(h.launch==null?"":`, carrying launch revision ${S.launch_revision} for its next Worker`)}}function Ii(c,h){let y=Ze("project-deregister",h,c);if(!y.permitted)throw new Error(y.reason);let R=I.delete(c);return{version:1,project_label:c,released:R,reach:y,detail:R?`redskilled released the registration for project ${JSON.stringify(c)}`:`redskilled held no registration for project ${JSON.stringify(c)}, so there was nothing to release`}}async function hp(c,h){try{await X(c)}catch{}return bt(c.worker_id),ke("worker-death",c,h),N(),!0}function Ni(c){return Ba({ceiling:i,workers:[...v.values()],budget:c.budget,projectLabel:c.project_label})}function Ar(c){let h=Fa({ceiling:i,workers:[...v.values()],budget:c.budget}),y=s({spec:c,admission:Ni(c),memoryCeiling:h,liveWorkerIds:v.keys(),clock:o,onExit:(R,x,S)=>{let A=v.get(R);if(A==null){N();return}up(A,x,S).catch(()=>{})}});return v.set(y.worker.worker_id,y.worker),ke("worker-birth",y.worker,null),N(),y}function ke(c,h,y,R={}){if(K)return;let x=o();(c==="worker-death"||c==="worker-budget-kill")&&(op({worker_id:h.worker_id,ts:x,outcome:c}),Mi({version:1,ts:x,event:c,worker_id:h.worker_id,project_label:h.project_label,pid:h.pid,workspace_path:h.workspace_path,log_path:h.log_path??null,isolated:h.isolated,unit:h.unit??null,memory_high:h.budget?.memory_high??null,memory_max:h.budget?.memory_max??null,cpu_weight:h.budget?.cpu_weight??null,detail:y,reason:null,exit_code:R.exitCode??null,signal:R.signal??null}),pp(h.project_label,Date.parse(x)-Date.parse(h.started_at))),k.record({event:c,worker:h,ts:x,detail:y,...R.exitCode!==void 0?{exitCode:R.exitCode}:{},...R.signal!==void 0?{signal:R.signal}:{}}).catch(()=>{})}function Mi(c){let h=Fb(c);if(h==null)return;let y=[h,...(ft??[]).filter(R=>R.kind!==h.kind||R.id!==h.id)].sort((R,x)=>Date.parse(R.ts)-Date.parse(x.ts));ft=Vn(y,R=>R.ts,{now:o()})}async function Lr(){let c=Date.parse(o()),h=[...v.values()].filter(R=>{if(Se.has(R.worker_id))return!0;let x=Date.parse(R.started_at);return!Number.isFinite(x)||c-x>=O});if(h.length===0)return[];let{dead:y}=await Cs(h,w);for(let R of y)bt(R.worker_id),ke("worker-death",R,"the host no longer confirms this Worker");return y.length>0&&N(),y}async function Ci(c,h){let y=v.get(c);if(!y)return!1;try{await X(y)}catch{}return bt(c),ke("worker-budget-kill",y,h),N(),!0}async function Wi(){let c=[...v.values()];if(c.length===0)return[];let h;try{h=await qe(c)}catch{return[]}let y=h.rss;xi=y,_r=o(),gp(h.cpu_seconds,_r);let{terminations:R}=Td({workers:c,rss:y}),x=[];for(let S of R)await Ci(S.worker_id,S.reason)&&x.push(S);return x}function gp(c,h){for(let[y,R]of Object.entries(c)){if(typeof R!="number"||!Number.isFinite(R))continue;let x=v.get(y);x&&v.set(y,{...x,cpu:{cpu_seconds:R,sampled_at:h}})}}async function yp(){try{return yi<=0?await hi(t):await new Promise(c=>{let h=setTimeout(()=>c(Tr()),yi);h.unref(),hi(t).then(y=>{clearTimeout(h),c(y)},()=>{clearTimeout(h),c(Tr())})})}catch{return Tr()}}function Tr(){try{return Xu(t)}catch{return null}}async function Bi(){if(it(t))return xr+=1,wr=o(),Sr="local-build",{act:"hold",reason:"local-build"};let c=zc(await yp()),h=c.version;Si=h,vr=c.newest??null,wr=o(),Ei=Yc({running:t,newest:vr,supervised:Ri});let y=Xc({running:t,published:h,supervised:Ri});return vi=y.act==="replace",xr+=1,Sr=y.act==="hold"?y.reason:null,wn!=="in-progress"&&(wn=y.act==="replace"?"pending":"none"),y}async function _t(){let c=await Bi();if(c.act!=="replace"||wn==="in-progress")return c;let h=eu(c,bi);return wn="in-progress",await k.flush().catch(()=>{}),await xt({reason:"replaced"}),nu(h,n,{...r==null?{}:{idleMs:r},io:bi}),c}function kp(){K||On!=null||gi<=0||(!Zu&&ki>0&&(gt=setTimeout(()=>{_t().catch(()=>{})},ki),gt.unref()),On=setInterval(()=>{_t().catch(()=>{})},gi),On.unref())}async function Fi(){return await a.renew(l).catch(()=>null)}function Rp(){K||Pn!=null||fi<=0||(Pn=setInterval(()=>{Fi()},fi),Pn.unref())}function bp(){K||Dn!=null||mi<=0||(Dn=setInterval(()=>{Xe(o())},mi),Dn.unref())}function _p(){K||En!=null||pi<=0||(En=setInterval(()=>{Wi().catch(()=>{})},pi),En.unref())}function wp(){K||An!=null||oe==null||oe.projects.length===0||_i<=0||(Or().catch(()=>{}),An=setInterval(()=>{Or().catch(()=>{})},_i),An.unref())}function xp(){if(K||Ye!=null||kr<=0)return;let c=h=>{Ye=setTimeout(()=>{Ye=void 0,Oi().catch(()=>{}).finally(()=>{if(K)return;let y=Date.parse(o());c(Ac(G,kr,Number.isFinite(y)?y:Date.now()))})},h),Ye.unref()};c(kr)}function Sp(){K||jn!=null||wi<=0||(jn=setInterval(()=>{Ai().catch(()=>{})},wi),jn.unref())}function N(){K||(Qe&&clearTimeout(Qe),Qe=setTimeout(()=>{Lr().catch(()=>{}).then(()=>Hi())},r),Qe.unref())}function Hi(){return v.size>0?(N(),"held-by-workers"):(Xe(o()),I.size>0?(N(),"held-by-registrations"):(vp(),"exited"))}async function vp(){if(!it(t)){if((await _t().catch(()=>null))?.act==="replace"||Dr||K)return;if(v.size>0||I.size>0){N();return}}await xt({reason:"idle"})}function wt(c){return Xa({reason:c,socketPath:n.socketPath,daemonVersion:t,pid:l.pid,workers:[...v.values()],projects:[...I.keys()]})}function Ui(c){if(yt!=null)return yt;let h=c.reason??"requested",y=c.note?.trim();return yt=k.recordDaemonStop({ts:o(),pid:l.pid,socketPath:n.socketPath,reason:h,detail:y==null||y===""?wt(h).detail:`${wt(h).detail} \u2014 ${y}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),yt}async function xt(c={}){if(Dr)return await jr;Dr=!0,await Ui(c),K=!0,Qe&&clearTimeout(Qe),En&&clearInterval(En),Pn&&clearInterval(Pn),Dn&&clearInterval(Dn),On&&clearInterval(On),gt&&clearTimeout(gt),An&&clearInterval(An),ze&&clearTimeout(ze),Ye&&clearTimeout(Ye),jn&&clearInterval(jn),await k.flush().catch(()=>{}),g.close();for(let h of br)h.destroy();return await new Promise(h=>g.once("close",()=>h())),await mu(n.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await p.release(d).catch(()=>{}),Pi(),await jr}let $r=await k.read().catch(()=>[]);for(let c of $r)Mi(c);pt=Vn($r.filter(c=>c.event==="worker-death"||c.event==="worker-budget-kill").map(c=>({worker_id:c.worker_id,ts:c.ts,outcome:c.event})),c=>c.ts,{now:o()});let Ep=Va($r),Ir=await Cs(Ep,w);for(let c of Ir.alive){let h=Sc(c),y=h.unit==null||B(h.pid)?null:ge(h.unit);v.set(h.worker_id,y!=null&&y>0?{...h,pid:y}:h),Se.add(h.worker_id)}for(let c of Ir.dead)ke("worker-death",c,"the Worker ended while no daemon was watching");let Pp=xc({units:await Promise.resolve(he()).catch(()=>[]),held:[...v.values()],mainPid:ge,now:_});for(let c of Pp)v.set(c.worker_id,c),Se.add(c.worker_id),ke("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of Ir.alive){if(c.log_path==null||Je.has(c.worker_id))continue;let h=await gr(c.log_path).catch(()=>null);h==null||h.trim()===""||Je.set(c.worker_id,{line:h,published_at:o(),source:"rehydrated"})}g.on("connection",c=>{br.add(c),c.once("close",()=>br.delete(c)),N(),Kb(c,async(h,y)=>{N();let R=await Dp(h);y(R),h.op==="shutdown"&&setImmediate(()=>void xt({reason:"requested"}))})});async function Dp(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:or,daemon_version:t,pid:l.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:kt()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:Ud(Rt(),c.extras)};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:ap(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:dp(c.dashboard)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:Li(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:Ti(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:$i(c.project_label,{...c.session_project==null?{}:{sessionProject:c.session_project},...c.renew_within_ms==null?{}:{renewWithinMs:c.renew_within_ms},...c.launch==null?{}:{launch:c.launch}})};if(c.op==="project-deregister")return{id:c.id,ok:!0,value:Ii(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await cp(c.command)};if(c.op==="worker-start"){let y=Ze("worker-start",c.session_project,c.spec.project_label);if(!y.permitted)return{id:c.id,ok:!1,error:y.reason};let R=Ar(c.spec);return await k.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:R.worker,admission:R.admission,warnings:R.warnings}}}if(c.op==="shutdown"){let y=wt("requested");return await Ui({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:y}}let h=c;return{id:h.id??ur(),ok:!1,error:`unsupported redskilled op: ${h.op??"unknown"}`}}catch(h){return{id:c.id??ur(),ok:!1,error:h instanceof Error?h.message:String(h)}}}return N(),_p(),Rp(),bp(),kp(),wp(),sp(),xp(),Sp(),{socketPath:n.socketPath,lease:m.lease,startedAt:_,closed:jr,startWorker:Ar,admit:Ni,ceiling:()=>i,killWorkerOverBudget:Ci,sampleMemoryBudgets:Wi,renewLease:Fi,pollRepositoryActivity:Or,pollGithubBalance:ji,githubBalance:()=>xn,pollQueueDiscovery:Oi,queueDiscovery:()=>G,driveDemand:Ai,demand:()=>mt,sweepWorkerLiveness:Lr,publishWorkerHeartbeat:Li,reattached:()=>[...Se].map(c=>v.get(c)).filter(c=>c!=null),flushEvents:()=>k.flush(),trackWorker(c){v.set(c.worker_id,c),ke("worker-birth",c,null),N()},releaseWorker(c){let h=v.get(c),y=v.delete(c);return Se.delete(c),Je.delete(c),ut.delete(c),h&&ke("worker-death",h,"released by the daemon"),N(),y},workerCount:()=>v.size,registerProject:Ti,renewProject:$i,deregisterProject:Ii,registrations:()=>kt().registrations??[],hostState:kt,statuslinePayload:Rt,evaluateIdle:Hi,observePublishedVersion:Bi,checkForReplacement:_t,stopReport:wt,stop:xt}}async function Ub(e,n=250){return await new Promise(t=>{let r=Tb(e),o=!1,s=l=>{o||(o=!0,clearTimeout(i),r.destroy(),t(l))},i=setTimeout(()=>s("unknown"),n);i.unref?.(),r.once("connect",()=>s("owned")),r.once("error",l=>{s(l.code==="ECONNREFUSED"||l.code==="ENOENT"?"unowned":"unknown")})})}async function Gb(e,n){for(let t=0;t<2;t++){let r=$b();try{return await new Promise((o,s)=>{r.once("error",s),r.listen(e,()=>{r.off("error",s),o()})}),r}catch(o){if(r.close(),o.code!=="EADDRINUSE")throw o;if(await Ub(e)!=="unowned")throw new Ke(e);if(await n?.())throw new Ke(e);await mu(e,{force:!0})}}throw new Ke(e)}async function fe(e,n=250){try{return(await Ct({socketPath:e,timeoutMs:n},{id:ur(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function Kb(e,n){Ra(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??ur(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function Xs(e){let n=e.socketPath,t=Vb(e);return e.answers?{version:1,kind:"answering",socket_path:n,holder:t,reason:`a redskilled daemon answered on ${JSON.stringify(n)}`,repair:"nothing to repair"}:t!=null?{version:1,kind:"held-unresponsive",socket_path:n,holder:t,reason:`redskilled pid ${t.pid} is alive and has held ${JSON.stringify(n)} since ${t.acquired_at}${t.uptime_ms==null?"":` (up ${gu(t.uptime_ms)})`}, but it did not answer a ping \u2014 this is a daemon that could not be REACHED, not one that is missing.`,repair:`Do not provision: a daemon is already running. Inspect it (\`ps -p ${t.pid}\`), or stop it with \`${Oe("red-skills-redskilled",["stop"])}\` and let the next client start a fresh one.`}:{version:1,kind:"absent",socket_path:n,holder:null,reason:`nothing answered on ${JSON.stringify(n)} and no live process holds its lease`,repair:`Install and start one with \`${Oe("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function Zs(e){return`${e.reason} ${e.repair}`}function Vb(e){let n=e.lease;return n==null||e.holderAlive!==!0||n.socket_path!==e.socketPath?null:{pid:n.pid,socket_path:n.socket_path,acquired_at:n.acquired_at,renewed_at:n.renewed_at,uptime_ms:qb(n.acquired_at,e.now??new Date().toISOString())}}function qb(e,n){let t=Date.parse(e),r=Date.parse(n);return!Number.isFinite(t)||!Number.isFinite(r)?null:Math.max(0,r-t)}function gu(e){let n=Math.floor(e/1e3),t=Math.floor(n/3600),r=Math.floor(n%3600/60),o=n%60;return t>0?`${t}h${String(r).padStart(2,"0")}m`:r>0?`${r}m${String(o).padStart(2,"0")}s`:`${o}s`}_e();var Ru=1e4,Ve=class extends Error{constructor(t,r,o){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}${o!=null&&o.kind==="held-unresponsive"?`. ${Zs(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},ei=class extends Ve{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}},pr=class extends Error{constructor(t){super(t);this.refusal=t;this.name="RedskilledRequestRefusedError"}};async function fr(e,n={}){let t=n.answers??await fe(e.socketPath),r=await lt(e.leasePath).catch(()=>{});return Xs({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&B(r.pid)})}async function ni(e,n={}){try{return await Yb(e,n)}catch(t){if(t instanceof De||t instanceof Ve)throw t;let r=await fr(e).catch(()=>{});throw new Ve(e.socketPath,t,r)}}async function Yb(e,n){if(await Qb(zb(e.socketPath),{recursive:!0,mode:448}),await fe(e.socketPath))return"already-running";await e_(e);let t=await Zb(e,n);if(t!=null)return t;let r=await _a(e.lockPath,{...n.spawnLockMaxAgeMs==null?{}:{maxAgeMs:n.spawnLockMaxAgeMs},onReap:n.onSpawnLockReaped??Xb});if(!r.acquired)return await yu(e,n,void 0,r),"joined";try{if(await fe(e.socketPath))return"already-running";let o=await t_(e,n);return await yu(e,n,o),"spawned"}finally{await wa(r)}}function Xb(e){process.stderr.write(`redskilled: reaped the spawn lock ${JSON.stringify(e.lockPath)} (${e.reason}, ${Math.round(e.ageMs/1e3)}s old, holder ${e.holder==null?"unnamed":`pid ${e.holder.pid}`}) and went on to spawn
81
- `)}async function Zb(e,n){let t=await fr(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??Ru,o=Date.now()+r;for(;;){if(await fe(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(i=>setTimeout(i,25))}let s=await fr(e).catch(()=>{});if(s==null||s.kind!=="held-unresponsive")return null;throw new ei(e.socketPath,s,new Error(`it did not answer a ping within ${r}ms, and no second daemon was spawned because pid ${s.holder?.pid??"unknown"} still holds this socket`))}async function e_(e){let t=await qt(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&B(t.pid))throw new De(e.machineClaimPath,"held",t)}async function bu(e,n,t={}){await ni(e,t);let r;try{r=await ot({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:ku()})}catch(o){throw new Ve(e.socketPath,o,await fr(e).catch(()=>{}))}if(!r.ok)throw new pr(r.error);return r.value}async function _u(e,n={},t={}){if(!await fe(e.socketPath))return Za(e.socketPath);let r;try{r=await ot({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:ku(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new Ve(e.socketPath,i)}if(!r.ok)throw new pr(r.error);if(!Fo(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await n_(e.socketPath,n.settleTimeoutMs??5e3)?o:{...o,stopped:!1,detail:`${o.detail}; the daemon accepted the stop and is still answering on ${JSON.stringify(e.socketPath)}`}}async function n_(e,n){let t=Date.now()+n;for(;;){if(!await fe(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function wu(e,n={}){let t=await bu(e,{op:"host-state"},n);if(!ec(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function xu(e,n={},t){let r=await bu(e,{op:"statusline-payload",...n.sessionProject!=null?{session_project:n.sessionProject}:{},...t==null?{}:{extras:t}},n);if(!fs(r))throw new Error("redskilled daemon returned a malformed statusline payload");return r}async function Su(e,n=j,t={}){let r=await xu(e,t,{vitals:!0,logs:n.verbose,display:!0});return Ue(r,n)}async function vu(e,n={},t={}){let r=await xu(e,t,{vitals:!0,logs:!0,display:!0});return yn(r,{...pe,...n})}async function yu(e,n,t,r){let o=Date.now()+(n.readyTimeoutMs??Ru);for(;;){if(await fe(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=o){if(r!=null)throw new Error(`no redskilled daemon answered on ${JSON.stringify(e.socketPath)} within the ready window, and ${xa(r)}`);let s=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${s}`)}await new Promise(s=>setTimeout(s,25))}}async function t_(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await Ta({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,...Ce(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=Jb(r.command,s,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return i.on("error",l=>{o.failure=l}),i.on("exit",(l,a)=>{o.exit=a?`died on ${a}`:`exited with code ${l??-1}`}),i.unref(),o}_e();import{chmod as Lu,mkdir as $u,readFile as Iu,stat as f_,writeFile as m_}from"node:fs/promises";import{homedir as oi}from"node:os";import{dirname as h_,join as si}from"node:path";import{join as r_}from"node:path";var Eu=["local","tmp","host"],o_="local",at="plugins.dev.workspace.target";var ti=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function Du(e){let n=dn(e,at),t=l_(n??"").trim();return t===""?void 0:t}function ju(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:o_};let t=Eu.find(r=>r===n.toLowerCase());if(t)return{kind:"preset",preset:t};if(n.startsWith("/")||n==="~"||n.startsWith("~/"))return{kind:"custom",parentDir:n};throw new ti(`${at}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${Eu.join(", ")}) or an absolute parent directory for Workers.`)}function Ou(e,n){return e.kind==="preset"?e.preset==="host":i_(s_(e.parentDir,n),Me(n))}function s_(e,n){return e==="~"?Pu(n):e.startsWith("~/")?r_(n,e.slice(2)):Pu(e)}function i_(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Pu(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function l_(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}_e();import{createHash as a_}from"node:crypto";import{hostname as d_}from"node:os";import{join as mr}from"node:path";var _n="redskilled.sock",c_="REDSKILLED_SESSION";function u_(e={}){let n=e.env??process.env,t=n[c_]?.trim();if(t)return t;let r=n.XDG_RUNTIME_DIR?.trim();return r||`uid:${e.uid??(typeof process.getuid=="function"?process.getuid():"nouid")}`}function p_(e={}){return Au(e.host??d_())}function me(e={}){let n=u_(e),t=e.runtimeDir??Wt({key:`redskilled:${n}`,socketFileName:_n,env:e.env,uid:e.uid}),r=p_(e);return{sessionKey:n,sessionKeyHash:Au(n),machineIdHash:r,runtimeDir:t,socketPath:mr(t,_n),lockPath:mr(t,"redskilled.spawn.lock"),leasePath:mr(t,"redskilled.lease.toon"),eventLanePath:mr(t,Ga),machineClaimPath:e.machineClaimPath??Vt({env:e.env,machineIdHash:r,platform:e.platform})}}function Au(e){return a_("sha256").update(e).digest("hex").slice(0,12)}var ri=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${Oe("red-skills-redskilled",["provision"])}\` directly`;async function Nu(e=oi()){let n=Me(e),t=await li(n);return t===void 0?(await $u(n,{recursive:!0,mode:ae}),await Lu(n,ae),{path:n,created:!0,tightened:!1,mode:ae}):t===ae?{path:n,created:!1,tightened:!1,mode:t}:(await Lu(n,ae),{path:n,created:!1,tightened:!0,mode:ae})}var Mu={needed:!1,declaredBy:`no ${at} in view`};async function ii(e={}){let n=e.homeDir??oi(),t=e.declaredTarget?.trim();if(t)return Tu(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return Mu;let o=si(r,".red","config.yaml"),s=await Iu(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=Du(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Tu(i,n,o)}function Tu(e,n,t){let r=`${at}: ${e} (${t})`;try{return{needed:Ou(ju(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function Cu(e){let n=[g_(e),y_(e),k_(e),R_(e)],t=n.filter(o=>o.verdict!=="ok");return{verdict:t.some(o=>o.verdict==="missing")?"missing":t.length>0?"degraded":"ok",rows:n,findings:t}}function g_(e){let n=e.homeNeed??Mu;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:ri}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??ae;return t!==ae?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${ae.toString(8)}`,fix:`${ri} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function y_(e){return ce(e.entry)?{check:"daemon-entry",verdict:"ok",evidence:`${e.entry.entry??e.entry.command} (resolved as ${e.entry.source})`,fix:""}:{check:"daemon-entry",verdict:"missing",evidence:`no published redskilled bundle; probed ${e.entry.searched.join(", ")||"nothing"}`,fix:`install or warm the RedSkills bundle for this host, then re-run \`${Oe("red-skills-redskilled",["provision"])}\``}}function k_(e){return e.reachable?{check:"reach",verdict:"ok",evidence:`daemon answered on ${e.socketPath}`,fix:""}:{check:"reach",verdict:"missing",evidence:`no daemon answered on ${e.socketPath}`,fix:`${ri} \u2014 it starts the daemon and waits for the socket`}}function R_(e){return{check:"supervisor-unit",verdict:"ok",evidence:e.supervisorUnit==="installed"?"redskilled.service is installed (optional supervision, Restart=on-failure)":e.supervisorUnit==="unsupported"?"optional: this host has no systemd --user session; auto-spawn is the only start path":"optional: not installed; auto-spawn already starts the daemon on first use",fix:""}}async function Wu(e={}){let n=e.env??process.env,t=e.homeDir??oi(),r=e.paths??me({env:n}),o=Me(t),[s,i,l]=await Promise.all([li(o),fe(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):ii({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:Pe(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await __(w_(e,n,t),n)}}var b_="redskilled.service";function Bu(e){return si(e,"systemd","user",b_)}function Fu(e){let n=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${n}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
82
- `)}async function Hu(e){let n=Bu(e.configHome);return await li(n)!==void 0?{path:n,status:"already-present"}:(await $u(h_(n),{recursive:!0}),await m_(n,e.unit,"utf8"),{path:n,status:"installed"})}async function __(e,n){if(process.platform!=="linux")return"unsupported";try{return await Iu(Bu(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function w_(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??si(t,".config")}async function li(e){try{return(await f_(e)).mode&511}catch{return}}import{readdir as Gu,rm as x_,stat as S_}from"node:fs/promises";import{dirname as v_,join as ai}from"node:path";var E_=5*6e4,P_="redskilled.";function D_(e={}){let n=e.env??process.env,t=i=>v_(Wt({key:"redskilled:reclaim-probe",socketFileName:_n,env:i,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=n,s=[t(n),t(o)];return[...new Set(s)]}async function Ku(e={}){let n=e.roots??D_(e),t=e.graceMs??E_,r=e.now??Date.now,o=e.isPidAlive??B,s=e.answers??L_,i=e.dryRun===!0,l=[];for(let a of n){let d;try{d=(await Gu(a,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name)}catch{continue}for(let u of d.sort())l.push(await j_(ai(a,u),{graceMs:t,now:r,pidAlive:o,answers:s,dryRun:i}))}return{roots:n,scanned:l.length,reclaimed:l.filter(a=>a.verdict==="reclaimed").length,dryRun:i,entries:l}}async function j_(e,n){let t;try{t=(await Gu(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:Vu(i),removed:[]}}let r=t.filter(i=>i.startsWith(P_));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await O_(ai(e,"redskilled.lease.toon"));if(o!==void 0)return await n.pidAlive(o.pid)?{dir:e,verdict:"live",reason:`lease pid ${o.pid} is alive`,removed:[]}:await Uu(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(_n)&&await n.answers(ai(e,_n)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await A_(e,n.now);return s!==void 0&&s<n.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(s/1e3)}s ago`,removed:[]}:await Uu(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function Uu(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await x_(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:Vu(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function O_(e){try{return await lt(e)}catch{return}}async function A_(e,n){try{return Math.max(0,n()-(await S_(e)).mtimeMs)}catch{return}}async function L_(e){try{return(await ot({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function Vu(e){return e instanceof Error?e.message:String(e)}var T_="plugins.dev.statusline",$_="dev.statusline";function I_(e){let n=[],t=l=>{for(let a of[T_,$_]){let d=`${a}.${l}`,u=dn(e,d)?.trim();if(u!=null&&u!=="")return{key:d,value:u}}},r=t("mode"),o={};r!=null&&(r.value==="local"||r.value==="global"?o.mode=r.value:n.push({...r,reason:"expected `local` or `global`"}));let s=[{leaf:"max_workers",assign:l=>{o.maxWorkers=l}},{leaf:"max_projects",assign:l=>{o.maxProjects=l}},{leaf:"max_width",assign:l=>{o.maxWidth=l}}];for(let l of s){let a=t(l.leaf);if(a==null)continue;let d=Number(a.value);Number.isInteger(d)&&d>=0?l.assign(d):n.push({...a,reason:"expected a whole number of zero or more"})}let i=t("verbose");return i!=null&&(i.value==="true"||i.value==="false"?o.verbose=i.value==="true":n.push({...i,reason:"expected `true` or `false`"})),{config:o,warnings:n}}var N_={mode:{kind:"value",coerce:e=>e},verbose:{kind:"boolean"},project:{kind:"value",coerce:e=>e},"max-workers":{kind:"value",coerce:e=>e},"max-projects":{kind:"value",coerce:e=>e},"max-width":{kind:"value",coerce:e=>e}};function di(e){let{values:n,positionals:t}=Ie(e,N_),r=[],o={},s=n.mode??t.find(l=>l==="global"||l==="local");s!=null&&(s==="local"||s==="global"?o.mode=s:r.push({key:"--mode",value:s,reason:"expected `local` or `global`"})),n.project!=null&&(o.project=n.project),n.verbose!==void 0&&(o.verbose=n.verbose===!0);let i=[{flag:"max-workers",assign:l=>{o.maxWorkers=l}},{flag:"max-projects",assign:l=>{o.maxProjects=l}},{flag:"max-width",assign:l=>{o.maxWidth=l}}];for(let l of i){let a=n[l.flag];if(a==null)continue;let d=Number(a);Number.isInteger(d)&&d>=0?l.assign(d):r.push({key:`--${l.flag}`,value:a,reason:"expected a whole number of zero or more"})}return{flags:o,warnings:r}}function ci(e={}){let n=e.configText==null?{config:{},warnings:[]}:I_(e.configText),t=e.flags??{};return{options:{...j,mode:t.mode??n.config.mode??j.mode,project:t.project!==void 0?t.project:e.project??j.project,maxWorkers:t.maxWorkers??n.config.maxWorkers??j.maxWorkers,maxProjects:t.maxProjects??n.config.maxProjects??j.maxProjects,maxWidth:t.maxWidth??n.config.maxWidth??j.maxWidth,verbose:t.verbose??n.config.verbose??j.verbose},warnings:n.warnings}}var C_=`Usage: redskilled <command> [options]
78
+ `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function Xb(e,n={}){let t=n.env??process.env,r=n.exists??Vb,o=n.execPath??process.execPath,s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,l=[],a=[[iu(qt(t),i),"bundle-cache"]];s&&a.push([iu(Jb(Qb(s)),i),"caller-sibling-bundle"]);for(let[d,u]of a)if(l.push(d),r(d))return{command:o,args:[d],version:e,source:u,searched:l};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new li(e,l);return{command:t.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:l}}function gu(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>Xb(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function yu(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??e_)(lu),{...e,exitCode:lu};let o=[...e.entry.args,...Ue(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??Zb(r.env))(e.entry,o),e}function Zb(e){return(n,t)=>{let r=Kb(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[cu]:"1"}});r.on("error",()=>{}),r.unref()}}function e_(e){process.exitCode=e,process.exit(e)}async function ku(e,n=process.env,t=n_){let r=bu(n),o=_u(e,n);if(n[zb]==="1")return{version:o,newest:r};let s=oe(e)===null?"0.0.0":e;try{let i=await Ba({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function Ru(e,n=process.env,t){let r=t??ai;return{version:_u(e,n,r),newest:bu(n,r)}}function bu(e=process.env,n=ai){return xu(wu(e,n))}function _u(e,n=process.env,t=ai){let r=oe(e.trim())?.major;return r===void 0?null:xu(wu(n,t).filter(o=>oe(o)?.major===r))}function wu(e,n){let t=[];for(let r of n(qt(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||oe(o)===null||t.push(o)}return t}function xu(e){let n=null;for(let t of e)(n===null||ti(t,n)>0)&&(n=t);return n}function ai(e){try{return qb(e)}catch{return[]}}async function n_(e){let n=await fetch(e,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`registry read failed with HTTP ${n.status}`);return await n.text()}import{mkdir as t_,readFile as r_,rename as o_,rm as di,writeFile as Su}from"node:fs/promises";import{randomUUID as s_}from"node:crypto";import{dirname as i_}from"node:path";var yr=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function ct(e){let n;try{n=await r_(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=l_(n);return a_(t)?t:void 0}var vu;function Pu(){return vu??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},vu}function Du(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??H;async function s(){return await ct(e)}async function i(a){let d=`${e}.${a.pid}.${s_()}.tmp`;await Su(d,Eu(a),{encoding:"utf8",mode:384}),await o_(d,e)}function l(a,d){return{version:1,pid:a.pid,start_time:a.startTime,session_key_hash:n.sessionKeyHash,machine_id_hash:n.machineIdHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}return{read:s,async acquire(a){await t_(i_(e),{recursive:!0,mode:448});let d=!1;for(;;){let u=r(),p=l(a,u);try{return await Su(e,Eu(p),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:p}}catch(m){if(m.code!=="EEXIST")throw m}let f=await s();if(!f){await di(e,{force:!0}),d=!0;continue}if(ci(f,a))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await di(e,{force:!0}),d=!0}},async renew(a){let d=await s();if(!d||!ci(d,a))throw new yr(e);let u={...d,renewed_at:r()};return await i(u),u},async release(a){let d=await s();if(!d)return!1;if(!ci(d,a))throw new yr(e);return await di(e,{force:!0}),!0}}}function ci(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function Eu(e){return`${W(e,{keyedMapCollapse:!0})}
79
+ `}function l_(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Y(n)}catch{return null}}}function a_(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;if(n.version!==1||!Number.isInteger(n.pid)||n.pid<=0)return!1;for(let t of["start_time","session_key_hash","machine_id_hash","socket_path","acquired_at","renewed_at"])if(typeof n[t]!="string"||n[t].length===0)return!1;return!0}var ut=3e5,y_=1e4,k_=6e4,R_=15e3,b_=3e4,__=6e4,kr=16;function w_(e,n={}){if(e.event!=="worker-death"&&e.event!=="worker-budget-kill")return null;let t=e.event==="worker-budget-kill",r=!t&&n.refusal!=null,o=n.refusal??e.detail??`redskilled observed exit code=${e.exit_code??"null"} signal=${e.signal??"null"}`,s=n.startedAt==null?null:Date.parse(n.startedAt),i=Date.parse(e.ts),l=s!=null&&Number.isFinite(s)&&Number.isFinite(i)?Math.max(0,i-s)/1e3:void 0;return{version:1,ts:e.ts,kind:"worker",id:e.worker_id,pid:e.pid,last_seen:e.ts,last_phase:r?"boot-refused":"unreported",sender_class:t?"teardown":r?"boot-refused":"unknown",confidence:t||r?"high":"none",signal:e.signal,host_boot_changed:!1,evidence:t||r?[o]:[],checked:r?["Worker log tail"]:[`redskilled host event: ${o}`],project_label:e.project_label,...l===void 0?{}:{uptime_s:l},detail:n.refusal??e.detail}}function ju(e){let n=e?.match(/\bsession-error:\s*(.+)$/)?.[1]?.trim();return n==null||n===""?null:n}var ze=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},x_="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Au(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??ut,o=e.clock??(()=>new Date().toISOString()),s=e.launch??Zc,i=e.ceiling??Xt();e.repositoryActivity!=null&&vs(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??Pu(),a=e.leaseStore??Du(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??_d(),u={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},p=e.machineClaimStore??nr(n.machineClaimPath,u,{clock:o});await f_(g_(n.socketPath),{recursive:!0,mode:448});let f=await p.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new ze(n.socketPath):new Le(p.claimPath,f.reason,f.claim);let m=await a.acquire(l);if(!m.acquired)throw await p.release(d).catch(()=>{}),new ze(n.socketPath,m.lease);let g;try{g=await v_(n.socketPath,async()=>{let[c,h]=await Promise.all([a.read().catch(()=>{}),p.read().catch(()=>{})]);return c!=null&&c.pid!==l.pid&&H(c.pid)?!0:h!=null&&h.socket_path===n.socketPath&&h.pid!==d.pid&&H(h.pid)})}catch(c){throw await a.release(l).catch(()=>{}),await p.release(d).catch(()=>{}),c}let _=o(),k=e.eventLane??ld(n.eventLanePath),x=e.liveness??Tc,v=e.livenessGraceMs??$c,G=e.stopWorker??Bc,ye=e.unitInventory??(()=>Mc(n.machineClaimPath,er({machineIdHash:n.machineIdHash}))?Cc():[]),ke=e.unitMainPid??Nc,Xe=e.treeSampler??zd,ft=e.readLogTail??eu,Si=e.sampleMs??R_,vi=e.leaseRenewMs??b_,Ei=e.registrationSustainMs??__,Pi=e.publishedVersion??(c=>ku(c)),Di=e.replaceCheckMs??du,ji=e.publishedProbeTimeoutMs??y_,Rp=e.localPublishedEvidence??(c=>Ru(c,e.replacementIO?.env??process.env)),bp=e.bornByReplacement??uu(),Oi=e.replaceBootCheckMs??k_,Ai=e.supervised??hu(),Li=e.replacementIO??{},se=e.repositoryActivity,$i=se?.intervalMs??Ss,mt=e.githubBalance,Ne=e.queueDiscovery,ht=Ne?.transport??se?.transport,Pr=Ne?.unconfiguredReason??x_,Dr=Ne?.intervalMs??15e3,Ti=e.demandMs??15e3,_p=e.demandBackoffMs??3e4,E=new Map,je=new Set,Ze=new Map,gt=new Map,jr=[],yt=[],kt=e.deaths===void 0?void 0:[...e.deaths],$=new Map,ie=new Map,Or=new Set,Ii={},Ar=null,Ni=null,Lr=null,Mi=!1,$r=0,Tr=null,Dn="none",Ir=null,Ci=null,Nr=null,jn=null,K=null,Rt=null,Re=[],be=[],Mr=new Map((e.orphanedRegistrations??[]).map(c=>[c.project_label,c])),On=null,bt={},Cr=!1,en,An,Ln,$n,Tn,In,_t,Nn,nn,tn,V=!1,Wr=!1,wt=null,Wi,Hr=new Promise(c=>{Wi=c});function rn(c){Hi(c);let h=Date.parse(c),y=Dd($.values(),h);for(let b of y.lapsed){$.delete(b.project_label);let w=K?.projects.find(O=>O.project_label===b.project_label),S=[...E.values()].some(O=>O.project_label===b.project_label);(w?.outcome==="counted"&&(w.depth??0)>0||S)&&ie.set(b.project_label,b),wp(b,h)}return y.lapsed}function wp(c,h){let y=Number.isFinite(h)?new Date(h).toISOString():c.renew_by;Re.push({project_label:c.project_label,registered_at:c.registered_at,at:y,renew_by:c.renew_by,renewals:c.renewals,sustains:c.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(c.project_label)}: it stood until ${c.renew_by} and nothing renewed it \u2014 no session spoke for it, and no poll found it work or a Worker to hold it up`}),Re.length>kr&&Re.splice(0,Re.length-kr)}function Hi(c){if($.size===0)return;let h=Date.parse(c);if(!Number.isFinite(h))return;let y={};for(let S of E.values())y[S.project_label]=(y[S.project_label]??0)+1;let b=K==null?Number.NaN:Date.parse(K.fetched_at),w=new Map((K?.projects??[]).map(S=>[S.project_label,S]));for(let S of[...$.values()]){let D=Number.isFinite(b)&&h-b<=S.renew_within_ms?w.get(S.project_label):void 0,Q=as(S,{now:c,...D==null?{}:{queue:{outcome:D.outcome,depth:D.depth}},liveWorkers:y[S.project_label]??0});Q.registration!==S&&$.set(S.project_label,Q.registration)}}function xp(c){if(ie.size===0||K==null)return;let h=Date.parse(c);if(!Number.isFinite(h))return;let y=new Map(K.projects.map(b=>[b.project_label,b]));for(let[b,w]of[...ie]){if(h-Date.parse(w.renew_by)>w.renew_within_ms){ie.delete(b);continue}let S=y.get(b);if(S==null)continue;let O=as(w,{now:c,queue:{outcome:S.outcome,depth:S.depth},liveWorkers:[...E.values()].filter(D=>D.project_label===b).length});O.verdict==="open-work"||O.verdict==="live-worker"?($.set(b,O.registration),ie.delete(b)):O.verdict==="drained"&&ie.delete(b)}}function xt(){let c=o();return rn(c),hc({now:c,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:l.pid,startedAt:_,ceiling:i,scope:wd(p.claimPath,u,d),workers:[...E.values()],registrations:[...$.values()],lapses:Re,stops:be,orphanedRegistrations:[...Mr.values()],queue:K,published:{version:Ni,checkedAt:Lr,newer:Mi,replacement:Dn,newest:Ir,majorHold:Ci,checks:$r,holdReason:Tr}})}function St(){return ic({hostState:xt(),ceiling:i,rss:Ii,sampledAt:Ar,logLines:Object.fromEntries(Ze),displays:Object.fromEntries(gt),now:o(),reattachedWorkerIds:[...je],repositoryActivity:Nr,githubBalance:jn,...kt===void 0?{}:{deaths:kt},metrics:qd({observations:jr,outcomes:yt,now:o()})})}function Sp(c,h){jr=Xn([...jr,{worker_id:h,observed_at:c.published_at,tokens:c.display.tokens,tools:c.display.tools,runner:c.display.runner,model:c.display.model}],y=>y.observed_at,{now:o()})}function vp(c){yt=Xn([...yt,c],h=>h.ts,{now:o()})}async function Br(){return se==null||se.projects.length===0?null:(Nr=await ec({projects:se.projects,hostTokenRef:se.hostTokenRef,transport:se.transport,closedWindowMs:se.closedWindowMs,now:o()}),Nr)}async function Bi(){return mt==null?null:(jn=await ms({transport:mt.transport,now:o()}),jn)}function Ep(){if(V||nn!=null||mt==null)return;let c=()=>{nn=void 0,Bi().catch(()=>{}).then(()=>{if(V)return;let h=mt.intervalMsOverride??lr(jn??Pp(),{now:o()});nn=setTimeout(c,h),nn.unref()})};c()}function Pp(){return ir(o())}function Dp(){if(!(ht!=null||Ne?.armTransport==null))try{let c=Ne.armTransport();if(c.transport!=null){ht=c.transport;return}c.unconfiguredReason!=null&&(Pr=c.unconfiguredReason)}catch(c){Pr=`this host could not resolve a tracker credential: ${c instanceof Error?c.message:String(c)}`}}async function Fi(){let c=o();rn(c);let h=Date.parse(c);for(let[S,O]of[...ie])Number.isFinite(h)&&h-Date.parse(O.renew_by)>O.renew_within_ms&&ie.delete(S);let b=[...new Map([...ie,...$]).values()].map(S=>({project_label:S.project_label,selector:S.selector})).sort((S,O)=>S.project_label.localeCompare(O.project_label));if(b.length===0)return null;if(Dp(),ht==null)return K=Uc(b,c,Pr),K;K=await Gc({projects:b,transport:ht,now:c,...Ne?.batchSize==null?{}:{batchSize:Ne.batchSize}});let w=o();return xp(w),Hi(w),K}async function Ui(){let c=o();if(Cr)return Rt??cd(c);Cr=!0;try{await Ur().catch(()=>{});let h={};for(let D of E.values())h[D.project_label]=(h[D.project_label]??0)+1;let y={};for(let D of K?.projects??[])y[D.project_label]=D.depth;let b=Date.parse(c),w=dd({projects:[...$.values()].map(D=>({project_label:D.project_label,selector:D.selector,argv:D.argv,workspace_path:D.workspace_path,target:D.target})),queue:y,live:h,nowMs:Number.isFinite(b)?b:0,backoffUntilMs:On,birthHaltUntilMs:pd(bt,Number.isFinite(b)?b:0)}),S=[],O=null;for(let D of w.births){let Q,zp=ni(E.keys()),Ot=$.get(D.project_label),rl=Sd({argv:D.argv,...Ot?.env==null?{}:{env:Ot.env},...Ot?.log_path==null?{}:{log_path:Ot.log_path}},{worker_id:zp,slot:D.index,workspace_path:D.workspace_path},{project_label:D.project_label});try{Q=Fr(rl)}catch(qr){O=qr instanceof Error?qr.message:String(qr),On=(Number.isFinite(b)?b:Date.now())+_p;break}S.push({project_label:D.project_label,worker_id:Q.worker.worker_id,pid:Q.worker.pid,warnings:rl.log_path==null?[...Q.warnings,`project ${JSON.stringify(D.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(Q.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:Q.warnings})}return O==null&&w.births.length>0&&(On=null),Rt={version:1,at:c,requested:w.births.length,granted:S,shortfall:w.births.length-S.length,refusal:O,retry_after:On==null?null:new Date(On).toISOString(),projects:w.intents},Rt}finally{Cr=!1}}function jp(c){return Je(St(),{...A,mode:c?.mode??A.mode,project:c?.project??A.project,maxWorkers:c?.max_workers??A.maxWorkers,maxProjects:c?.max_projects??A.maxProjects,maxWidth:c?.max_width??A.maxWidth,verbose:c?.verbose??A.verbose})}function Op(c){return xn(St(),{mode:c?.mode??me.mode,project:c?.project??me.project,maxWidth:c?.max_width??me.maxWidth,maxRows:c?.max_rows??me.maxRows})}function on(c,h,y){return Od({op:c,sessionProject:h??null,targetProject:y})}async function Ap(c){let h=E.get(c.worker_id),y=on(jd(c.command),c.session_project,h?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(c.command!=="stop")throw new Error(`redskilled does not implement ${c.command}: it owns birth, death and limits, and ${c.command} is a work decision the project's own bundle makes on top of them`);let b=h!=null&&await Np(h,c.detail??"stopped by its own project");return{version:1,command:c.command,worker_id:c.worker_id,applied:b,reach:y,detail:b?`redskilled stopped Worker ${JSON.stringify(c.worker_id)} of project ${JSON.stringify(h.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function vt(c){E.delete(c),je.delete(c),Ze.delete(c),gt.delete(c)}function Gi(c){let h=E.get(c.worker_id),y=on("worker-heartbeat",c.session_project,h?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(typeof c.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(h==null)return{version:1,worker_id:c.worker_id,accepted:!1,reach:y,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to publish a line for`};let b=o();Ze.set(c.worker_id,{line:c.last_log_line,published_at:b,source:"heartbeat"});let w=c.display===void 0?null:Jc(c.display);if(w!=null){let S={display:w,published_at:b};gt.set(c.worker_id,S),Sp(S,c.worker_id)}return{version:1,worker_id:c.worker_id,accepted:!0,reach:y,published_at:b,detail:`redskilled stored a line for Worker ${JSON.stringify(c.worker_id)} without reading it`}}async function Lp(c,h,y){let b=`exit code=${h??"null"} signal=${y??"null"}`;if(c.unit!=null&&c.unit!==""&&await Tp(c)){Ip(c,`its launch client ended (${b}) while unit ${JSON.stringify(c.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}let w=c.log_path==null?null:ju(await ft(c.log_path).catch(()=>null));vt(c.worker_id),_e("worker-death",c,w==null?b:`session-error: ${w}`,{exitCode:h,signal:y,refusal:w}),N()}function $p(c,h){if(!Number.isFinite(h)||h<0){bt[c]=Zt;return}let y=bt[c]??Zt,b=ud(y,h,Date.parse(o()));bt[c]=b,b.haltUntilMs!=null&&y.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(c)} lost ${b.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(b.haltUntilMs).toISOString()}
80
+ `)}async function Tp(c){try{return await x(c)===!0}catch{return!1}}function Ip(c,h){let y=c.unit==null?null:ke(c.unit);E.set(c.worker_id,{...c,...y!=null&&y>0?{pid:y}:{},warnings:[...c.warnings,h]}),je.add(c.worker_id),N()}function Ki(c,h){let y=on("project-register",h,c.project_label);if(!y.permitted)throw new Error(y.reason);let b=o();rn(b);let w=vd(c,{now:b,held:$.get(c.project_label)});return $.set(w.project_label,w),Ji(w.project_label),N(),{version:1,registration:w,reach:y,detail:`redskilled holds a registration for project ${JSON.stringify(w.project_label)} at a target of ${w.target} until ${w.renew_by}, and has read neither its selector nor its argv`}}function Vi(c,h={}){let y=on("project-renew",h.sessionProject,c);if(!y.permitted)throw new Error(y.reason);let b=o();rn(b);let w=$.get(c);if(w==null){if(Mr.has(c))throw new Ve(c,{kind:"orphaned"});let O=[...be].reverse().find(Q=>Q.project_label===c);if(O!=null)throw new Ve(c,{kind:"stopped",at:O.at});let D=[...Re].reverse().find(Q=>Q.project_label===c);throw D!=null?new Ve(c,{kind:"lapsed",at:D.at,...D.registered_at==null?{}:{registered_at:D.registered_at}}):new Ve(c)}let S=Ed(w,{now:b,...h.renewWithinMs==null?{}:{renew_within_ms:h.renewWithinMs},...h.launch==null?{}:{launch:h.launch}});return $.set(S.project_label,S),N(),{version:1,registration:S,reach:y,detail:`redskilled renewed the registration for project ${JSON.stringify(S.project_label)}, which now stands until ${S.renew_by} after renewal ${S.renewals}`+(h.launch==null?"":`, carrying launch revision ${S.launch_revision} for its next Worker`)}}function qi(c,h){let y=on("project-deregister",h,c);if(!y.permitted)throw new Error(y.reason);let b=$.get(c),w=$.delete(c);if(b!=null){let S=`redskilled released the registration for project ${JSON.stringify(c)}`;Ji(c),be.push({project_label:c,registered_at:b.registered_at,at:o(),detail:S}),be.length>kr&&be.splice(0,be.length-kr)}return{version:1,project_label:c,released:w,reach:y,detail:w?`redskilled released the registration for project ${JSON.stringify(c)}`:`redskilled held no registration for project ${JSON.stringify(c)}, so there was nothing to release`}}function Ji(c){ie.delete(c);for(let h=Re.length-1;h>=0;h-=1)Re[h].project_label===c&&Re.splice(h,1);for(let h=be.length-1;h>=0;h-=1)be[h].project_label===c&&be.splice(h,1);Mr.delete(c)}async function Np(c,h){try{await G(c)}catch{}return vt(c.worker_id),_e("worker-death",c,h),N(),!0}function Qi(c){return td({ceiling:i,workers:[...E.values()],budget:c.budget,projectLabel:c.project_label,...c.reservation==null?{}:{reservation:c.reservation}})}function Fr(c){let h=rd({ceiling:i,workers:[...E.values()],budget:c.budget}),y=s({spec:c,admission:Qi(c),memoryCeiling:h,liveWorkerIds:E.keys(),clock:o,onExit:(b,w,S)=>{let O=E.get(b);if(O==null){N();return}Lp(O,w,S).catch(()=>{})}});return E.set(y.worker.worker_id,y.worker),_e("worker-birth",y.worker,null),N(),y}function _e(c,h,y,b={}){if(V)return;let w=o();(c==="worker-death"||c==="worker-budget-kill")&&(vp({worker_id:h.worker_id,ts:w,outcome:c}),zi({version:1,ts:w,event:c,worker_id:h.worker_id,project_label:h.project_label,pid:h.pid,workspace_path:h.workspace_path,log_path:h.log_path??null,isolated:h.isolated,unit:h.unit??null,memory_high:h.budget?.memory_high??null,memory_max:h.budget?.memory_max??null,cpu_weight:h.budget?.cpu_weight??null,detail:y,reason:null,exit_code:b.exitCode??null,signal:b.signal??null},{startedAt:h.started_at,...b.refusal==null?{}:{refusal:b.refusal}}),$p(h.project_label,Date.parse(w)-Date.parse(h.started_at))),k.record({event:c,worker:h,ts:w,detail:y,...b.exitCode!==void 0?{exitCode:b.exitCode}:{},...b.signal!==void 0?{signal:b.signal}:{}}).catch(()=>{})}function zi(c,h={}){let y=w_(c,h);if(y==null)return;let b=[y,...(kt??[]).filter(w=>w.kind!==y.kind||w.id!==y.id||w.ts!==y.ts)].sort((w,S)=>Date.parse(w.ts)-Date.parse(S.ts));kt=Xn(b,w=>w.ts,{now:o()})}async function Ur(){let c=Date.parse(o()),h=[...E.values()].filter(b=>{if(je.has(b.worker_id))return!0;let w=Date.parse(b.started_at);return!Number.isFinite(w)||c-w>=v});if(h.length===0)return[];let{dead:y}=await Xs(h,x);for(let b of y)vt(b.worker_id),_e("worker-death",b,"the host no longer confirms this Worker");return y.length>0&&N(),y}async function Yi(c,h){let y=E.get(c);if(!y)return!1;try{await G(y)}catch{}return vt(c),_e("worker-budget-kill",y,h),N(),!0}async function Xi(){let c=[...E.values()];if(c.length===0)return[];let h;try{h=await Xe(c)}catch{return[]}let y=h.rss;Ii=y,Ar=o(),Mp(h.cpu_seconds,Ar);let{terminations:b}=Qd({workers:c,rss:y}),w=[];for(let S of b)await Yi(S.worker_id,S.reason)&&w.push(S);return w}function Mp(c,h){for(let[y,b]of Object.entries(c)){if(typeof b!="number"||!Number.isFinite(b))continue;let w=E.get(y);w&&E.set(y,{...w,cpu:{cpu_seconds:b,sampled_at:h}})}}async function Cp(){try{return ji<=0?await Pi(t):await new Promise(c=>{let h=setTimeout(()=>c(Gr()),ji);h.unref(),Pi(t).then(y=>{clearTimeout(h),c(y)},()=>{clearTimeout(h),c(Gr())})})}catch{return Gr()}}function Gr(){try{return Rp(t)}catch{return null}}async function Zi(){if(dt(t))return $r+=1,Lr=o(),Tr="local-build",{act:"hold",reason:"local-build"};let c=pu(await Cp()),h=c.version;Ni=h,Ir=c.newest??null,Lr=o(),Ci=fu({running:t,newest:Ir,supervised:Ai});let y=mu({running:t,published:h,supervised:Ai});return Mi=y.act==="replace",$r+=1,Tr=y.act==="hold"?y.reason:null,Dn!=="in-progress"&&(Dn=y.act==="replace"?"pending":"none"),y}async function Et(){let c=await Zi();if(c.act!=="replace"||Dn==="in-progress")return c;let h=gu(c,Li);return Dn="in-progress",await k.flush().catch(()=>{}),await Dt({reason:"replaced"}),yu(h,n,{...r==null?{}:{idleMs:r},io:Li}),c}function Wp(){V||In!=null||Di<=0||(!bp&&Oi>0&&(_t=setTimeout(()=>{Et().catch(()=>{})},Oi),_t.unref()),In=setInterval(()=>{Et().catch(()=>{})},Di),In.unref())}async function el(){return await a.renew(l).catch(()=>null)}function Hp(){V||Ln!=null||vi<=0||(Ln=setInterval(()=>{el()},vi),Ln.unref())}function Bp(){V||$n!=null||Ei<=0||($n=setInterval(()=>{rn(o())},Ei),$n.unref())}function Fp(){V||An!=null||Si<=0||(An=setInterval(()=>{Xi().catch(()=>{})},Si),An.unref())}function Up(){V||Nn!=null||se==null||se.projects.length===0||$i<=0||(Br().catch(()=>{}),Nn=setInterval(()=>{Br().catch(()=>{})},$i),Nn.unref())}function Gp(){if(V||tn!=null||Dr<=0)return;let c=h=>{tn=setTimeout(()=>{tn=void 0,Fi().catch(()=>{}).finally(()=>{if(V)return;let y=Date.parse(o());c(qc(K,Dr,Number.isFinite(y)?y:Date.now()))})},h),tn.unref()};c(Dr)}function Kp(){V||Tn!=null||Ti<=0||(Tn=setInterval(()=>{Ui().catch(()=>{})},Ti),Tn.unref())}function N(){V||(en&&clearTimeout(en),en=setTimeout(()=>{Ur().catch(()=>{}).then(()=>nl())},r),en.unref())}function nl(){return E.size>0?(N(),"held-by-workers"):(rn(o()),$.size>0?(N(),"held-by-registrations"):(Vp(),"exited"))}async function Vp(){if(!dt(t)){if((await Et().catch(()=>null))?.act==="replace"||Wr||V)return;if(E.size>0||$.size>0){N();return}}await Dt({reason:"idle"})}function Pt(c){return md({reason:c,socketPath:n.socketPath,daemonVersion:t,pid:l.pid,workers:[...E.values()],projects:[...$.keys()]})}function tl(c){if(wt!=null)return wt;let h=c.reason??"requested",y=c.note?.trim();return wt=k.recordDaemonStop({ts:o(),pid:l.pid,socketPath:n.socketPath,reason:h,detail:y==null||y===""?Pt(h).detail:`${Pt(h).detail} \u2014 ${y}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),wt}async function Dt(c={}){if(Wr)return await Hr;Wr=!0,await tl(c),V=!0,en&&clearTimeout(en),An&&clearInterval(An),Ln&&clearInterval(Ln),$n&&clearInterval($n),In&&clearInterval(In),_t&&clearTimeout(_t),Nn&&clearInterval(Nn),nn&&clearTimeout(nn),tn&&clearTimeout(tn),Tn&&clearInterval(Tn),await k.flush().catch(()=>{}),g.close();for(let h of Or)h.destroy();return await new Promise(h=>g.once("close",()=>h())),await Ou(n.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await p.release(d).catch(()=>{}),Wi(),await Hr}let Kr=await k.read().catch(()=>[]),jt=new Map;for(let c of Kr){if(c.event==="worker-birth"){jt.set(c.worker_id,c.ts);continue}let h=ju(c.detail);zi(c,{...jt.get(c.worker_id)==null?{}:{startedAt:jt.get(c.worker_id)},...h==null?{}:{refusal:h}}),(c.event==="worker-death"||c.event==="worker-budget-kill")&&jt.delete(c.worker_id)}yt=Xn(Kr.filter(c=>c.event==="worker-death"||c.event==="worker-budget-kill").map(c=>({worker_id:c.worker_id,ts:c.ts,outcome:c.event})),c=>c.ts,{now:o()});let qp=ad(Kr),Vr=await Xs(qp,x);for(let c of Vr.alive){let h=Hc(c),y=h.unit==null||H(h.pid)?null:ke(h.unit);E.set(h.worker_id,y!=null&&y>0?{...h,pid:y}:h),je.add(h.worker_id)}for(let c of Vr.dead)_e("worker-death",c,"the Worker ended while no daemon was watching");let Jp=Wc({units:await Promise.resolve(ye()).catch(()=>[]),held:[...E.values()],mainPid:ke,now:_});for(let c of Jp)E.set(c.worker_id,c),je.add(c.worker_id),_e("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of Vr.alive){if(c.log_path==null||Ze.has(c.worker_id))continue;let h=await ft(c.log_path).catch(()=>null);h==null||h.trim()===""||Ze.set(c.worker_id,{line:h,published_at:o(),source:"rehydrated"})}g.on("connection",c=>{Or.add(c),c.once("close",()=>Or.delete(c)),N(),E_(c,async(h,y)=>{N();let b=await Qp(h);y(b),h.op==="shutdown"&&setImmediate(()=>void Dt({reason:"requested"}))})});async function Qp(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:ur,daemon_version:t,pid:l.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:xt()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:sc(St(),c.extras)};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:jp(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:Op(c.dashboard)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:Gi(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:Ki(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:Vi(c.project_label,{...c.session_project==null?{}:{sessionProject:c.session_project},...c.renew_within_ms==null?{}:{renewWithinMs:c.renew_within_ms},...c.launch==null?{}:{launch:c.launch}})};if(c.op==="project-deregister")return{id:c.id,ok:!0,value:qi(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await Ap(c.command)};if(c.op==="worker-start"){let y=on("worker-start",c.session_project,c.spec.project_label);if(!y.permitted)return{id:c.id,ok:!1,error:y.reason};let b=Fr(c.spec);return await k.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:b.worker,admission:b.admission,warnings:b.warnings}}}if(c.op==="shutdown"){let y=Pt("requested");return await tl({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:y}}let h=c;return{id:h.id??Rr(),ok:!1,error:`unsupported redskilled op: ${h.op??"unknown"}`}}catch(h){return{id:c.id??Rr(),ok:!1,error:h instanceof Error?h.message:String(h)}}}return N(),Fp(),Hp(),Bp(),Wp(),Up(),Ep(),Gp(),Kp(),{socketPath:n.socketPath,lease:m.lease,startedAt:_,closed:Hr,startWorker:Fr,admit:Qi,ceiling:()=>i,killWorkerOverBudget:Yi,sampleMemoryBudgets:Xi,renewLease:el,pollRepositoryActivity:Br,pollGithubBalance:Bi,githubBalance:()=>jn,pollQueueDiscovery:Fi,queueDiscovery:()=>K,driveDemand:Ui,demand:()=>Rt,sweepWorkerLiveness:Ur,publishWorkerHeartbeat:Gi,reattached:()=>[...je].map(c=>E.get(c)).filter(c=>c!=null),flushEvents:()=>k.flush(),trackWorker(c){E.set(c.worker_id,c),_e("worker-birth",c,null),N()},releaseWorker(c){let h=E.get(c),y=E.delete(c);return je.delete(c),Ze.delete(c),gt.delete(c),h&&_e("worker-death",h,"released by the daemon"),N(),y},workerCount:()=>E.size,registerProject:Ki,renewProject:Vi,deregisterProject:qi,registrations:()=>xt().registrations??[],hostState:xt,statuslinePayload:St,evaluateIdle:nl,observePublishedVersion:Zi,checkForReplacement:Et,stopReport:Pt,stop:Dt}}async function S_(e,n=250){return await new Promise(t=>{let r=m_(e),o=!1,s=l=>{o||(o=!0,clearTimeout(i),r.destroy(),t(l))},i=setTimeout(()=>s("unknown"),n);i.unref?.(),r.once("connect",()=>s("owned")),r.once("error",l=>{s(l.code==="ECONNREFUSED"||l.code==="ENOENT"?"unowned":"unknown")})})}async function v_(e,n){for(let t=0;t<2;t++){let r=h_();try{return await new Promise((o,s)=>{r.once("error",s),r.listen(e,()=>{r.off("error",s),o()})}),r}catch(o){if(r.close(),o.code!=="EADDRINUSE")throw o;if(await S_(e)!=="unowned")throw new ze(e);if(await n?.())throw new ze(e);await Ou(e,{force:!0})}}throw new ze(e)}async function he(e,n=250){try{return(await Gt({socketPath:e,timeoutMs:n},{id:Rr(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function E_(e,n){La(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??Rr(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function ui(e){let n=e.socketPath,t=P_(e);return e.answers?{version:1,kind:"answering",socket_path:n,holder:t,reason:`a redskilled daemon answered on ${JSON.stringify(n)}`,repair:"nothing to repair"}:t!=null?{version:1,kind:"held-unresponsive",socket_path:n,holder:t,reason:`redskilled pid ${t.pid} is alive and has held ${JSON.stringify(n)} since ${t.acquired_at}${t.uptime_ms==null?"":` (up ${Lu(t.uptime_ms)})`}, but it did not answer a ping \u2014 this is a daemon that could not be REACHED, not one that is missing.`,repair:`Do not provision: a daemon is already running. Inspect it (\`ps -p ${t.pid}\`), or stop it with \`${Ie("red-skills-redskilled",["stop"])}\` and let the next client start a fresh one.`}:{version:1,kind:"absent",socket_path:n,holder:null,reason:`nothing answered on ${JSON.stringify(n)} and no live process holds its lease`,repair:`Install and start one with \`${Ie("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function pi(e){return`${e.reason} ${e.repair}`}function P_(e){let n=e.lease;return n==null||e.holderAlive!==!0||n.socket_path!==e.socketPath?null:{pid:n.pid,socket_path:n.socket_path,acquired_at:n.acquired_at,renewed_at:n.renewed_at,uptime_ms:D_(n.acquired_at,e.now??new Date().toISOString())}}function D_(e,n){let t=Date.parse(e),r=Date.parse(n);return!Number.isFinite(t)||!Number.isFinite(r)?null:Math.max(0,r-t)}function Lu(e){let n=Math.floor(e/1e3),t=Math.floor(n/3600),r=Math.floor(n%3600/60),o=n%60;return t>0?`${t}h${String(r).padStart(2,"0")}m`:r>0?`${r}m${String(o).padStart(2,"0")}s`:`${o}s`}Se();var Iu=1e4,Ye=class extends Error{constructor(t,r,o){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}${o!=null&&o.kind==="held-unresponsive"?`. ${pi(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},fi=class extends Ye{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}},br=class extends Error{constructor(t){super(t);this.refusal=t;this.name="RedskilledRequestRefusedError"}};async function _r(e,n={}){let t=n.answers??await he(e.socketPath),r=await ct(e.leasePath).catch(()=>{});return ui({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&H(r.pid)})}async function mi(e,n={}){try{return await L_(e,n)}catch(t){if(t instanceof Le||t instanceof Ye)throw t;let r=await _r(e).catch(()=>{});throw new Ye(e.socketPath,t,r)}}async function L_(e,n){if(await O_(A_(e.socketPath),{recursive:!0,mode:448}),await he(e.socketPath))return"already-running";await I_(e);let t=await T_(e,n);if(t!=null)return t;let r=await Ta(e.lockPath,{...n.spawnLockMaxAgeMs==null?{}:{maxAgeMs:n.spawnLockMaxAgeMs},onReap:n.onSpawnLockReaped??$_});if(!r.acquired)return await $u(e,n,void 0,r),"joined";try{if(await he(e.socketPath))return"already-running";let o=await M_(e,n);return await $u(e,n,o),"spawned"}finally{await Ia(r)}}function $_(e){process.stderr.write(`redskilled: reaped the spawn lock ${JSON.stringify(e.lockPath)} (${e.reason}, ${Math.round(e.ageMs/1e3)}s old, holder ${e.holder==null?"unnamed":`pid ${e.holder.pid}`}) and went on to spawn
81
+ `)}async function T_(e,n){let t=await _r(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??Iu,o=Date.now()+r;for(;;){if(await he(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(i=>setTimeout(i,25))}let s=await _r(e).catch(()=>{});if(s==null||s.kind!=="held-unresponsive")return null;throw new fi(e.socketPath,s,new Error(`it did not answer a ping within ${r}ms, and no second daemon was spawned because pid ${s.holder?.pid??"unknown"} still holds this socket`))}async function I_(e){let t=await nr(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&H(t.pid))throw new Le(e.machineClaimPath,"held",t)}async function Nu(e,n,t={}){await mi(e,t);let r;try{r=await lt({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:Tu()})}catch(o){throw new Ye(e.socketPath,o,await _r(e).catch(()=>{}))}if(!r.ok)throw new br(r.error);return r.value}async function Mu(e,n={},t={}){if(!await he(e.socketPath))return hd(e.socketPath);let r;try{r=await lt({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Tu(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new Ye(e.socketPath,i)}if(!r.ok)throw new br(r.error);if(!es(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await N_(e.socketPath,n.settleTimeoutMs??5e3)?o:{...o,stopped:!1,detail:`${o.detail}; the daemon accepted the stop and is still answering on ${JSON.stringify(e.socketPath)}`}}async function N_(e,n){let t=Date.now()+n;for(;;){if(!await he(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function Cu(e,n={}){let t=await Nu(e,{op:"host-state"},n);if(!gc(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Wu(e,n={},t){let r=await Nu(e,{op:"statusline-payload",...n.sessionProject!=null?{session_project:n.sessionProject}:{},...t==null?{}:{extras:t}},n);if(!Es(r))throw new Error("redskilled daemon returned a malformed statusline payload");return r}async function Hu(e,n=A,t={}){let r=await Wu(e,t,{vitals:!0,logs:n.verbose,display:!0});return Je(r,n)}async function Bu(e,n={},t={}){let r=await Wu(e,t,{vitals:!0,logs:!0,display:!0});return xn(r,{...me,...n})}async function $u(e,n,t,r){let o=Date.now()+(n.readyTimeoutMs??Iu);for(;;){if(await he(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=o){if(r!=null)throw new Error(`no redskilled daemon answered on ${JSON.stringify(e.socketPath)} within the ready window, and ${Na(r)}`);let s=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${s}`)}await new Promise(s=>setTimeout(s,25))}}async function M_(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await Va({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,...Ue(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=j_(r.command,s,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return i.on("error",l=>{o.failure=l}),i.on("exit",(l,a)=>{o.exit=a?`died on ${a}`:`exited with code ${l??-1}`}),i.unref(),o}Se();import{readFile as C_}from"node:fs/promises";import{homedir as W_,totalmem as H_}from"node:os";import{join as B_}from"node:path";var F_="REDSKILLED_IDLE_MS",U_=".red/config.yaml";async function Uu(e=W_()){let n=B_(e,U_),t;try{t=await C_(n,"utf8")}catch(r){return r.code==="ENOENT"?{}:(hi(`redskilled: cannot read host config ${JSON.stringify(n)}; using environment and defaults instead: ${Fu(r)}`),{})}try{let r=K_(t);return{...wr(r,"plugins.dev.redskilled.worker_ceiling","workerCeiling"),...wr(r,"plugins.dev.redskilled.memory_ceiling","memoryCeiling"),...wr(r,"plugins.dev.redskilled.validation_ceiling","validationCeiling"),...wr(r,"plugins.dev.redskilled.idle_ms","idleMs")}}catch(r){return hi(`redskilled: malformed host config ${JSON.stringify(n)}; using environment and defaults instead: ${Fu(r)}`),{}}}function Gu(e={}){let n=e.env??process.env,t=e.config??{},r=Xt(n,e.totalMemoryBytes??H_(),{flags:e.flags,config:t,...e.availableParallelism==null?{}:{availableParallelism:e.availableParallelism}}),o=G_(e.flags?.idleMs==null?void 0:String(e.flags.idleMs),n[F_],t.idleMs);if(o==null)return{ceiling:r,idleMs:ut,idleMsSource:"derived-default"};let s=Number(o.value);return Number.isSafeInteger(s)&&s>0?{ceiling:r,idleMs:s,idleMsSource:o.source}:(hi(`redskilled: ${J_(o.source)} idle_ms=${JSON.stringify(o.value)} is not a positive integer; using the default ${ut}ms instead.`),{ceiling:r,idleMs:ut,idleMsSource:"derived-default"})}function G_(e,n,t){if(e!==void 0)return{value:e.trim(),source:"flag"};if(n!==void 0)return{value:n.trim(),source:"environment"};if(t!==void 0)return{value:t.trim(),source:"home-config"}}function wr(e,n,t){let r=e[n];return r===void 0?{}:{[t]:r}}function K_(e){let n={},t=[];for(let[r,o]of e.split(/\r?\n/).entries()){let s=V_(o);if(s.trim()==="")continue;let i=s.match(/^ */)?.[0].length??0;if(i%2!==0||/\t/.test(s.slice(0,i)))throw new Error(`line ${r+1} has unsupported indentation`);let l=/^([A-Za-z_][A-Za-z0-9_-]*):(?:\s*(.*))?$/.exec(s.slice(i).trimEnd());if(l==null)throw new Error(`line ${r+1} is not a mapping entry`);let a=i/2;if(a>t.length)throw new Error(`line ${r+1} skips a mapping level`);t.splice(a);let d=l[1],u=l[2]??"";if(u===""){t.push(d);continue}n[[...t,d].join(".")]=q_(u.trim())}return n}function V_(e){let n;for(let t=0;t<e.length;t+=1){let r=e[t];if(n==null&&(r==="'"||r==='"'))n=r;else if(n===r)n=void 0;else if(n==null&&r==="#"&&(t===0||/\s/.test(e[t-1])))return e.slice(0,t).trimEnd()}if(n!=null)throw new Error("unclosed quoted scalar");return e}function q_(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function J_(e){return e==="flag"?"serve flag":e==="environment"?"environment":e==="home-config"?"home config":"derived default"}function Fu(e){return e instanceof Error?e.message:String(e)}function hi(e){process.stderr.write(`${e}
82
+ `)}import{chmod as Yu,mkdir as Zu,readFile as ep,stat as sw,writeFile as np}from"node:fs/promises";import{homedir as ki}from"node:os";import{dirname as tp,join as Sr}from"node:path";import{join as Q_}from"node:path";var Ku=["local","tmp","host"],z_="local",pt="plugins.dev.workspace.target";var gi=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function qu(e){let n=mn(e,pt),t=Z_(n??"").trim();return t===""?void 0:t}function Ju(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:z_};let t=Ku.find(r=>r===n.toLowerCase());if(t)return{kind:"preset",preset:t};if(n.startsWith("/")||n==="~"||n.startsWith("~/"))return{kind:"custom",parentDir:n};throw new gi(`${pt}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${Ku.join(", ")}) or an absolute parent directory for Workers.`)}function Qu(e,n){return e.kind==="preset"?e.preset==="host":X_(Y_(e.parentDir,n),Fe(n))}function Y_(e,n){return e==="~"?Vu(n):e.startsWith("~/")?Q_(n,e.slice(2)):Vu(e)}function X_(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Vu(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function Z_(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}Se();import{createHash as ew}from"node:crypto";import{hostname as nw}from"node:os";import{join as xr}from"node:path";var Pn="redskilled.sock",tw="REDSKILLED_SESSION";function rw(e={}){let n=e.env??process.env,t=n[tw]?.trim();if(t)return t;let r=n.XDG_RUNTIME_DIR?.trim();return r||`uid:${e.uid??(typeof process.getuid=="function"?process.getuid():"nouid")}`}function ow(e={}){return zu(e.host??nw())}function ge(e={}){let n=rw(e),t=e.runtimeDir??Kt({key:`redskilled:${n}`,socketFileName:Pn,env:e.env,uid:e.uid}),r=ow(e);return{sessionKey:n,sessionKeyHash:zu(n),machineIdHash:r,runtimeDir:t,socketPath:xr(t,Pn),lockPath:xr(t,"redskilled.spawn.lock"),leasePath:xr(t,"redskilled.lease.toon"),eventLanePath:xr(t,id),machineClaimPath:e.machineClaimPath??er({env:e.env,machineIdHash:r,platform:e.platform})}}function zu(e){return ew("sha256").update(e).digest("hex").slice(0,12)}var yi=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${Ie("red-skills-redskilled",["provision"])}\` directly`,iw=`# Host-scoped redskilled policy. This file is never read from a repository.
83
+ plugins:
84
+ dev:
85
+ redskilled:
86
+ # worker_ceiling: 6
87
+ # memory_ceiling: 8G
88
+ # validation_ceiling: 2
89
+ # idle_ms: 300000
90
+ `;async function rp(e=ki()){let n=Fe(e),t=Sr(tp(n),"config.yaml"),r=await bi(n),o=!1,s=!1;r===void 0?(await Zu(n,{recursive:!0,mode:xe}),await Yu(n,xe),o=!0):r!==xe&&(await Yu(n,xe),s=!0);let i=!1;try{await np(t,iw,{encoding:"utf8",flag:"wx",mode:384}),i=!0}catch(l){if(l.code!=="EEXIST")throw l}return{path:n,created:o,tightened:s,mode:xe,configPath:t,configCreated:i}}var op={needed:!1,declaredBy:`no ${pt} in view`};async function Ri(e={}){let n=e.homeDir??ki(),t=e.declaredTarget?.trim();if(t)return Xu(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return op;let o=Sr(r,".red","config.yaml"),s=await ep(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=qu(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Xu(i,n,o)}function Xu(e,n,t){let r=`${pt}: ${e} (${t})`;try{return{needed:Qu(Ju(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function sp(e){let n=[lw(e),aw(e),dw(e),cw(e)],t=n.filter(o=>o.verdict!=="ok");return{verdict:t.some(o=>o.verdict==="missing")?"missing":t.length>0?"degraded":"ok",rows:n,findings:t}}function lw(e){let n=e.homeNeed??op;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:yi}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??xe;return t!==xe?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${xe.toString(8)}`,fix:`${yi} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function aw(e){return pe(e.entry)?{check:"daemon-entry",verdict:"ok",evidence:`${e.entry.entry??e.entry.command} (resolved as ${e.entry.source})`,fix:""}:{check:"daemon-entry",verdict:"missing",evidence:`no published redskilled bundle; probed ${e.entry.searched.join(", ")||"nothing"}`,fix:`install or warm the RedSkills bundle for this host, then re-run \`${Ie("red-skills-redskilled",["provision"])}\``}}function dw(e){return e.reachable?{check:"reach",verdict:"ok",evidence:`daemon answered on ${e.socketPath}`,fix:""}:{check:"reach",verdict:"missing",evidence:`no daemon answered on ${e.socketPath}`,fix:`${yi} \u2014 it starts the daemon and waits for the socket`}}function cw(e){return{check:"supervisor-unit",verdict:"ok",evidence:e.supervisorUnit==="installed"?"redskilled.service is installed (optional supervision, Restart=on-failure)":e.supervisorUnit==="unsupported"?"optional: this host has no systemd --user session; auto-spawn is the only start path":"optional: not installed; auto-spawn already starts the daemon on first use",fix:""}}async function ip(e={}){let n=e.env??process.env,t=e.homeDir??ki(),r=e.paths??ge({env:n}),o=Fe(t),[s,i,l]=await Promise.all([bi(o),he(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Ri({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:Ae(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await pw(fw(e,n,t),n)}}var uw="redskilled.service";function lp(e){return Sr(e,"systemd","user",uw)}function ap(e){let n=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${n}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
91
+ `)}async function dp(e){let n=lp(e.configHome);return await bi(n)!==void 0?{path:n,status:"already-present"}:(await Zu(tp(n),{recursive:!0}),await np(n,e.unit,"utf8"),{path:n,status:"installed"})}async function pw(e,n){if(process.platform!=="linux")return"unsupported";try{return await ep(lp(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function fw(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??Sr(t,".config")}async function bi(e){try{return(await sw(e)).mode&511}catch{return}}import{readdir as up,rm as mw,stat as hw}from"node:fs/promises";import{dirname as gw,join as _i}from"node:path";var yw=5*6e4,kw="redskilled.";function Rw(e={}){let n=e.env??process.env,t=i=>gw(Kt({key:"redskilled:reclaim-probe",socketFileName:Pn,env:i,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=n,s=[t(n),t(o)];return[...new Set(s)]}async function pp(e={}){let n=e.roots??Rw(e),t=e.graceMs??yw,r=e.now??Date.now,o=e.isPidAlive??H,s=e.answers??xw,i=e.dryRun===!0,l=[];for(let a of n){let d;try{d=(await up(a,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name)}catch{continue}for(let u of d.sort())l.push(await bw(_i(a,u),{graceMs:t,now:r,pidAlive:o,answers:s,dryRun:i}))}return{roots:n,scanned:l.length,reclaimed:l.filter(a=>a.verdict==="reclaimed").length,dryRun:i,entries:l}}async function bw(e,n){let t;try{t=(await up(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:fp(i),removed:[]}}let r=t.filter(i=>i.startsWith(kw));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await _w(_i(e,"redskilled.lease.toon"));if(o!==void 0)return await n.pidAlive(o.pid)?{dir:e,verdict:"live",reason:`lease pid ${o.pid} is alive`,removed:[]}:await cp(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(Pn)&&await n.answers(_i(e,Pn)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await ww(e,n.now);return s!==void 0&&s<n.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(s/1e3)}s ago`,removed:[]}:await cp(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function cp(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await mw(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:fp(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function _w(e){try{return await ct(e)}catch{return}}async function ww(e,n){try{return Math.max(0,n()-(await hw(e)).mtimeMs)}catch{return}}async function xw(e){try{return(await lt({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function fp(e){return e instanceof Error?e.message:String(e)}var Sw="plugins.dev.statusline",vw="dev.statusline";function Ew(e){let n=[],t=l=>{for(let a of[Sw,vw]){let d=`${a}.${l}`,u=mn(e,d)?.trim();if(u!=null&&u!=="")return{key:d,value:u}}},r=t("mode"),o={};r!=null&&(r.value==="local"||r.value==="global"?o.mode=r.value:n.push({...r,reason:"expected `local` or `global`"}));let s=[{leaf:"max_workers",assign:l=>{o.maxWorkers=l}},{leaf:"max_projects",assign:l=>{o.maxProjects=l}},{leaf:"max_width",assign:l=>{o.maxWidth=l}}];for(let l of s){let a=t(l.leaf);if(a==null)continue;let d=Number(a.value);Number.isInteger(d)&&d>=0?l.assign(d):n.push({...a,reason:"expected a whole number of zero or more"})}let i=t("verbose");return i!=null&&(i.value==="true"||i.value==="false"?o.verbose=i.value==="true":n.push({...i,reason:"expected `true` or `false`"})),{config:o,warnings:n}}var Pw={mode:{kind:"value",coerce:e=>e},verbose:{kind:"boolean"},project:{kind:"value",coerce:e=>e},"max-workers":{kind:"value",coerce:e=>e},"max-projects":{kind:"value",coerce:e=>e},"max-width":{kind:"value",coerce:e=>e}};function wi(e){let{values:n,positionals:t}=He(e,Pw),r=[],o={},s=n.mode??t.find(l=>l==="global"||l==="local");s!=null&&(s==="local"||s==="global"?o.mode=s:r.push({key:"--mode",value:s,reason:"expected `local` or `global`"})),n.project!=null&&(o.project=n.project),n.verbose!==void 0&&(o.verbose=n.verbose===!0);let i=[{flag:"max-workers",assign:l=>{o.maxWorkers=l}},{flag:"max-projects",assign:l=>{o.maxProjects=l}},{flag:"max-width",assign:l=>{o.maxWidth=l}}];for(let l of i){let a=n[l.flag];if(a==null)continue;let d=Number(a);Number.isInteger(d)&&d>=0?l.assign(d):r.push({key:`--${l.flag}`,value:a,reason:"expected a whole number of zero or more"})}return{flags:o,warnings:r}}function xi(e={}){let n=e.configText==null?{config:{},warnings:[]}:Ew(e.configText),t=e.flags??{};return{options:{...A,mode:t.mode??n.config.mode??A.mode,project:t.project!==void 0?t.project:e.project??A.project,maxWorkers:t.maxWorkers??n.config.maxWorkers??A.maxWorkers,maxProjects:t.maxProjects??n.config.maxProjects??A.maxProjects,maxWidth:t.maxWidth??n.config.maxWidth??A.maxWidth,verbose:t.verbose??n.config.verbose??A.verbose},warnings:n.warnings}}var jw=`Usage: redskilled <command> [options]
83
92
 
84
93
  Commands:
85
94
  host-state (default) print the host's state as JSON
@@ -92,7 +101,7 @@ Commands:
92
101
 
93
102
  Run \`redskilled <command> --help\` for a command's own usage.
94
103
  \`--version\` (\`-v\`) prints the build stamp; both answer offline.
95
- `,W_={serve:`Usage: redskilled serve [options]
104
+ `,Ow={serve:`Usage: redskilled serve [options]
96
105
 
97
106
  Runs the daemon in this process. Every path is a flag and none is derived
98
107
  (ADR 0130 rule 3); what is absent falls back to the session derivation.
@@ -103,6 +112,8 @@ Runs the daemon in this process. Every path is a flag and none is derived
103
112
  --session-key-hash <hex> publishable session identity
104
113
  --machine-id-hash <hex> publishable host label
105
114
  --machine-claim <path> the machine-wide claim record
115
+ --worker-ceiling <n> host-wide Worker slots across every project
116
+ --memory-ceiling <size> host-wide Worker memory budget
106
117
  --idle-ms <n> exit after this long with no work
107
118
  --daemon-version <v> the version this daemon reports as
108
119
  --queue-endpoint <url> where the queue poll asks; GitHub's when absent
@@ -143,9 +154,10 @@ with no unit is a supported configuration (ADR 0130 rule 7). Defaults to status.
143
154
  Makes a machine with no prior state ready, and prints the audit. Idempotent: a
144
155
  second run creates nothing and reports the same verdicts.
145
156
 
146
- The host-scoped home is created only when a declared workspace target reads it
157
+ The host-scoped state home is created only when a declared workspace target reads it
147
158
  (the \`host\` preset, or a custom parent under the home). The daemon never reads
148
- the home, so the default \`local\` preset needs none \u2014 and never gets an empty one.
159
+ that state directory, so the default \`local\` preset needs none \u2014 and never gets
160
+ an empty one. Host policy is read separately from ~/.red/config.yaml.
149
161
 
150
162
  --check read-only; creates and starts nothing
151
163
  --no-start make the host ready without starting the daemon
@@ -166,24 +178,24 @@ Reports every session runtime dir it looked at and why it kept or removed it.
166
178
 
167
179
  --dry-run the same report with nothing removed
168
180
  --grace-ms <n> how long a dir must be idle before it is reclaimed
169
- `};function B_(e){return e==="--help"||e==="-h"||e==="help"}var F_={socket:{kind:"value",coerce:e=>e},lease:{kind:"value",coerce:e=>e},events:{kind:"value",coerce:e=>e},"session-key-hash":{kind:"value",coerce:e=>e},"machine-id-hash":{kind:"value",coerce:e=>e},"machine-claim":{kind:"value",coerce:e=>e},"idle-ms":{kind:"value",coerce:e=>Number(e)},"daemon-version":{kind:"value",coerce:e=>e},"queue-endpoint":{kind:"value",coerce:e=>e},"queue-ms":{kind:"value",coerce:e=>Number(e)},"demand-ms":{kind:"value",coerce:e=>Number(e)}},Qu="REDSKILLED_HOST_TOKEN";function hr(){try{let n=M_("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function zu(e=process.env,n=hr){let t=(e[Qu]??e.GITHUB_TOKEN??e.GH_TOKEN??"").trim();if(t!=="")return{token:t,source:"env"};let r=(n()??"").trim();return r!==""?{token:r,source:"tracker-cli"}:null}function H_(e,n=process.env,t=hr){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...qu(e,n,t),armTransport:()=>qu(e,n,t)}}function U_(e,n=process.env,t=hr){let r=zu(n,t);if(r==null)return null;let o=n.GITHUB_API_URL;return{transport:is({token:r.token,...o?{origin:o}:{}})}}function qu(e,n=process.env,t=hr){let r=zu(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${Qu}, GITHUB_TOKEN and GH_TOKEN are all unset in the daemon's environment and \`gh auth token\` returned nothing \u2014 so no queue depth is asked for, and no depth is invented either`};let o=e["queue-endpoint"]??n.GITHUB_GRAPHQL_URL;return{transport:Fd({token:r.token,...o?{endpoint:o}:{}})}}async function G_(e){if(e[0]==="--version"||e[0]==="-v"){let o=to("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
170
- `:`${Dl(o)}
171
- `),0}if(B_(e[0]))return process.stdout.write(C_),0;let{command:n,args:t}=Ll(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},dashboard:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(W_[n]),0;if(n==="serve"){let{values:o}=Ie(t,F_),s=H_(o),i=U_(o),l=Ju(Me(ui()),"state"),a=Xl({stateRoot:l});process.stderr.write(`${Zl(a)}
172
- `);let d=ql({lanePath:Cn(l),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),u=await hu({paths:ew(o),idleMs:o["idle-ms"]??Ys,daemonVersion:o["daemon-version"]??to("redskilled").version,deaths:a.attributions,queueDiscovery:s,...i==null?{}:{githubBalance:i},...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let p of["SIGTERM","SIGINT"])process.once(p,()=>void u.stop({reason:"signal",signal:p}).catch(()=>{}));return await u.closed,d.phase("closed"),0}if(n==="stop")return await V_(t);if(n==="statusline")return await J_(t);if(n==="dashboard")return await tw(t);if(n==="unit")return await q_(t);if(n==="provision")return await z_(t);if(n==="reclaim")return await X_(t);let r=await wu(me());return process.stdout.write(`${JSON.stringify(r,null,2)}
173
- `),0}var K_={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function V_(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=Ie(e,K_),o=await _u(n.paths??me(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${W({running:o.running,stopped:o.stopped,reason:o.reason,socket:o.socket_path,daemon_version:o.daemon_version,pid:o.pid,holding:{workers:o.holding.workers.length,projects:[...o.holding.projects]},surviving:[...o.surviving],workers:o.holding.workers.map(s=>({worker_id:s.worker_id,project_label:s.project_label,pid:s.pid,unit:s.unit,isolated:s.isolated,survives:s.survives})),detail:o.detail})}
174
- `),o.running&&!o.stopped?1:0}async function q_(e,n={}){let t=n.write??(s=>process.stdout.write(s)),r=n.paths??me(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(Uc(n.unitIO??{}),null,2)}
175
- `),0;if(o==="install"){let s=await Fc(Wc(r),n.unitIO??{});return t(`${JSON.stringify(s,null,2)}
176
- `),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await Hc(n.unitIO??{}),null,2)}
177
- `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function J_(e,n={}){let t=n.write??(a=>process.stdout.write(a)),r=n.warn??(a=>process.stderr.write(a)),o=di(e),s=Yu(n.cwd??process.cwd()),i=ci({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let a of[...i.warnings,...o.warnings])r(`redskilled statusline: ignoring ${a.key}=${a.value} \u2014 ${a.reason}
178
- `);let l;try{l=await Su(n.paths??me(),i.options,{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(a){r(`redskilled statusline: ${a instanceof Error?a.message:String(a)}
179
- `),l=As({options:i.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${l.lines.join(`
181
+ `};function Aw(e){return e==="--help"||e==="-h"||e==="help"}var Lw={socket:{kind:"value",coerce:e=>e},lease:{kind:"value",coerce:e=>e},events:{kind:"value",coerce:e=>e},"session-key-hash":{kind:"value",coerce:e=>e},"machine-id-hash":{kind:"value",coerce:e=>e},"machine-claim":{kind:"value",coerce:e=>e},"worker-ceiling":{kind:"value",coerce:e=>e},"memory-ceiling":{kind:"value",coerce:e=>e},"idle-ms":{kind:"value",coerce:e=>Number(e)},"daemon-version":{kind:"value",coerce:e=>e},"queue-endpoint":{kind:"value",coerce:e=>e},"queue-ms":{kind:"value",coerce:e=>Number(e)},"demand-ms":{kind:"value",coerce:e=>Number(e)}},gp="REDSKILLED_HOST_TOKEN";function Er(){try{let n=Dw("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function yp(e=process.env,n=Er){let t=(e[gp]??e.GITHUB_TOKEN??e.GH_TOKEN??"").trim();if(t!=="")return{token:t,source:"env"};let r=(n()??"").trim();return r!==""?{token:r,source:"tracker-cli"}:null}function $w(e,n=process.env,t=Er){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...mp(e,n,t),armTransport:()=>mp(e,n,t)}}function Tw(e,n=process.env,t=Er){let r=yp(n,t);if(r==null)return null;let o=n.GITHUB_API_URL;return{transport:Rs({token:r.token,...o?{origin:o}:{}})}}function mp(e,n=process.env,t=Er){let r=yp(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${gp}, GITHUB_TOKEN and GH_TOKEN are all unset in the daemon's environment and \`gh auth token\` returned nothing \u2014 so no queue depth is asked for, and no depth is invented either`};let o=e["queue-endpoint"]??n.GITHUB_GRAPHQL_URL;return{transport:rc({token:r.token,...o?{endpoint:o}:{}})}}async function Iw(e){if(e[0]==="--version"||e[0]==="-v"){let o=mo("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
182
+ `:`${Bl(o)}
183
+ `),0}if(Aw(e[0]))return process.stdout.write(jw),0;let{command:n,args:t}=Kl(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},dashboard:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(Ow[n]),0;if(n==="serve"){let{values:o}=He(t,Lw),s=await Uu(vr()),i=Gu({flags:{...o["worker-ceiling"]==null?{}:{workerCeiling:o["worker-ceiling"]},...o["memory-ceiling"]==null?{}:{memoryCeiling:o["memory-ceiling"]},...o["idle-ms"]==null?{}:{idleMs:o["idle-ms"]}},config:s}),l=$w(o),a=Tw(o),d=hp(Fe(vr()),"state"),u=ua({stateRoot:d});process.stderr.write(`${pa(u)}
184
+ `);let p=ia({lanePath:Un(d),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),f=await Au({paths:Kw(o),idleMs:i.idleMs,ceiling:i.ceiling,daemonVersion:o["daemon-version"]??mo("redskilled").version,deaths:u.attributions,queueDiscovery:l,...a==null?{}:{githubBalance:a},...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let m of["SIGTERM","SIGINT"])process.once(m,()=>void f.stop({reason:"signal",signal:m}).catch(()=>{}));return await f.closed,p.phase("closed"),0}if(n==="stop")return await Mw(t);if(n==="statusline")return await Ww(t);if(n==="dashboard")return await qw(t);if(n==="unit")return await Cw(t);if(n==="provision")return await Bw(t);if(n==="reclaim")return await Uw(t);let r=await Cu(ge());return process.stdout.write(`${JSON.stringify(r,null,2)}
185
+ `),0}var Nw={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function Mw(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=He(e,Nw),o=await Mu(n.paths??ge(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${W({running:o.running,stopped:o.stopped,reason:o.reason,socket:o.socket_path,daemon_version:o.daemon_version,pid:o.pid,holding:{workers:o.holding.workers.length,projects:[...o.holding.projects]},surviving:[...o.surviving],workers:o.holding.workers.map(s=>({worker_id:s.worker_id,project_label:s.project_label,pid:s.pid,unit:s.unit,isolated:s.isolated,survives:s.survives})),detail:o.detail})}
186
+ `),o.running&&!o.stopped?1:0}async function Cw(e,n={}){let t=n.write??(s=>process.stdout.write(s)),r=n.paths??ge(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(su(n.unitIO??{}),null,2)}
187
+ `),0;if(o==="install"){let s=await ru(nu(r),n.unitIO??{});return t(`${JSON.stringify(s,null,2)}
188
+ `),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await ou(n.unitIO??{}),null,2)}
189
+ `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function Ww(e,n={}){let t=n.write??(a=>process.stdout.write(a)),r=n.warn??(a=>process.stderr.write(a)),o=wi(e),s=kp(n.cwd??process.cwd()),i=xi({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let a of[...i.warnings,...o.warnings])r(`redskilled statusline: ignoring ${a.key}=${a.value} \u2014 ${a.reason}
190
+ `);let l;try{l=await Hu(n.paths??ge(),i.options,{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(a){r(`redskilled statusline: ${a instanceof Error?a.message:String(a)}
191
+ `),l=Ks({options:i.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${l.lines.join(`
180
192
  `)}
181
- `),0}var Q_={"no-start":{kind:"boolean"},"install-unit":{kind:"boolean"},check:{kind:"boolean"},project:{kind:"value",coerce:e=>e},workspace:{kind:"value",coerce:e=>e}};async function z_(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=Ie(e,Q_),o=n.paths??me(),s=n.homeDir??ui(),i=await ii({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),l=r.check||!i.needed?void 0:await Nu(s),a;if(!r.check&&!r["no-start"])try{await ni(o,n.client??{})}catch(f){a=f instanceof Error?f.message:String(f)}let d=await Wu({paths:o,homeNeed:i,...n.homeDir==null?{}:{homeDir:n.homeDir},...n.configHome==null?{}:{configHome:n.configHome},...n.client?.serverCommand==null?{}:{entryOverride:{serverCommand:n.client.serverCommand,serverArgs:n.client.serverArgs}}}),u=r["install-unit"]&&ce(d.entry)?await Hu({configHome:n.configHome??Z_(),unit:Fu({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,p=Cu(d);return t(`${W({verdict:p.verdict,home:{path:l?.path??d.homePath,created:l?.created??!1,tightened:l?.tightened??!1,needed:i.needed,needed_by:i.declaredBy},socket:d.socketPath,...a==null?{}:{start_error:a},...u==null?{}:{unit:{path:u.path,status:u.status}},checks:p.rows.map(f=>({check:f.check,verdict:f.verdict,evidence:f.evidence})),fixes:p.findings.map(f=>({check:f.check,fix:f.fix}))})}
182
- `),p.verdict==="ok"?0:1}var Y_={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function X_(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=Ie(e,Y_),o=await Ku({...n.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return t(`${W({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(s=>({dir:s.dir,verdict:s.verdict,reason:s.reason,removed:[...s.removed]}))})}
183
- `),o.entries.some(s=>s.verdict==="failed")?1:0}function Z_(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:Ju(ui(),".config")}function Yu(e){let n=wo(e);return n.configText==null?{label:null}:{configText:n.configText,label:la(e)}}function ew(e){let n=me();return{...n,socketPath:e.socket??n.socketPath,leasePath:e.lease??n.leasePath,eventLanePath:e.events??n.eventLanePath,sessionKeyHash:e["session-key-hash"]??n.sessionKeyHash,machineIdHash:e["machine-id-hash"]??n.machineIdHash,machineClaimPath:e["machine-claim"]??n.machineClaimPath}}var nw=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;nw&&G_(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
184
- `),process.exitCode=1});async function tw(e,n={}){let t=n.write??(l=>process.stdout.write(l)),r=n.warn??(l=>process.stderr.write(l)),o=di(e),s=Yu(n.cwd??process.cwd()),i=ci({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let l of[...i.warnings,...o.warnings])r(`redskilled dashboard: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
185
- `);try{let l=await vu(n.paths??me(),{...i.options.project==null?{}:{project:i.options.project},mode:i.options.mode,...i.options.maxWidth==null?{}:{maxWidth:i.options.maxWidth}},{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}});t(`${l.lines.join(`
193
+ `),0}var Hw={"no-start":{kind:"boolean"},"install-unit":{kind:"boolean"},check:{kind:"boolean"},project:{kind:"value",coerce:e=>e},workspace:{kind:"value",coerce:e=>e}};async function Bw(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=He(e,Hw),o=n.paths??ge(),s=n.homeDir??vr(),i=await Ri({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),l=r.check||!i.needed?void 0:await rp(s),a;if(!r.check&&!r["no-start"])try{await mi(o,n.client??{})}catch(f){a=f instanceof Error?f.message:String(f)}let d=await ip({paths:o,homeNeed:i,...n.homeDir==null?{}:{homeDir:n.homeDir},...n.configHome==null?{}:{configHome:n.configHome},...n.client?.serverCommand==null?{}:{entryOverride:{serverCommand:n.client.serverCommand,serverArgs:n.client.serverArgs}}}),u=r["install-unit"]&&pe(d.entry)?await dp({configHome:n.configHome??Gw(),unit:ap({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,p=sp(d);return t(`${W({verdict:p.verdict,home:{path:l?.path??d.homePath,created:l?.created??!1,tightened:l?.tightened??!1,needed:i.needed,needed_by:i.declaredBy},socket:d.socketPath,...a==null?{}:{start_error:a},...u==null?{}:{unit:{path:u.path,status:u.status}},checks:p.rows.map(f=>({check:f.check,verdict:f.verdict,evidence:f.evidence})),fixes:p.findings.map(f=>({check:f.check,fix:f.fix}))})}
194
+ `),p.verdict==="ok"?0:1}var Fw={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function Uw(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=He(e,Fw),o=await pp({...n.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return t(`${W({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(s=>({dir:s.dir,verdict:s.verdict,reason:s.reason,removed:[...s.removed]}))})}
195
+ `),o.entries.some(s=>s.verdict==="failed")?1:0}function Gw(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:hp(vr(),".config")}function kp(e){let n=$o(e);return n.configText==null?{label:null}:{configText:n.configText,label:ba(e)}}function Kw(e){let n=ge();return{...n,socketPath:e.socket??n.socketPath,leasePath:e.lease??n.leasePath,eventLanePath:e.events??n.eventLanePath,sessionKeyHash:e["session-key-hash"]??n.sessionKeyHash,machineIdHash:e["machine-id-hash"]??n.machineIdHash,machineClaimPath:e["machine-claim"]??n.machineClaimPath}}var Vw=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;Vw&&Iw(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
196
+ `),process.exitCode=1});async function qw(e,n={}){let t=n.write??(l=>process.stdout.write(l)),r=n.warn??(l=>process.stderr.write(l)),o=wi(e),s=kp(n.cwd??process.cwd()),i=xi({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let l of[...i.warnings,...o.warnings])r(`redskilled dashboard: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
197
+ `);try{let l=await Bu(n.paths??ge(),{...i.options.project==null?{}:{project:i.options.project},mode:i.options.mode,...i.options.maxWidth==null?{}:{maxWidth:i.options.maxWidth}},{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}});t(`${l.lines.join(`
186
198
  `)}
187
199
  `)}catch(l){r(`redskilled dashboard: ${l instanceof Error?l.message:String(l)}
188
200
  `),t(`redskilled unreachable \u2014 the host was not asked, so its Workers are unknown
189
- `)}return 0}export{Qu as REDSKILLED_HOST_TOKEN_ENV,C_ as REDSKILLED_USAGE,qu as armRedskilledQueueTransport,zu as resolveRedskilledHostToken,U_ as resolveServeGithubBalance,H_ as resolveServeQueueDiscovery,tw as runDashboard,z_ as runProvision,X_ as runReclaim,G_ as runRedskilledCli,J_ as runStatusline,V_ as runStop,q_ as runUnit};
201
+ `)}return 0}export{gp as REDSKILLED_HOST_TOKEN_ENV,jw as REDSKILLED_USAGE,mp as armRedskilledQueueTransport,yp as resolveRedskilledHostToken,Tw as resolveServeGithubBalance,$w as resolveServeQueueDiscovery,qw as runDashboard,Bw as runProvision,Uw as runReclaim,Iw as runRedskilledCli,Ww as runStatusline,Mw as runStop,Cw as runUnit};