@reddb-io/red-skills 3.3.11 → 3.3.12

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,81 +1,81 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var Bc=Object.defineProperty;var Kc=(e,n)=>()=>(e&&(n=e(e=0)),n);var Vc=(e,n)=>{for(var t in n)Bc(e,t,{get:n[t],enumerable:!0})};var ol={};Vc(ol,{REDSKILLED_BIN_ENV:()=>Gr,REDSKILLED_BUNDLE_ASSET:()=>le,REDSKILLED_ENTRY_UNRESOLVED:()=>xn,RedskilledDaemonEntryError:()=>Sn,isRedskilledEntryPath:()=>Qr,isResolvedRedskilledEntry:()=>ae,redskilledBundleCacheRoot:()=>mt,redskilledServeArgv:()=>Ae,requireRedskilledEntry:()=>ht,resolveRedskilledEntry:()=>Re});import{existsSync as Bf,readdirSync as Kf}from"node:fs";import{homedir as Vf}from"node:os";import{basename as qr,dirname as Vr,join as V,resolve as ft}from"node:path";function ae(e){return"command"in e}function Ae(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 mt(e=process.env){return rl(e)}function Re(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??Bf,o=n.execPath??process.execPath,i=n.execArgv??[],s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,a=(p,u)=>({command:o,args:[...i,p],source:u,entry:p}),l=t[Gr];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(s&&Qr(s))return a(ft(s),"caller-entry");let d=[];for(let[p,u]of Qf(s,n.rootDir,t,n.listDir??Xf))if(d.push(p),r(p))return a(p,u);return{diagnostic:xn,searched:d,...s?{callerEntry:ft(s)}:{}}}function ht(e={},n={}){let t=Re(e,n);if(ae(t))return t;throw new Sn(t)}function Qr(e){let n=qr(e);return n===le||Jr.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:Jf(ft(e))}function Jf(e){let n=Vr(e);for(let t=0;t<4;t++){if(qr(n)==="redskilled")return!0;let r=Vr(n);if(r===n)return!1;n=r}return!1}function*Qf(e,n,t,r){if(e){let i=Vr(ft(e));yield[V(i,le),"caller-sibling-bundle"];let s=qf.exec(qr(e));s&&(yield[V(i,`redskilled-${s[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[V(i,"..","dist",le),"caller-sibling-bundle"]}for(let i of Gf){let s=t[i];s&&(yield[V(s,"dist",le),"plugin-root-bundle"],yield[V(s,"..","..","dist",le),"plugin-root-bundle"])}n&&(yield[V(n,"dist",le),"repo-bundle"],yield[V(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[V(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=rl(t);yield[V(o,le),"bundle-cache"];for(let i of zf(o,r))yield[V(o,i),"bundle-cache"]}function rl(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||V(e.HOME||Vf(),".cache");return V(n,"red-skills","bundles")}function zf(e,n){return n(e).filter(t=>Jr.test(t)).sort((t,r)=>Yf(tl(r),tl(t)))}function tl(e){return Jr.exec(e)?.[1]??""}function Yf(e,n){let t=i=>i.split(".").map(s=>Number.parseInt(s,10)),[r,o]=[t(e),t(n)];for(let i=0;i<Math.max(r.length,o.length);i++){let[s,a]=[r[i],o[i]];if(Number.isNaN(s)||s===void 0)return Number.isNaN(a)||a===void 0?e.localeCompare(n):-1;if(Number.isNaN(a)||a===void 0)return 1;if(s!==a)return s-a}return 0}function Xf(e){try{return Kf(e)}catch{return[]}}var le,xn,Gr,Sn,qf,Jr,Gf,fe=Kc(()=>{"use strict";le="redskilled.bundle.min.mjs",xn="redskilled-daemon-entry-unresolved",Gr="REDSKILLED_BIN";Sn=class extends Error{code=xn;searched;callerEntry;constructor(n){super(`${xn}: no published ${le} found to spawn the redskilled daemon from${n.callerEntry?` (caller entry: ${n.callerEntry}, which is NOT used as a fallback)`:""}
3
+ var yu=Object.defineProperty;var ku=(e,n)=>()=>(e&&(n=e(e=0)),n);var bu=(e,n)=>{for(var t in n)yu(e,t,{get:n[t],enumerable:!0})};var Sl={};bu(Sl,{REDSKILLED_BIN_ENV:()=>ro,REDSKILLED_BUNDLE_ASSET:()=>le,REDSKILLED_ENTRY_UNRESOLVED:()=>jn,RedskilledDaemonEntryError:()=>Dn,isRedskilledEntryPath:()=>io,isResolvedRedskilledEntry:()=>ae,redskilledBundleCacheRoot:()=>bt,redskilledServeArgv:()=>Ae,requireRedskilledEntry:()=>Rt,resolveRedskilledEntry:()=>Re});import{existsSync as ym,readdirSync as km}from"node:fs";import{homedir as bm}from"node:os";import{basename as to,dirname as no,join as V,resolve as kt}from"node:path";function ae(e){return"command"in e}function Ae(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 bt(e=process.env){return xl(e)}function Re(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??ym,o=n.execPath??process.execPath,i=n.execArgv??[],s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,a=(p,u)=>({command:o,args:[...i,p],source:u,entry:p}),l=t[ro];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(s&&io(s))return a(kt(s),"caller-entry");let d=[];for(let[p,u]of xm(s,n.rootDir,t,n.listDir??Em))if(d.push(p),r(p))return a(p,u);return{diagnostic:jn,searched:d,...s?{callerEntry:kt(s)}:{}}}function Rt(e={},n={}){let t=Re(e,n);if(ae(t))return t;throw new Dn(t)}function io(e){let n=to(e);return n===le||oo.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:wm(kt(e))}function wm(e){let n=no(e);for(let t=0;t<4;t++){if(to(n)==="redskilled")return!0;let r=no(n);if(r===n)return!1;n=r}return!1}function*xm(e,n,t,r){if(e){let i=no(kt(e));yield[V(i,le),"caller-sibling-bundle"];let s=Rm.exec(to(e));s&&(yield[V(i,`redskilled-${s[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[V(i,"..","dist",le),"caller-sibling-bundle"]}for(let i of _m){let s=t[i];s&&(yield[V(s,"dist",le),"plugin-root-bundle"],yield[V(s,"..","..","dist",le),"plugin-root-bundle"])}n&&(yield[V(n,"dist",le),"repo-bundle"],yield[V(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[V(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=xl(t);yield[V(o,le),"bundle-cache"];for(let i of Sm(o,r))yield[V(o,i),"bundle-cache"]}function xl(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||V(e.HOME||bm(),".cache");return V(n,"red-skills","bundles")}function Sm(e,n){return n(e).filter(t=>oo.test(t)).sort((t,r)=>vm(wl(r),wl(t)))}function wl(e){return oo.exec(e)?.[1]??""}function vm(e,n){let t=i=>i.split(".").map(s=>Number.parseInt(s,10)),[r,o]=[t(e),t(n)];for(let i=0;i<Math.max(r.length,o.length);i++){let[s,a]=[r[i],o[i]];if(Number.isNaN(s)||s===void 0)return Number.isNaN(a)||a===void 0?e.localeCompare(n):-1;if(Number.isNaN(a)||a===void 0)return 1;if(s!==a)return s-a}return 0}function Em(e){try{return km(e)}catch{return[]}}var le,jn,ro,Dn,Rm,oo,_m,pe=ku(()=>{"use strict";le="redskilled.bundle.min.mjs",jn="redskilled-daemon-entry-unresolved",ro="REDSKILLED_BIN";Dn=class extends Error{code=jn;searched;callerEntry;constructor(n){super(`${jn}: no published ${le} 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)}};qf=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Jr=/^redskilled-(.+)\.bundle\.min\.mjs$/,Gf=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as xR}from"node:child_process";import{homedir as zo}from"node:os";import{join as pc}from"node:path";var Fe=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},ve=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 Fe(e,n)}function S(e,n){return new ve(e,n)}function Ue(e){return e instanceof ve?e:e instanceof Fe?new ve(e.line,e.reason):new ve(0,String(e&&e.message?e.message:e))}var Di=["type","kind","event"],Ee="|",Oi=new Set(["order","discriminator","rows","common"]);var D=",";function Xn(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 re(e){return R(e,"invalid quoted string")}function B(e,n){if(e==="")return"";if(e.startsWith('"'))return $i(e,n);if(e.includes('"'))throw re(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:qc(e)?Number(e):e}function J(e,n){let t=e.trim();if(t.startsWith('"'))return[$i(t,n),!0];if(t.includes('"')||/\s/.test(t))throw R(n,"expected non-empty field name");return[t,!1]}var Ai=/["\\\u0000-\u0008\u000a-\u001f]/g;function $i(e,n){if(e.charCodeAt(0)!==34)throw re(n);let t="",r=1;for(;r<e.length;){Ai.lastIndex=r;let o=Ai.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(r,o.index);throw re(n)}if(o[0]!=="\\")throw re(n);t+=e.slice(r,o.index);let i=e[o.index+1];switch(r=o.index+2,i){case'"':t+='"';break;case"\\":t+="\\";break;case"n":t+=`
8
- `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let s=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw re(n);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw re(n);t+=String.fromCharCode(a),r+=4;break}default:throw re(n)}}throw re(n)}function Ii(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 re(t);n=o+2;continue}if(r===-1)throw re(t);return r+1}}function Q(e,n,t){if(e==="")return[];let r=[],o=0,i=0;for(;i<e.length;){let s=e.indexOf('"',i),a=e.indexOf(n,i);if(a!==-1&&(s===-1||a<s))r.push(e.slice(o,a).trim()),o=a+1,i=a+1;else if(s!==-1)i=Ii(e,s+1,t);else break}return r.push(e.slice(o).trim()),r}function W(e,n,t){let r=0;for(;r<e.length;){let o=e.indexOf('"',r),i=e.indexOf(n,r);if(i!==-1&&(o===-1||i<o))return i;if(o===-1)return-1;r=Ii(e,o+1,t)}return-1}function qc(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Gc(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Jc(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 oe(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 Jc(e);if(typeof e=="string")return zc(e,n);throw R(0,"not a primitive")}function Qc(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function N(e){return Qc(e)?e:Zn(e)}function zc(e,n){return nr(e,n)?Zn(e):e}function nr(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Gc(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}var Li=/["\\\u0000-\u001f]/g;function Zn(e){let n='"',t=0;Li.lastIndex=0;let r;for(;(r=Li.exec(e))!==null;){let o=e.charCodeAt(r.index),i;o===34?i='\\"':o===92?i="\\\\":o===10?i="\\n":o===13?i="\\r":o===9?i="\\t":i=`\\u${o.toString(16).padStart(4,"0")}`,n+=e.slice(t,r.index)+i,t=r.index+1}return`${n}${e.slice(t)}"`}function z(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function A(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ti(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 Ni(e,n){let t=[],r=!1;return Xn(e).forEach((o,i)=>{let s=i+1;if(o.trim()===""){r=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw R(s,"invalid indentation");if(n.strict&&a%n.indent!==0)throw R(s,"invalid indentation");let l=Math.floor(a/n.indent);ie(l,s,n),t.push({number:s,depth:l,content:o.slice(a),blankBefore:r}),r=!1}),t}function ie(e,n,t){if(t.maxDepth!==0&&e>t.maxDepth)throw R(n,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function gn(e,n,t){if(t.maxDepth===0)return;let r=0,o=!1,i=!1;for(let s of e){if(i){i=!1;continue}if(o&&s==="\\"){i=!0;continue}if(s==='"'){o=!o;continue}o||(s==="{"?(r+=1,ie(r,n,t)):s==="}"&&(r=Math.max(0,r-1)))}}function Wi(e){if(!A(e)||Object.keys(e).length===0)return e;let n={};for(let[t,r]of Object.entries(e)){let o=Yc(r,1);if(o===void 0)return e;z(n,t,o)}return n}function Yc(e,n){if(!A(e)||!Xc(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 i=Zc(t,o,n),s=e.common,a=s===void 0?Array.from({length:o},()=>({})):s;if(!Array.isArray(a)||a.length!==o||!a.every(A))throw Hi(n);let l=new Map;for(let[u,f]of Object.entries(e))if(!Oi.has(u)){if(!Array.isArray(f)||!f.every(A))throw C(n);l.set(u,f)}if(l.size===0)throw C(n);let d=new Map,p=i.map((u,f)=>{let m=l.get(u);if(m===void 0)throw tr(n);let h=d.get(u)??0,b=m[h];if(b===void 0)throw tr(n);return d.set(u,h+1),eu(r,u,a[f],b,n)});for(let[u,f]of l)if((d.get(u)??0)!==f.length)throw tr(n);return p}function Xc(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function Zc(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 i=r.slice(0,o),s=r.slice(o+2);if(i===""||s.includes("+tail("))throw C(t);let a=i.split(",").map(p=>ou(p,t));if(a.some(p=>p===""))throw C(t);let l=ru(s,t),d=a.length*l;if(!Number.isSafeInteger(d))throw C(t);if(d!==n)throw Hi(t);return Array.from({length:d},(p,u)=>a[u%a.length])}function eu(e,n,t,r,o){let i={};z(i,e,n);for(let[s,a]of Object.entries(t??{})){if(s===e||Object.prototype.hasOwnProperty.call(i,s))throw C(o);z(i,s,a)}for(let[s,a]of Object.entries(nu(r,o))){if(s===e||Object.prototype.hasOwnProperty.call(i,s))throw C(o);z(i,s,a)}return i}function nu(e,n){let t={};for(let[r,o]of Object.entries(e))tu(t,r.split("."),o,n);return et(t,n)}function tu(e,n,t,r){if(n.some(i=>i===""))throw C(r);let o=e;for(let i=0;i<n.length;i+=1){let s=n[i];if(i===n.length-1){o[s]=t;return}if(o[s]??={},o=o[s],!A(o))throw C(r)}}function et(e,n){return Array.isArray(e)?e.map(t=>et(t,n)):A(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 et(e[String(r)],n)}):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,et(r,n)])):e}function ru(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 ou(e,n){try{return decodeURIComponent(e)}catch{throw C(n)}}function Ci(e){return encodeURIComponent(e)}function C(e){return R(e,"invalid cyclic array wire")}function Hi(e){return R(e,"cyclic array length mismatch")}function tr(e){return R(e,"cyclic array group length mismatch")}function Fi(e){if(!A(e))return;let n=Object.entries(e);if(n.length===0)return;let t=[];for(let[o,i]of n){let s=iu(i);if(s===void 0)return;t.push([o,s])}let r=[];for(let[o,i]of t)du(r,o,i);return r.join("")}function iu(e){if(!Array.isArray(e)||e.length===0||!e.every(A))return;let n=su(e);if(n===void 0)return;let t=e.map(a=>a[n]),r=lu(t);if(r===void 0)return;let o=au(e,n),i=new Map;for(let a of e){let l=a[n];i.has(l)||i.set(l,[]);let d={};for(let[p,u]of Object.entries(a))if(p!==n&&!o.includes(p)&&!rr(u,p,d))return;i.get(l).push(d)}let s=[];for(let a of r.cycle){let l=i.get(a),d=uu(l);if(d===void 0||d.length===0)return;s.push({fields:d,label:a,rows:l})}return{common:o,commonRows:e.map(a=>Object.fromEntries(o.map(l=>[l,a[l]]))),discriminator:n,groups:s,order:r,rows:e}}function su(e){return Di.find(n=>e.every(t=>typeof t[n]=="string"))}function lu(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((s,a)=>s===t[a%n]))continue;let r=e.length/n;if(r<3)continue;let o=e.map(Ci).join(","),i=`cycle(${t.map(Ci).join(",")})*${r}`;if(i.length<=o.length*.4)return{cycle:t,encoded:i,repeats:r}}}function au(e,n){let t=[],r=Object.keys(e[0]),o=r.indexOf(n)+1;for(let i of r.slice(o).filter(s=>s!==n)){if(!cu(i)||!e.every(s=>Object.prototype.hasOwnProperty.call(s,i))||!e.every(s=>oe(s[i])))break;t.push(i)}return t}function du(e,n,t){e.push(N(n),`:
9
- `),e.push(" order: ",H(t.order.encoded,Ee),`
10
- `),e.push(" discriminator: ",H(t.discriminator,Ee),`
6
+ `)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};Rm=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,oo=/^redskilled-(.+)\.bundle\.min\.mjs$/,_m=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as eR}from"node:child_process";import{homedir as hi}from"node:os";import{join as Mc}from"node:path";var He=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},ve=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 He(e,n)}function S(e,n){return new ve(e,n)}function Ue(e){return e instanceof ve?e:e instanceof He?new ve(e.line,e.reason):new ve(0,String(e&&e.message?e.message:e))}var Qi=["type","kind","event"],Ee="|",zi=new Set(["order","discriminator","rows","common"]);var D=",";function rt(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 re(e){return b(e,"invalid quoted string")}function G(e,n){if(e==="")return"";if(e.startsWith('"'))return Zi(e,n);if(e.includes('"'))throw re(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:Ru(e)?Number(e):e}function J(e,n){let t=e.trim();if(t.startsWith('"'))return[Zi(t,n),!0];if(t.includes('"')||/\s/.test(t))throw b(n,"expected non-empty field name");return[t,!1]}var Yi=/["\\\u0000-\u0008\u000a-\u001f]/g;function Zi(e,n){if(e.charCodeAt(0)!==34)throw re(n);let t="",r=1;for(;r<e.length;){Yi.lastIndex=r;let o=Yi.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(r,o.index);throw re(n)}if(o[0]!=="\\")throw re(n);t+=e.slice(r,o.index);let i=e[o.index+1];switch(r=o.index+2,i){case'"':t+='"';break;case"\\":t+="\\";break;case"n":t+=`
8
+ `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let s=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(s))throw re(n);let a=Number.parseInt(s,16);if(a>=55296&&a<=57343)throw re(n);t+=String.fromCharCode(a),r+=4;break}default:throw re(n)}}throw re(n)}function es(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 re(t);n=o+2;continue}if(r===-1)throw re(t);return r+1}}function Q(e,n,t){if(e==="")return[];let r=[],o=0,i=0;for(;i<e.length;){let s=e.indexOf('"',i),a=e.indexOf(n,i);if(a!==-1&&(s===-1||a<s))r.push(e.slice(o,a).trim()),o=a+1,i=a+1;else if(s!==-1)i=es(e,s+1,t);else break}return r.push(e.slice(o).trim()),r}function W(e,n,t){let r=0;for(;r<e.length;){let o=e.indexOf('"',r),i=e.indexOf(n,r);if(i!==-1&&(o===-1||i<o))return i;if(o===-1)return-1;r=es(e,o+1,t)}return-1}function Ru(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function _u(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function wu(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 oe(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 wu(e);if(typeof e=="string")return Su(e,n);throw b(0,"not a primitive")}function xu(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function N(e){return xu(e)?e:ot(e)}function Su(e,n){return ur(e,n)?ot(e):e}function ur(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||_u(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}var Xi=/["\\\u0000-\u001f]/g;function ot(e){let n='"',t=0;Xi.lastIndex=0;let r;for(;(r=Xi.exec(e))!==null;){let o=e.charCodeAt(r.index),i;o===34?i='\\"':o===92?i="\\\\":o===10?i="\\n":o===13?i="\\r":o===9?i="\\t":i=`\\u${o.toString(16).padStart(4,"0")}`,n+=e.slice(t,r.index)+i,t=r.index+1}return`${n}${e.slice(t)}"`}function z(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function A(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ns(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 ts(e,n){let t=[],r=!1;return rt(e).forEach((o,i)=>{let s=i+1;if(o.trim()===""){r=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw b(s,"invalid indentation");if(n.strict&&a%n.indent!==0)throw b(s,"invalid indentation");let l=Math.floor(a/n.indent);ie(l,s,n),t.push({number:s,depth:l,content:o.slice(a),blankBefore:r}),r=!1}),t}function ie(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,i=!1;for(let s of e){if(i){i=!1;continue}if(o&&s==="\\"){i=!0;continue}if(s==='"'){o=!o;continue}o||(s==="{"?(r+=1,ie(r,n,t)):s==="}"&&(r=Math.max(0,r-1)))}}function is(e){if(!A(e)||Object.keys(e).length===0)return e;let n={};for(let[t,r]of Object.entries(e)){let o=vu(r,1);if(o===void 0)return e;z(n,t,o)}return n}function vu(e,n){if(!A(e)||!Eu(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 i=Pu(t,o,n),s=e.common,a=s===void 0?Array.from({length:o},()=>({})):s;if(!Array.isArray(a)||a.length!==o||!a.every(A))throw ss(n);let l=new Map;for(let[u,f]of Object.entries(e))if(!zi.has(u)){if(!Array.isArray(f)||!f.every(A))throw C(n);l.set(u,f)}if(l.size===0)throw C(n);let d=new Map,p=i.map((u,f)=>{let m=l.get(u);if(m===void 0)throw pr(n);let h=d.get(u)??0,R=m[h];if(R===void 0)throw pr(n);return d.set(u,h+1),ju(r,u,a[f],R,n)});for(let[u,f]of l)if((d.get(u)??0)!==f.length)throw pr(n);return p}function Eu(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function Pu(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 i=r.slice(0,o),s=r.slice(o+2);if(i===""||s.includes("+tail("))throw C(t);let a=i.split(",").map(p=>Tu(p,t));if(a.some(p=>p===""))throw C(t);let l=Au(s,t),d=a.length*l;if(!Number.isSafeInteger(d))throw C(t);if(d!==n)throw ss(t);return Array.from({length:d},(p,u)=>a[u%a.length])}function ju(e,n,t,r,o){let i={};z(i,e,n);for(let[s,a]of Object.entries(t??{})){if(s===e||Object.prototype.hasOwnProperty.call(i,s))throw C(o);z(i,s,a)}for(let[s,a]of Object.entries(Du(r,o))){if(s===e||Object.prototype.hasOwnProperty.call(i,s))throw C(o);z(i,s,a)}return i}function Du(e,n){let t={};for(let[r,o]of Object.entries(e))Ou(t,r.split("."),o,n);return it(t,n)}function Ou(e,n,t,r){if(n.some(i=>i===""))throw C(r);let o=e;for(let i=0;i<n.length;i+=1){let s=n[i];if(i===n.length-1){o[s]=t;return}if(o[s]??={},o=o[s],!A(o))throw C(r)}}function it(e,n){return Array.isArray(e)?e.map(t=>it(t,n)):A(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 it(e[String(r)],n)}):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,it(r,n)])):e}function Au(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 Tu(e,n){try{return decodeURIComponent(e)}catch{throw C(n)}}function rs(e){return encodeURIComponent(e)}function C(e){return b(e,"invalid cyclic array wire")}function ss(e){return b(e,"cyclic array length mismatch")}function pr(e){return b(e,"cyclic array group length mismatch")}function ls(e){if(!A(e))return;let n=Object.entries(e);if(n.length===0)return;let t=[];for(let[o,i]of n){let s=$u(i);if(s===void 0)return;t.push([o,s])}let r=[];for(let[o,i]of t)Cu(r,o,i);return r.join("")}function $u(e){if(!Array.isArray(e)||e.length===0||!e.every(A))return;let n=Lu(e);if(n===void 0)return;let t=e.map(a=>a[n]),r=Iu(t);if(r===void 0)return;let o=Nu(e,n),i=new Map;for(let a of e){let l=a[n];i.has(l)||i.set(l,[]);let d={};for(let[p,u]of Object.entries(a))if(p!==n&&!o.includes(p)&&!fr(u,p,d))return;i.get(l).push(d)}let s=[];for(let a of r.cycle){let l=i.get(a),d=Wu(l);if(d===void 0||d.length===0)return;s.push({fields:d,label:a,rows:l})}return{common:o,commonRows:e.map(a=>Object.fromEntries(o.map(l=>[l,a[l]]))),discriminator:n,groups:s,order:r,rows:e}}function Lu(e){return Qi.find(n=>e.every(t=>typeof t[n]=="string"))}function Iu(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((s,a)=>s===t[a%n]))continue;let r=e.length/n;if(r<3)continue;let o=e.map(rs).join(","),i=`cycle(${t.map(rs).join(",")})*${r}`;if(i.length<=o.length*.4)return{cycle:t,encoded:i,repeats:r}}}function Nu(e,n){let t=[],r=Object.keys(e[0]),o=r.indexOf(n)+1;for(let i of r.slice(o).filter(s=>s!==n)){if(!Mu(i)||!e.every(s=>Object.prototype.hasOwnProperty.call(s,i))||!e.every(s=>oe(s[i])))break;t.push(i)}return t}function Cu(e,n,t){e.push(N(n),`:
9
+ `),e.push(" order: ",F(t.order.encoded,Ee),`
10
+ `),e.push(" discriminator: ",F(t.discriminator,Ee),`
11
11
  `),e.push(" rows: ",String(t.rows.length),`
12
- `),t.common.length>0&&Mi(e,"common",t.common,t.commonRows);for(let r of t.groups)Mi(e,r.label,r.fields,r.rows)}function Mi(e,n,t,r){e.push(" ",N(n),"[",String(r.length),Ee,"]{",t.map(N).join(Ee),`}:
13
- `);for(let o of r)e.push(" ",t.map(i=>H(o[i],Ee)).join(Ee),`
14
- `)}function cu(e){return e!==""&&or(e)}function rr(e,n,t,r=new Set){if(!or(n))return!1;if(oe(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((i,s)=>rr(i,`${n}.${s}`,t,r));return r.delete(e),o}if(A(e)){if(r.has(e))return!1;r.add(e);let o=Object.entries(e).every(([i,s])=>!i.includes(".")&&rr(s,`${n}.${i}`,t,r));return r.delete(e),o}return!1}function uu(e){let n=Object.keys(e[0]??{});if(e.every(t=>pu(Object.keys(t),n)))return n.every(or)?n:void 0}function pu(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function or(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function Be(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function nt(e,n){if(n===-1)throw R(0,"array header missing colon");let t=e.slice(0,n),r=W(t,"[",0);if(r===-1)throw R(0,"invalid array header");let o,i;try{[o,i]=J(t.slice(0,r),0)}catch{throw R(0,"invalid array header")}let s=t.slice(r+1),a=s.indexOf("]");if(a===-1)throw R(0,"invalid array header");let l=s.slice(0,a),d=/^[0-9]*/.exec(l)[0];if(d===""||d.length>1&&d.startsWith("0"))throw R(0,"invalid array header");let p=Number.parseInt(d,10),u;switch(l.slice(d.length)){case"":u=",";break;case" ":u=" ";break;case"|":u="|";break;default:throw R(0,"invalid array header")}let f=s.slice(a+1),m,h;if(f==="")m=void 0,h=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{h=mu(f.slice(1,-1),u),m=sr(h)}catch(b){throw R(0,b.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw R(0,"invalid array header");return{key:o,keyQuoted:i,len:p,delimiter:u,fields:m,fieldTree:h}}function Ui(e){let n=W(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=J(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),i=D;(o.startsWith("|")||o.startsWith(" "))&&(i=o[0],o=o.slice(1));let s;try{s=fu(o,i,i)}catch(a){throw R(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:i,fields:s}}function fu(e,n,t){let r=[],o=0;function i(l,d){let p=0;for(;o<e.length&&!(d&&e[o]==="}");){if(e[o]===n||e[o]==="}")throw R(0,"invalid array header");let u=o;for(;o<e.length;){let h=e[o];if(h==='"'){s();continue}if(h===n||h==="{"||h==="}"||h==="[")break;o+=1}let[f,m]=J(e.slice(u,o),0);if(f===""&&!m)throw R(0,"invalid array header");if(p+=1,e[o]==="["){o+=1;let h=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw R(0,"invalid array header");let b=e.slice(h,o);if(!Bi(b,t))throw R(0,"invalid array header");o+=1,r.push({path:[...l,f],listDelimiter:b})}else if(e[o]==="{"){o+=1;let h=r.length;if(i([...l,f],!0),e[o]!=="}"||r.length===h)throw R(0,"invalid array header");o+=1}else r.push({path:[...l,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(p===0)throw R(0,"invalid array header")}function s(){for(o+=1;o<e.length;){let l=e[o];if(o+=1,l==="\\")o+=1;else if(l==='"')return}}if(i([],!1),o!==e.length)throw R(0,"invalid array header");let a=new Set;for(let l=0;l<r.length;l+=1)for(let d=l+1;d<r.length;d+=1)if(Ki(r[l].path,r[d].path)||yn(r[l].path,r[d].path)||yn(r[d].path,r[l].path))throw R(0,"duplicate key");for(let l of r){let p=l.path.join("\0");if(a.has(p))throw R(0,"duplicate key");a.add(p)}return r}function mu(e,n){if(n!==D&&e.includes(D)&&(e.includes("[")||e.includes("{")))return ir(e,D,n);try{return ir(e,n,n)}catch(t){if(n!==D&&t.reason!=="duplicate key")return ir(e,D,n);throw t}}function ir(e,n,t){let r=0;function o(l){let d=[];for(;r<e.length&&!(l&&e[r]==="}");){if(e[r]===n||e[r]==="}")throw R(0,"invalid array header");let p=r;for(;r<e.length;){let h=e[r];if(h==='"'){i();continue}if(h===n||h==="{"||h==="}"||h==="[")break;r+=1}let[u,f]=J(e.slice(p,r),0);if(u===""&&!f)throw R(0,"invalid array header");let m={key:u};if(e[r]==="["){r+=1;let h=r;for(;r<e.length&&e[r]!=="]";)r+=1;if(r>=e.length)throw R(0,"invalid array header");let b=e.slice(h,r);r+=1;let k=hu(b);if(k!==void 0){if(k.delimiter!==t)throw R(0,"invalid array header");m.fixedLength=k.len,m.fixedDelimiter=k.delimiter}else if(Bi(b,t))m.listDelimiter=b;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(l?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 i(){for(r+=1;r<e.length;){let l=e[r];if(r+=1,l==="\\")r+=1;else if(l==='"')return}}let s=o(!1);if(r!==e.length)throw R(0,"invalid array header");let a=sr(s);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(Ki(a[l].path,a[d].path)||yn(a[l].path,a[d].path)||yn(a[d].path,a[l].path))throw R(0,"duplicate key");return s}function hu(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=D;break;case" ":r=" ";break;case"|":r="|";break;default:return}return{len:Number.parseInt(n,10),delimiter:r}}function sr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?sr(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function tt(e,n,t){return e.listDelimiter===void 0?B(n,t):Q(n,e.listDelimiter,t).map(r=>B(r,t))}function Bi(e,n){return e.length===1&&e!==n&&!/[ \t\r\n"[\]{}:]/.test(e)}function Ki(e,n){return e.length===n.length&&yn(e,n)}function yn(e,n){return n.every((t,r)=>e[r]===t)}function rt(e,n){return R(n,e.reason??String(e.message))}function Y(e,n){let t=Ti(n),r=Ni(e,t),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw R(o.number,"invalid indentation");let i=r.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){gn(o.content,o.number,t);let d;try{d=nt(o.content,W(o.content,":",o.number))}catch(p){if(t.strict)throw rt(p,o.number);d=void 0}if(d!==void 0)return ku(d,r,t)}if(i&&W(o.content,":",o.number)===-1)return B(o.content.trim(),o.number);let s={index:0},a=ar(r,s,0,t),l=r[s.index];if(l!==void 0)throw R(l.number,"expected end of document");return t.cyclicDiscriminatedArrays?Wi(a):a}function ar(e,n,t,r){let o={};for(;n.index<e.length;){let i=e[n.index];if(i.depth<t)break;if(i.depth>t)throw R(i.number,"invalid indentation");let{key:s,quoted:a,value:l}=gu(e,n,t,r);Yi(o,s,a,l,r,i.number)}return o}function gu(e,n,t,r){let o=e[n.index],i=o.content,s=W(i,":",o.number);if(s===-1)throw R(o.number,"expected `key: value`");let a=i.slice(0,s),l=i.slice(s+1),d=W(a,"[",o.number),p=W(a,"{",o.number);if(p!==-1&&(d===-1||p<d)){gn(a,o.number,r);let h;try{h=Ui(a)}catch(k){if(r.strict)throw rt(k,o.number);n.index+=1;let w=lr(e,n,t,l,o.number,r);return{key:a.trim(),quoted:!1,value:w}}if(l.trim()!=="")throw R(o.number,"expected keyed map rows");let b=yu(h,e,n,t+1,r);return{key:h.key,quoted:h.keyQuoted,value:b}}if(d!==-1){gn(a,o.number,r);let h;try{h=nt(a,s)}catch(k){if(r.strict)throw rt(k,o.number);n.index+=1;let w=lr(e,n,t,l,o.number,r);return{key:a.trim(),quoted:!1,value:w}}if(h.key===""&&!h.keyQuoted)throw R(o.number,"expected non-empty field name");let b=dr(h,l,e,n,t,r);return{key:h.key,quoted:h.keyQuoted,value:b}}let[u,f]=J(a,o.number);if(u===""&&!f)throw R(o.number,"expected non-empty field name");n.index+=1;let m=lr(e,n,t,l,o.number,r);return{key:u,quoted:f,value:m}}function lr(e,n,t,r,o,i){let s=r.trim();if(s==="[]")return[];if(s!=="")return B(s,o);let a=e[n.index];return a!==void 0&&a.depth>t?ar(e,n,t+1,i):{}}function yu(e,n,t,r,o){let i={};for(t.index+=1;t.index<n.length;){let s=n[t.index];if(s.depth<r)break;if(s.depth>r)throw R(s.number,"invalid indentation");if(s.blankBefore&&o.strict)throw R(s.number,"blank line inside keyed map");let a=W(s.content,":",s.number);if(a===-1)throw R(s.number,"expected `key: value`");let[l,d]=J(s.content.slice(0,a),s.number);if(l===""&&!d)throw R(s.number,"expected non-empty field name");let p=Q(s.content.slice(a+1).trim(),e.delimiter,s.number);if(p.length!==e.fields.length)throw R(s.number,"keyed map row length mismatch");let u={};e.fields.forEach((f,m)=>{Ve(u,f.path,tt(f,p[m],s.number),o,s.number)}),Yi(i,l,d,u,o,s.number),t.index+=1}return i}function ku(e,n,t){let r=n[0],o=W(r.content,":",r.number);if(o===-1)throw R(r.number,"expected `key: value`");let i=r.content.slice(o+1),s={index:0},a=dr(e,i,n,s,0,t),l=n[s.index];if(l!==void 0)throw R(l.number,"expected end of document");return a}function dr(e,n,t,r,o,i){let s=t[r.index].number,a=n.trim();if(r.index+=1,e.fields!==void 0){if(a!=="")throw R(s,"expected tabular rows");return Ru(e,e.fields,t,r,o+1,i)}if(a!==""){let l=Q(a,e.delimiter,s).map(d=>B(d,s));if(l.length!==e.len)throw R(s,"array length mismatch");return l}return Eu(e,t,r,o+1,i)}function Ru(e,n,t,r,o,i){if(e.fieldTree!==void 0&&Su(e.fieldTree))return bu(e,t,r,o,i);let s=[];for(;s.length<e.len;){let l=t[r.index];if(l===void 0)throw Be(t,r.index);if(l.depth<o)break;if(l.depth>o)throw R(l.number,"invalid indentation");if(l.blankBefore&&i.strict)throw R(l.number,"blank line inside array");if(!Ke(l.content,e.delimiter,l.number))break;let d=Q(l.content,e.delimiter,l.number);if(d.length!==n.length)throw R(l.number,"array row length mismatch");let p={};n.forEach((u,f)=>{Ve(p,u.path,tt(u,d[f],l.number),i,l.number)}),s.push(p),r.index+=1}if(s.length!==e.len)throw Be(t,r.index);let a=t[r.index];if(a!==void 0&&a.depth>=o&&Ke(a.content,e.delimiter,a.number))throw R(a.number,"array length mismatch");return s}function bu(e,n,t,r,o){return Vi(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function Vi(e,n,t,r,o,i,s,a){let l=[],d=Gi(e,n,t,r,o.index,i,s);for(;l.length<e;){let u=r[o.index];if(u===void 0)throw Be(r,o.index);if(u.depth<i)break;if(u.depth>i)throw R(u.number,"invalid indentation");if(u.blankBefore&&s.strict)throw R(u.number,"blank line inside array");if(!Ke(u.content,t,u.number))break;let f=Q(u.content,t,u.number),m={cellIndex:0,nextIndex:o.index+1,flatWidth:ot(n),childTableFields:d},h=qi(n,f,u.number,r,m,i+1,t,s);if(m.cellIndex!==f.length)throw R(u.number,"array row length mismatch");l.push(xu(n,h,a)),o.index=m.nextIndex}if(l.length!==e)throw Be(r,o.index);let p=r[o.index];if(p!==void 0&&p.depth>=i&&Ke(p.content,t,p.number))throw R(p.number,"array length mismatch");return l}function qi(e,n,t,r,o,i,s,a){let l={};return e.forEach((d,p)=>{let u=e.slice(p+1),f=_u(d,u,n,t,r,o,i,s,a);Ve(l,[d.key],f,a,t)}),l}function _u(e,n,t,r,o,i,s,a,l){if(e.fixedLength!==void 0){if(i.cellIndex+e.fixedLength>t.length)throw R(r,"array row length mismatch");let p=t.slice(i.cellIndex,i.cellIndex+e.fixedLength).map(u=>B(u,r));return i.cellIndex+=e.fixedLength,p}if(e.children!==void 0){let p=ot(e.children),u=t[i.cellIndex],f=Qi(u),m=t.length-i.cellIndex-1,h=o[i.nextIndex],b=h!==void 0&&h.depth===s,k=i.childTableFields===void 0?void 0:i.childTableFields.has(e);if(k===void 0?f!==void 0&&(b||t.length!==i.flatWidth&&m<p+vu(n)):k){if(f===void 0)throw R(r,"array row length mismatch");return i.cellIndex+=1,Vi(f,e.children,a,o,{get index(){return i.nextIndex},set index(j){i.nextIndex=j}},s,l,!1)}return qi(e.children,t,r,o,i,s,a,l)}let d=t[i.cellIndex];if(d===void 0)throw R(r,"array row length mismatch");return i.cellIndex+=1,tt(e,d,r)}function Gi(e,n,t,r,o,i,s){let a=n.filter(p=>p.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let l,d=1<<a.length;for(let p=0;p<d;p+=1){let u=new Set;a.forEach((m,h)=>{p&1<<h&&u.add(m)});let f=Ji(e,n,u,t,r,o,i,s);f!==void 0&&(l===void 0||f.consumedChildRows>l.consumedChildRows||f.consumedChildRows===l.consumedChildRows&&u.size<l.childTableFields.size)&&(l={childTableFields:u,consumedChildRows:f.consumedChildRows})}return l?.childTableFields}function Ji(e,n,t,r,o,i,s,a){let l=i,d=0;try{for(let u=0;u<e;u+=1){let f=o[l];if(f===void 0||f.depth!==s||f.blankBefore&&a.strict||!Ke(f.content,r,f.number))return;let m=Q(f.content,r,f.number),h=wu(n,t,m,r,o,l+1,s+1,a);if(h===void 0||o[h.nextIndex]?.depth>s)return;d+=h.consumedChildRows,l=h.nextIndex}let p=o[l];if(p!==void 0&&p.depth>=s&&Ke(p.content,r,p.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function wu(e,n,t,r,o,i,s,a){let l=0,d=i,p=0;for(let u of e){if(u.fixedLength!==void 0)l+=u.fixedLength;else if(u.children!==void 0)if(n.has(u)){let f=Qi(t[l]);if(f===void 0)return;l+=1;let m=Gi(f,u.children,r,o,d,s,a);if(m===void 0)return;let h=Ji(f,u.children,m,r,o,d,s,a);if(h===void 0)return;d=h.nextIndex,p+=f+h.consumedChildRows}else l+=ot(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:p}}function xu(e,n,t){return t&&e.length===1&&e[0].fixedLength!==void 0?n[e[0].key]:n}function Qi(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function Su(e){return e.some(n=>n.fixedLength!==void 0||n.children!==void 0)}function ot(e){return e.reduce((n,t)=>n+zi(t),0)}function zi(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?ot(e.children):1}function vu(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+zi(t),0)}function Ke(e,n,t){let r=W(e,":",t);if(r===-1)return!0;let o=W(e,n,t);return o===-1?!1:o<r}function Eu(e,n,t,r,o){let i=[];for(;i.length<e.len;){let a=n[t.index];if(a===void 0||a.depth<r)throw Be(n,t.index);if(a.depth>r)throw R(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw R(a.number,"blank line inside array");i.push(Pu(n,t,r,o))}let s=n[t.index];if(s!==void 0&&s.depth>=r)throw R(s.number,"array length mismatch");return i}function Pu(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw R(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return n.index+=1,{};if(i.startsWith("[")){let s=W(i,":",o.number);gn(i,o.number,r);let a;try{a=nt(i,s)}catch{a=void 0}if(a!==void 0){let l=i.slice(s+1);return dr(a,l,e,n,t,r)}}if(W(i,":",o.number)!==-1){let s=[{number:o.number,depth:t+1,content:i,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let a=e[n.index];if(a.depth<=t)break;s.push(a),n.index+=1}return ar(s,{index:0},t+1,r)}return n.index+=1,B(i,o.number)}function Yi(e,n,t,r,o,i){if(o.expandPaths&&!t&&n.includes(".")){let s=n.split(".");if(s.every(ju)){Ve(e,s,r,o,i);return}}Ve(e,[n],r,o,i)}function Ve(e,n,t,r,o){ie(n.length-1,o,r);let i=n[0],s=Object.prototype.hasOwnProperty.call(e,i);if(n.length===1){if(s&&r.strict)throw R(o,"duplicate key");z(e,i,t);return}if(s&&!A(e[i])){if(r.strict)throw R(o,"path expansion conflict");z(e,i,{})}else s||z(e,i,{});Ve(e[i],n.slice(1),t,r,o)}function ju(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function M(e,n={}){let t=n.maxDepth??1e3,r=n.delimiter??D;if(![D,"|"," "].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 s=Fi(e);if(s!==void 0)return s}let i=[];return Array.isArray(e)?fr(i,void 0,e,0,!1,o):A(e)?Xi(i,e,0,o):i.push(H(e,r)),i.join("")}function qe(e,n){e.push(" ".repeat(n*2))}function Xi(e,n,t,r){ie(t,0,r);for(let[o,i]of Object.entries(n))qe(e,t),ur(e,o,i,t,r)}function ur(e,n,t,r,o){if(ie(r,0,o),Array.isArray(t)){fr(e,n,t,r,!1,o);return}if(A(t)){let i=o.keyedMapCollapse?Ou(t,o,r+1):void 0;if(i!==void 0){e.push(N(n),"{",mr(o.delimiter),i.fields.map(s=>yr(s,o.delimiter)).join(o.delimiter),`}:
15
- `);for(let[s,a]of Object.entries(t)){qe(e,r+1);let l=[];e.push(N(s),": ",i.paths.map(d=>kr(gr(a,d.path),d,o.delimiter,o,l,r+2)).join(o.delimiter),`
12
+ `),t.common.length>0&&os(e,"common",t.common,t.commonRows);for(let r of t.groups)os(e,r.label,r.fields,r.rows)}function os(e,n,t,r){e.push(" ",N(n),"[",String(r.length),Ee,"]{",t.map(N).join(Ee),`}:
13
+ `);for(let o of r)e.push(" ",t.map(i=>F(o[i],Ee)).join(Ee),`
14
+ `)}function Mu(e){return e!==""&&mr(e)}function fr(e,n,t,r=new Set){if(!mr(n))return!1;if(oe(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((i,s)=>fr(i,`${n}.${s}`,t,r));return r.delete(e),o}if(A(e)){if(r.has(e))return!1;r.add(e);let o=Object.entries(e).every(([i,s])=>!i.includes(".")&&fr(s,`${n}.${i}`,t,r));return r.delete(e),o}return!1}function Wu(e){let n=Object.keys(e[0]??{});if(e.every(t=>Fu(Object.keys(t),n)))return n.every(mr)?n:void 0}function Fu(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function mr(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function Ge(e,n){let t=e[n]??e[e.length-1];return b(t===void 0?1:t.number,"array length mismatch")}function st(e,n){if(n===-1)throw b(0,"array header missing colon");let t=e.slice(0,n),r=W(t,"[",0);if(r===-1)throw b(0,"invalid array header");let o,i;try{[o,i]=J(t.slice(0,r),0)}catch{throw b(0,"invalid array header")}let s=t.slice(r+1),a=s.indexOf("]");if(a===-1)throw b(0,"invalid array header");let l=s.slice(0,a),d=/^[0-9]*/.exec(l)[0];if(d===""||d.length>1&&d.startsWith("0"))throw b(0,"invalid array header");let p=Number.parseInt(d,10),u;switch(l.slice(d.length)){case"":u=",";break;case" ":u=" ";break;case"|":u="|";break;default:throw b(0,"invalid array header")}let f=s.slice(a+1),m,h;if(f==="")m=void 0,h=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{h=Hu(f.slice(1,-1),u),m=gr(h)}catch(R){throw b(0,R.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw b(0,"invalid array header");return{key:o,keyQuoted:i,len:p,delimiter:u,fields:m,fieldTree:h}}function as(e){let n=W(e,"{",0);if(n===-1||!e.endsWith("}"))throw b(0,"invalid keyed map header");let t,r;try{[t,r]=J(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),i=D;(o.startsWith("|")||o.startsWith(" "))&&(i=o[0],o=o.slice(1));let s;try{s=Bu(o,i,i)}catch(a){throw b(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:i,fields:s}}function Bu(e,n,t){let r=[],o=0;function i(l,d){let p=0;for(;o<e.length&&!(d&&e[o]==="}");){if(e[o]===n||e[o]==="}")throw b(0,"invalid array header");let u=o;for(;o<e.length;){let h=e[o];if(h==='"'){s();continue}if(h===n||h==="{"||h==="}"||h==="[")break;o+=1}let[f,m]=J(e.slice(u,o),0);if(f===""&&!m)throw b(0,"invalid array header");if(p+=1,e[o]==="["){o+=1;let h=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw b(0,"invalid array header");let R=e.slice(h,o);if(!ds(R,t))throw b(0,"invalid array header");o+=1,r.push({path:[...l,f],listDelimiter:R})}else if(e[o]==="{"){o+=1;let h=r.length;if(i([...l,f],!0),e[o]!=="}"||r.length===h)throw b(0,"invalid array header");o+=1}else r.push({path:[...l,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(p===0)throw b(0,"invalid array header")}function s(){for(o+=1;o<e.length;){let l=e[o];if(o+=1,l==="\\")o+=1;else if(l==='"')return}}if(i([],!1),o!==e.length)throw b(0,"invalid array header");let a=new Set;for(let l=0;l<r.length;l+=1)for(let d=l+1;d<r.length;d+=1)if(cs(r[l].path,r[d].path)||wn(r[l].path,r[d].path)||wn(r[d].path,r[l].path))throw b(0,"duplicate key");for(let l of r){let p=l.path.join("\0");if(a.has(p))throw b(0,"duplicate key");a.add(p)}return r}function Hu(e,n){if(n!==D&&e.includes(D)&&(e.includes("[")||e.includes("{")))return hr(e,D,n);try{return hr(e,n,n)}catch(t){if(n!==D&&t.reason!=="duplicate key")return hr(e,D,n);throw t}}function hr(e,n,t){let r=0;function o(l){let d=[];for(;r<e.length&&!(l&&e[r]==="}");){if(e[r]===n||e[r]==="}")throw b(0,"invalid array header");let p=r;for(;r<e.length;){let h=e[r];if(h==='"'){i();continue}if(h===n||h==="{"||h==="}"||h==="[")break;r+=1}let[u,f]=J(e.slice(p,r),0);if(u===""&&!f)throw b(0,"invalid array header");let m={key:u};if(e[r]==="["){r+=1;let h=r;for(;r<e.length&&e[r]!=="]";)r+=1;if(r>=e.length)throw b(0,"invalid array header");let R=e.slice(h,r);r+=1;let k=Uu(R);if(k!==void 0){if(k.delimiter!==t)throw b(0,"invalid array header");m.fixedLength=k.len,m.fixedDelimiter=k.delimiter}else if(ds(R,t))m.listDelimiter=R;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(l?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 i(){for(r+=1;r<e.length;){let l=e[r];if(r+=1,l==="\\")r+=1;else if(l==='"')return}}let s=o(!1);if(r!==e.length)throw b(0,"invalid array header");let a=gr(s);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(cs(a[l].path,a[d].path)||wn(a[l].path,a[d].path)||wn(a[d].path,a[l].path))throw b(0,"duplicate key");return s}function Uu(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=D;break;case" ":r=" ";break;case"|":r="|";break;default:return}return{len:Number.parseInt(n,10),delimiter:r}}function gr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?gr(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function lt(e,n,t){return e.listDelimiter===void 0?G(n,t):Q(n,e.listDelimiter,t).map(r=>G(r,t))}function ds(e,n){return e.length===1&&e!==n&&!/[ \t\r\n"[\]{}:]/.test(e)}function cs(e,n){return e.length===n.length&&wn(e,n)}function wn(e,n){return n.every((t,r)=>e[r]===t)}function at(e,n){return b(n,e.reason??String(e.message))}function Y(e,n){let t=ns(n),r=ts(e,t),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw b(o.number,"invalid indentation");let i=r.length===1;if(i&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){_n(o.content,o.number,t);let d;try{d=st(o.content,W(o.content,":",o.number))}catch(p){if(t.strict)throw at(p,o.number);d=void 0}if(d!==void 0)return Vu(d,r,t)}if(i&&W(o.content,":",o.number)===-1)return G(o.content.trim(),o.number);let s={index:0},a=kr(r,s,0,t),l=r[s.index];if(l!==void 0)throw b(l.number,"expected end of document");return t.cyclicDiscriminatedArrays?is(a):a}function kr(e,n,t,r){let o={};for(;n.index<e.length;){let i=e[n.index];if(i.depth<t)break;if(i.depth>t)throw b(i.number,"invalid indentation");let{key:s,quoted:a,value:l}=Gu(e,n,t,r);ys(o,s,a,l,r,i.number)}return o}function Gu(e,n,t,r){let o=e[n.index],i=o.content,s=W(i,":",o.number);if(s===-1)throw b(o.number,"expected `key: value`");let a=i.slice(0,s),l=i.slice(s+1),d=W(a,"[",o.number),p=W(a,"{",o.number);if(p!==-1&&(d===-1||p<d)){_n(a,o.number,r);let h;try{h=as(a)}catch(k){if(r.strict)throw at(k,o.number);n.index+=1;let _=yr(e,n,t,l,o.number,r);return{key:a.trim(),quoted:!1,value:_}}if(l.trim()!=="")throw b(o.number,"expected keyed map rows");let R=Ku(h,e,n,t+1,r);return{key:h.key,quoted:h.keyQuoted,value:R}}if(d!==-1){_n(a,o.number,r);let h;try{h=st(a,s)}catch(k){if(r.strict)throw at(k,o.number);n.index+=1;let _=yr(e,n,t,l,o.number,r);return{key:a.trim(),quoted:!1,value:_}}if(h.key===""&&!h.keyQuoted)throw b(o.number,"expected non-empty field name");let R=br(h,l,e,n,t,r);return{key:h.key,quoted:h.keyQuoted,value:R}}let[u,f]=J(a,o.number);if(u===""&&!f)throw b(o.number,"expected non-empty field name");n.index+=1;let m=yr(e,n,t,l,o.number,r);return{key:u,quoted:f,value:m}}function yr(e,n,t,r,o,i){let s=r.trim();if(s==="[]")return[];if(s!=="")return G(s,o);let a=e[n.index];return a!==void 0&&a.depth>t?kr(e,n,t+1,i):{}}function Ku(e,n,t,r,o){let i={};for(t.index+=1;t.index<n.length;){let s=n[t.index];if(s.depth<r)break;if(s.depth>r)throw b(s.number,"invalid indentation");if(s.blankBefore&&o.strict)throw b(s.number,"blank line inside keyed map");let a=W(s.content,":",s.number);if(a===-1)throw b(s.number,"expected `key: value`");let[l,d]=J(s.content.slice(0,a),s.number);if(l===""&&!d)throw b(s.number,"expected non-empty field name");let p=Q(s.content.slice(a+1).trim(),e.delimiter,s.number);if(p.length!==e.fields.length)throw b(s.number,"keyed map row length mismatch");let u={};e.fields.forEach((f,m)=>{Ve(u,f.path,lt(f,p[m],s.number),o,s.number)}),ys(i,l,d,u,o,s.number),t.index+=1}return i}function Vu(e,n,t){let r=n[0],o=W(r.content,":",r.number);if(o===-1)throw b(r.number,"expected `key: value`");let i=r.content.slice(o+1),s={index:0},a=br(e,i,n,s,0,t),l=n[s.index];if(l!==void 0)throw b(l.number,"expected end of document");return a}function br(e,n,t,r,o,i){let s=t[r.index].number,a=n.trim();if(r.index+=1,e.fields!==void 0){if(a!=="")throw b(s,"expected tabular rows");return qu(e,e.fields,t,r,o+1,i)}if(a!==""){let l=Q(a,e.delimiter,s).map(d=>G(d,s));if(l.length!==e.len)throw b(s,"array length mismatch");return l}return ep(e,t,r,o+1,i)}function qu(e,n,t,r,o,i){if(e.fieldTree!==void 0&&Xu(e.fieldTree))return Ju(e,t,r,o,i);let s=[];for(;s.length<e.len;){let l=t[r.index];if(l===void 0)throw Ge(t,r.index);if(l.depth<o)break;if(l.depth>o)throw b(l.number,"invalid indentation");if(l.blankBefore&&i.strict)throw b(l.number,"blank line inside array");if(!Ke(l.content,e.delimiter,l.number))break;let d=Q(l.content,e.delimiter,l.number);if(d.length!==n.length)throw b(l.number,"array row length mismatch");let p={};n.forEach((u,f)=>{Ve(p,u.path,lt(u,d[f],l.number),i,l.number)}),s.push(p),r.index+=1}if(s.length!==e.len)throw Ge(t,r.index);let a=t[r.index];if(a!==void 0&&a.depth>=o&&Ke(a.content,e.delimiter,a.number))throw b(a.number,"array length mismatch");return s}function Ju(e,n,t,r,o){return us(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function us(e,n,t,r,o,i,s,a){let l=[],d=fs(e,n,t,r,o.index,i,s);for(;l.length<e;){let u=r[o.index];if(u===void 0)throw Ge(r,o.index);if(u.depth<i)break;if(u.depth>i)throw b(u.number,"invalid indentation");if(u.blankBefore&&s.strict)throw b(u.number,"blank line inside array");if(!Ke(u.content,t,u.number))break;let f=Q(u.content,t,u.number),m={cellIndex:0,nextIndex:o.index+1,flatWidth:dt(n),childTableFields:d},h=ps(n,f,u.number,r,m,i+1,t,s);if(m.cellIndex!==f.length)throw b(u.number,"array row length mismatch");l.push(Yu(n,h,a)),o.index=m.nextIndex}if(l.length!==e)throw Ge(r,o.index);let p=r[o.index];if(p!==void 0&&p.depth>=i&&Ke(p.content,t,p.number))throw b(p.number,"array length mismatch");return l}function ps(e,n,t,r,o,i,s,a){let l={};return e.forEach((d,p)=>{let u=e.slice(p+1),f=Qu(d,u,n,t,r,o,i,s,a);Ve(l,[d.key],f,a,t)}),l}function Qu(e,n,t,r,o,i,s,a,l){if(e.fixedLength!==void 0){if(i.cellIndex+e.fixedLength>t.length)throw b(r,"array row length mismatch");let p=t.slice(i.cellIndex,i.cellIndex+e.fixedLength).map(u=>G(u,r));return i.cellIndex+=e.fixedLength,p}if(e.children!==void 0){let p=dt(e.children),u=t[i.cellIndex],f=hs(u),m=t.length-i.cellIndex-1,h=o[i.nextIndex],R=h!==void 0&&h.depth===s,k=i.childTableFields===void 0?void 0:i.childTableFields.has(e);if(k===void 0?f!==void 0&&(R||t.length!==i.flatWidth&&m<p+Zu(n)):k){if(f===void 0)throw b(r,"array row length mismatch");return i.cellIndex+=1,us(f,e.children,a,o,{get index(){return i.nextIndex},set index(j){i.nextIndex=j}},s,l,!1)}return ps(e.children,t,r,o,i,s,a,l)}let d=t[i.cellIndex];if(d===void 0)throw b(r,"array row length mismatch");return i.cellIndex+=1,lt(e,d,r)}function fs(e,n,t,r,o,i,s){let a=n.filter(p=>p.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let l,d=1<<a.length;for(let p=0;p<d;p+=1){let u=new Set;a.forEach((m,h)=>{p&1<<h&&u.add(m)});let f=ms(e,n,u,t,r,o,i,s);f!==void 0&&(l===void 0||f.consumedChildRows>l.consumedChildRows||f.consumedChildRows===l.consumedChildRows&&u.size<l.childTableFields.size)&&(l={childTableFields:u,consumedChildRows:f.consumedChildRows})}return l?.childTableFields}function ms(e,n,t,r,o,i,s,a){let l=i,d=0;try{for(let u=0;u<e;u+=1){let f=o[l];if(f===void 0||f.depth!==s||f.blankBefore&&a.strict||!Ke(f.content,r,f.number))return;let m=Q(f.content,r,f.number),h=zu(n,t,m,r,o,l+1,s+1,a);if(h===void 0||o[h.nextIndex]?.depth>s)return;d+=h.consumedChildRows,l=h.nextIndex}let p=o[l];if(p!==void 0&&p.depth>=s&&Ke(p.content,r,p.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function zu(e,n,t,r,o,i,s,a){let l=0,d=i,p=0;for(let u of e){if(u.fixedLength!==void 0)l+=u.fixedLength;else if(u.children!==void 0)if(n.has(u)){let f=hs(t[l]);if(f===void 0)return;l+=1;let m=fs(f,u.children,r,o,d,s,a);if(m===void 0)return;let h=ms(f,u.children,m,r,o,d,s,a);if(h===void 0)return;d=h.nextIndex,p+=f+h.consumedChildRows}else l+=dt(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:p}}function Yu(e,n,t){return t&&e.length===1&&e[0].fixedLength!==void 0?n[e[0].key]:n}function hs(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function Xu(e){return e.some(n=>n.fixedLength!==void 0||n.children!==void 0)}function dt(e){return e.reduce((n,t)=>n+gs(t),0)}function gs(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?dt(e.children):1}function Zu(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+gs(t),0)}function Ke(e,n,t){let r=W(e,":",t);if(r===-1)return!0;let o=W(e,n,t);return o===-1?!1:o<r}function ep(e,n,t,r,o){let i=[];for(;i.length<e.len;){let a=n[t.index];if(a===void 0||a.depth<r)throw Ge(n,t.index);if(a.depth>r)throw b(a.number,"invalid indentation");if(a.blankBefore&&o.strict)throw b(a.number,"blank line inside array");i.push(np(n,t,r,o))}let s=n[t.index];if(s!==void 0&&s.depth>=r)throw b(s.number,"array length mismatch");return i}function np(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw b(o.number,"expected array item");let i=o.content.slice(1).replace(/^\s+/,"");if(i==="")return n.index+=1,{};if(i.startsWith("[")){let s=W(i,":",o.number);_n(i,o.number,r);let a;try{a=st(i,s)}catch{a=void 0}if(a!==void 0){let l=i.slice(s+1);return br(a,l,e,n,t,r)}}if(W(i,":",o.number)!==-1){let s=[{number:o.number,depth:t+1,content:i,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let a=e[n.index];if(a.depth<=t)break;s.push(a),n.index+=1}return kr(s,{index:0},t+1,r)}return n.index+=1,G(i,o.number)}function ys(e,n,t,r,o,i){if(o.expandPaths&&!t&&n.includes(".")){let s=n.split(".");if(s.every(tp)){Ve(e,s,r,o,i);return}}Ve(e,[n],r,o,i)}function Ve(e,n,t,r,o){ie(n.length-1,o,r);let i=n[0],s=Object.prototype.hasOwnProperty.call(e,i);if(n.length===1){if(s&&r.strict)throw b(o,"duplicate key");z(e,i,t);return}if(s&&!A(e[i])){if(r.strict)throw b(o,"path expansion conflict");z(e,i,{})}else s||z(e,i,{});Ve(e[i],n.slice(1),t,r,o)}function tp(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function M(e,n={}){let t=n.maxDepth??1e3,r=n.delimiter??D;if(![D,"|"," "].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 s=ls(e);if(s!==void 0)return s}let i=[];return Array.isArray(e)?xr(i,void 0,e,0,!1,o):A(e)?ks(i,e,0,o):i.push(F(e,r)),i.join("")}function qe(e,n){e.push(" ".repeat(n*2))}function ks(e,n,t,r){ie(t,0,r);for(let[o,i]of Object.entries(n))qe(e,t),_r(e,o,i,t,r)}function _r(e,n,t,r,o){if(ie(r,0,o),Array.isArray(t)){xr(e,n,t,r,!1,o);return}if(A(t)){let i=o.keyedMapCollapse?op(t,o,r+1):void 0;if(i!==void 0){e.push(N(n),"{",Sr(o.delimiter),i.fields.map(s=>Pr(s,o.delimiter)).join(o.delimiter),`}:
15
+ `);for(let[s,a]of Object.entries(t)){qe(e,r+1);let l=[];e.push(N(s),": ",i.paths.map(d=>jr(Er(a,d.path),d,o.delimiter,o,l,r+2)).join(o.delimiter),`
16
16
  `),e.push(...l)}return}e.push(N(n),`:
17
- `),Xi(e,t,r+1,o);return}e.push(N(n),": ",H(t,o.delimiter),`
18
- `)}function fr(e,n,t,r,o,i){if(ie(r,0,i),t.length===0){n!==void 0?e.push(N(n),`: []
17
+ `),ks(e,t,r+1,o);return}e.push(N(n),": ",F(t,o.delimiter),`
18
+ `)}function xr(e,n,t,r,o,i){if(ie(r,0,i),t.length===0){n!==void 0?e.push(N(n),`: []
19
19
  `):o?e.push(`[0]:
20
20
  `):e.push(`[]
21
- `);return}if(t.every(oe)){cr(e,n,t.length,void 0,i.delimiter),e.push(" "),e.push(t.map(a=>H(a,i.delimiter)).join(i.delimiter)),e.push(`
22
- `);return}let s=o?void 0:Zi(t,i,r+1);if(s!==void 0){cr(e,n,t.length,s.fields,i.delimiter),e.push(`
23
- `);for(let a of t){qe(e,r+1);let l=[];e.push(s.paths.map(d=>kr(gr(a,d.path),d,i.delimiter,i,l,r+2)).join(i.delimiter)),e.push(`
24
- `),e.push(...l)}return}cr(e,n,t.length,void 0,i.delimiter),e.push(`
25
- `);for(let a of t)qe(e,r+1),Du(e,a,r+1,i)}function Du(e,n,t,r){if(ie(t,0,r),Array.isArray(n)){e.push("- "),fr(e,void 0,n,t,!0,r);return}if(A(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
26
- `);return}e.push("- "),ur(e,o[0][0],o[0][1],t+1,r);for(let[i,s]of o.slice(1))qe(e,t+1),ur(e,i,s,t+1,r);return}e.push("- ",H(n,r.delimiter),`
27
- `)}function cr(e,n,t,r,o){n!==void 0&&e.push(N(n)),e.push("[",String(t),mr(o),"]"),r!==void 0&&e.push("{",r.map(i=>yr(i,o)).join(o),"}"),e.push(":")}function mr(e){return e===D?"":e}function Zi(e,n,t){let r=Au(e,n);if(r!==void 0)return r;let o=pr(e.map(i=>({value:i})),n,t);return o===void 0?void 0:{fields:o,paths:hr(o)}}function Ou(e,n,t){let r=Object.values(e);if(!(r.length<2))return Zi(r,n,t)}function pr(e,n,t){ie(t,0,n);let r=e[0]?.value;if(!A(r))return;let o=Object.keys(r).map(i=>({key:i}));if(o.length!==0){for(let{value:i}of e)if(!A(i)||Object.keys(i).length!==o.length||o.some(a=>!Object.prototype.hasOwnProperty.call(i,a.key)))return;for(let i of o){let s=e.map(({value:l})=>({value:l[i.key]}));if(s.every(({value:l})=>oe(l)))continue;if(n.primitiveArrayColumns&&s.every(({value:l})=>Array.isArray(l)&&l.every(oe))){i.listDelimiter=";";continue}if(n.objectArrayColumns&&s.every(({value:l})=>Array.isArray(l))){let l=es(s.map(({value:p})=>p));if(l!==void 0){i.fixedLength=l.fixedLength,i.fixedDelimiter=n.delimiter;continue}let d=pr(s.flatMap(({value:p})=>p.map(u=>({value:u}))),n,t+1);if(d!==void 0){i.children=d,i.childTable=!0;continue}}if(!n.nestedTabularHeaders)return;let a=pr(s,n,t+1);if(a===void 0)return;i.children=a}return o}}function Au(e,n){if(!n.objectArrayColumns)return;let t=es(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:n.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function es(e){let n=e[0]?.length;if(!(!Number.isInteger(n)||n===0)&&e.every(t=>Array.isArray(t)&&t.length===n&&t.every(oe)))return{fixedLength:n}}function hr(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}]:hr(t.children,r)})}function gr(e,n){let t=e;for(let r of n)t=t[r];return t}function yr(e,n){return e.listDelimiter!==void 0?`${N(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${N(e.key)}[${e.fixedLength}${mr(n)}]`:e.children===void 0?N(e.key):`${N(e.key)}{${e.children.map(t=>yr(t,n)).join(n)}}`}function kr(e,n,t,r,o,i){return n.childFields!==void 0?(Lu(o,e,n.childFields,r,i),String(e.length)):n.fixedLength!==void 0?e.map(s=>H(s,t)).join(t):n.listDelimiter===void 0?H(e,t):e.map(s=>$u(s,t,n.listDelimiter)).join(n.listDelimiter)}function Lu(e,n,t,r,o){for(let i of n){qe(e,o);let s=[];e.push(hr(t).map(a=>kr(gr(i,a.path),a,r.delimiter,r,s,o+1)).join(r.delimiter)),e.push(`
28
- `),e.push(...s)}}function $u(e,n,t){return typeof e!="string"?H(e,n):nr(e,n)||e.includes(t)?Zn(e):e}var as=[D,"|"," "];var ds=8,cs=/^[A-Za-z0-9_-]+$/,Hb=new TextEncoder,Fb=new TextDecoder;function Cu(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw S(n,"invalid trailer count");return Number.parseInt(t,10)}function us(e,n){if(!cs.test(e))throw S(n,"invalid tag")}function Mu(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!cs.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw S(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function Wu(e,n){if(!e.startsWith("["))return null;let t=e.slice(1),r=t.indexOf("]");if(r===-1)throw S(n,"invalid header");let o=t.slice(0,r),i=o.startsWith("~"),s=i?o.slice(1):o;if(!i&&s.startsWith("="))return null;if(!as.includes(s)&&s!=="")throw S(n,"invalid header delimiter");let a=s===""?D:s,l=t.slice(r+1),d=null;if(!i&&l.startsWith("<")){let f=l.indexOf(">");if(f===-1)throw S(n,"invalid tag");if(d=l.slice(1,f),us(d,n),s!=="")throw S(n,"invalid header delimiter");l=l.slice(f+1)}if(!l.startsWith("{")||!l.endsWith("}:"))throw S(n,"invalid header");let p=l.slice(1,-2),u;try{u=Q(p,a,n).map(f=>J(f,n)[0])}catch(f){throw Ue(f)}if(u.length===0||u.some(f=>f===""))throw S(n,"invalid header fields");return{delimiter:a,fields:u,fieldText:p,continuation:i,tag:d}}function Hu(e,n,t){if(e===null||e.delimiter===void 0)throw S(t,"continuation header before header");if(e.delimiter!==n.delimiter||e.fieldText!==n.fieldText)throw S(t,"continuation header mismatch")}function ns(e,n,t,r){let o;try{o=Q(e,n,r)}catch(i){throw Ue(i)}if(o.length!==t)throw S(r,"row arity mismatch");for(let i of o)try{B(i,r)}catch(s){throw Ue(s)}return o}function Fu(e,n,t){let r={};return e.forEach((o,i)=>{try{z(r,o,B(n[i],t))}catch(s){throw Ue(s)}}),r}function Uu(e,n,t){if(e.startsWith("- "))throw S(n,"reserved line prefix");let r=Cu(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw S(n,"trailer without header");if(t.rowCount!==r)throw S(n,"trailer count mismatch");return{kind:"trailer"}}let o=Wu(e,n);if(o!==null)return o.continuation?(Hu(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let i=Mu(e,n);if(i!==null){let s=t?.taggedLanes?.get(i.tag);if(s===void 0)throw S(n,"unknown tag");return{kind:"tagged-row",tag:i.tag,cells:ns(i.cellsText,s.delimiter,s.fields.length,n)}}if(t===null||t.delimiter===void 0)throw S(n,"row before header");return{kind:"row",cells:ns(e,t.delimiter,t.fields.length,n)}}function Bu(e,n={}){let t=[],r=new Map,o=[],i=[],s=null,a=!1,l=!1;function d(m,h){let b=i.at(-1);if(b!==void 0&&b.lane===m.lane&&b.delimiter===m.delimiter&&b.fieldText===m.fieldText){b.rows.push(h);return}i.push({lane:m.lane,delimiter:m.delimiter,fields:m.fields,fieldText:m.fieldText,rows:[h]})}function p(){s!==null&&o.push({delimiter:s.delimiter,fields:s.fields,fieldText:s.fieldText,lane:s.lane,rows:s.rows})}function u(m,h,b){let k=r.get(m);if(k===void 0){if(r.size>=ds)throw S(b,"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:h.delimiter,fields:h.fields,fieldText:h.fieldText,rows:[]},k.delimiter=h.delimiter,k.fields=h.fields,k.fieldText=h.fieldText}if(Xn(e).forEach((m,h)=>{let b=h+1;if(m==="")return;let k=s===null?{taggedLanes:r}:{delimiter:s.delimiter,fields:s.fields,fieldText:s.fieldText,rowCount:s.rows.length,taggedLanes:r},w=Uu(m,b,k);if(w.kind==="trailer"){p(),s=null;return}if(w.kind!=="continuation"){if(w.kind==="tag-header"){l=!0,u(w.header.tag,w.header,b);return}if(w.kind==="header"){p(),a||(t.push(null),a=!0),s={lane:null,delimiter:w.header.delimiter,fields:w.header.fields,fieldText:w.header.fieldText,rows:[]};return}if(w.kind==="tagged-row"){l=!0;let j=r.get(w.tag).current;j.rows.push(w.cells),d(j,w.cells);return}if(s===null)throw S(b,"row before header");s.rows.push(w.cells),d(s,w.cells)}}),!l)return p(),n.preserveInterleaving===!0,o;let f=[];p();for(let m of t){if(m===null){f.push(...o);continue}let h=r.get(m);f.push(...h.segments),h.current!==null&&f.push(h.current)}return n.preserveInterleaving===!0?i:f}function ye(e){return Bu(e).flatMap(n=>n.rows.map(t=>Fu(n.fields,t,0)))}function Ku(e){if(!as.includes(e))throw S(0,"invalid header delimiter")}function ts(e,n,t=!1){return`[${`${t?"~":""}${e===D?"":e}`}]{${n}}:
29
- `}function rs(e,n){return`[]<${e}>{${n}}:
30
- `}function Rr(e,n){return n.map(N).join(e)}function Vu(e){if(!Array.isArray(e)||e.length===0)throw S(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=J(String(n),0)}catch(r){throw Ue(r)}if(t==="")throw S(0,"TOONL header requires fields");return t})}function os(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function is(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw S(0,"TOONL continuation cadence must be positive")}function qu(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function ss(e){if(e===null||typeof e!="object"||Array.isArray(e))throw S(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw S(0,"TOONL output requires object rows");if(n.some(t=>!oe(e[t])))throw S(0,"TOONL rows must be flat objects");return n}function Gu(e){return JSON.stringify([...e].sort())}function ls(e,n){let t=Gu(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function pe({delimiter:e=D,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){Ku(e),is(t),is(r);let o=null,i="",s=new Map,a=0,l=0,d=0,p=new Map,u=!1,f={continuationEveryRows:t,continuationEveryBytes:r},m=()=>o===null||!n?"":`[=${a}]
31
- `,h=()=>qu(f,l,d)?(l=0,d=0,ts(e,i,!0)):"",b=k=>{us(k,0);let w=p.get(k);if(w===void 0){if(p.size>=ds)throw S(0,"too many tagged lanes");w={fields:null,fieldsByShape:new Map},p.set(k,w)}return w};return{push(k){if(u)throw S(0,"TOONL encoder is closed");let w=ls(ss(k),s),j="";(o===null||o.length!==w.length||o.some((we,Ne)=>we!==w[Ne]))&&(j+=m(),o=w,i=Rr(e,o),a=0,l=0,d=0,j+=ts(e,i));let ne=o.map(we=>H(k[we],e));j+=h();let q=`${ne.join(e)}
32
- `;return j+=q,a+=1,l+=1,d+=q.length,j},declareLane(k,w){if(u)throw S(0,"TOONL encoder is closed");let j=Vu(w),ne=Rr(D,j),q=b(k);return os(q.fields,j)?"":(q.fields=j,rs(k,ne))},pushTagged(k,w){if(u)throw S(0,"TOONL encoder is closed");let j=b(k),ne=ls(ss(w),j.fieldsByShape),q=Rr(D,ne),we=ne.map(Cn=>H(w[Cn],D)),Ne="";return os(j.fields,ne)||(j.fields=ne,Ne+=rs(k,q)),`${Ne}${k}:${we.join(D)}
33
- `},end(){return u?"":(u=!0,m())}}}function br(e){let n={app:e,version:Ju(Ge("__RED_BUILD_VERSION__",()=>"3.3.11")??"0.0.0-dev"),gitSha:Ge("__RED_BUILD_GIT_SHA__",()=>"0ac7e9947aa678cf8956b86c0428874cb3a09c31")??"unknown",buildTime:Ge("__RED_BUILD_TIME__",()=>"2026-08-02T23:50:43-03:00")??"unknown",bundleAsset:Ge("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=Ge("__REDDB_SDK_VERSION__",()=>""),r=Ge("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function Ju(e){return e.startsWith("v")?e.slice(1):e}function ps(e){return`${e.app} ${e.version} ${e.gitSha}`}function Ge(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var fs={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Qu=/^[a-z][a-z0-9+.-]*:\/\//i;function zu(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 Yu(e=fs){return Object.entries(e).map(([n,t])=>zu(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function Xu(e){return/^-\d+(\.\d+)?$/.test(e)}function kn(e){return!(!e||e.startsWith("-")&&!Xu(e))}function it(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 ms(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=>ms(t.trim())):e}function Pe(e,n){switch(n){case"boolean":return Zu(e);case"number":return ep(e);case"array":return e.split(",").map(t=>it(t.trim()));case"string":default:return e}}function Zu(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function ep(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 ke(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function np(e,n={}){return e.map(t=>{let r=n[t.type];return r?r(t.value):t.value}).join("")}function E(e,n){return{type:e,value:n}}function tp(e){let n=[],t=op(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
21
+ `);return}if(t.every(oe)){Rr(e,n,t.length,void 0,i.delimiter),e.push(" "),e.push(t.map(a=>F(a,i.delimiter)).join(i.delimiter)),e.push(`
22
+ `);return}let s=o?void 0:bs(t,i,r+1);if(s!==void 0){Rr(e,n,t.length,s.fields,i.delimiter),e.push(`
23
+ `);for(let a of t){qe(e,r+1);let l=[];e.push(s.paths.map(d=>jr(Er(a,d.path),d,i.delimiter,i,l,r+2)).join(i.delimiter)),e.push(`
24
+ `),e.push(...l)}return}Rr(e,n,t.length,void 0,i.delimiter),e.push(`
25
+ `);for(let a of t)qe(e,r+1),rp(e,a,r+1,i)}function rp(e,n,t,r){if(ie(t,0,r),Array.isArray(n)){e.push("- "),xr(e,void 0,n,t,!0,r);return}if(A(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
26
+ `);return}e.push("- "),_r(e,o[0][0],o[0][1],t+1,r);for(let[i,s]of o.slice(1))qe(e,t+1),_r(e,i,s,t+1,r);return}e.push("- ",F(n,r.delimiter),`
27
+ `)}function Rr(e,n,t,r,o){n!==void 0&&e.push(N(n)),e.push("[",String(t),Sr(o),"]"),r!==void 0&&e.push("{",r.map(i=>Pr(i,o)).join(o),"}"),e.push(":")}function Sr(e){return e===D?"":e}function bs(e,n,t){let r=ip(e,n);if(r!==void 0)return r;let o=wr(e.map(i=>({value:i})),n,t);return o===void 0?void 0:{fields:o,paths:vr(o)}}function op(e,n,t){let r=Object.values(e);if(!(r.length<2))return bs(r,n,t)}function wr(e,n,t){ie(t,0,n);let r=e[0]?.value;if(!A(r))return;let o=Object.keys(r).map(i=>({key:i}));if(o.length!==0){for(let{value:i}of e)if(!A(i)||Object.keys(i).length!==o.length||o.some(a=>!Object.prototype.hasOwnProperty.call(i,a.key)))return;for(let i of o){let s=e.map(({value:l})=>({value:l[i.key]}));if(s.every(({value:l})=>oe(l)))continue;if(n.primitiveArrayColumns&&s.every(({value:l})=>Array.isArray(l)&&l.every(oe))){i.listDelimiter=";";continue}if(n.objectArrayColumns&&s.every(({value:l})=>Array.isArray(l))){let l=Rs(s.map(({value:p})=>p));if(l!==void 0){i.fixedLength=l.fixedLength,i.fixedDelimiter=n.delimiter;continue}let d=wr(s.flatMap(({value:p})=>p.map(u=>({value:u}))),n,t+1);if(d!==void 0){i.children=d,i.childTable=!0;continue}}if(!n.nestedTabularHeaders)return;let a=wr(s,n,t+1);if(a===void 0)return;i.children=a}return o}}function ip(e,n){if(!n.objectArrayColumns)return;let t=Rs(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:n.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function Rs(e){let n=e[0]?.length;if(!(!Number.isInteger(n)||n===0)&&e.every(t=>Array.isArray(t)&&t.length===n&&t.every(oe)))return{fixedLength:n}}function vr(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}]:vr(t.children,r)})}function Er(e,n){let t=e;for(let r of n)t=t[r];return t}function Pr(e,n){return e.listDelimiter!==void 0?`${N(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${N(e.key)}[${e.fixedLength}${Sr(n)}]`:e.children===void 0?N(e.key):`${N(e.key)}{${e.children.map(t=>Pr(t,n)).join(n)}}`}function jr(e,n,t,r,o,i){return n.childFields!==void 0?(sp(o,e,n.childFields,r,i),String(e.length)):n.fixedLength!==void 0?e.map(s=>F(s,t)).join(t):n.listDelimiter===void 0?F(e,t):e.map(s=>lp(s,t,n.listDelimiter)).join(n.listDelimiter)}function sp(e,n,t,r,o){for(let i of n){qe(e,o);let s=[];e.push(vr(t).map(a=>jr(Er(i,a.path),a,r.delimiter,r,s,o+1)).join(r.delimiter)),e.push(`
28
+ `),e.push(...s)}}function lp(e,n,t){return typeof e!="string"?F(e,n):ur(e,n)||e.includes(t)?ot(e):e}var js=[D,"|"," "];var Ds=8,Os=/^[A-Za-z0-9_-]+$/,y_=new TextEncoder,k_=new TextDecoder;function up(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw S(n,"invalid trailer count");return Number.parseInt(t,10)}function As(e,n){if(!Os.test(e))throw S(n,"invalid tag")}function pp(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!Os.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw S(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function fp(e,n){if(!e.startsWith("["))return null;let t=e.slice(1),r=t.indexOf("]");if(r===-1)throw S(n,"invalid header");let o=t.slice(0,r),i=o.startsWith("~"),s=i?o.slice(1):o;if(!i&&s.startsWith("="))return null;if(!js.includes(s)&&s!=="")throw S(n,"invalid header delimiter");let a=s===""?D:s,l=t.slice(r+1),d=null;if(!i&&l.startsWith("<")){let f=l.indexOf(">");if(f===-1)throw S(n,"invalid tag");if(d=l.slice(1,f),As(d,n),s!=="")throw S(n,"invalid header delimiter");l=l.slice(f+1)}if(!l.startsWith("{")||!l.endsWith("}:"))throw S(n,"invalid header");let p=l.slice(1,-2),u;try{u=Q(p,a,n).map(f=>J(f,n)[0])}catch(f){throw Ue(f)}if(u.length===0||u.some(f=>f===""))throw S(n,"invalid header fields");return{delimiter:a,fields:u,fieldText:p,continuation:i,tag:d}}function mp(e,n,t){if(e===null||e.delimiter===void 0)throw S(t,"continuation header before header");if(e.delimiter!==n.delimiter||e.fieldText!==n.fieldText)throw S(t,"continuation header mismatch")}function _s(e,n,t,r){let o;try{o=Q(e,n,r)}catch(i){throw Ue(i)}if(o.length!==t)throw S(r,"row arity mismatch");for(let i of o)try{G(i,r)}catch(s){throw Ue(s)}return o}function hp(e,n,t){let r={};return e.forEach((o,i)=>{try{z(r,o,G(n[i],t))}catch(s){throw Ue(s)}}),r}function gp(e,n,t){if(e.startsWith("- "))throw S(n,"reserved line prefix");let r=up(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw S(n,"trailer without header");if(t.rowCount!==r)throw S(n,"trailer count mismatch");return{kind:"trailer"}}let o=fp(e,n);if(o!==null)return o.continuation?(mp(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let i=pp(e,n);if(i!==null){let s=t?.taggedLanes?.get(i.tag);if(s===void 0)throw S(n,"unknown tag");return{kind:"tagged-row",tag:i.tag,cells:_s(i.cellsText,s.delimiter,s.fields.length,n)}}if(t===null||t.delimiter===void 0)throw S(n,"row before header");return{kind:"row",cells:_s(e,t.delimiter,t.fields.length,n)}}function yp(e,n={}){let t=[],r=new Map,o=[],i=[],s=null,a=!1,l=!1;function d(m,h){let R=i.at(-1);if(R!==void 0&&R.lane===m.lane&&R.delimiter===m.delimiter&&R.fieldText===m.fieldText){R.rows.push(h);return}i.push({lane:m.lane,delimiter:m.delimiter,fields:m.fields,fieldText:m.fieldText,rows:[h]})}function p(){s!==null&&o.push({delimiter:s.delimiter,fields:s.fields,fieldText:s.fieldText,lane:s.lane,rows:s.rows})}function u(m,h,R){let k=r.get(m);if(k===void 0){if(r.size>=Ds)throw S(R,"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:h.delimiter,fields:h.fields,fieldText:h.fieldText,rows:[]},k.delimiter=h.delimiter,k.fields=h.fields,k.fieldText=h.fieldText}if(rt(e).forEach((m,h)=>{let R=h+1;if(m==="")return;let k=s===null?{taggedLanes:r}:{delimiter:s.delimiter,fields:s.fields,fieldText:s.fieldText,rowCount:s.rows.length,taggedLanes:r},_=gp(m,R,k);if(_.kind==="trailer"){p(),s=null;return}if(_.kind!=="continuation"){if(_.kind==="tag-header"){l=!0,u(_.header.tag,_.header,R);return}if(_.kind==="header"){p(),a||(t.push(null),a=!0),s={lane:null,delimiter:_.header.delimiter,fields:_.header.fields,fieldText:_.header.fieldText,rows:[]};return}if(_.kind==="tagged-row"){l=!0;let j=r.get(_.tag).current;j.rows.push(_.cells),d(j,_.cells);return}if(s===null)throw S(R,"row before header");s.rows.push(_.cells),d(s,_.cells)}}),!l)return p(),n.preserveInterleaving===!0,o;let f=[];p();for(let m of t){if(m===null){f.push(...o);continue}let h=r.get(m);f.push(...h.segments),h.current!==null&&f.push(h.current)}return n.preserveInterleaving===!0?i:f}function ke(e){return yp(e).flatMap(n=>n.rows.map(t=>hp(n.fields,t,0)))}function kp(e){if(!js.includes(e))throw S(0,"invalid header delimiter")}function ws(e,n,t=!1){return`[${`${t?"~":""}${e===D?"":e}`}]{${n}}:
29
+ `}function xs(e,n){return`[]<${e}>{${n}}:
30
+ `}function Dr(e,n){return n.map(N).join(e)}function bp(e){if(!Array.isArray(e)||e.length===0)throw S(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=J(String(n),0)}catch(r){throw Ue(r)}if(t==="")throw S(0,"TOONL header requires fields");return t})}function Ss(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function vs(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw S(0,"TOONL continuation cadence must be positive")}function Rp(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function Es(e){if(e===null||typeof e!="object"||Array.isArray(e))throw S(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw S(0,"TOONL output requires object rows");if(n.some(t=>!oe(e[t])))throw S(0,"TOONL rows must be flat objects");return n}function _p(e){return JSON.stringify([...e].sort())}function Ps(e,n){let t=_p(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function ue({delimiter:e=D,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){kp(e),vs(t),vs(r);let o=null,i="",s=new Map,a=0,l=0,d=0,p=new Map,u=!1,f={continuationEveryRows:t,continuationEveryBytes:r},m=()=>o===null||!n?"":`[=${a}]
31
+ `,h=()=>Rp(f,l,d)?(l=0,d=0,ws(e,i,!0)):"",R=k=>{As(k,0);let _=p.get(k);if(_===void 0){if(p.size>=Ds)throw S(0,"too many tagged lanes");_={fields:null,fieldsByShape:new Map},p.set(k,_)}return _};return{push(k){if(u)throw S(0,"TOONL encoder is closed");let _=Ps(Es(k),s),j="";(o===null||o.length!==_.length||o.some((xe,Ne)=>xe!==_[Ne]))&&(j+=m(),o=_,i=Dr(e,o),a=0,l=0,d=0,j+=ws(e,i));let ne=o.map(xe=>F(k[xe],e));j+=h();let q=`${ne.join(e)}
32
+ `;return j+=q,a+=1,l+=1,d+=q.length,j},declareLane(k,_){if(u)throw S(0,"TOONL encoder is closed");let j=bp(_),ne=Dr(D,j),q=R(k);return Ss(q.fields,j)?"":(q.fields=j,xs(k,ne))},pushTagged(k,_){if(u)throw S(0,"TOONL encoder is closed");let j=R(k),ne=Ps(Es(_),j.fieldsByShape),q=Dr(D,ne),xe=ne.map(Bn=>F(_[Bn],D)),Ne="";return Ss(j.fields,ne)||(j.fields=ne,Ne+=xs(k,q)),`${Ne}${k}:${xe.join(D)}
33
+ `},end(){return u?"":(u=!0,m())}}}function Or(e){let n={app:e,version:wp(Je("__RED_BUILD_VERSION__",()=>"3.3.12")??"0.0.0-dev"),gitSha:Je("__RED_BUILD_GIT_SHA__",()=>"3e486286ba395dca464d73f749ce20409c47a59c")??"unknown",buildTime:Je("__RED_BUILD_TIME__",()=>"2026-08-03T01:28:04-03:00")??"unknown",bundleAsset:Je("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=Je("__REDDB_SDK_VERSION__",()=>""),r=Je("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function wp(e){return e.startsWith("v")?e.slice(1):e}function Ts(e){return`${e.app} ${e.version} ${e.gitSha}`}function Je(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var $s={"=":"data",":=":{to:"data",typed:!0},":":"meta"},xp=/^[a-z][a-z0-9+.-]*:\/\//i;function Sp(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 vp(e=$s){return Object.entries(e).map(([n,t])=>Sp(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function Ep(e){return/^-\d+(\.\d+)?$/.test(e)}function xn(e){return!(!e||e.startsWith("-")&&!Ep(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 Ls(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=>Ls(t.trim())):e}function Pe(e,n){switch(n){case"boolean":return Pp(e);case"number":return jp(e);case"array":return e.split(",").map(t=>ct(t.trim()));case"string":default:return e}}function Pp(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function jp(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 be(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Dp(e,n={}){return e.map(t=>{let r=n[t.type];return r?r(t.value):t.value}).join("")}function E(e,n){return{type:e,value:n}}function Op(e){let n=[],t=Tp(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
34
34
  `),E("newline",`
35
35
  `)),e.positional&&e.positional.length>0){n.push(E("section-header","Arguments:"),E("newline",`
36
36
  `));for(let r of e.positional)if(r.description){let o=r.variadic?`${r.name}...`:r.name;n.push(E("indent"," "),E("positional-name",`<${o}>`)),r.required||n.push(E("positional-optional"," (optional)")),n.push(E("newline",`
37
37
  `),E("indent"," "),E("option-description",r.description),E("newline",`
38
38
  `))}n.push(E("newline",`
39
39
  `))}if(e.options&&Object.keys(e.options).length>0){n.push(E("section-header","Options:"),E("newline",`
40
- `));let r=ip(e.options);n.push(...r)}return n}function rp(e,n){let t=tp(e);return np(t,n)}function op(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 ip(e,n=!1){let t=[],r=[],o=n?"global-option-flag":"option-flag",i=n?"global-option-type":"option-type",s=n?"global-option-default":"option-default",a=n?"global-option-description":"option-description";for(let[d,p]of Object.entries(e)){if(p.hidden)continue;let u=[],f=b=>{u.includes(b)||u.push(b)};p.short&&f(`-${p.short}`),f(`--${d}`);for(let b of p.aliases??[])b.length===1?f(`-${b}`):f(`--${b}`);let m=u.join(", "),h=p.type&&p.type!=="boolean"?`<${p.type}>`:void 0;r.push({flags:m,type:h,desc:p.description??"",default:p.default!==void 0?String(p.default):void 0})}let l=Math.max(...r.map(d=>d.flags.length+(d.type?d.type.length+1:0)),20);for(let d of r){let p=d.flags.length+(d.type?d.type.length+1:0),u=" ".repeat(l-p+2);t.push(E("indent"," ")),t.push(E(o,d.flags)),d.type&&(t.push(E("text"," ")),t.push(E(i,d.type))),t.push(E("text",u)),t.push(E(a,d.desc)),d.default!==void 0&&(t.push(E("text"," ")),t.push(E(s,`(default: ${d.default})`))),t.push(E("newline",`
41
- `))}return t}function hs(e){let n=pp(e.options??{},e.autoShort??!1),t=Yu(e.separators??fs);return{schema:e,parse(r){return sp(r,e,n,t)},help(){return rp(e,e.formatter)}}}function sp(e,n,t,r){let o={positional:{},options:{},errors:[],rest:[]},i=new Set(r.map(p=>p.to));for(let p of i)o[p]={};let s=0,a=n.positional??[],l=0,d=!1;for(;l<e.length;){let p=e[l];if(n.stopEarly&&s>0){o.rest=e.slice(l);break}if(p==="--"&&!d){d=!0,l++;continue}if(d){if(s<a.length){let f=a[s];if(f.variadic){let m=[];for(;l<e.length;){let h=e[l];m.push(f.type?Pe(h,f.type):h),l++}o.positional[f.name]=m,s++}else{let m=f.type?Pe(p,f.type):p;o.positional[f.name]=m,s++,l++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(p)),l++;continue}if(p.startsWith("--")){l=cp(p,l,e,o,t,n);continue}if(p.startsWith("-")&&p.length>1&&!yp(p)){l=up(p,l,e,o,t,n);continue}let u=lp(p,r);if(u){let{key:f,value:m,config:h}=u,b=o,k=b[h.to]??(b[h.to]={});k[f]=h.typed?ms(m):ke(m),l++;continue}if(s<a.length){let f=a[s];if(f.variadic){let h=[];for(;l<e.length&&!e[l].startsWith("-");){let b=e[l];h.push(f.type?Pe(b,f.type):b),l++}o.positional[f.name]=h,s++;continue}let m=f.type?Pe(p,f.type):p;o.positional[f.name]=m,s++}else n.allowUnknown!==!1?o.rest.push(p):o.errors.push(`Unexpected positional argument: ${p}`);l++}return mp(o,n,t),hp(o,n,a),gp(o,n,t),o}function lp(e,n){if(Qu.test(e))return null;for(let t of n){if(t.prefix&&e.startsWith(t.separator)){let o=e.slice(t.separator.length),i=o.indexOf(":");if(i>0){let s=o.slice(0,i),a=o.slice(i+1);if(ap(s))return{key:s,value:a,config:t}}continue}let r=e.indexOf(t.separator);if(r>0){let o=e.slice(0,r),i=e.slice(r+t.separator.length);if(dp(o,i,t))return{key:o,value:i,config:t}}}return null}function ap(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function dp(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 cp(e,n,t,r,o,i){let s=e.slice(2);if(s.startsWith("no-")){let l=s.slice(3),d=o.get(l);if(d?.negatable!==!1&&d?.type==="boolean")return r.options[d.name]=!1,n+1}if(s.includes("=")){let l=s.indexOf("="),d=s.slice(0,l),p=s.slice(l+1);return st(d,p,n+1,r,o,i)}let a=o.get(s);if(a){if(a.type!=="boolean"){let l=t[n+1];return kn(l)?st(a.name,l,n+2,r,o,i):(r.errors.push(`Option --${s} requires a value`),n+1)}return r.options[a.name]=!0,n+1}return i.strict?r.errors.push(`Unknown option: --${s}`):i.allowUnknown!==!1&&(r.options[s]=!0),n+1}function up(e,n,t,r,o,i){let s=e.slice(1);if(s.includes("=")){let a=s.indexOf("="),l=s.slice(0,a),d=s.slice(a+1),p=_r(l,o);return p?st(p.name,d,n+1,r,o,i):(i.strict?r.errors.push(`Unknown option: -${l}`):i.allowUnknown!==!1&&(r.options[l]=it(ke(d))),n+1)}if(s.length===1){let a=_r(s,o);if(a){if(a.type!=="boolean"){let l=t[n+1];return kn(l)?st(a.name,l,n+2,r,o,i):(r.errors.push(`Option -${s} requires a value`),n+1)}return r.options[a.name]=!0,n+1}if(i.strict)r.errors.push(`Unknown option: -${s}`);else if(i.allowUnknown!==!1){let l=t[n+1];if(kn(l))return r.options[s]=it(ke(l)),n+2;r.options[s]=!0}return n+1}for(let a of s){let l=_r(a,o);l?l.type==="boolean"?r.options[l.name]=!0:r.errors.push(`Option -${a} requires a value`):i.strict?r.errors.push(`Unknown option: -${a}`):i.allowUnknown!==!1&&(r.options[a]=!0)}return n+1}function st(e,n,t,r,o,i){let s=o.get(e);if(s){if(s.choices){let l=s.type?Pe(ke(n),s.type):ke(n);if(!s.choices.includes(l))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${s.choices.join(", ")}`),t}let a=s.type?Pe(ke(n),s.type):ke(n);if(s.type==="array"){let l=r.options[e];Array.isArray(l)?l.push(...a):r.options[e]=a}else r.options[e]=a}else i.strict?r.errors.push(`Unknown option: --${e}`):i.allowUnknown!==!1&&(r.options[e]=it(ke(n)));return t}function pp(e,n=!1){let t=new Map,r=Object.entries(e).sort(([i],[s])=>i.localeCompare(s)),o=new Set;for(let[,i]of r)i.short&&o.add(i.short);for(let[i,s]of r){let a=s.short??"";n&&!a&&(a=fp(i,o),a&&o.add(a));let l={name:i,short:a,aliases:s.aliases??[],type:s.type??"string",description:s.description??"",required:s.required??!1,hidden:s.hidden??!1,negatable:s.negatable??!0,default:s.default,choices:s.choices,env:s.env,validate:s.validate};t.set(i,l);for(let d of l.aliases)t.set(d,l)}return t}function fp(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 _r(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function mp(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?Pe(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 hp(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 gp(e,n,t){for(let r of t.values()){let o=e.options[r.name];if(r.validate&&o!==void 0){let i=r.validate(o);i!==!0&&e.errors.push(i)}}for(let r of n.positional??[]){let o=e.positional[r.name];if(r.validate&&o!==void 0){let i=r.validate(o);i!==!0&&e.errors.push(i)}}}function yp(e){return/^-\d+(\.\d+)?$/.test(e)}var wr=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 kp(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 Rp(e,n){let t=new Map;for(let[o,i]of Object.entries(n))if(!(i.kind!=="value"||i.type!=="array")){t.set(o,o);for(let s of i.aliases??[])t.set(s,o)}let r=new Map;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="--")break;let s=i.match(/^--([^=]+)(?:=(.*))?$/)??i.match(/^-([^=])(?:=(.*))?$/);if(s===null)continue;let a=t.get(s[1]);if(a===void 0)continue;let l=s[2];if(l===void 0&&kn(e[o+1])&&(l=e[o+1],o+=1),l===void 0)continue;let d=r.get(a)??[];d.push(l),r.set(a,d)}return r}function je(e,n,t={}){let o=hs({options:kp(n),separators:{},allowUnknown:!0}).parse([...e]),i={},s=Rp(e,n),a=o.errors.find(l=>/^Option --?\S+ requires a value$/.test(l));if(a!==void 0)throw new Error(a.replace(/^Option /,""));if(o.errors.length>0)throw new Error(o.errors[0]);if(t.unknownFlags==="error"){let l=new Set(Object.keys(n));for(let d of Object.keys(o.options))if(!l.has(d))throw new wr(d.length===1?`-${d}`:`--${d}`,Object.keys(n).map(p=>p.length===1?`-${p}`:`--${p}`))}for(let[l,d]of Object.entries(n)){let p=o.options[l];p!==void 0&&(d.kind==="boolean"?i[l]=p:d.type==="array"?i[l]=(s.get(l)??[]).map(u=>d.coerce(u)):i[l]=d.coerce(String(p)))}return{values:i,positionals:o.rest}}var xr=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 gs(e,n){let[t,...r]=e;if(t!==void 0){for(let[i,s]of Object.entries(n.commands))if(t===i||(s.aliases??[]).includes(t))return{command:i,args:r};if(n.errorOnUnknownCommand&&!t.startsWith("-"))throw new xr(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as Op,mkdirSync as Ap,readFileSync as Es,statSync as Lp}from"node:fs";import{dirname as js,join as $p}from"node:path";var ys="RED_WORKER_SCOPE",ks="RED_WORKER_MEMORY_CEILING",Rs="RED_WORKER_SCOPE_DEGRADATION",vr={scope:null,memory_ceiling:null,scope_degradation:null};function Er(e){return{scope:Sr(e[ys]),memory_ceiling:Sr(e[ks]),scope_degradation:Sr(e[Rs])}}function Rn(e){let n={};return e.scope!=null&&e.scope!==""&&(n[ys]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[ks]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[Rs]=e.scope_degradation),n}function Sr(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as wp,readdirSync as xp,readFileSync as xs,rmSync as Sp,writeFileSync as vp}from"node:fs";import{basename as Ep,join as Je}from"node:path";import{isAbsolute as b_,join as lt,resolve as __}from"node:path";function bp(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var bs="deaths",_s="deaths.toonl";function at(e){return lt(bp(e),bs)}function bn(e){return lt(at(e),_s)}var _n="live",ws="attributions.toonl";function dt(e){return lt(at(e),_n)}function Pr(e){return lt(at(e),ws)}var Dr=Je("sys","kernel","random","boot_id"),Ss=1;function Or(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:Ss,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:vs(Je(t,Dr)),cgroup:Pp(t,r),last_phase:e.last_phase}}function vs(e){try{let n=xs(e,"utf8").trim();return n===""?null:n}catch{return null}}function Pp(e,n){let t=vs(Je(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
42
- `),o=r.find(s=>s.startsWith("0::"));if(o)return o.slice(3)||null;let i=r[0]?.split(":").slice(2).join(":");return i===void 0||i===""?null:i}function Ar(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function Lr(e,n){let t=Je(e,Ar(n));try{return wp(e,{recursive:!0,mode:448}),vp(t,pe({trailer:!1}).push(Dp(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function De(e,n){try{Sp(Je(e,Ar(n)),{force:!0})}catch{}}function $r(e,n){let t;try{t=xp(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let i=Je(e,o);try{let a=ye(xs(i,"utf8"))[0];if(a===void 0)throw new Error("anchor holds no record");r.push(jp(a))}catch(s){n?.(Ep(i),s instanceof Error?s.message:String(s))}}return r}function jp(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:jr(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:jr(e.pid),ppid:jr(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 jr(e){return typeof e=="number"?e:Number(e)}function Dp(e){return{...e}}var Ip=1,Tp=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Np(e){return typeof e=="string"&&Tp.has(e)}var Cp="startup";function Mp(e,n){return{...e.scope??vr,version:Ip,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 Wp(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 Tr={mkdir(e){Ap(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=Lp(e).size}catch{return!0}if(n===0)return!0;try{return Es(e,"utf8").endsWith(`
43
- `)}catch{return!0}},append(e,n){Op(e,n,{encoding:"utf8",mode:384})},read(e){return Es(e,"utf8")}};function Hp(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function Fp(e,n,t=Tr){let r=pe({trailer:!1}).push(Hp(n));return t.mkdir(js(e)),t.endsClean(e)||t.append(e,`
44
- `),t.append(e,r),n}function Ds(e){let n=e.endsWith(`
40
+ `));let r=$p(e.options);n.push(...r)}return n}function Ap(e,n){let t=Op(e);return Dp(t,n)}function Tp(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 $p(e,n=!1){let t=[],r=[],o=n?"global-option-flag":"option-flag",i=n?"global-option-type":"option-type",s=n?"global-option-default":"option-default",a=n?"global-option-description":"option-description";for(let[d,p]of Object.entries(e)){if(p.hidden)continue;let u=[],f=R=>{u.includes(R)||u.push(R)};p.short&&f(`-${p.short}`),f(`--${d}`);for(let R of p.aliases??[])R.length===1?f(`-${R}`):f(`--${R}`);let m=u.join(", "),h=p.type&&p.type!=="boolean"?`<${p.type}>`:void 0;r.push({flags:m,type:h,desc:p.description??"",default:p.default!==void 0?String(p.default):void 0})}let l=Math.max(...r.map(d=>d.flags.length+(d.type?d.type.length+1:0)),20);for(let d of r){let p=d.flags.length+(d.type?d.type.length+1:0),u=" ".repeat(l-p+2);t.push(E("indent"," ")),t.push(E(o,d.flags)),d.type&&(t.push(E("text"," ")),t.push(E(i,d.type))),t.push(E("text",u)),t.push(E(a,d.desc)),d.default!==void 0&&(t.push(E("text"," ")),t.push(E(s,`(default: ${d.default})`))),t.push(E("newline",`
41
+ `))}return t}function Is(e){let n=Fp(e.options??{},e.autoShort??!1),t=vp(e.separators??$s);return{schema:e,parse(r){return Lp(r,e,n,t)},help(){return Ap(e,e.formatter)}}}function Lp(e,n,t,r){let o={positional:{},options:{},errors:[],rest:[]},i=new Set(r.map(p=>p.to));for(let p of i)o[p]={};let s=0,a=n.positional??[],l=0,d=!1;for(;l<e.length;){let p=e[l];if(n.stopEarly&&s>0){o.rest=e.slice(l);break}if(p==="--"&&!d){d=!0,l++;continue}if(d){if(s<a.length){let f=a[s];if(f.variadic){let m=[];for(;l<e.length;){let h=e[l];m.push(f.type?Pe(h,f.type):h),l++}o.positional[f.name]=m,s++}else{let m=f.type?Pe(p,f.type):p;o.positional[f.name]=m,s++,l++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(p)),l++;continue}if(p.startsWith("--")){l=Mp(p,l,e,o,t,n);continue}if(p.startsWith("-")&&p.length>1&&!Kp(p)){l=Wp(p,l,e,o,t,n);continue}let u=Ip(p,r);if(u){let{key:f,value:m,config:h}=u,R=o,k=R[h.to]??(R[h.to]={});k[f]=h.typed?Ls(m):be(m),l++;continue}if(s<a.length){let f=a[s];if(f.variadic){let h=[];for(;l<e.length&&!e[l].startsWith("-");){let R=e[l];h.push(f.type?Pe(R,f.type):R),l++}o.positional[f.name]=h,s++;continue}let m=f.type?Pe(p,f.type):p;o.positional[f.name]=m,s++}else n.allowUnknown!==!1?o.rest.push(p):o.errors.push(`Unexpected positional argument: ${p}`);l++}return Hp(o,n,t),Up(o,n,a),Gp(o,n,t),o}function Ip(e,n){if(xp.test(e))return null;for(let t of n){if(t.prefix&&e.startsWith(t.separator)){let o=e.slice(t.separator.length),i=o.indexOf(":");if(i>0){let s=o.slice(0,i),a=o.slice(i+1);if(Np(s))return{key:s,value:a,config:t}}continue}let r=e.indexOf(t.separator);if(r>0){let o=e.slice(0,r),i=e.slice(r+t.separator.length);if(Cp(o,i,t))return{key:o,value:i,config:t}}}return null}function Np(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function Cp(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 Mp(e,n,t,r,o,i){let s=e.slice(2);if(s.startsWith("no-")){let l=s.slice(3),d=o.get(l);if(d?.negatable!==!1&&d?.type==="boolean")return r.options[d.name]=!1,n+1}if(s.includes("=")){let l=s.indexOf("="),d=s.slice(0,l),p=s.slice(l+1);return ut(d,p,n+1,r,o,i)}let a=o.get(s);if(a){if(a.type!=="boolean"){let l=t[n+1];return xn(l)?ut(a.name,l,n+2,r,o,i):(r.errors.push(`Option --${s} requires a value`),n+1)}return r.options[a.name]=!0,n+1}return i.strict?r.errors.push(`Unknown option: --${s}`):i.allowUnknown!==!1&&(r.options[s]=!0),n+1}function Wp(e,n,t,r,o,i){let s=e.slice(1);if(s.includes("=")){let a=s.indexOf("="),l=s.slice(0,a),d=s.slice(a+1),p=Ar(l,o);return p?ut(p.name,d,n+1,r,o,i):(i.strict?r.errors.push(`Unknown option: -${l}`):i.allowUnknown!==!1&&(r.options[l]=ct(be(d))),n+1)}if(s.length===1){let a=Ar(s,o);if(a){if(a.type!=="boolean"){let l=t[n+1];return xn(l)?ut(a.name,l,n+2,r,o,i):(r.errors.push(`Option -${s} requires a value`),n+1)}return r.options[a.name]=!0,n+1}if(i.strict)r.errors.push(`Unknown option: -${s}`);else if(i.allowUnknown!==!1){let l=t[n+1];if(xn(l))return r.options[s]=ct(be(l)),n+2;r.options[s]=!0}return n+1}for(let a of s){let l=Ar(a,o);l?l.type==="boolean"?r.options[l.name]=!0:r.errors.push(`Option -${a} requires a value`):i.strict?r.errors.push(`Unknown option: -${a}`):i.allowUnknown!==!1&&(r.options[a]=!0)}return n+1}function ut(e,n,t,r,o,i){let s=o.get(e);if(s){if(s.choices){let l=s.type?Pe(be(n),s.type):be(n);if(!s.choices.includes(l))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${s.choices.join(", ")}`),t}let a=s.type?Pe(be(n),s.type):be(n);if(s.type==="array"){let l=r.options[e];Array.isArray(l)?l.push(...a):r.options[e]=a}else r.options[e]=a}else i.strict?r.errors.push(`Unknown option: --${e}`):i.allowUnknown!==!1&&(r.options[e]=ct(be(n)));return t}function Fp(e,n=!1){let t=new Map,r=Object.entries(e).sort(([i],[s])=>i.localeCompare(s)),o=new Set;for(let[,i]of r)i.short&&o.add(i.short);for(let[i,s]of r){let a=s.short??"";n&&!a&&(a=Bp(i,o),a&&o.add(a));let l={name:i,short:a,aliases:s.aliases??[],type:s.type??"string",description:s.description??"",required:s.required??!1,hidden:s.hidden??!1,negatable:s.negatable??!0,default:s.default,choices:s.choices,env:s.env,validate:s.validate};t.set(i,l);for(let d of l.aliases)t.set(d,l)}return t}function Bp(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 Ar(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function Hp(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?Pe(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 Up(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 Gp(e,n,t){for(let r of t.values()){let o=e.options[r.name];if(r.validate&&o!==void 0){let i=r.validate(o);i!==!0&&e.errors.push(i)}}for(let r of n.positional??[]){let o=e.positional[r.name];if(r.validate&&o!==void 0){let i=r.validate(o);i!==!0&&e.errors.push(i)}}}function Kp(e){return/^-\d+(\.\d+)?$/.test(e)}var Tr=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 Vp(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 qp(e,n){let t=new Map;for(let[o,i]of Object.entries(n))if(!(i.kind!=="value"||i.type!=="array")){t.set(o,o);for(let s of i.aliases??[])t.set(s,o)}let r=new Map;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="--")break;let s=i.match(/^--([^=]+)(?:=(.*))?$/)??i.match(/^-([^=])(?:=(.*))?$/);if(s===null)continue;let a=t.get(s[1]);if(a===void 0)continue;let l=s[2];if(l===void 0&&xn(e[o+1])&&(l=e[o+1],o+=1),l===void 0)continue;let d=r.get(a)??[];d.push(l),r.set(a,d)}return r}function je(e,n,t={}){let o=Is({options:Vp(n),separators:{},allowUnknown:!0}).parse([...e]),i={},s=qp(e,n),a=o.errors.find(l=>/^Option --?\S+ requires a value$/.test(l));if(a!==void 0)throw new Error(a.replace(/^Option /,""));if(o.errors.length>0)throw new Error(o.errors[0]);if(t.unknownFlags==="error"){let l=new Set(Object.keys(n));for(let d of Object.keys(o.options))if(!l.has(d))throw new Tr(d.length===1?`-${d}`:`--${d}`,Object.keys(n).map(p=>p.length===1?`-${p}`:`--${p}`))}for(let[l,d]of Object.entries(n)){let p=o.options[l];p!==void 0&&(d.kind==="boolean"?i[l]=p:d.type==="array"?i[l]=(s.get(l)??[]).map(u=>d.coerce(u)):i[l]=d.coerce(String(p)))}return{values:i,positionals:o.rest}}var $r=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 Ns(e,n){let[t,...r]=e;if(t!==void 0){for(let[i,s]of Object.entries(n.commands))if(t===i||(s.aliases??[]).includes(t))return{command:i,args:r};if(n.errorOnUnknownCommand&&!t.startsWith("-"))throw new $r(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as of,mkdirSync as sf,readFileSync as Vs,statSync as lf}from"node:fs";import{dirname as Js,join as af}from"node:path";var Cs="RED_WORKER_SCOPE",Ms="RED_WORKER_MEMORY_CEILING",Ws="RED_WORKER_SCOPE_DEGRADATION",Ir={scope:null,memory_ceiling:null,scope_degradation:null};function Nr(e){return{scope:Lr(e[Cs]),memory_ceiling:Lr(e[Ms]),scope_degradation:Lr(e[Ws])}}function Sn(e){let n={};return e.scope!=null&&e.scope!==""&&(n[Cs]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[Ms]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[Ws]=e.scope_degradation),n}function Lr(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as zp,readdirSync as Yp,readFileSync as Us,rmSync as Xp,writeFileSync as Zp}from"node:fs";import{basename as ef,join as Qe}from"node:path";import{isAbsolute as Y_,join as pt,resolve as X_}from"node:path";function Jp(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var Fs="deaths",Bs="deaths.toonl";function ft(e){return pt(Jp(e),Fs)}function vn(e){return pt(ft(e),Bs)}var En="live",Hs="attributions.toonl";function mt(e){return pt(ft(e),En)}function Cr(e){return pt(ft(e),Hs)}var Wr=Qe("sys","kernel","random","boot_id"),Gs=1;function Fr(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:Gs,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:Ks(Qe(t,Wr)),cgroup:nf(t,r),last_phase:e.last_phase}}function Ks(e){try{let n=Us(e,"utf8").trim();return n===""?null:n}catch{return null}}function nf(e,n){let t=Ks(Qe(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
42
+ `),o=r.find(s=>s.startsWith("0::"));if(o)return o.slice(3)||null;let i=r[0]?.split(":").slice(2).join(":");return i===void 0||i===""?null:i}function Br(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function Hr(e,n){let t=Qe(e,Br(n));try{return zp(e,{recursive:!0,mode:448}),Zp(t,ue({trailer:!1}).push(rf(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function De(e,n){try{Xp(Qe(e,Br(n)),{force:!0})}catch{}}function Ur(e,n){let t;try{t=Yp(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let i=Qe(e,o);try{let a=ke(Us(i,"utf8"))[0];if(a===void 0)throw new Error("anchor holds no record");r.push(tf(a))}catch(s){n?.(ef(i),s instanceof Error?s.message:String(s))}}return r}function tf(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:Mr(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:Mr(e.pid),ppid:Mr(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 Mr(e){return typeof e=="number"?e:Number(e)}function rf(e){return{...e}}var df=1,cf=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function uf(e){return typeof e=="string"&&cf.has(e)}var pf="startup";function ff(e,n){return{...e.scope??Ir,version:df,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 mf(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 Kr={mkdir(e){sf(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=lf(e).size}catch{return!0}if(n===0)return!0;try{return Vs(e,"utf8").endsWith(`
43
+ `)}catch{return!0}},append(e,n){of(e,n,{encoding:"utf8",mode:384})},read(e){return Vs(e,"utf8")}};function hf(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function gf(e,n,t=Kr){let r=ue({trailer:!1}).push(hf(n));return t.mkdir(Js(e)),t.endsClean(e)||t.append(e,`
44
+ `),t.append(e,r),n}function Qs(e){let n=e.endsWith(`
45
45
  `)?e:e.slice(0,e.lastIndexOf(`
46
- `)+1);return n===""?[]:ye(n).map(Up)}function Up(e){let n=e.exit_path;if(!Np(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:K(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:K(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:K(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:K(e.uptime_s),rss_kb:K(e.rss_kb),max_rss_kb:K(e.max_rss_kb),user_cpu_us:K(e.user_cpu_us),system_cpu_us:K(e.system_cpu_us),minor_page_faults:K(e.minor_page_faults),major_page_faults:K(e.major_page_faults),voluntary_ctx_switches:K(e.voluntary_ctx_switches),involuntary_ctx_switches:K(e.involuntary_ctx_switches)}}function K(e){return typeof e=="number"?e:Number(e)}function Os(e,n=Tr){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return Ds(t)}var Bp=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],Ir=null;function As(e){let n=e.host??process,t=e.io??Tr,r=e.clock??(()=>new Date().toISOString()),o=n.pid,i=e.scope??Er(process.env),s=e.phase??Cp,a=null,l=e.presenceDir===void 0?$p(js(e.lanePath),_n):e.presenceDir,d=null,p=()=>{l!==null&&(d=Or({kind:e.kind,id:e.id,last_phase:s,pid:o},{procRoot:e.procRoot}),Lr(l,d))},u=k=>{if(!a){try{a=Fp(e.lanePath,Mp({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:s,scope:i,...k},Wp(n)),t)}catch{}l!==null&&d!==null&&De(l,d)}},f={signal(k){u({exit_path:"signal",signal:k})},exit(k){u({exit_path:"exit",exit_code:k})},uncaughtException(k){u({exit_path:"uncaught-exception",detail:Ps(k)})},unhandledRejection(k){u({exit_path:"unhandled-rejection",detail:Ps(k)})}},h=[...(e.signals??Bp).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 h)n.on(k,w);let b={lanePath:e.lanePath,phase(k){s=k,a||p()},currentPhase:()=>s,written:()=>a,uninstall(){for(let[k,w]of h)n.off(k,w);l!==null&&d!==null&&De(l,d),Ir===b&&(Ir=null)},handlers:f};return e.setActive!==!1&&(Ir=b),p(),b}function Ps(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Kp,readdirSync as Vp,readFileSync as ct,statSync as qp,writeFileSync as Gp}from"node:fs";import{join as Ts}from"node:path";var Jp=1,Qp=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],zp=512*1024;function Yp(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??Qp,r=[],o=Ts(n,Dr),i=null;try{let l=ct(o,"utf8").trim();i=l===""?null:l,r.push({source:o,result:i?"read":"empty",detail:i})}catch(l){r.push({source:o,result:Nr(l),detail:null})}let s=new Set;try{for(let l of Vp(n))/^\d+$/.test(l)&&s.add(Number(l));r.push({source:n,result:"read",detail:`${s.size} live pids`})}catch(l){r.push({source:n,result:Nr(l),detail:null})}let a=[];for(let l of t)try{let p=Xp(l,e.tailBytes??zp).split(`
47
- `).filter(u=>u.trim()!=="");a.push(...p),r.push({source:l,result:p.length===0?"empty":"read",detail:`${p.length} lines`})}catch(d){r.push({source:l,result:Nr(d),detail:null})}return{boot_id:i,live_pids:s,journal:a,probes:r}}function Nr(e){return e.code==="ENOENT"?"absent":"unreadable"}function Xp(e,n){let t=qp(e).size,r=ct(e,"utf8");return t<=n?r:r.slice(r.length-n)}var Zp=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,ef=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,nf=/Killed (\/\S*) due to memory pressure/,tf=/\bopid=(\d+)\b/,Ls=/\bsig=(\d+)\b/,rf=/\buid=(\d+)\b/,of=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,sf={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function lf(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,i=[...n.probes.map(u=>`${u.source}: ${u.result}${u.detail?` (${u.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"}`],s=(u,f,m,h)=>({version:Jp,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:u,confidence:f,signal:m,host_boot_changed:o,evidence:h,checked:i}),a=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],l=n.journal.find(u=>$s(u,e.pid,Zp)||$s(u,e.pid,ef));if(l!==void 0)return s("oomd",o?"medium":"high","SIGKILL",[l,...a]);if(e.cgroup!==null)for(let u of n.journal){let f=nf.exec(u)?.[1];if(f!==void 0){if(f===e.cgroup)return s("oomd",o?"medium":"high","SIGKILL",[u,...a]);if(e.cgroup.startsWith(`${f}/`))return s("oomd","medium","SIGKILL",[u,`the killed scope ${f} is an ancestor of this process's ${e.cgroup}`,...a])}}let d=n.journal.find(u=>Number(tf.exec(u)?.[1])===e.pid&&Ls.test(u));if(d!==void 0){let u=Number(Ls.exec(d)?.[1]),f=rf.exec(d)?.[1];return s("user-signal",o?"medium":"high",sf[u]??null,[d,...f===void 0?[]:[`sent by uid ${f}`],...a])}let p=t.find(u=>u.pid===e.ppid);if(p!==void 0&&!n.live_pids.has(e.ppid))return s("parent-death","medium",null,[`parent pid ${e.ppid} (${p.kind} ${p.id}) recorded its own death at ${p.ts} via ${p.exit_path}${p.signal?` ${p.signal}`:""}`]);if(o){let u=n.journal.find(f=>of.test(f));return u!==void 0?s("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,u]):s("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 s("unknown","none",null,[])}function $s(e,n,t){return Number(t.exec(e)?.[1])===n}var af=" | ";function Is(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(af)}function df(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:Is(e.evidence),checked:Is(e.checked)}}function cf(e){let n=pe({trailer:!1});return e.map(t=>n.push(df(t))).join("")}function Ns(e){let n=dt(e.stateRoot),t=Pr(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??Yp({procRoot:e.procRoot,journalPaths:e.journalPaths}),i=[],s=$r(n,u=>i.push(u)),a=Os(bn(e.stateRoot)),l=[],d=[],p=[];for(let u of s){if(o.live_pids.has(u.pid)){d.push(u);continue}if(a.find(m=>m.pid===u.pid&&m.id===u.id)!==void 0){p.push(u),De(n,u);continue}l.push(lf(u,o,a,r())),De(n,u)}return l.length>0&&uf(t,l),{attributions:l,alive:d,self_recorded:p,skipped:i,laneText:()=>{try{return ct(t,"utf8")}catch{return""}}}}function Cs(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 uf(e,n){try{Kp(Ts(e,".."),{recursive:!0,mode:448});let t=pf(e),r=t===""||t.endsWith(`
46
+ `)+1);return n===""?[]:ke(n).map(yf)}function yf(e){let n=e.exit_path;if(!uf(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:K(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:K(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:K(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:K(e.uptime_s),rss_kb:K(e.rss_kb),max_rss_kb:K(e.max_rss_kb),user_cpu_us:K(e.user_cpu_us),system_cpu_us:K(e.system_cpu_us),minor_page_faults:K(e.minor_page_faults),major_page_faults:K(e.major_page_faults),voluntary_ctx_switches:K(e.voluntary_ctx_switches),involuntary_ctx_switches:K(e.involuntary_ctx_switches)}}function K(e){return typeof e=="number"?e:Number(e)}function zs(e,n=Kr){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return Qs(t)}var kf=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],Gr=null;function Ys(e){let n=e.host??process,t=e.io??Kr,r=e.clock??(()=>new Date().toISOString()),o=n.pid,i=e.scope??Nr(process.env),s=e.phase??pf,a=null,l=e.presenceDir===void 0?af(Js(e.lanePath),En):e.presenceDir,d=null,p=()=>{l!==null&&(d=Fr({kind:e.kind,id:e.id,last_phase:s,pid:o},{procRoot:e.procRoot}),Hr(l,d))},u=k=>{if(!a){try{a=gf(e.lanePath,ff({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:s,scope:i,...k},mf(n)),t)}catch{}l!==null&&d!==null&&De(l,d)}},f={signal(k){u({exit_path:"signal",signal:k})},exit(k){u({exit_path:"exit",exit_code:k})},uncaughtException(k){u({exit_path:"uncaught-exception",detail:qs(k)})},unhandledRejection(k){u({exit_path:"unhandled-rejection",detail:qs(k)})}},h=[...(e.signals??kf).map(k=>{let _=()=>{if(f.signal(k),!(n.listenerCount?.(k)!==1||!n.kill)){n.off(k,_);try{n.kill(o,k)}catch{}}};return[k,_]}),["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,_]of h)n.on(k,_);let R={lanePath:e.lanePath,phase(k){s=k,a||p()},currentPhase:()=>s,written:()=>a,uninstall(){for(let[k,_]of h)n.off(k,_);l!==null&&d!==null&&De(l,d),Gr===R&&(Gr=null)},handlers:f};return e.setActive!==!1&&(Gr=R),p(),R}function qs(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as bf,readdirSync as Rf,readFileSync as ht,statSync as _f,writeFileSync as wf}from"node:fs";import{join as nl}from"node:path";var xf=1,Sf=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],vf=512*1024;function Ef(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??Sf,r=[],o=nl(n,Wr),i=null;try{let l=ht(o,"utf8").trim();i=l===""?null:l,r.push({source:o,result:i?"read":"empty",detail:i})}catch(l){r.push({source:o,result:Vr(l),detail:null})}let s=new Set;try{for(let l of Rf(n))/^\d+$/.test(l)&&s.add(Number(l));r.push({source:n,result:"read",detail:`${s.size} live pids`})}catch(l){r.push({source:n,result:Vr(l),detail:null})}let a=[];for(let l of t)try{let p=Pf(l,e.tailBytes??vf).split(`
47
+ `).filter(u=>u.trim()!=="");a.push(...p),r.push({source:l,result:p.length===0?"empty":"read",detail:`${p.length} lines`})}catch(d){r.push({source:l,result:Vr(d),detail:null})}return{boot_id:i,live_pids:s,journal:a,probes:r}}function Vr(e){return e.code==="ENOENT"?"absent":"unreadable"}function Pf(e,n){let t=_f(e).size,r=ht(e,"utf8");return t<=n?r:r.slice(r.length-n)}var jf=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,Df=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,Of=/Killed (\/\S*) due to memory pressure/,Af=/\bopid=(\d+)\b/,Xs=/\bsig=(\d+)\b/,Tf=/\buid=(\d+)\b/,$f=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,Lf={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function If(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,i=[...n.probes.map(u=>`${u.source}: ${u.result}${u.detail?` (${u.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"}`],s=(u,f,m,h)=>({version:xf,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:u,confidence:f,signal:m,host_boot_changed:o,evidence:h,checked:i}),a=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],l=n.journal.find(u=>Zs(u,e.pid,jf)||Zs(u,e.pid,Df));if(l!==void 0)return s("oomd",o?"medium":"high","SIGKILL",[l,...a]);if(e.cgroup!==null)for(let u of n.journal){let f=Of.exec(u)?.[1];if(f!==void 0){if(f===e.cgroup)return s("oomd",o?"medium":"high","SIGKILL",[u,...a]);if(e.cgroup.startsWith(`${f}/`))return s("oomd","medium","SIGKILL",[u,`the killed scope ${f} is an ancestor of this process's ${e.cgroup}`,...a])}}let d=n.journal.find(u=>Number(Af.exec(u)?.[1])===e.pid&&Xs.test(u));if(d!==void 0){let u=Number(Xs.exec(d)?.[1]),f=Tf.exec(d)?.[1];return s("user-signal",o?"medium":"high",Lf[u]??null,[d,...f===void 0?[]:[`sent by uid ${f}`],...a])}let p=t.find(u=>u.pid===e.ppid);if(p!==void 0&&!n.live_pids.has(e.ppid))return s("parent-death","medium",null,[`parent pid ${e.ppid} (${p.kind} ${p.id}) recorded its own death at ${p.ts} via ${p.exit_path}${p.signal?` ${p.signal}`:""}`]);if(o){let u=n.journal.find(f=>$f.test(f));return u!==void 0?s("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,u]):s("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 s("unknown","none",null,[])}function Zs(e,n,t){return Number(t.exec(e)?.[1])===n}var Nf=" | ";function el(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(Nf)}function Cf(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:el(e.evidence),checked:el(e.checked)}}function Mf(e){let n=ue({trailer:!1});return e.map(t=>n.push(Cf(t))).join("")}function tl(e){let n=mt(e.stateRoot),t=Cr(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??Ef({procRoot:e.procRoot,journalPaths:e.journalPaths}),i=[],s=Ur(n,u=>i.push(u)),a=zs(vn(e.stateRoot)),l=[],d=[],p=[];for(let u of s){if(o.live_pids.has(u.pid)){d.push(u);continue}if(a.find(m=>m.pid===u.pid&&m.id===u.id)!==void 0){p.push(u),De(n,u);continue}l.push(If(u,o,a,r())),De(n,u)}return l.length>0&&Wf(t,l),{attributions:l,alive:d,self_recorded:p,skipped:i,laneText:()=>{try{return ht(t,"utf8")}catch{return""}}}}function rl(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 Wf(e,n){try{bf(nl(e,".."),{recursive:!0,mode:448});let t=Ff(e),r=t===""||t.endsWith(`
48
48
  `)?"":`
49
- `;Gp(e,`${t}${r}${cf(n)}`,{encoding:"utf8",mode:384})}catch{}}function pf(e){try{return ct(e,"utf8")}catch{return""}}import{join as ff}from"node:path";var mf=[".red","redskilled"],se=448;function Oe(e){return ff(e,...mf)}import{execFileSync as jf}from"node:child_process";import{readFileSync as Df}from"node:fs";import{dirname as Ks,join as Of}from"node:path";import{existsSync as hf,readFileSync as X_}from"node:fs";import{dirname as gf,join as yf}from"node:path";function Ms(e,n){let t=e;for(let r=0;r<16;r++){let o=yf(t,n);if(hf(o))return o;let i=gf(t);if(i===t)break;t=i}return null}function kf(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function Qe(e,n){let t=[];for(let r of e.split(`
50
- `)){let o=r.replace(/\r$/,""),i=o.trim();if(!i||i.startsWith("#"))continue;let s=o.indexOf(":");if(s<0)continue;let a=o.length-o.trimStart().length,l=o.slice(0,s).trim();if(!l)continue;let d=o.slice(s+1).trim();for(;t.length&&t[t.length-1].indent>=a;)t.pop();if(t.push({indent:a,key:l}),d&&t.map(u=>u.key).join(".")===n)return kf(d)}}import{createHash as Rf}from"node:crypto";var bf="project.name";function Hs(e){let n=Qe(e,bf)?.trim();return n===void 0||n===""?void 0:n}var _f=8,Fs="project";function Us(e){let n=Ef(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:wf(e.remoteUrl)??{name:xf(e.checkoutPath,n),source:"basename"},o=vf(n??Cr(e.checkoutPath));return{name:r.name,slug:`${Sf(r.name)}-${o}`,hash:o,source:r.source}}function Bs(e){let n=(e??"").trim();if(n==="")return;let t=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),r=/^[^/]*?:(?!\d)(.+)$/.exec(t),i=(r?r[1]:t.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(s=>s.trim()).filter(s=>s!=="");if(i.length!==0)return i.slice(-2).join("/")}function wf(e){let n=Bs(e);return n===void 0?void 0:{name:n,source:"remote"}}function xf(e,n){let t=n===void 0?"":Ws(Pf(n));if(t!=="")return t;let r=Ws(Cr(e));return r===""?Fs:r}function Sf(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?Fs:t}function vf(e){return Rf("sha256").update(e).digest("hex").slice(0,_f)}function Ef(e){let n=Cr(e??"");return n===""?void 0:n}function Cr(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function Ws(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function Pf(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var Af=2e3;function Vs(e){return Lf(e).name}function Lf(e){let n=Wr(e),t=Mr(e,["rev-parse","--absolute-git-dir"])??Mr(e,["rev-parse","--git-common-dir"]),r=Mr(e,["remote","get-url","origin"]);return Us({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function Wr(e){let n=Ms(e,Of(".red","config.yaml"));if(n==null)return{};let t;try{t=Df(n,"utf8")}catch{return{}}let r=Hs(t),o=Ks(Ks(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function Mr(e,n){try{let t=jf("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Af}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as Nd}from"node:crypto";import{spawn as $k}from"node:child_process";import{mkdir as Ik,rm as Tk}from"node:fs/promises";import{dirname as Nk}from"node:path";import{createHash as Tf}from"node:crypto";import{constants as Kr}from"node:fs";import{mkdir as Nf,open as Cf}from"node:fs/promises";import{createConnection as Mf}from"node:net";import{tmpdir as Wf}from"node:os";import{dirname as Hf,join as wn}from"node:path";var $f="toon";function Js(e){return e.trimStart().startsWith("{")?"json":"toon"}function Fr(e){let n=0;for(;e[n]===`
51
- `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=Js(t);if(r==="json"){let i=t.indexOf(`
49
+ `;wf(e,`${t}${r}${Mf(n)}`,{encoding:"utf8",mode:384})}catch{}}function Ff(e){try{return ht(e,"utf8")}catch{return""}}import{join as Bf}from"node:path";var Hf=[".red","redskilled"],se=448;function Oe(e){return Bf(e,...Hf)}import{execFileSync as tm}from"node:child_process";import{readFileSync as rm}from"node:fs";import{dirname as cl,join as om}from"node:path";import{existsSync as Uf,readFileSync as Dw}from"node:fs";import{dirname as Gf,join as Kf}from"node:path";function ol(e,n){let t=e;for(let r=0;r<16;r++){let o=Kf(t,n);if(Uf(o))return o;let i=Gf(t);if(i===t)break;t=i}return null}function Vf(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function ze(e,n){let t=[];for(let r of e.split(`
50
+ `)){let o=r.replace(/\r$/,""),i=o.trim();if(!i||i.startsWith("#"))continue;let s=o.indexOf(":");if(s<0)continue;let a=o.length-o.trimStart().length,l=o.slice(0,s).trim();if(!l)continue;let d=o.slice(s+1).trim();for(;t.length&&t[t.length-1].indent>=a;)t.pop();if(t.push({indent:a,key:l}),d&&t.map(u=>u.key).join(".")===n)return Vf(d)}}import{createHash as qf}from"node:crypto";var Jf="project.name";function sl(e){let n=ze(e,Jf)?.trim();return n===void 0||n===""?void 0:n}var Qf=8,ll="project";function al(e){let n=em(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:zf(e.remoteUrl)??{name:Yf(e.checkoutPath,n),source:"basename"},o=Zf(n??qr(e.checkoutPath));return{name:r.name,slug:`${Xf(r.name)}-${o}`,hash:o,source:r.source}}function dl(e){let n=(e??"").trim();if(n==="")return;let t=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),r=/^[^/]*?:(?!\d)(.+)$/.exec(t),i=(r?r[1]:t.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(s=>s.trim()).filter(s=>s!=="");if(i.length!==0)return i.slice(-2).join("/")}function zf(e){let n=dl(e);return n===void 0?void 0:{name:n,source:"remote"}}function Yf(e,n){let t=n===void 0?"":il(nm(n));if(t!=="")return t;let r=il(qr(e));return r===""?ll:r}function Xf(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?ll:t}function Zf(e){return qf("sha256").update(e).digest("hex").slice(0,Qf)}function em(e){let n=qr(e??"");return n===""?void 0:n}function qr(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function il(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function nm(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var im=2e3;function ul(e){return sm(e).name}function sm(e){let n=Qr(e),t=Jr(e,["rev-parse","--absolute-git-dir"])??Jr(e,["rev-parse","--git-common-dir"]),r=Jr(e,["remote","get-url","origin"]);return al({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function Qr(e){let n=ol(e,om(".red","config.yaml"));if(n==null)return{};let t;try{t=rm(n,"utf8")}catch{return{}}let r=sl(t),o=cl(cl(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function Jr(e,n){try{let t=tm("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:im}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as ac}from"node:crypto";import{spawn as cb}from"node:child_process";import{mkdir as ub,rm as pb}from"node:fs/promises";import{dirname as fb}from"node:path";import{createHash as dm}from"node:crypto";import{constants as eo}from"node:fs";import{mkdir as cm,open as um}from"node:fs/promises";import{createConnection as pm}from"node:net";import{tmpdir as fm}from"node:os";import{dirname as mm,join as Pn}from"node:path";var lm="toon";function ml(e){return e.trimStart().startsWith("{")?"json":"toon"}function Yr(e){let n=0;for(;e[n]===`
51
+ `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=ml(t);if(r==="json"){let i=t.indexOf(`
52
52
  `);return i<0?null:{frame:t.slice(0,i),dialect:r,rest:t.slice(i+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 Ur(e){let n=Js(e)==="json"?Hr:qs,t=n===Hr?qs:Hr;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function Hr(e){return JSON.parse(e)}function qs(e){return Y(e)}function Br(e,n){if(n==="toon"){let t=If(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 Xr(e){let n=ml(e)==="json"?zr:pl,t=n===zr?pl:zr;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function zr(e){return JSON.parse(e)}function pl(e){return Y(e)}function Zr(e,n){if(n==="toon"){let t=am(e);if(t!==null)return t.endsWith(`
55
55
  `)?`${t}
56
56
  `:`${t}
57
57
 
58
58
  `}return`${JSON.stringify(e)}
59
- `}function If(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=M(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function Qs(e,n){return!Gs(e)||!Gs(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function Gs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zs=new Set;function Ys(e){return zs.has(e)?"json":$f}function Xs(e){zs.add(e)}var Ff=108;async function ut(e,n,t="resident server"){let r=e.wire,o=r??Ys(e.socketPath),i=await Zs(e,n,t,o);return r||o==="json"||!Qs(n,i)?i:(Xs(e.socketPath),await Zs(e,n,t,"json"))}async function Zs(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((i,s)=>{let a=Mf(e.socketPath),l=!1,d="",p=setTimeout(()=>{u(()=>s(new Error(`${t} timed out`))),a.destroy()},o);function u(f){l||(l=!0,clearTimeout(p),f())}a.on("connect",()=>{a.write(Br(n,r))}),a.on("data",f=>{d+=f.toString("utf8");let m=Fr(d);m&&(d=m.rest,u(()=>{try{i(Ur(m.frame))}catch(h){s(h)}}),a.end())}),a.on("error",f=>u(()=>s(f))),a.on("close",()=>{l||u(()=>s(new Error(`${t} closed without response`)))})})}function el(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let i=Fr(r);if(!i)return;r=i.rest,e.pause();let s=a=>{if(!(e.destroyed||!e.writable))try{e.write(Br(a,i.dialect))}catch{}};(async()=>{let a;try{a=Ur(i.frame),await n(a,s)}catch(l){t(l,a,s)}finally{e.end()}})()})}async function nl(e){await Nf(Hf(e),{recursive:!0,mode:448});try{return await Cf(e,Kr.O_CREAT|Kr.O_EXCL|Kr.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}function U(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var Uf="/tmp";function pt(e){let n=e.env??process.env,t=Tf("sha256").update(e.key).digest("hex").slice(0,20),r=l=>wn(l,e.socketFileName).length<Ff,o=n.XDG_RUNTIME_DIR;if(o){let l=wn(o,"red-skills",t);if(r(l))return l}let i=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),s=wn(`red-skills-${i}`,t),a=wn(Wf(),s);return r(a)||process.platform==="win32"?a:wn(Uf,s)}fe();import{homedir as um}from"node:os";import{join as Xr}from"node:path";import{spawnSync as pm}from"node:child_process";import{createHash as fm}from"node:crypto";import{existsSync as mm}from"node:fs";import{mkdir as al,readFile as hm,writeFile as gm}from"node:fs/promises";import{dirname as ym}from"node:path";var Le="@reddb-io/red-skills",Zf="https://registry.npmjs.org",em="canary",ze=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function nm(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function gt(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return yt(r,nm(n,t,o))}function tm(e){return e==="dev"?["rsp","redskilled"]:[]}function rm(e){return`${e}.bundle.min.mjs`}function om(e){return yt("dist",rm(e))}function im(e,n="stable"){return`${Le}@${n==="canary"?em:e}`}function sm(e=Le){return`${Zf}/${e.replace("/","%2F")}`}async function Yr(e,n){let{plugin:t,version:r,cacheDir:o,channel:i="stable"}=n,s=gt({plugin:t,version:r,cacheDir:o,channel:i}),a=tm(t),l=a.map(f=>gt({plugin:f,version:r,cacheDir:o,channel:i}));if(i!=="canary"&&await e.exists(s)&&await lm(e,l))return s;let d=im(r,i),p=yt(o,`.staging-${t}-${i==="canary"?"canary":r}`),u;try{u=await e.materialize(d,p)}catch(f){throw ll(f,d)}for(let f of[t,...a]){let m=om(f),h=yt(u,m);if(!await e.exists(h))throw new ze("bundle-missing",`npm package ${d} has no ${m}`);let b=f===t?s:gt({plugin:f,version:r,cacheDir:o,channel:i});await e.writeFile(b,await e.readFile(h))}return s}async function lm(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function il(e,n,t=Le){let r;try{r=await e.fetchText(sm(t))}catch(i){throw ll(i,t)}let o=am(r);return{sameMajor:dm(o,n),newest:cm(o)}}function am(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 dm(e,n){let t=zr(n);if(t===null)return null;let r=null;for(let o of e)zr(o)===t&&(r===null||sl(o,r)>0)&&(r=o);return r}function cm(e){let n=null;for(let t of e){let r=String(t).trim();zr(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||sl(r,n)>0)&&(n=r)}return n}function zr(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function sl(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 ll(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new ze("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new ze("package-missing",`npm could not resolve ${n}: ${t}`,e):new ze("network",`failed to resolve ${n}: ${t}`,e)}function yt(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}fe();var km={async materialize(e,n){await al(n,{recursive:!0});let t=pm("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 Xr(n,"node_modules",...Le.split("/"))},async readFile(e){return new Uint8Array(await hm(e))},async writeFile(e,n){await al(ym(e),{recursive:!0}),await gm(e,n)},async exists(e){return mm(e)},sha256(e){return fm("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()}},Rm="redskilled";function bm(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Xr(e.HOME||um(),".cache");return Xr(n,"red-skills","bundles")}async function _m(e={},n={},t={}){let r=Re(e,n);if(ae(r))return r;let o=t.env??n.env??process.env;try{await Yr(t.bundleIO??km,{plugin:Rm,version:t.version??"",cacheDir:bm(o)})}catch{return r}return Re(e,n)}async function dl(e={},n={},t={}){let r=await _m(e,n,t);if(ae(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(fe(),ol));throw new o(r)}import{randomUUID as Tn}from"node:crypto";import{mkdir as _k,rm as Ld}from"node:fs/promises";import{createServer as wk}from"node:net";import{dirname as xk}from"node:path";import{totalmem as xm}from"node:os";function vn(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 cl(e,n={}){let t=0,r=0,o=0,i=[],s=[];for(let d of e){let p=vn(d),u=!1;for(let[f,m]of[[p.memory_high,h=>t+=h],[p.memory_max,h=>r+=h]]){if(f==null)continue;let h=Ye(f);h==null?u=!0:m(h)}p.cpu_weight!=null&&(o+=p.cpu_weight),u&&i.push(d.worker_id),d.isolated||s.push(d.worker_id)}let a=n.hostCeilingBytes??null,l=a==null?0:Math.max(0,r-a);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:r,cpu_weight_total:o,unaccounted_workers:i.sort(),unisolated_workers:s.sort(),memory_ceiling_bytes:a,over_committed_bytes:l,over_commitment_reason:l===0?null:wm(e.length,r,a,l)}}function wm(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 Ye(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 ul(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 Sm="REDSKILLED_MEMORY_CEILING",pl="REDSKILLED_WORKER_CEILING",vm=.7;function fl(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return Ye(n)}function kt(e){let n=0,t=[];for(let r of e){let o=fl(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 ml(e){let{ceiling:n}=e,t=kt(e.workers),r=fl(e.budget),o=r===void 0?null:r,i=t.memory_bytes+(r??0),s=t.worker_count+1,a=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",l=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,d=(p,u)=>({version:1,admitted:!1,verdict:p,reason:u,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:s,projected_memory_bytes:i});return n.worker_count!=null&&s>n.worker_count?d("refused-over-worker-ceiling",`redskilled refused this Worker${a}: it would be Worker ${s} past a host ceiling of ${n.worker_count} Worker(s), and ${l}`):n.memory_bytes!=null&&r===null?d("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 ${l}`):n.memory_bytes!=null&&i>n.memory_bytes?d("refused-over-memory-ceiling",`redskilled refused this Worker${a}: it would take the host to ${i} bytes of declared Worker memory, past the host ceiling of ${n.memory_bytes} bytes, and ${l}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${a}: ${i} bytes of declared Worker memory against a host ceiling of ${n.memory_bytes??"unbounded"} bytes, and ${l}`,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:s,projected_memory_bytes:i}}function hl(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=kt(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,i=o==null?r:Math.floor(e.ceiling.memory_bytes/o),s=Math.min(r,i);if(s<=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 a=o==null?`the headroom under this host's memory ceiling of ${e.ceiling.memory_bytes} bytes; this host declares no Worker slot count (${pl} 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(s),reason:`derived from ${a} (ceiling source: ${e.ceiling.source})`}}function gl(e=process.env,n=xm()){let t=(e[Sm]??"").trim(),r=(e[pl]??"").trim(),o=Pm(r);if(t!==""){let i=Em(t,n);if(i!==void 0)return{memory_bytes:i,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(n*vm),worker_count:o,source:r!==""?"declared":"host-fraction"}}function Em(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)):Ye(e)??void 0}function Pm(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 jm,mkdir as Dm,open as Om,readFile as Am,stat as Lm,truncate as yl}from"node:fs/promises";import{dirname as $m}from"node:path";var kl="redskilled.events.toonl";function Im(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 Tm="daemon:";function Nm(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${Tm}${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 Rl(e){let n=pe({trailer:!1}),t=Promise.resolve();async function r(o){let i=t.then(async()=>{await Dm($m(e),{recursive:!0,mode:448}),await Cm(e),await jm(e,n.push(Fm(o)),{encoding:"utf8",mode:384})});return t=i.catch(()=>{}),await i,o}return{path:e,record:o=>r(Im(o)),recordDaemonStop:o=>r(Nm(o)),read:()=>Mm(e),flush:async()=>{await t}}}async function Cm(e){let n;try{n=(await Lm(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await Om(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let i=n;i>0;i-=t){let s=Math.min(t,i),a=Buffer.alloc(s);await r.read(a,0,s,i-s);let l=a.lastIndexOf(10);if(l>=0){await yl(e,i-s+l+1);return}}await yl(e,0)}finally{await r.close()}}async function Mm(e){let n;try{n=await Am(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return Wm(n)}function Wm(e){let n=e.split(`
60
- `);return n.pop(),n.length===0?[]:ye(`${n.join(`
59
+ `}function am(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=M(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function hl(e,n){return!fl(e)||!fl(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function fl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var gl=new Set;function yl(e){return gl.has(e)?"json":lm}function kl(e){gl.add(e)}var hm=108;async function gt(e,n,t="resident server"){let r=e.wire,o=r??yl(e.socketPath),i=await bl(e,n,t,o);return r||o==="json"||!hl(n,i)?i:(kl(e.socketPath),await bl(e,n,t,"json"))}async function bl(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((i,s)=>{let a=pm(e.socketPath),l=!1,d="",p=setTimeout(()=>{u(()=>s(new Error(`${t} timed out`))),a.destroy()},o);function u(f){l||(l=!0,clearTimeout(p),f())}a.on("connect",()=>{a.write(Zr(n,r))}),a.on("data",f=>{d+=f.toString("utf8");let m=Yr(d);m&&(d=m.rest,u(()=>{try{i(Xr(m.frame))}catch(h){s(h)}}),a.end())}),a.on("error",f=>u(()=>s(f))),a.on("close",()=>{l||u(()=>s(new Error(`${t} closed without response`)))})})}function Rl(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let i=Yr(r);if(!i)return;r=i.rest,e.pause();let s=a=>{if(!(e.destroyed||!e.writable))try{e.write(Zr(a,i.dialect))}catch{}};(async()=>{let a;try{a=Xr(i.frame),await n(a,s)}catch(l){t(l,a,s)}finally{e.end()}})()})}async function _l(e){await cm(mm(e),{recursive:!0,mode:448});try{return await um(e,eo.O_CREAT|eo.O_EXCL|eo.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;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 gm="/tmp";function yt(e){let n=e.env??process.env,t=dm("sha256").update(e.key).digest("hex").slice(0,20),r=l=>Pn(l,e.socketFileName).length<hm,o=n.XDG_RUNTIME_DIR;if(o){let l=Pn(o,"red-skills",t);if(r(l))return l}let i=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),s=Pn(`red-skills-${i}`,t),a=Pn(fm(),s);return r(a)||process.platform==="win32"?a:Pn(gm,s)}pe();import{homedir as Wm}from"node:os";import{join as ao}from"node:path";import{spawnSync as Fm}from"node:child_process";import{createHash as Bm}from"node:crypto";import{existsSync as Hm}from"node:fs";import{mkdir as jl,readFile as Um,writeFile as Gm}from"node:fs/promises";import{dirname as Km}from"node:path";var Te="@reddb-io/red-skills",Pm="https://registry.npmjs.org",jm="canary",Ye=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function Dm(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function _t(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return wt(r,Dm(n,t,o))}function Om(e){return e==="dev"?["rsp","redskilled"]:[]}function Am(e){return`${e}.bundle.min.mjs`}function Tm(e){return wt("dist",Am(e))}function $m(e,n="stable"){return`${Te}@${n==="canary"?jm:e}`}function Lm(e=Te){return`${Pm}/${e.replace("/","%2F")}`}async function lo(e,n){let{plugin:t,version:r,cacheDir:o,channel:i="stable"}=n,s=_t({plugin:t,version:r,cacheDir:o,channel:i}),a=Om(t),l=a.map(f=>_t({plugin:f,version:r,cacheDir:o,channel:i}));if(i!=="canary"&&await e.exists(s)&&await Im(e,l))return s;let d=$m(r,i),p=wt(o,`.staging-${t}-${i==="canary"?"canary":r}`),u;try{u=await e.materialize(d,p)}catch(f){throw Pl(f,d)}for(let f of[t,...a]){let m=Tm(f),h=wt(u,m);if(!await e.exists(h))throw new Ye("bundle-missing",`npm package ${d} has no ${m}`);let R=f===t?s:_t({plugin:f,version:r,cacheDir:o,channel:i});await e.writeFile(R,await e.readFile(h))}return s}async function Im(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function vl(e,n,t=Te){let r;try{r=await e.fetchText(Lm(t))}catch(i){throw Pl(i,t)}let o=Nm(r);return{sameMajor:Cm(o,n),newest:Mm(o)}}function Nm(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 Cm(e,n){let t=so(n);if(t===null)return null;let r=null;for(let o of e)so(o)===t&&(r===null||El(o,r)>0)&&(r=o);return r}function Mm(e){let n=null;for(let t of e){let r=String(t).trim();so(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||El(r,n)>0)&&(n=r)}return n}function so(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function El(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 Pl(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Ye("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Ye("package-missing",`npm could not resolve ${n}: ${t}`,e):new Ye("network",`failed to resolve ${n}: ${t}`,e)}function wt(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}pe();var Vm={async materialize(e,n){await jl(n,{recursive:!0});let t=Fm("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 ao(n,"node_modules",...Te.split("/"))},async readFile(e){return new Uint8Array(await Um(e))},async writeFile(e,n){await jl(Km(e),{recursive:!0}),await Gm(e,n)},async exists(e){return Hm(e)},sha256(e){return Bm("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()}},qm="redskilled";function Jm(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||ao(e.HOME||Wm(),".cache");return ao(n,"red-skills","bundles")}async function Qm(e={},n={},t={}){let r=Re(e,n);if(ae(r))return r;let o=t.env??n.env??process.env;try{await lo(t.bundleIO??Vm,{plugin:qm,version:t.version??"",cacheDir:Jm(o)})}catch{return r}return Re(e,n)}async function Dl(e={},n={},t={}){let r=await Qm(e,n,t);if(ae(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(pe(),Sl));throw new o(r)}import{randomUUID as Wn}from"node:crypto";import{mkdir as Xk,rm as oc}from"node:fs/promises";import{createServer as Zk}from"node:net";import{dirname as eb}from"node:path";import{totalmem as Ym}from"node:os";function On(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 Ol(e,n={}){let t=0,r=0,o=0,i=[],s=[];for(let d of e){let p=On(d),u=!1;for(let[f,m]of[[p.memory_high,h=>t+=h],[p.memory_max,h=>r+=h]]){if(f==null)continue;let h=Xe(f);h==null?u=!0:m(h)}p.cpu_weight!=null&&(o+=p.cpu_weight),u&&i.push(d.worker_id),d.isolated||s.push(d.worker_id)}let a=n.hostCeilingBytes??null,l=a==null?0:Math.max(0,r-a);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:r,cpu_weight_total:o,unaccounted_workers:i.sort(),unisolated_workers:s.sort(),memory_ceiling_bytes:a,over_committed_bytes:l,over_commitment_reason:l===0?null:zm(e.length,r,a,l)}}function zm(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 Xe(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 Al(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 Xm="REDSKILLED_MEMORY_CEILING",Tl="REDSKILLED_WORKER_CEILING",Zm=.7;function $l(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return Xe(n)}function xt(e){let n=0,t=[];for(let r of e){let o=$l(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 Ll(e){let{ceiling:n}=e,t=xt(e.workers),r=$l(e.budget),o=r===void 0?null:r,i=t.memory_bytes+(r??0),s=t.worker_count+1,a=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",l=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,d=(p,u)=>({version:1,admitted:!1,verdict:p,reason:u,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:s,projected_memory_bytes:i});return n.worker_count!=null&&s>n.worker_count?d("refused-over-worker-ceiling",`redskilled refused this Worker${a}: it would be Worker ${s} past a host ceiling of ${n.worker_count} Worker(s), and ${l}`):n.memory_bytes!=null&&r===null?d("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 ${l}`):n.memory_bytes!=null&&i>n.memory_bytes?d("refused-over-memory-ceiling",`redskilled refused this Worker${a}: it would take the host to ${i} bytes of declared Worker memory, past the host ceiling of ${n.memory_bytes} bytes, and ${l}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${a}: ${i} bytes of declared Worker memory against a host ceiling of ${n.memory_bytes??"unbounded"} bytes, and ${l}`,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:s,projected_memory_bytes:i}}function Il(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=xt(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,i=o==null?r:Math.floor(e.ceiling.memory_bytes/o),s=Math.min(r,i);if(s<=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 a=o==null?`the headroom under this host's memory ceiling of ${e.ceiling.memory_bytes} bytes; this host declares no Worker slot count (${Tl} 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(s),reason:`derived from ${a} (ceiling source: ${e.ceiling.source})`}}function Nl(e=process.env,n=Ym()){let t=(e[Xm]??"").trim(),r=(e[Tl]??"").trim(),o=nh(r);if(t!==""){let i=eh(t,n);if(i!==void 0)return{memory_bytes:i,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(n*Zm),worker_count:o,source:r!==""?"declared":"host-fraction"}}function eh(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)):Xe(e)??void 0}function nh(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 th,mkdir as rh,open as oh,readFile as ih,stat as sh,truncate as Cl}from"node:fs/promises";import{dirname as lh}from"node:path";var Ml="redskilled.events.toonl";function ah(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 dh="daemon:";function ch(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${dh}${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 Wl(e){let n=ue({trailer:!1}),t=Promise.resolve();async function r(o){let i=t.then(async()=>{await rh(lh(e),{recursive:!0,mode:448}),await uh(e),await th(e,n.push(hh(o)),{encoding:"utf8",mode:384})});return t=i.catch(()=>{}),await i,o}return{path:e,record:o=>r(ah(o)),recordDaemonStop:o=>r(ch(o)),read:()=>ph(e),flush:async()=>{await t}}}async function uh(e){let n;try{n=(await sh(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await oh(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let i=n;i>0;i-=t){let s=Math.min(t,i),a=Buffer.alloc(s);await r.read(a,0,s,i-s);let l=a.lastIndexOf(10);if(l>=0){await Cl(e,i-s+l+1);return}}await Cl(e,0)}finally{await r.close()}}async function ph(e){let n;try{n=await ih(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return fh(n)}function fh(e){let n=e.split(`
60
+ `);return n.pop(),n.length===0?[]:ke(`${n.join(`
61
61
  `)}
62
- `).filter(Um).map(Bm)}function bl(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,Hm(t)):n.delete(t.worker_id));return[...n.values()]}function Hm(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 Fm(e){return{...e}}function Um(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 Bm(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:me(e.project_label)??"",pid:Number(e.pid??0),workspace_path:me(e.workspace_path)??"",log_path:me(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:me(e.unit),memory_high:me(e.memory_high),memory_max:me(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:me(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:me(e.signal),reason:me(e.reason)}}function me(e){return e==null||e===""?null:String(e)}function _l(e){let n=[...e.projects].sort((s,a)=>s.project_label.localeCompare(a.project_label)),t=e.backoffUntilMs??null,r=t!=null&&e.nowMs<t,o=[],i=[];for(let s of n){let a=Math.max(0,e.live[s.project_label]??0),l=Object.prototype.hasOwnProperty.call(e.queue,s.project_label),d=l?e.queue[s.project_label]??null:null,p={project_label:s.project_label,queue_depth:d,target:s.target,live:a};if(r){o.push({...p,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 u=e.birthHaltUntilMs?.[s.project_label];if(u!=null&&e.nowMs<u){o.push({...p,outcome:"birth-halted",wanted:0,detail:`project ${JSON.stringify(s.project_label)} lost 3 Workers in a row inside 60000ms of birth, so it is not asked for another before ${new Date(u).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({...p,outcome:"queue-unknown",wanted:0,detail:l?`the last poll produced no depth for project ${JSON.stringify(s.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(s.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...p,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(s.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,s.target),d)-a);if(f===0){o.push({...p,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(s.project_label)} holds ${a} Worker(s) against a target of ${s.target} and a queue of ${d}, so it asks for none`});continue}o.push({...p,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(s.project_label)} holds ${a} Worker(s) against a target of ${s.target} and a queue of ${d}, so it asks for ${f} more`});for(let m=0;m<f;m+=1)(i[m]??(i[m]=[])).push({project_label:s.project_label,index:a+m,argv:s.argv,workspace_path:s.workspace_path})}return{intents:o,births:i.flat()}}function wl(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}var Rt={shortLifeStreak:0,haltUntilMs:null};function xl(e,n,t){if(n>=6e4)return Rt;let r=e.shortLifeStreak+1;return r<3?{shortLifeStreak:r,haltUntilMs:null}:{shortLifeStreak:r,haltUntilMs:t+6e5}}function Sl(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 El(e){let n=e.workers.map(Km),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:qm({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function Pl(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 Km(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 Vm(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 qm(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Vm(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${vl(e.held,"Worker")} across ${vl(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 vl(e,n){return`${e} ${n}${e===1?"":"s"}`}function Zr(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 Gm,mkdir as Jm,readFile as Qm,rm as zm,writeFile as Ym}from"node:fs/promises";import{dirname as jl,join as Ll}from"node:path";import{tmpdir as Dl}from"node:os";var Xm="redskilled.machine.claim.toon",Zm="REDSKILLED_MACHINE_DIR",eh=8,be=class extends Error{constructor(t,r,o){super(th(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},Ol;function $l(){return Ol??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},Ol}function nh(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[Zm]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||Dl():Dl();return Ll(o,`redskilled-${e.machineIdHash}`)}function bt(e){return Ll(nh(e),Xm)}function _t(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??U;async function i(){let l;try{l=await Qm(e,"utf8")}catch(p){if(p.code==="ENOENT"||eo(p))return;throw p}let d=oh(l);return ih(d)?d:void 0}function s(l,d){return{version:1,scope:"machine",pid:l.pid,start_time:l.startTime,uid:l.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}async function a(){try{return await zm(e,{force:!0}),!0}catch(l){if(eo(l))return!1;throw l}}return{claimPath:e,read:i,async claim(l){await Jm(jl(e),{recursive:!0,mode:1023})!=null&&await Gm(jl(e),1023).catch(()=>{});let p=!1;for(let u=0;u<eh;u+=1){let f=s(l,r());try{return await Ym(e,rh(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:p,claim:f}}catch(h){if(h.code!=="EEXIST"){if(eo(h))return{claimed:!1,reason:"stale-claim-not-reapable"};throw h}}let m=await i();if(!m){if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable"};p=!0;continue}if(Al(m,l,n.socketPath))return{claimed:!0,reaped:p,claim:m};if(await o(m.pid))return{claimed:!1,reason:"held",claim:m};if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable",claim:m};p=!0}return{claimed:!1,reason:"contended"}},async release(l){let d=await i();return!d||!Al(d,l,n.socketPath)?!1:await a()}}}function Il(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 Tl(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 th(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 eo(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function Al(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function rh(e){return`${M(e,{keyedMapCollapse:!0})}
63
- `}function oh(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Y(n)}catch{return null}}}function ih(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 sh=["worker_id","slot","workspace_path","log_path"],no=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${sh.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},lh=/\{\{([a-z_]+)\}\}/g;function ah(e,n){let t=(s,a)=>s.replace(lh,(l,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 no(d,a)}}),r=e.argv.map((s,a)=>t(s,`argv word ${a}`)),o={};for(let[s,a]of Object.entries(e.env??{}))o[s]=t(a,`env entry ${JSON.stringify(s)}`);let i=e.log_path==null?void 0:t(e.log_path,"the log path");return{argv:r,env:o,...i==null||i===""?{}:{log_path:i}}}function Nl(e,n,t){let r=ah(e,n),o=r.log_path??n.log_path,[i,...s]=r.argv;if(i===void 0||i==="")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:i,args:s,env:r.env}}function to(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 ro(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 oo(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 dh=3e5,ch=.5,so=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 Cl(e,n){if(n.held!=null)throw new so(n.held);let t=io(e.project_label,"a project label"),r=io(e.selector,"a selector"),o=to(e.argv,t),i=oo(e.env,t),s=ro(e.log_path,t),a=io(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 l=e.renew_within_ms??dh;if(!Number.isFinite(l)||l<=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:a,env:i,...s==null?{}:{log_path:s},target:e.target,registered_at:new Date(d).toISOString(),renew_within_ms:l,renew_by:new Date(d+l).toISOString(),renewed_at:new Date(d).toISOString(),renewals:0,launch_revision:0}}var wt=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 Ml(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:to(n.launch.argv,e.project_label),env:oo(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},i=n.launch==null?e.log_path:ro(n.launch.log_path,e.project_label),{log_path:s,...a}=e;return{...a,...i==null?{}:{log_path:i},...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1}}function Wl(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),i=n.queue,s=i!=null&&i.outcome==="counted"?i.depth:null,a=s!=null&&s>0?"open-work":o>0?"live-worker":null;if(a==null){let l=s===0?"drained":"uncounted";return{registration:e,verdict:l,detail:l==="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:a},verdict:a,detail:a==="open-work"?`project ${r} has ${s} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function uh(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function Hl(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=i=>Number.isFinite(i)&&n-i<=e.renew_within_ms*ch;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 Fl(e,n){let t=[],r=[];for(let o of e)(uh(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function lo(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.env===void 0||ph(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 ph(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function io(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var fh={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 Ul(e){return`worker-${e}`}function Bl(e){let n=fh[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 Jl(e){return{generated_at:e.now,hour:Kl("hour",36e5,e),day:Kl("day",864e5,e)}}function xt(e,n,t){let r=En(t.now),o=t.retentionMs??864e5,i=t.limit??8192,s=e.filter(a=>{let l=En(n(a));return l==null?!1:r==null||r-l<=o});return s.length<=i?s:s.slice(s.length-i)}function Kl(e,n,t){let r=En(t.now),o=r==null?null:r-n,i=e==="hour"?"1h":"24h",s=t.observations.map(u=>({observation:u,at:En(u.observed_at)})).filter(u=>u.at!=null&&Gl(u.at,o,r)).sort((u,f)=>u.at-f.at),a=t.outcomes.map(u=>En(u.ts)).filter(u=>u!=null&&Gl(u,o,r)),l=Vl(s,u=>u.tokens,"tokens",i),d=Vl(s,u=>u.tools,"tools",i),p=[];return s.length===0?p.push("worker-vitals"):(l.samples===0&&p.push("worker-vitals.tokens"),d.samples===0&&p.push("worker-vitals.tools")),a.length===0&&p.push("worker-outcomes"),{window:e,window_ms:n,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:l,tools_per_min:d,issues_per_hour:mh(a.length,n,i),runner_share:ql("runner",s,u=>u.runner,i),model_share:ql("model",s,u=>u.model,i),unavailable:p}}function Vl(e,n,t,r){let o=new Map,i=0;for(let d of e){let p=n(d.observation);if(p==null||!Number.isFinite(p))continue;i+=1;let u=o.get(d.observation.worker_id)??[];u.push({at:d.at,count:p}),o.set(d.observation.worker_id,u)}if(i===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${r}`,samples:0};let s=0,a=null,l=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],h=d[f];m==null||h==null||(s+=Math.max(0,h.count-m.count))}let p=d[0],u=d[d.length-1];p!=null&&(a=a==null?p.at:Math.min(a,p.at)),u!=null&&(l=l==null?u.at:Math.max(l,u.at))}return a==null||l==null||l<=a?{value:null,absent_reason:`the last ${r} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:i}:{value:s/((l-a)/6e4),absent_reason:null,samples:i}}function mh(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 ql(e,n,t,r){let o=new Map;for(let d of n){let p=t(d.observation);p!=null?o.set(d.observation.worker_id,p):o.has(d.observation.worker_id)||o.set(d.observation.worker_id,null)}let i=new Map,s=0,a=0;for(let d of o.values()){if(d==null){a+=1;continue}s+=1,i.set(d,(i.get(d)??0)+1)}let l=[...i.entries()].map(([d,p])=>({key:d,worker_count:p,share:p/s})).sort((d,p)=>p.worker_count-d.worker_count||d.key.localeCompare(p.key));return{dimension:e,attributed_workers:s,unattributed_workers:a,shares:l,absent_reason:l.length>0?null:o.size===0?`no Worker was observed in the last ${r}`:`no Worker published a ${e} in the last ${r}`}}function Gl(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function En(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}import{execFileSync as hh}from"node:child_process";import{existsSync as gh,readFileSync as St,readdirSync as yh}from"node:fs";import{dirname as kh,join as $e}from"node:path";function Pn(e){let n=vn(e),t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let i=Ye(o);return i==null?null:{name:r,declared:o,bytes:i}}return null}function Ql(e){let n=[],t=[];for(let r of e.workers){let o=Pn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(vn(r).memory_max??vn(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 i=e.rss[r.worker_id];if(typeof i!="number"||!Number.isFinite(i)){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(!(i<=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(Rh(r,o,i))}}return{terminations:n,unenforceable:t}}function Rh(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 bh=4096;function zl(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return r;let o={},i={},s={},a=wh(e,t,n);for(let[u,f]of a){let m=vh(f);m!=null&&(o[u]=m.memoryBytes,m.cpuSeconds!=null&&(i[u]=m.cpuSeconds),s[u]="cgroup")}let l=e.filter(u=>s[u.worker_id]==null);if(l.length===0)return{rss:o,cpu_seconds:i,sources:s};let d=jh(t,n);if(d.size===0)return{rss:o,cpu_seconds:i,sources:s};let p=new Map;for(let u of d.values()){let f=p.get(u.ppid);f?f.push(u.pid):p.set(u.ppid,[u.pid])}for(let u of l){if(!d.has(u.pid))continue;let f=0,m=0,h=[u.pid],b=new Set;for(;h.length>0;){let k=h.pop();if(b.has(k))continue;b.add(k);let w=d.get(k);if(w){f+=w.rssBytes,m+=w.cpuSeconds;for(let j of p.get(k)??[])h.push(j)}}o[u.worker_id]=f,i[u.worker_id]=m,s[u.worker_id]="process-tree"}return{rss:o,cpu_seconds:i,sources:s}}var _h="/sys/fs/cgroup";function wh(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let i=t.cgroupRoot??_h,s=e.filter(l=>l.unit!=null&&l.unit!=="");if(s.length===0)return r;let a=xh(i,t);for(let l of s)for(let d of a){let p=$e(d,l.unit);if(gh($e(p,"memory.current"))){r.set(l.worker_id,p);break}}return r}function xh(e,n){let t=n.selfCgroupPath??Sh(),r=[],o=a=>{r.includes(a)||r.push(a)},i=t;for(;i!=null&&i!==""&&i!=="/"&&i!==".";){o($e(e,i));let a=kh(i);if(a===i)break;i=a}o(e);let s=n.uid??process.getuid?.();return s!=null&&o($e(e,"user.slice",`user-${s}.slice`,`user@${s}.service`,"app.slice")),r}function Sh(){try{for(let e of St("/proc/self/cgroup","utf8").split(`
64
- `))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function vh(e){let n;try{n=St($e(e,"memory.current"),"utf8")}catch{return null}let t=Number(n.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:Eh(e)}}function Eh(e){let n;try{n=St($e(e,"cpu.stat"),"utf8")}catch{return null}return Ph(n)}function Ph(e){for(let n of e.split(`
65
- `)){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 jh(e,n){return n.procRoot!=null||e==="linux"?Ih(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?Lh(Dh(n.psTable)):new Map}function Dh(e){try{return(e??Oh)()}catch{return""}}function Oh(){return hh("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Ah=1024;function Lh(e){let n=new Map;for(let t of e.split(`
66
- `)){let r=t.trim().split(/\s+/);if(r.length!==4)continue;let[o,i,s]=r.slice(0,3).map(Number);if(![o,i,s].every(l=>l!=null&&Number.isSafeInteger(l)&&l>=0))continue;let a=$h(r[3]);a!=null&&n.set(o,{pid:o,ppid:i,rssBytes:s*Ah,cpuSeconds:a})}return n}function $h(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,i=1;for(let s=r.length-1;s>=0;s--){let a=Number(r[s]);if(!Number.isFinite(a)||a<0||r[s]==="")return null;o+=a*i,i*=60}return o}function Ih(e){let n=new Map,t;try{t=yh(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=St($e(e,r,"stat"),"utf8")}catch{continue}let i=Nh(o);i&&n.set(i.pid,{pid:i.pid,ppid:i.ppid,rssBytes:i.rssPages*bh,cpuSeconds:i.cpuTicks/Th})}return n}var Th=100;function Nh(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]),i=Number(r[11]),s=Number(r[12]),a=Number(r[21]);return!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||!Number.isFinite(a)||!Number.isFinite(i)||!Number.isFinite(s)?null:{pid:t,ppid:o,rssPages:Math.max(0,a),cpuTicks:Math.max(0,i)+Math.max(0,s)}}function Yl(e){return e==="single-object"?"rest":"graphql"}function L(e,n,t,r,o){return{key:e,kind:"read",cardinality:n,surface:o??Yl(n),budget:t,...o?{only:o}:{},why:r}}function F(e,n,t,r){return{key:e,kind:"write",cardinality:"single-object",surface:n,budget:t,why:r}}var Xl=[L("issue view","single-object","rest","one issue by number; REST answers it in one request against the idle pool"),L("pr view","single-object","rest","one pull request by number, polled per Worker per iteration"),L("repo view","single-object","rest","one repository's own metadata"),L("run view","single-object","rest","one Actions run; the Actions API has no GraphQL surface either way"),L("release view","single-object","rest","one release by tag"),L("pr diff","single-object","rest","one pull request's diff, served by a REST media type"),L("issue list","multi-node","graphql","a connection of issues; one GraphQL query beats N REST pages"),L("pr list","multi-node","graphql","a connection of pull requests; one GraphQL query beats N REST pages"),L("pr checks","multi-node","graphql","every check context on one commit, which is a connection, not an object"),L("release list","multi-node","rest","Releases have no GraphQL connection gh reads; REST pages them","rest"),L("run list","multi-node","rest","the Actions API has no GraphQL surface, so a listing draws the request pool","rest"),L("label list","multi-node","graphql","a connection of labels inside one repository"),L("issue list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),L("pr list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),L("search issues","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),L("search prs","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),L("search repos","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),L("api graphql","multi-node","graphql","the caller wrote the query; `gh api graphql` is GraphQL by construction"),L("api rest","single-object","rest","any `gh api <path>` that is not `graphql` is a REST request"),F("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),F("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),F("issue close","graphql","graphql","gh closes with the closeIssue mutation"),F("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),F("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),F("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),F("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),F("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),F("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),F("pr close","graphql","graphql","gh closes with a GraphQL mutation"),F("pr edit","graphql","graphql","gh edits with GraphQL mutations"),F("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),F("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),F("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],Ch=new Map(Xl.map(e=>[e.key,e]));function Zl(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 ao(e){let n=Zl(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 vt=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(n){let t=ao(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 ea(e){return Ch.get(ao(e))??null}function na(e){let n=ea(e);if(!n)throw new vt(e);return n}function co(e){return na(e).surface}var Mh=["api","graphql"],Wh=co(Mh);function Hh(e,n="https://api.github.com"){return e==="graphql"?`${n}/graphql`:n}var ta=100,fo=6e4,Fh=2*fo,Uh=7*24*60*60*1e3,uo=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 mo(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new uo(t.project_label,t.token_ref,n)}function Bh(e,n={now:new Date(0).toISOString()}){qh(e);let t=n.closedWindowMs??Uh,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(),i=e.map((l,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:l}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { remaining resetAt }",...i.flatMap(({alias:l,search_alias:d,project:p})=>{let u=JSON.stringify(p.owner),f=JSON.stringify(p.name),m=JSON.stringify(`repo:${p.owner}/${p.name} is:closed closed:>=${o}`);return[` ${l}: repository(owner: ${u}, 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(`
67
- `),aliases:i,closed_since:o}}function Kh(e,n,t){let r=Xe(n),o=Xe(r.data),i=Array.isArray(r.errors)?r.errors.map(Xe):[],s=Gh(o.rateLimit,i),a=e.aliases.map(({alias:l,search_alias:d,project:p})=>{let u=p.owner+"/"+p.name,f=o[l],m=i.find(h=>ra(h.path,l)||ra(h.path,d));if(da(f)){let h=oa(f.open_pull_requests),b=oa(f.open_issues),k=Jh(o[d]);if(h!=null&&b!=null&&k!=null)return{project_label:p.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:h,open_issues:b,recently_closed:k},detail:`counted ${u} for project ${JSON.stringify(p.project_label)}`}}return s.exhausted||aa(m)?{project_label:p.project_label,repository:u,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${u} answered, so this project has no counts rather than zero counts${s.reset_at==null?"":`; the quota resets at ${s.reset_at}`}`}:{project_label:p.project_label,repository:u,outcome:"unreachable",counts:null,detail:`${u} is not reachable with the host token: ${po(m?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:a.length,rate_limit:s,projects:a}}function Vh(e){return{version:1,fetched_at:e,request_count:0,project_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}async function ia(e){if(e.projects.length===0)return Vh(e.now);mo(e.projects,e.hostTokenRef);let n=Bh(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return Kh(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},projects:e.projects.map(i=>({project_label:i.project_label,repository:`${i.owner}/${i.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${i.owner}/${i.name} answered: ${r}`}))}}}function sa(e){let n=e.stalenessMs??Fh,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},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),i=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,s=i==null||i>n;return{version:1,fetched_at:t.fetched_at,age_ms:i,threshold_ms:n,stale:t.projects.length>0&&s,request_count:t.request_count,rate_limit:t.rate_limit,projects:t.projects.map(a=>({...a,fetched_at:t.fetched_at,age_ms:i,stale:s})),reason:t.projects.length===0?"the daemon polls no repository, so there are no counts to age":i==null?"these counts carry no readable instant, so they cannot be presented as current":s?`these counts are ${i}ms old, past the ${n}ms window`:`fetched ${i}ms ago, within the ${n}ms window`}}function la(e){let n=e.endpoint??Hh(Wh),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 i=o.headers.get("x-ratelimit-remaining"),s=o.status===429||i==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(s?": the host token's rate limit is spent":""))}return await o.json()}}function qh(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>ta)throw new Error(`redskilled activity fetch spans at most ${ta} 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 Gh(e,n){let t=Xe(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,i=n.some(aa);return{remaining:r,reset_at:o,exhausted:i||r===0}}function aa(e){if(e==null)return!1;let n=po(e.type),t=po(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function ra(e,n){return Array.isArray(e)&&e.includes(n)}function oa(e){let n=Xe(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function Jh(e){let n=Xe(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Xe(e){return da(e)?e:{}}function da(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function po(e){return typeof e=="string"?e:""}var Qh=3e4,zh=4;function ca(e){let n=e.stalenessMs??Qh,t=jn(e.now),r=e.sampledAt==null?null:jn(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),i=o!=null&&o<=n,s=new Set(e.reattachedWorkerIds??[]),a=e.hostState.workers.map(f=>Zh(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:i,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:s.has(f.worker_id)?"reattached":"running"})),l=a.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=a.length-l.length,p=a.reduce((f,m)=>f+(m.vitals.rss_bytes??0),0),u=kt(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:rg({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:a.length,measuredCount:d,unmeasured:l}),host:{worker_count:a.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:u,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:p,measured_worker_count:d,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:u.memory_bytes/e.ceiling.memory_bytes},projects:tg(a),known_projects:ng(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,m)=>f.localeCompare(m)),workers:a,repository_activity:sa({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:Yh(e.deaths,e.recentDeathLimit??zh)},engine:Xh(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function Yh(e,n){let t=[...e].sort((o,i)=>(jn(i.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 Xh(e){let n=e.upgrade,t=n?.running_version??e.daemon_version,r=n?.published_version??null,o=n?.newest_published_version??null,i=(n?.newer_published??0)>0,s=(n?.major_held??0)>0;return{running_version:t,published_version:r,newer_published:i,major_held:s,current:r==null&&o==null?null:!i&&!s}}function Zh(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=Pn(e),i=e.budget?.memory_max??e.budget?.memory_high??null,s=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||s==null?null:Math.max(0,n.nowMs-s),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??i,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:eg(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function eg(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 ng(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);return[...n].sort((t,r)=>t.localeCompare(r))}function tg(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 rg(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}var $={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function ua(e,n=$){let t=cg(e,n),r=ag(e,n),o=dg(e,n),i=ug(e,n,r,t),s=sg(n,r,o),a={detail:"host",line:i};for(let u of s){let f=_g(i,lg(u,n,r,o),n.separator);if(a={detail:u,line:f},wg(f)<=n.maxWidth)break}let l=ko(a.line,n.maxWidth),d=n.verbose&&a.detail==="workers"?yg(r,n):[],p=r.length>0?"workers":"host";return{version:1,line:l,lines:[l,...d],verbose:n.verbose,mode:n.mode,project:n.project,project_match:t,detail:a.detail,degraded:a.detail!==p||l!==a.line,stale:e.staleness.stale,generated_at:e.generated_at}}function pa(e){let n=e.options??$,t=ko(ig,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}}var og="!unregistered",go="\u21E1",Et="\u2020",ig="redskilled unreachable \u2014 Worker state unknown";function sg(e,n,t){let r=[];return n.length>0&&n.length<=e.maxWorkers&&r.push("workers"),e.mode==="global"&&t.length>0&&t.length<=e.maxProjects&&r.push("projects"),r.push("host"),r}function lg(e,n,t,r){return e==="workers"?t.map(o=>gg(o,n)):e==="projects"?r.map(bg):[]}function ag(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function dg(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function cg(e,n){return yo(e,n.project)}function yo(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":"name-only":"unregistered"}function ug(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(ho(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(ho(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(ho(e,n)),o.push(og)):o.push(mg(n.project,r)),o.push(pg(e));let i=fg(e);return i!=null&&o.push(i),e.staleness.stale&&o.push(hg(e)),o.join(" ")}function pg(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${go}`}function fg(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Et}${n.count} ${n.latest.sender_class}`}function mg(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 ho(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,i)=>o+i.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${X(t)}/${X(r)}`:X(t)}function hg(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function gg(e,n){let t=fa(e,n),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?X(r):`${X(r)}/${X(e.budget.bytes)}`;return`${t} ${o}`}function yg(e,n){let t=[];for(let r of e){let o=Rg(r.log.last_line);o!=null&&t.push(ko(` ${kg} ${fa(r,n)}: ${o}`,n.maxWidth))}return t}var kg="\u21B3";function Rg(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}function fa(e,n){return n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function bg(e){return`${e.project_label} ${e.worker_count}w ${X(e.observed_rss_bytes)}`}function _g(e,n,t){return[e,...n].join(t)}function wg(e){return[...e].length}function ko(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}function X(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]}`}var Ro={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},xg=["runner","model","effort","origin","issue","phase","step","heartbeat"],Sg=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function ma(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...Ro};for(let r of xg){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of Sg){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}var Pt=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],Ze={mode:"local",project:null,maxWidth:200,maxRows:16};var vg=" ",ha="\u2588",Eg="\u25B6",Pg="\u2717",jg="\u2591";function ga(e,n=Ze){let t=yo(e,n.project),r=Dg(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),i=o.map(u=>Og(u,n)),s=Wg(i),a=o.map((u,f)=>({worker_id:u.worker_id,project_label:u.project_label,mine:n.project!=null&&u.project_label===n.project,cells:i[f],line:Dn(Hg(i[f],s),n.maxWidth)})),l=Lg(e,n,r,t),d=r.length-o.length,p=[l.line,...a.map(u=>u.line)];return d>0&&p.push(Dn(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),p.push(...Ig(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Pt,header:l,rows:a,lines:p,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Dg(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Og(e,n){let t=e.display??Ro,r=[t.runner,t.model,t.effort].filter(o=>!!o).join(" ");return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:r===""?"":`run=${r}`,org:t.origin==null?"":`org=${t.origin}`,iss:t.issue==null?"":`iss=${t.issue}`,bar:Ag(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:Mg(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:Cg(t.added,t.removed),tks:t.tokens==null?"":`tks=${ya(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function Ag(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 ha.repeat(Math.floor(n));let o=e.failed?Pg:Eg;return`${ha.repeat(r)}${o}${jg.repeat(Math.floor(n)-r-1)}`}function Lg(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(w=>w.project_label===n.project),i={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},s={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},a=Ng(t),l=o?.repository??n.project,d=e.engine??null,p=d?.running_version??e.daemon.daemon_version,u=e.deaths??null,f=e.metrics??null,m=[`\xBB ${l??"host"} v${p}${d!=null&&d.current===!1?go:""}`];r==="unregistered"&&m.push("!unregistered"),r==="name-only"&&m.push("!lapsed"),a!=null&&m.push(a),m.push(`wrk=${t.length}/${e.host.worker_count}`),m.push(s.worker_ceiling==null?"slots=\u221E":`slots=${s.worker_count}/${s.worker_ceiling}`),m.push(Tg(s)),i.open_pull_requests!=null&&m.push(`prs=${i.open_pull_requests}`),i.recently_closed!=null&&m.push(`cpr=${i.recently_closed}`),i.open_issues!=null&&m.push(`iss=${i.open_issues}`),i.stale&&m.push("!counts stale");let h=f==null?null:$g(f.hour);if(h!=null&&m.push(h),u!=null&&u.count>0&&u.latest!=null&&m.push(`${Et}${u.count} ${u.latest.sender_class}`),e.staleness.stale){let w=e.staleness.age_ms;m.push(w==null?"!unmeasured":`!stale ${Math.round(w/1e3)}s`)}let b=m.join(" \xB7 "),k=h!=null&&_o(b)>n.maxWidth?m.filter(w=>w!==h).join(" \xB7 "):b;return{repo:l,project:n.project,project_match:r,version:p,engine:d,deaths:u,metrics:f,model:a,windows:s,counts:i,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:Dn(k,n.maxWidth)}}function $g(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${bo(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${bo(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${bo(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 Ig(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(i=>Dn(`${Et} ${i.kind} ${i.id} pid=${i.pid} ${i.sender_class}/${i.confidence} phase=${i.last_phase}`+(i.signal==null?"":` signal=${i.signal}`)+(i.evidence==null?"":` \u2014 ${i.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(Dn(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function Tg(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${X(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${X(e.memory_used_bytes)}/${X(e.memory_ceiling_bytes)}${n}`}function Ng(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 Cg(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 ya(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 bo(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return ya(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 Mg(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 Wg(e){let n=Object.fromEntries(Pt.map(t=>[t,0]));for(let t of e)for(let r of Pt)n[r]=Math.max(n[r],_o(t[r]));return n}function Hg(e,n){return Pt.filter(r=>n[r]>0).map(r=>Fg(e[r],n[r])).join(vg).replace(/\s+$/,"")}function Fg(e,n){return e+" ".repeat(Math.max(0,n-_o(e)))}function _o(e){return[...e].length}function Dn(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}var jt=1;async function On(e,n){return await ut(e,n,"redskilled daemon")}function ka(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.line=="string"&&Array.isArray(n.lines)&&n.lines.every(t=>typeof t=="string")&&typeof n.verbose=="boolean"&&(n.mode==="local"||n.mode==="global")&&(n.project===null||typeof n.project=="string")&&typeof n.detail=="string"&&(n.project_match===void 0||typeof n.project_match=="string")&&typeof n.degraded=="boolean"&&typeof n.stale=="boolean"&&typeof n.generated_at=="string"}function Ra(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:jt,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:Kg(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:cl(n,{hostCeilingBytes:e.hostCeilingBytes??null}),upgrade:Vg(e)}}function Kg(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(i=>[i.project_label,i]));return[...e.registrations??[]].map(i=>{let s=o.get(i.project_label);return{...i,...t?{renewal:Hl(i,n)}:{},...r==null||s==null?{}:{last_poll:{at:r.fetched_at,outcome:s.outcome,depth:s.depth,request_count:r.request_count,detail:s.detail}}}}).sort((i,s)=>i.project_label.localeCompare(s.project_label))}function Vg(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 ba(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)&&ul(n.budget_accounting)&&(n.scope===void 0||Tl(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(lo))&&(n.upgrade===void 0||qg(n.upgrade))}function qg(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||Gg(n.major_hold))}function Gg(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 At}from"node:child_process";import{existsSync as Eo}from"node:fs";import{delimiter as ty,join as Oa}from"node:path";import{join as _a}from"node:path";import{existsSync as Jg}from"node:fs";import{createRequire as Qg}from"node:module";var wa="redskilled-job-object.node",Ie=100;function en(e){return{available:!1,reason:e}}function zg(e,n,t){return[_a(t,"prebuilds",`${e}-${n}`,wa),_a(t,"native","build","Release",wa)]}function xa(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return en(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??Xg(),o=e.exists??Jg,i=zg(n,t,r),s=i.find(d=>o(d));if(s==null)return en(`no Job Object addon was found for ${n}-${t} (looked in ${i.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let a=e.requireFn??Qg(import.meta.url),l;try{l=a(s)}catch(d){return en(`the Job Object addon at ${s} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return Yg(l)?{available:!0,binding:l}:en(`the Job Object addon at ${s} does not export createJobObject, so it cannot be the native reach`)}function Yg(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Xg(){return new URL("..",import.meta.url).pathname}function Sa(e){let n=e??{},t=[],r=Zg(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<Ie?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 ${Ie}, 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 Zg(e){return Pn({budget:e})}var Dt=5,va=19;function wo(e){return{available:!1,reason:e}}var ey="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 Pa(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=Dt;else if(t.cpu_weight<Ie){let a=Math.round(va*(Ie-t.cpu_weight)/Ie);o=Math.min(va,Math.max(Dt,a))}else o=Dt,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${Ie}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Dt}`);let i=Ea(t.max_processes);i==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 s=Ea(t.cpu_seconds);return s==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}:{},...i!=null?{max_processes:i}:{},...s!=null?{cpu_seconds:s}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:ey,...r.length>0?{note:r.join("; ")}:{}}}function ja(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 ${ny(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
68
- `),e.command,...e.args]}function Da(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 xo(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 Ea(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function ny(e){return`'${e.replace(/'/g,"'\\''")}'`}var Aa="REDSKILLED_PLACEMENT",Ot="red-worker",So="/bin/sh";function La(e=process.env,n=process.platform){let t=wo(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:xa({platform:n}),posix:t};let r=en(`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:ry(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),i=o!==""&&Eo(Oa(o,"systemd","private"));return{platform:n,systemdRun:Na("systemd-run",e),userSession:i,jobObjects:r,posix:t}}function ry(e){return Eo(So)?{available:!0,shell:So,nice:Na("nice",e)}:wo(`no POSIX shell was found at ${So}, so there is nothing to apply rlimits or priority in`)}function $a(e=process.env){let n=(e[Aa]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function oy(e,n,t=Ot){return Ia(e,n,t).replace(/\.service$/,"")}function Ia(e,n,t=Ot){return`${vo(t,"red-worker",24)}-${vo(e,"project",32)}-${vo(n,"worker",32)}.service`}function Ta(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,i=e.target??{isolation:"transient-unit"},s=u=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:u,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Rn({scope:null,memory_ceiling:r,scope_degradation:u}),...o?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(i.isolation==="inherit")return s("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 s(`worker isolation disabled by ${Aa}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return sy(e,n,t,r,o,s);if(e.probes.platform==="darwin")return iy(e,n,t,r,s);if(e.probes.platform!=="linux")return s(`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 s("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 s("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 a=Ia(e.projectLabel,e.workerId,i.unit_prefix),l=["--user","--collect","--quiet","--wait",`--unit=${a}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&l.push("--pipe"),t.memory_high!=null&&l.push(`--property=MemoryHigh=${t.memory_high}`),t.memory_max!=null&&l.push(`--property=MemoryMax=${t.memory_max}`),t.cpu_weight!=null&&l.push(`--property=CPUWeight=${t.cpu_weight}`);let d=Rn({scope:a,memory_ceiling:r,scope_degradation:null});for(let[u,f]of Object.entries({...e.env??{},...d}))l.push(`--setenv=${u}=${f}`);let p=xo(e.budget);return{isolated:!0,backend:"transient-unit",unit:a,command:e.probes.systemdRun,args:[...l,"--",e.command,...n],budget:t,...r!=null?{memoryCeiling:r}:{},environment:d,...p!=null?{budgetWarning:p}:{}}}function iy(e,n,t,r,o){let i=e.probes.posix;if(!i.available)return o(`POSIX limit 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 s=Pa(t,{canRenice:i.nice!=null}),a=t.memory_high!=null||t.memory_max!=null,l=Da(s);return{isolated:!1,backend:"posix-limits",command:i.shell,args:ja({limits:s,nice:i.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:s,warning:l,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Rn({scope:null,memory_ceiling:r,scope_degradation:l}),...a?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+s.memory_ceiling_reason}:{}}}function sy(e,n,t,r,o,i){let s=e.probes.jobObjects;if(!s.available)return i(`Job Object 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 a=Sa(t),l=oy(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...n],cwd:e.workspacePath,job:{name:l,limits:a},budget:t,...r!=null?{memoryCeiling:r}:{},environment:Rn({scope:l,memory_ceiling:r,scope_degradation:null}),...ly(o&&a.note!=null?`${a.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,xo(e.budget))}}function ly(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function Na(e,n){for(let t of(n.PATH??"").split(ty)){if(!t)continue;let r=Oa(t,e);if(Eo(r))return r}return null}function vo(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function Po(e,n){let t=[],r=[];for(let o of e){let i=!1;try{i=await n(o)===!0}catch{i=!1}(i?t:r).push(o)}return{alive:t,dead:r}}function Ca(e){return e.unit!=null&&e.unit!==""?ay(e.unit):U(e.pid)}function ay(e){let n=At("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var dy="REDSKILLED_UNIT_DISCOVERY",Ma="(unowned)";function Wa(e){let n=At("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 cy(e=process.env){let n=(e[dy]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Ha(e,n,t=process.env){return cy(t)&&e===n}function Fa(e=Ot){let n=At("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(`
69
- `).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function Ua(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:Ma,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 Ba(e){return e.project_label.trim()!==""?e:{...e,project_label:Ma,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 Ka(e){if(e.unit!=null&&e.unit!==""){let n=At("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 uy(e,n=50){if(Ja(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 py(e,n={}){let t=n.batchSize??50;if(Ja(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((s,a)=>({alias:`q${a}`,project:s}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...r.map(({alias:s,project:a})=>` ${s}: search(query: ${JSON.stringify(a.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
70
- `),aliases:r}}function fy(e,n){let t=An(n),r=An(t.data),o=Array.isArray(t.errors)?t.errors.map(An):[],i=hy(r.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=yy(r[a]);if(d!=null)return{project_label:l.project_label,outcome:"counted",depth:d,detail:`project ${JSON.stringify(l.project_label)} has ${d} item(s) matching its selector`};let p=o.find(u=>gy(u.path,a));return i.exhausted||Qa(p)?{project_label:l.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(l.project_label)} answered, so this queue has no depth rather than a depth of zero`+(i.reset_at==null?"":`; the quota resets at ${i.reset_at}`)}:{project_label:l.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(l.project_label)} could not be counted with the host token: ${jo(p?.message)||"the query returned no count for this selector"}`}}),rate_limit:i}}function my(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 qa(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 Ga(e){if(e.projects.length===0)return my(e.now);let n=e.batchSize??50,t=uy(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let i of t){let s=py(i,{batchSize:n});try{let a=await e.transport(s.query),l=fy(s,a);r.push(...l.projects),o=Va(o,l.rate_limit)}catch(a){let l=a instanceof Error?a.message:String(a),d=/rate limit|secondary rate|429/i.test(l);o=Va(o,{remaining:null,reset_at:null,exhausted:d});for(let p of i)r.push({project_label:p.project_label,outcome:d?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(p.project_label)} answered: ${l}`})}}return{version:1,fetched_at:e.now,request_count:t.length,project_count:r.length,batch_size:n,rate_limit:o,projects:r}}function Ja(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 Va(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 hy(e,n){let t=An(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(Qa)||r===0}}function Qa(e){return e==null?!1:jo(e.type)==="RATE_LIMITED"||/rate limit/i.test(jo(e.message))}function gy(e,n){return Array.isArray(e)&&e.includes(n)}function yy(e){let n=An(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function An(e){return ky(e)?e:{}}function ky(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jo(e){return typeof e=="string"?e:""}function za(e,n,t){let r=e?.rate_limit;if(r==null)return n;if(r.exhausted){let i=r.reset_at==null?Number.NaN:Date.parse(r.reset_at),s=Number.isFinite(i)?i-t+1e3:n*4;return Math.min(Ry,Math.max(n,s))}let o=r.remaining;return o==null?n:o<=by?Math.max(n,3e4):o<=_y?Math.max(n,2e4):n}var Ry=3e5,by=250,_y=1e3;import{randomUUID as Za}from"node:crypto";import{spawn as vy}from"node:child_process";import{closeSync as Ey,mkdirSync as Py,openSync as jy}from"node:fs";import{dirname as Dy}from"node:path";import{delimiter as Ya,dirname as wy}from"node:path";function xy(e,n=Ya){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function Sy(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=wy(n);return t===""||t==="."?null:t}function Xa(e,n=process.execPath,t=Ya){let r=xy(e,t),o=Sy(n);return o==null?r.join(t):[o,...r.filter(i=>i!==o)].join(t)}var Ln=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},Lt=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function Oy(e){if(e==null||e.trim()==="")return null;try{return Py(Dy(e),{recursive:!0}),jy(e,"a")}catch{return null}}function Ay(e){try{Ey(e)}catch{}}function Ly(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 Ln(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new Ln("redskilled worker spec args must be an array")}function $y(e){if(e==null)throw new Lt("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new Lt(e.reason,e)}function nd(e){let{spec:n,admission:t}=e;$y(t),Ly(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),i=(n.worker_id??e.workerId??Za()).trim()||Za(),s=e.probes??La(r),a=e.openLog===!1?null:Oy(n.log_path),l={...n.env??{},PATH:Xa(n.env?.PATH??r.PATH,e.execPath??process.execPath)},d=Ta({workerId:i,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:l,enabled:e.enabled??$a(r),probes:s,pipeOutput:a!==null}),u=(e.spawnFn??vy)(d.command,d.args,{...d.cwd!=null?{cwd:d.cwd}:{},detached:!0,stdio:a===null?"ignore":["ignore",a,a],env:d.backend==="transient-unit"?{...r}:{...r,...l,...d.environment}});if(a!==null&&Ay(a),u.pid==null)throw u.once("error",()=>{}),new Ln(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${i}`);let f=d.job!=null?Iy(d,s,u.pid):null;u.once("error",()=>{}),u.once("exit",(k,w)=>{try{f?.job?.close()}catch{}e.onExit?.(i,k,w)}),u.unref();let m=d.job!=null?f?.job!=null:d.isolated,h=[d.warning,f?.warning,d.budgetWarning].filter(k=>k!=null);return{worker:{worker_id:i,project_label:n.project_label,pid:u.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:h},admission:t,warnings:h,plan:d,child:u,...f?.job!=null?{job:f.job}:{}}}function Iy(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 i;try{i=n.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(s){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${ed(s)}. ${o}`}}try{i.assign(t)}catch(s){try{i.close()}catch{}return{warning:`Worker pid ${t} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${ed(s)}. ${o}`}}return{job:i}}function ed(e){return e instanceof Error?e.message:String(e)}import{open as Ty,stat as Ny}from"node:fs/promises";var Cy=16*1024;async function td(e,n=Cy){let t;try{t=(await Ny(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let i=await Ty(e,"r");try{let s=Buffer.alloc(r);await i.read(s,0,r,t-r),o=s.toString("utf8")}finally{await i.close()}}catch{return null}return My(o)}function My(e){let n=e.split(`
71
- `);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 Zy}from"node:child_process";import{existsSync as ek,readdirSync as nk}from"node:fs";import{dirname as tk,join as ad,resolve as rk}from"node:path";var Wy="<version>";function _e(e,n=[],t){let r=t&&t.trim().length>0?t.trim():Wy;return[`npx -y -p ${Le}@${r}`,e,...n].join(" ")}function Z(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 Do(e,n){let t=Z(e),r=Z(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var QS=4*60*60*1e3;fe();fe();import{spawnSync as Hy}from"node:child_process";import{mkdir as Fy,rm as Uy,writeFile as By}from"node:fs/promises";import{existsSync as Ky}from"node:fs";import{homedir as Vy}from"node:os";import{dirname as qy,join as Oo}from"node:path";var nn="redskilled.service",Ao="REDSKILLED_SUPERVISED",Gy="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function Jy(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||Oo(e.HOME?.trim()||Vy(),".config");return Oo(n,"systemd","user")}function Lo(e=process.env){return Oo(Jy(e),nn)}function rd(e,n={}){let t=n.env??process.env,r=ht(n.override??{},n.entryLookup??{}),o=[...r.args,...Ae(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:nn,unitPath:Lo(t),command:r.command,args:o,text:Qy(r.command,o,e)}}function Qy(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${Gy}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(zy).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Ao}=1"`,`Environment="REDSKILLED_SESSION=${od(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
72
- `)}function zy(e){return/[\s"'\\$%]/.test(e)?`"${od(e)}"`:e}function od(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function id(e,n={}){let t=n.writeFile??Yy,r=n.run??$o,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push($t("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push($t("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(i=>i.ok),steps:o}}async function sd(e={}){let n=e.removeFile??Xy,t=e.run??$o,r=Lo(e.env??process.env),o=[$t("disable",t,["systemctl","--user","disable","--now",nn])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push($t("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function ld(e={}){let n=e.exists??Ky,t=e.run??$o,r=Lo(e.env??process.env),o=n(r);return{unitName:nn,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",nn]).status===0,active:o&&t(["systemctl","--user","is-active",nn]).status===0,floor:"auto-spawn"}}function $t(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 Yy(e,n){await Fy(qy(e),{recursive:!0}),await By(e,n,{encoding:"utf8",mode:420})}async function Xy(e){await Uy(e,{force:!0})}function $o(e){let n=Hy(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 dd=75,ud=9e5,cd="redskilled-replacement-entry-unresolved",ok="REDSKILLED_NO_REGISTRY_PROBE",pd="REDSKILLED_BORN_BY_REPLACEMENT";function fd(e=process.env){return e[pd]==="1"}function md(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function hd(e){let n=e.running.trim();if($n(n))return null;let t=e.newest?.trim()??"",r=Z(t),o=Z(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:ik(r.major,e.supervised)}}function ik(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: ${_e("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 gd(e){let n=e.running.trim();if($n(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||Z(t)===null?{act:"hold",reason:"published-unknown"}:Do(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function $n(e){let n=e.trim();return Z(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function yd(e=process.env){return e[Ao]==="1"}var Io=class extends Error{code=cd;searched;constructor(n,t){super(`${cd}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
62
+ `).filter(gh).map(yh)}function Fl(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,mh(t)):n.delete(t.worker_id));return[...n.values()]}function mh(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 hh(e){return{...e}}function gh(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 yh(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:fe(e.project_label)??"",pid:Number(e.pid??0),workspace_path:fe(e.workspace_path)??"",log_path:fe(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:fe(e.unit),memory_high:fe(e.memory_high),memory_max:fe(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:fe(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:fe(e.signal),reason:fe(e.reason)}}function fe(e){return e==null||e===""?null:String(e)}function Bl(e){let n=[...e.projects].sort((s,a)=>s.project_label.localeCompare(a.project_label)),t=e.backoffUntilMs??null,r=t!=null&&e.nowMs<t,o=[],i=[];for(let s of n){let a=Math.max(0,e.live[s.project_label]??0),l=Object.prototype.hasOwnProperty.call(e.queue,s.project_label),d=l?e.queue[s.project_label]??null:null,p={project_label:s.project_label,queue_depth:d,target:s.target,live:a};if(r){o.push({...p,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 u=e.birthHaltUntilMs?.[s.project_label];if(u!=null&&e.nowMs<u){o.push({...p,outcome:"birth-halted",wanted:0,detail:`project ${JSON.stringify(s.project_label)} lost 3 Workers in a row inside 60000ms of birth, so it is not asked for another before ${new Date(u).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({...p,outcome:"queue-unknown",wanted:0,detail:l?`the last poll produced no depth for project ${JSON.stringify(s.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(s.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...p,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(s.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,s.target),d)-a);if(f===0){o.push({...p,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(s.project_label)} holds ${a} Worker(s) against a target of ${s.target} and a queue of ${d}, so it asks for none`});continue}o.push({...p,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(s.project_label)} holds ${a} Worker(s) against a target of ${s.target} and a queue of ${d}, so it asks for ${f} more`});for(let m=0;m<f;m+=1)(i[m]??(i[m]=[])).push({project_label:s.project_label,index:a+m,argv:s.argv,workspace_path:s.workspace_path})}return{intents:o,births:i.flat()}}function Hl(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}var St={shortLifeStreak:0,haltUntilMs:null};function Ul(e,n,t){if(n>=6e4)return St;let r=e.shortLifeStreak+1;return r<3?{shortLifeStreak:r,haltUntilMs:null}:{shortLifeStreak:r,haltUntilMs:t+6e5}}function Gl(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 Vl(e){let n=e.workers.map(kh),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:Rh({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function ql(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 kh(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 bh(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 Rh(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${bh(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${Kl(e.held,"Worker")} across ${Kl(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 Kl(e,n){return`${e} ${n}${e===1?"":"s"}`}function co(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 _h,mkdir as wh,readFile as xh,rm as Sh,writeFile as vh}from"node:fs/promises";import{dirname as Jl,join as Xl}from"node:path";import{tmpdir as Ql}from"node:os";var Eh="redskilled.machine.claim.toon",Ph="REDSKILLED_MACHINE_DIR",jh=8,_e=class extends Error{constructor(t,r,o){super(Oh(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},zl;function Zl(){return zl??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},zl}function Dh(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[Ph]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||Ql():Ql();return Xl(o,`redskilled-${e.machineIdHash}`)}function vt(e){return Xl(Dh(e),Eh)}function Et(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??H;async function i(){let l;try{l=await xh(e,"utf8")}catch(p){if(p.code==="ENOENT"||uo(p))return;throw p}let d=Th(l);return $h(d)?d:void 0}function s(l,d){return{version:1,scope:"machine",pid:l.pid,start_time:l.startTime,uid:l.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}async function a(){try{return await Sh(e,{force:!0}),!0}catch(l){if(uo(l))return!1;throw l}}return{claimPath:e,read:i,async claim(l){await wh(Jl(e),{recursive:!0,mode:1023})!=null&&await _h(Jl(e),1023).catch(()=>{});let p=!1;for(let u=0;u<jh;u+=1){let f=s(l,r());try{return await vh(e,Ah(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:p,claim:f}}catch(h){if(h.code!=="EEXIST"){if(uo(h))return{claimed:!1,reason:"stale-claim-not-reapable"};throw h}}let m=await i();if(!m){if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable"};p=!0;continue}if(Yl(m,l,n.socketPath))return{claimed:!0,reaped:p,claim:m};if(await o(m.pid))return{claimed:!1,reason:"held",claim:m};if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable",claim:m};p=!0}return{claimed:!1,reason:"contended"}},async release(l){let d=await i();return!d||!Yl(d,l,n.socketPath)?!1:await a()}}}function ea(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 na(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 Oh(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 uo(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function Yl(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function Ah(e){return`${M(e,{keyedMapCollapse:!0})}
63
+ `}function Th(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Y(n)}catch{return null}}}function $h(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 Lh=["worker_id","slot","workspace_path","log_path"],po=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${Lh.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},Ih=/\{\{([a-z_]+)\}\}/g;function Nh(e,n){let t=(s,a)=>s.replace(Ih,(l,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 po(d,a)}}),r=e.argv.map((s,a)=>t(s,`argv word ${a}`)),o={};for(let[s,a]of Object.entries(e.env??{}))o[s]=t(a,`env entry ${JSON.stringify(s)}`);let i=e.log_path==null?void 0:t(e.log_path,"the log path");return{argv:r,env:o,...i==null||i===""?{}:{log_path:i}}}function ta(e,n,t){let r=Nh(e,n),o=r.log_path??n.log_path,[i,...s]=r.argv;if(i===void 0||i==="")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:i,args:s,env:r.env}}function fo(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 mo(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 ho(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 Ch=3e5,Mh=.5,yo=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 ra(e,n){if(n.held!=null)throw new yo(n.held);let t=go(e.project_label,"a project label"),r=go(e.selector,"a selector"),o=fo(e.argv,t),i=ho(e.env,t),s=mo(e.log_path,t),a=go(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 l=e.renew_within_ms??Ch;if(!Number.isFinite(l)||l<=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:a,env:i,...s==null?{}:{log_path:s},target:e.target,registered_at:new Date(d).toISOString(),renew_within_ms:l,renew_by:new Date(d+l).toISOString(),renewed_at:new Date(d).toISOString(),renewals:0,launch_revision:0}}var Pt=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 oa(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:fo(n.launch.argv,e.project_label),env:ho(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},i=n.launch==null?e.log_path:mo(n.launch.log_path,e.project_label),{log_path:s,...a}=e;return{...a,...i==null?{}:{log_path:i},...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1}}function ia(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),i=n.queue,s=i!=null&&i.outcome==="counted"?i.depth:null,a=s!=null&&s>0?"open-work":o>0?"live-worker":null;if(a==null){let l=s===0?"drained":"uncounted";return{registration:e,verdict:l,detail:l==="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:a},verdict:a,detail:a==="open-work"?`project ${r} has ${s} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function Wh(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function sa(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=i=>Number.isFinite(i)&&n-i<=e.renew_within_ms*Mh;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 la(e,n){let t=[],r=[];for(let o of e)(Wh(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function ko(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.env===void 0||Fh(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 Fh(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function go(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var Bh={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 aa(e){return`worker-${e}`}function da(e){let n=Bh[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 ca(e){return e==="single-object"?"rest":"graphql"}function T(e,n,t,r,o){return{key:e,kind:"read",cardinality:n,surface:o??ca(n),budget:t,...o?{only:o}:{},why:r}}function B(e,n,t,r){return{key:e,kind:"write",cardinality:"single-object",surface:n,budget:t,why:r}}var ua=[T("issue view","single-object","rest","one issue by number; REST answers it in one request against the idle pool"),T("pr view","single-object","rest","one pull request by number, polled per Worker per iteration"),T("repo view","single-object","rest","one repository's own metadata"),T("run view","single-object","rest","one Actions run; the Actions API has no GraphQL surface either way"),T("release view","single-object","rest","one release by tag"),T("pr diff","single-object","rest","one pull request's diff, served by a REST media type"),T("issue list","multi-node","graphql","a connection of issues; one GraphQL query beats N REST pages"),T("pr list","multi-node","graphql","a connection of pull requests; one GraphQL query beats N REST pages"),T("pr checks","multi-node","graphql","every check context on one commit, which is a connection, not an object"),T("release list","multi-node","rest","Releases have no GraphQL connection gh reads; REST pages them","rest"),T("run list","multi-node","rest","the Actions API has no GraphQL surface, so a listing draws the request pool","rest"),T("label list","multi-node","graphql","a connection of labels inside one repository"),T("issue list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),T("pr list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),T("search issues","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("search prs","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("search repos","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("api graphql","multi-node","graphql","the caller wrote the query; `gh api graphql` is GraphQL by construction"),T("api rest","single-object","rest","any `gh api <path>` that is not `graphql` is a REST request"),B("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),B("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),B("issue close","graphql","graphql","gh closes with the closeIssue mutation"),B("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),B("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),B("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),B("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),B("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),B("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),B("pr close","graphql","graphql","gh closes with a GraphQL mutation"),B("pr edit","graphql","graphql","gh edits with GraphQL mutations"),B("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),B("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),B("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],Hh=new Map(ua.map(e=>[e.key,e]));function pa(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 bo(e){let n=pa(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 jt=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(n){let t=bo(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 fa(e){return Hh.get(bo(e))??null}function ma(e){let n=fa(e);if(!n)throw new jt(e);return n}function Ro(e){return ma(e).surface}var ga="rate_limit",ya={rest:"core",graphql:"graphql",search:"search"},me=["rest","graphql","search"];function Tt(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:[...me],detail:n??"no balance has been asked for yet, so none is known"}}var wo=15e3,Ze=.15,Ot=[{at_or_below_fraction:0,every_ms:wo,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:Ze,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"}],_o=2;function ka(e,n){let t=ha(e),r=ha(t.resources),o={rest:null,graphql:null,search:null},i=[];for(let a of me){let l=ya[a],d=r[l],p=Kh(a,l,d);o[a]=p,p==null&&i.push(a)}let s=me.length-i.length;return{version:1,origin:"asked",outcome:s>0?"asked":"unanswered",source:"GET /rate_limit",asked_at:n.askedAt,request_count:1,pools:o,unreported_pools:i,detail:s>0?`the token's own answer for ${s} of ${me.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function xo(e){try{let n=await e.transport();return ka(n,{askedAt:e.now})}catch(n){let t=n instanceof Error?n.message:String(n);return{...Tt(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function So(e){let n=null;for(let t of me){let r=e.pools[t];r!=null&&(n==null||r.fraction<n.fraction)&&(n=r)}return n}function $t(e,n){let t=So(e);if(t==null)return At(Ze).every_ms;let r=At(t.fraction);if(t.remaining>0)return r.every_ms;let o=Ra(n.now,t.reset_at);return o==null?r.every_ms:Math.max(wo,Math.min(r.every_ms,o))}function vo(e,n=Ze){return Math.ceil(e.limit*n)}function ba(e,n,t=Ze){let r=e.pools[n];return r==null?"unknown":r.remaining<=0?"spent":r.remaining<vo(r,t)?"reserved":"open"}function Eo(e){let n=e.reservedFraction??Ze,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:At(n).every_ms*_o,stale:!1,posture:"unknown",reserved_fraction:n,next_poll_ms:At(n).every_ms,pools:[],unreported_pools:[...me],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let r=$t(t,{now:e.now}),o=e.stalenessMs??r*_o,i=Ra(t.asked_at,e.now),s=t.outcome==="asked"&&(i==null||i>o),a=me.map(p=>t.pools[p]).filter(p=>p!=null),l=Gh(t,n),d=So(t);return{version:1,origin:"asked",outcome:t.outcome,asked_at:t.asked_at,age_ms:i,threshold_ms:o,stale:s,posture:l,reserved_fraction:n,next_poll_ms:r,pools:a,unreported_pools:t.unreported_pools,reason:s?`this balance is stale: asked ${i==null?"at an unreadable instant":`${i}ms ago`}, past the ${o}ms window, so the posture below is the last one the token confirmed and not the current one`:Uh(l,d,t,n)}}function Uh(e,n,t,r){if(n==null)return t.detail;let o=vo(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 Gh(e,n){let t="unknown";for(let r of me){if(e.pools[r]==null)continue;let o=ba(e,r,n);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function At(e){for(let n of Ot)if(e<=n.at_or_below_fraction)return n;return Ot[Ot.length-1]}function Kh(e,n,t){if(!_a(t))return null;let r=Dt(t.limit),o=Dt(t.remaining),i=Dt(t.used),s=Dt(t.reset);return r==null||r<=0||o==null?null:{pool:e,resource:n,limit:r,remaining:o,used:i??0,reset_at:s==null?"":new Date(s*1e3).toISOString(),fraction:o/r}}function Po(e){let n=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let r=await t(`${n}/${ga}`,{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 Ra(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 Dt(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function ha(e){return _a(e)?e:{}}function _a(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ea(e){return{generated_at:e.now,hour:wa("hour",36e5,e),day:wa("day",864e5,e)}}function Lt(e,n,t){let r=An(t.now),o=t.retentionMs??864e5,i=t.limit??8192,s=e.filter(a=>{let l=An(n(a));return l==null?!1:r==null||r-l<=o});return s.length<=i?s:s.slice(s.length-i)}function wa(e,n,t){let r=An(t.now),o=r==null?null:r-n,i=e==="hour"?"1h":"24h",s=t.observations.map(u=>({observation:u,at:An(u.observed_at)})).filter(u=>u.at!=null&&va(u.at,o,r)).sort((u,f)=>u.at-f.at),a=t.outcomes.map(u=>An(u.ts)).filter(u=>u!=null&&va(u,o,r)),l=xa(s,u=>u.tokens,"tokens",i),d=xa(s,u=>u.tools,"tools",i),p=[];return s.length===0?p.push("worker-vitals"):(l.samples===0&&p.push("worker-vitals.tokens"),d.samples===0&&p.push("worker-vitals.tools")),a.length===0&&p.push("worker-outcomes"),{window:e,window_ms:n,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:l,tools_per_min:d,issues_per_hour:qh(a.length,n,i),runner_share:Sa("runner",s,u=>u.runner,i),model_share:Sa("model",s,u=>u.model,i),unavailable:p}}function xa(e,n,t,r){let o=new Map,i=0;for(let d of e){let p=n(d.observation);if(p==null||!Number.isFinite(p))continue;i+=1;let u=o.get(d.observation.worker_id)??[];u.push({at:d.at,count:p}),o.set(d.observation.worker_id,u)}if(i===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${r}`,samples:0};let s=0,a=null,l=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],h=d[f];m==null||h==null||(s+=Math.max(0,h.count-m.count))}let p=d[0],u=d[d.length-1];p!=null&&(a=a==null?p.at:Math.min(a,p.at)),u!=null&&(l=l==null?u.at:Math.max(l,u.at))}return a==null||l==null||l<=a?{value:null,absent_reason:`the last ${r} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:i}:{value:s/((l-a)/6e4),absent_reason:null,samples:i}}function qh(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 Sa(e,n,t,r){let o=new Map;for(let d of n){let p=t(d.observation);p!=null?o.set(d.observation.worker_id,p):o.has(d.observation.worker_id)||o.set(d.observation.worker_id,null)}let i=new Map,s=0,a=0;for(let d of o.values()){if(d==null){a+=1;continue}s+=1,i.set(d,(i.get(d)??0)+1)}let l=[...i.entries()].map(([d,p])=>({key:d,worker_count:p,share:p/s})).sort((d,p)=>p.worker_count-d.worker_count||d.key.localeCompare(p.key));return{dimension:e,attributed_workers:s,unattributed_workers:a,shares:l,absent_reason:l.length>0?null:o.size===0?`no Worker was observed in the last ${r}`:`no Worker published a ${e} in the last ${r}`}}function va(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function An(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}import{execFileSync as Jh}from"node:child_process";import{existsSync as Qh,readFileSync as It,readdirSync as zh}from"node:fs";import{dirname as Yh,join as $e}from"node:path";function Tn(e){let n=On(e),t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let i=Xe(o);return i==null?null:{name:r,declared:o,bytes:i}}return null}function Pa(e){let n=[],t=[];for(let r of e.workers){let o=Tn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(On(r).memory_max??On(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 i=e.rss[r.worker_id];if(typeof i!="number"||!Number.isFinite(i)){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(!(i<=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(Xh(r,o,i))}}return{terminations:n,unenforceable:t}}function Xh(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 Zh=4096;function ja(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return r;let o={},i={},s={},a=ng(e,t,n);for(let[u,f]of a){let m=og(f);m!=null&&(o[u]=m.memoryBytes,m.cpuSeconds!=null&&(i[u]=m.cpuSeconds),s[u]="cgroup")}let l=e.filter(u=>s[u.worker_id]==null);if(l.length===0)return{rss:o,cpu_seconds:i,sources:s};let d=lg(t,n);if(d.size===0)return{rss:o,cpu_seconds:i,sources:s};let p=new Map;for(let u of d.values()){let f=p.get(u.ppid);f?f.push(u.pid):p.set(u.ppid,[u.pid])}for(let u of l){if(!d.has(u.pid))continue;let f=0,m=0,h=[u.pid],R=new Set;for(;h.length>0;){let k=h.pop();if(R.has(k))continue;R.add(k);let _=d.get(k);if(_){f+=_.rssBytes,m+=_.cpuSeconds;for(let j of p.get(k)??[])h.push(j)}}o[u.worker_id]=f,i[u.worker_id]=m,s[u.worker_id]="process-tree"}return{rss:o,cpu_seconds:i,sources:s}}var eg="/sys/fs/cgroup";function ng(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let i=t.cgroupRoot??eg,s=e.filter(l=>l.unit!=null&&l.unit!=="");if(s.length===0)return r;let a=tg(i,t);for(let l of s)for(let d of a){let p=$e(d,l.unit);if(Qh($e(p,"memory.current"))){r.set(l.worker_id,p);break}}return r}function tg(e,n){let t=n.selfCgroupPath??rg(),r=[],o=a=>{r.includes(a)||r.push(a)},i=t;for(;i!=null&&i!==""&&i!=="/"&&i!==".";){o($e(e,i));let a=Yh(i);if(a===i)break;i=a}o(e);let s=n.uid??process.getuid?.();return s!=null&&o($e(e,"user.slice",`user-${s}.slice`,`user@${s}.service`,"app.slice")),r}function rg(){try{for(let e of It("/proc/self/cgroup","utf8").split(`
64
+ `))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function og(e){let n;try{n=It($e(e,"memory.current"),"utf8")}catch{return null}let t=Number(n.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:ig(e)}}function ig(e){let n;try{n=It($e(e,"cpu.stat"),"utf8")}catch{return null}return sg(n)}function sg(e){for(let n of e.split(`
65
+ `)){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 lg(e,n){return n.procRoot!=null||e==="linux"?fg(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?ug(ag(n.psTable)):new Map}function ag(e){try{return(e??dg)()}catch{return""}}function dg(){return Jh("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var cg=1024;function ug(e){let n=new Map;for(let t of e.split(`
66
+ `)){let r=t.trim().split(/\s+/);if(r.length!==4)continue;let[o,i,s]=r.slice(0,3).map(Number);if(![o,i,s].every(l=>l!=null&&Number.isSafeInteger(l)&&l>=0))continue;let a=pg(r[3]);a!=null&&n.set(o,{pid:o,ppid:i,rssBytes:s*cg,cpuSeconds:a})}return n}function pg(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,i=1;for(let s=r.length-1;s>=0;s--){let a=Number(r[s]);if(!Number.isFinite(a)||a<0||r[s]==="")return null;o+=a*i,i*=60}return o}function fg(e){let n=new Map,t;try{t=zh(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=It($e(e,r,"stat"),"utf8")}catch{continue}let i=hg(o);i&&n.set(i.pid,{pid:i.pid,ppid:i.ppid,rssBytes:i.rssPages*Zh,cpuSeconds:i.cpuTicks/mg})}return n}var mg=100;function hg(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]),i=Number(r[11]),s=Number(r[12]),a=Number(r[21]);return!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||!Number.isFinite(a)||!Number.isFinite(i)||!Number.isFinite(s)?null:{pid:t,ppid:o,rssPages:Math.max(0,a),cpuTicks:Math.max(0,i)+Math.max(0,s)}}var gg=["api","graphql"],yg=Ro(gg);function kg(e,n="https://api.github.com"){return e==="graphql"?`${n}/graphql`:n}var Da=100,Oo=6e4,bg=2*Oo,Rg=7*24*60*60*1e3,jo=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 Ao(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new jo(t.project_label,t.token_ref,n)}function _g(e,n={now:new Date(0).toISOString()}){Sg(e);let t=n.closedWindowMs??Rg,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(),i=e.map((l,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:l}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { cost remaining resetAt }",...i.flatMap(({alias:l,search_alias:d,project:p})=>{let u=JSON.stringify(p.owner),f=JSON.stringify(p.name),m=JSON.stringify(`repo:${p.owner}/${p.name} is:closed closed:>=${o}`);return[` ${l}: repository(owner: ${u}, 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(`
67
+ `),aliases:i,closed_since:o}}function wg(e,n,t){let r=en(n),o=en(r.data),i=Array.isArray(r.errors)?r.errors.map(en):[],s=vg(o.rateLimit,i),a=e.aliases.map(({alias:l,search_alias:d,project:p})=>{let u=p.owner+"/"+p.name,f=o[l],m=i.find(h=>Oa(h.path,l)||Oa(h.path,d));if(Na(f)){let h=Aa(f.open_pull_requests),R=Aa(f.open_issues),k=Eg(o[d]);if(h!=null&&R!=null&&k!=null)return{project_label:p.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:h,open_issues:R,recently_closed:k},detail:`counted ${u} for project ${JSON.stringify(p.project_label)}`}}return s.exhausted||Ia(m)?{project_label:p.project_label,repository:u,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${u} answered, so this project has no counts rather than zero counts${s.reset_at==null?"":`; the quota resets at ${s.reset_at}`}`}:{project_label:p.project_label,repository:u,outcome:"unreachable",counts:null,detail:`${u} is not reachable with the host token: ${Do(m?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:a.length,rate_limit:s,projects:a}}function xg(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 Ta(e){if(e.projects.length===0)return xg(e.now);Ao(e.projects,e.hostTokenRef);let n=_g(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return wg(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(i=>({project_label:i.project_label,repository:`${i.owner}/${i.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${i.owner}/${i.name} answered: ${r}`}))}}}function $a(e){let n=e.stalenessMs??bg,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),i=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,s=i==null||i>n;return{version:1,fetched_at:t.fetched_at,age_ms:i,threshold_ms:n,stale:t.projects.length>0&&s,request_count:t.request_count,rate_limit:t.rate_limit,projects:t.projects.map(a=>({...a,fetched_at:t.fetched_at,age_ms:i,stale:s})),reason:t.projects.length===0?"the daemon polls no repository, so there are no counts to age":i==null?"these counts carry no readable instant, so they cannot be presented as current":s?`these counts are ${i}ms old, past the ${n}ms window`:`fetched ${i}ms ago, within the ${n}ms window`}}function La(e){let n=e.endpoint??kg(yg),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 i=o.headers.get("x-ratelimit-remaining"),s=o.status===429||i==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(s?": the host token's rate limit is spent":""))}return await o.json()}}function Sg(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>Da)throw new Error(`redskilled activity fetch spans at most ${Da} 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 vg(e,n){let t=en(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,i=n.some(Ia),s=typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:null;return{remaining:r,reset_at:o,exhausted:i||r===0,point_cost:s}}function Ia(e){if(e==null)return!1;let n=Do(e.type),t=Do(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function Oa(e,n){return Array.isArray(e)&&e.includes(n)}function Aa(e){let n=en(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function Eg(e){let n=en(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function en(e){return Na(e)?e:{}}function Na(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Do(e){return typeof e=="string"?e:""}var Pg=3e4,jg=4;function Ca(e){let n=e.stalenessMs??Pg,t=$n(e.now),r=e.sampledAt==null?null:$n(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),i=o!=null&&o<=n,s=new Set(e.reattachedWorkerIds??[]),a=e.hostState.workers.map(f=>Ag(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:i,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:s.has(f.worker_id)?"reattached":"running"})),l=a.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=a.length-l.length,p=a.reduce((f,m)=>f+(m.vitals.rss_bytes??0),0),u=xt(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:Ig({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:a.length,measuredCount:d,unmeasured:l}),host:{worker_count:a.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:u,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:p,measured_worker_count:d,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:u.memory_bytes/e.ceiling.memory_bytes},projects:Lg(a),known_projects:$g(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,m)=>f.localeCompare(m)),workers:a,github_balance:Eo({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:$a({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:Dg(e.deaths,e.recentDeathLimit??jg)},engine:Og(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function Dg(e,n){let t=[...e].sort((o,i)=>($n(i.ts)??0)-($n(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 Og(e){let n=e.upgrade,t=n?.running_version??e.daemon_version,r=n?.published_version??null,o=n?.newest_published_version??null,i=(n?.newer_published??0)>0,s=(n?.major_held??0)>0;return{running_version:t,published_version:r,newer_published:i,major_held:s,current:r==null&&o==null?null:!i&&!s}}function Ag(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=Tn(e),i=e.budget?.memory_max??e.budget?.memory_high??null,s=$n(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||s==null?null:Math.max(0,n.nowMs-s),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??i,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:Tg(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function Tg(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 $g(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);return[...n].sort((t,r)=>t.localeCompare(r))}function Lg(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 Ig(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 $n(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}var $={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Ma(e,n=$){let t=Hg(e,n),r=Fg(e,n),o=Bg(e,n),i=Ug(e,n,r,t),s=Mg(n,r,o),a={detail:"host",line:i};for(let u of s){let f=ey(i,Wg(u,n,r,o),n.separator);if(a={detail:u,line:f},ny(f)<=n.maxWidth)break}let l=Co(a.line,n.maxWidth),d=n.verbose&&a.detail==="workers"?zg(r,n):[],p=r.length>0?"workers":"host";return{version:1,line:l,lines:[l,...d],verbose:n.verbose,mode:n.mode,project:n.project,project_match:t,detail:a.detail,degraded:a.detail!==p||l!==a.line,stale:e.staleness.stale,generated_at:e.generated_at}}function Wa(e){let n=e.options??$,t=Co(Cg,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}}var Ng="!unregistered",$o="\u21E1",Nt="\u2020",Lo="\u25D0",Io="\u25EF",Cg="redskilled unreachable \u2014 Worker state unknown";function Mg(e,n,t){let r=[];return n.length>0&&n.length<=e.maxWorkers&&r.push("workers"),e.mode==="global"&&t.length>0&&t.length<=e.maxProjects&&r.push("projects"),r.push("host"),r}function Wg(e,n,t,r){return e==="workers"?t.map(o=>Qg(o,n)):e==="projects"?r.map(Zg):[]}function Fg(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Bg(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function Hg(e,n){return No(e,n.project)}function No(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":"name-only":"unregistered"}function Ug(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(To(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(To(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(To(e,n)),o.push(Ng)):o.push(qg(n.project,r)),o.push(Gg(e));let i=Kg(e);i!=null&&o.push(i);let s=Vg(e);return s!=null&&o.push(s),e.staleness.stale&&o.push(Jg(e)),o.join(" ")}function Gg(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${$o}`}function Kg(e){let n=e.github_balance;return n==null?null:n.posture==="spent"?`${Io} quota spent`:n.posture==="reserved"?`${Lo} quota band`:null}function Vg(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Nt}${n.count} ${n.latest.sender_class}`}function qg(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 To(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,i)=>o+i.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${X(t)}/${X(r)}`:X(t)}function Jg(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function Qg(e,n){let t=Fa(e,n),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?X(r):`${X(r)}/${X(e.budget.bytes)}`;return`${t} ${o}`}function zg(e,n){let t=[];for(let r of e){let o=Xg(r.log.last_line);o!=null&&t.push(Co(` ${Yg} ${Fa(r,n)}: ${o}`,n.maxWidth))}return t}var Yg="\u21B3";function Xg(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}function Fa(e,n){return n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Zg(e){return`${e.project_label} ${e.worker_count}w ${X(e.observed_rss_bytes)}`}function ey(e,n,t){return[e,...n].join(t)}function ny(e){return[...e].length}function Co(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}function X(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]}`}var Mo={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},ty=["runner","model","effort","origin","issue","phase","step","heartbeat"],ry=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function Ba(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...Mo};for(let r of ty){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of ry){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}var Ct=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],tn={mode:"local",project:null,maxWidth:200,maxRows:16};var oy=" ",Ha="\u2588",iy="\u25B6",sy="\u2717",ly="\u2591";function Ua(e,n=tn){let t=No(e,n.project),r=ay(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),i=o.map(u=>dy(u,n)),s=by(i),a=o.map((u,f)=>({worker_id:u.worker_id,project_label:u.project_label,mine:n.project!=null&&u.project_label===n.project,cells:i[f],line:nn(Ry(i[f],s),n.maxWidth)})),l=uy(e,n,r,t),d=r.length-o.length,p=[l.line,...a.map(u=>u.line)];return d>0&&p.push(nn(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),p.push(...my(e,n)),p.push(...fy(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Ct,header:l,rows:a,lines:p,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function ay(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function dy(e,n){let t=e.display??Mo,r=[t.runner,t.model,t.effort].filter(o=>!!o).join(" ");return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:r===""?"":`run=${r}`,org:t.origin==null?"":`org=${t.origin}`,iss:t.issue==null?"":`iss=${t.issue}`,bar:cy(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:ky(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:yy(t.added,t.removed),tks:t.tokens==null?"":`tks=${Ga(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function cy(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 Ha.repeat(Math.floor(n));let o=e.failed?sy:iy;return`${Ha.repeat(r)}${o}${ly.repeat(Math.floor(n)-r-1)}`}function uy(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(_=>_.project_label===n.project),i={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},s={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},a=gy(t),l=o?.repository??n.project,d=e.engine??null,p=d?.running_version??e.daemon.daemon_version,u=e.deaths??null,f=e.metrics??null,m=[`\xBB ${l??"host"} v${p}${d!=null&&d.current===!1?$o:""}`];r==="unregistered"&&m.push("!unregistered"),r==="name-only"&&m.push("!lapsed"),a!=null&&m.push(a),m.push(`wrk=${t.length}/${e.host.worker_count}`),m.push(s.worker_ceiling==null?"slots=\u221E":`slots=${s.worker_count}/${s.worker_ceiling}`),m.push(hy(s)),i.open_pull_requests!=null&&m.push(`prs=${i.open_pull_requests}`),i.recently_closed!=null&&m.push(`cpr=${i.recently_closed}`),i.open_issues!=null&&m.push(`iss=${i.open_issues}`),i.stale&&m.push("!counts stale");let h=f==null?null:py(f.hour);if(h!=null&&m.push(h),u!=null&&u.count>0&&u.latest!=null&&m.push(`${Nt}${u.count} ${u.latest.sender_class}`),e.staleness.stale){let _=e.staleness.age_ms;m.push(_==null?"!unmeasured":`!stale ${Math.round(_/1e3)}s`)}let R=m.join(" \xB7 "),k=h!=null&&Fo(R)>n.maxWidth?m.filter(_=>_!==h).join(" \xB7 "):R;return{repo:l,project:n.project,project_match:r,version:p,engine:d,deaths:u,metrics:f,model:a,windows:s,counts:i,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:nn(k,n.maxWidth)}}function py(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${Wo(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${Wo(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${Wo(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 fy(e,n){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let r=t.posture==="spent"?Io:Lo,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[nn(`${r} github budget ${t.posture}${o} \u2014 ${t.reason}`,n.maxWidth)]}function my(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(i=>nn(`${Nt} ${i.kind} ${i.id} pid=${i.pid} ${i.sender_class}/${i.confidence} phase=${i.last_phase}`+(i.signal==null?"":` signal=${i.signal}`)+(i.evidence==null?"":` \u2014 ${i.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(nn(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function hy(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${X(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${X(e.memory_used_bytes)}/${X(e.memory_ceiling_bytes)}${n}`}function gy(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 yy(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 Ga(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 Wo(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return Ga(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 ky(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 by(e){let n=Object.fromEntries(Ct.map(t=>[t,0]));for(let t of e)for(let r of Ct)n[r]=Math.max(n[r],Fo(t[r]));return n}function Ry(e,n){return Ct.filter(r=>n[r]>0).map(r=>_y(e[r],n[r])).join(oy).replace(/\s+$/,"")}function _y(e,n){return e+" ".repeat(Math.max(0,n-Fo(e)))}function Fo(e){return[...e].length}function nn(e,n){if(n<=0)return"";let t=[...e];return t.length<=n?e:n===1?"\u2026":`${t.slice(0,n-1).join("")}\u2026`}var Mt=1;async function Ln(e,n){return await gt(e,n,"redskilled daemon")}function Ka(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.line=="string"&&Array.isArray(n.lines)&&n.lines.every(t=>typeof t=="string")&&typeof n.verbose=="boolean"&&(n.mode==="local"||n.mode==="global")&&(n.project===null||typeof n.project=="string")&&typeof n.detail=="string"&&(n.project_match===void 0||typeof n.project_match=="string")&&typeof n.degraded=="boolean"&&typeof n.stale=="boolean"&&typeof n.generated_at=="string"}function Va(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:Mt,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:Sy(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:Ol(n,{hostCeilingBytes:e.hostCeilingBytes??null}),upgrade:vy(e)}}function Sy(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(i=>[i.project_label,i]));return[...e.registrations??[]].map(i=>{let s=o.get(i.project_label);return{...i,...t?{renewal:sa(i,n)}:{},...r==null||s==null?{}:{last_poll:{at:r.fetched_at,outcome:s.outcome,depth:s.depth,request_count:r.request_count,detail:s.detail}}}}).sort((i,s)=>i.project_label.localeCompare(s.project_label))}function vy(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 qa(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)&&Al(n.budget_accounting)&&(n.scope===void 0||na(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(ko))&&(n.upgrade===void 0||Ey(n.upgrade))}function Ey(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||Py(n.major_hold))}function Py(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 Bt}from"node:child_process";import{existsSync as Ko}from"node:fs";import{delimiter as Ny,join as rd}from"node:path";import{join as Ja}from"node:path";import{existsSync as jy}from"node:fs";import{createRequire as Dy}from"node:module";var Qa="redskilled-job-object.node",Le=100;function rn(e){return{available:!1,reason:e}}function Oy(e,n,t){return[Ja(t,"prebuilds",`${e}-${n}`,Qa),Ja(t,"native","build","Release",Qa)]}function za(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return rn(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??Ty(),o=e.exists??jy,i=Oy(n,t,r),s=i.find(d=>o(d));if(s==null)return rn(`no Job Object addon was found for ${n}-${t} (looked in ${i.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let a=e.requireFn??Dy(import.meta.url),l;try{l=a(s)}catch(d){return rn(`the Job Object addon at ${s} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return Ay(l)?{available:!0,binding:l}:rn(`the Job Object addon at ${s} does not export createJobObject, so it cannot be the native reach`)}function Ay(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Ty(){return new URL("..",import.meta.url).pathname}function Ya(e){let n=e??{},t=[],r=$y(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<Le?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 ${Le}, 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 $y(e){return Tn({budget:e})}var Wt=5,Xa=19;function Bo(e){return{available:!1,reason:e}}var Ly="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 ed(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=Wt;else if(t.cpu_weight<Le){let a=Math.round(Xa*(Le-t.cpu_weight)/Le);o=Math.min(Xa,Math.max(Wt,a))}else o=Wt,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${Le}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Wt}`);let i=Za(t.max_processes);i==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 s=Za(t.cpu_seconds);return s==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}:{},...i!=null?{max_processes:i}:{},...s!=null?{cpu_seconds:s}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:Ly,...r.length>0?{note:r.join("; ")}:{}}}function nd(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 ${Iy(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
68
+ `),e.command,...e.args]}function td(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 Ho(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 Za(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function Iy(e){return`'${e.replace(/'/g,"'\\''")}'`}var od="REDSKILLED_PLACEMENT",Ft="red-worker",Uo="/bin/sh";function id(e=process.env,n=process.platform){let t=Bo(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:za({platform:n}),posix:t};let r=rn(`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:Cy(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),i=o!==""&&Ko(rd(o,"systemd","private"));return{platform:n,systemdRun:dd("systemd-run",e),userSession:i,jobObjects:r,posix:t}}function Cy(e){return Ko(Uo)?{available:!0,shell:Uo,nice:dd("nice",e)}:Bo(`no POSIX shell was found at ${Uo}, so there is nothing to apply rlimits or priority in`)}function sd(e=process.env){let n=(e[od]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function My(e,n,t=Ft){return ld(e,n,t).replace(/\.service$/,"")}function ld(e,n,t=Ft){return`${Go(t,"red-worker",24)}-${Go(e,"project",32)}-${Go(n,"worker",32)}.service`}function ad(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,i=e.target??{isolation:"transient-unit"},s=u=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:u,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Sn({scope:null,memory_ceiling:r,scope_degradation:u}),...o?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(i.isolation==="inherit")return s("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 s(`worker isolation disabled by ${od}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return Fy(e,n,t,r,o,s);if(e.probes.platform==="darwin")return Wy(e,n,t,r,s);if(e.probes.platform!=="linux")return s(`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 s("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 s("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 a=ld(e.projectLabel,e.workerId,i.unit_prefix),l=["--user","--collect","--quiet","--wait",`--unit=${a}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&l.push("--pipe"),t.memory_high!=null&&l.push(`--property=MemoryHigh=${t.memory_high}`),t.memory_max!=null&&l.push(`--property=MemoryMax=${t.memory_max}`),t.cpu_weight!=null&&l.push(`--property=CPUWeight=${t.cpu_weight}`);let d=Sn({scope:a,memory_ceiling:r,scope_degradation:null});for(let[u,f]of Object.entries({...e.env??{},...d}))l.push(`--setenv=${u}=${f}`);let p=Ho(e.budget);return{isolated:!0,backend:"transient-unit",unit:a,command:e.probes.systemdRun,args:[...l,"--",e.command,...n],budget:t,...r!=null?{memoryCeiling:r}:{},environment:d,...p!=null?{budgetWarning:p}:{}}}function Wy(e,n,t,r,o){let i=e.probes.posix;if(!i.available)return o(`POSIX limit 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 s=ed(t,{canRenice:i.nice!=null}),a=t.memory_high!=null||t.memory_max!=null,l=td(s);return{isolated:!1,backend:"posix-limits",command:i.shell,args:nd({limits:s,nice:i.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:s,warning:l,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Sn({scope:null,memory_ceiling:r,scope_degradation:l}),...a?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+s.memory_ceiling_reason}:{}}}function Fy(e,n,t,r,o,i){let s=e.probes.jobObjects;if(!s.available)return i(`Job Object 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 a=Ya(t),l=My(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...n],cwd:e.workspacePath,job:{name:l,limits:a},budget:t,...r!=null?{memoryCeiling:r}:{},environment:Sn({scope:l,memory_ceiling:r,scope_degradation:null}),...By(o&&a.note!=null?`${a.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,Ho(e.budget))}}function By(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function dd(e,n){for(let t of(n.PATH??"").split(Ny)){if(!t)continue;let r=rd(t,e);if(Ko(r))return r}return null}function Go(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function Vo(e,n){let t=[],r=[];for(let o of e){let i=!1;try{i=await n(o)===!0}catch{i=!1}(i?t:r).push(o)}return{alive:t,dead:r}}function cd(e){return e.unit!=null&&e.unit!==""?Hy(e.unit):H(e.pid)}function Hy(e){let n=Bt("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var Uy="REDSKILLED_UNIT_DISCOVERY",ud="(unowned)";function pd(e){let n=Bt("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 Gy(e=process.env){let n=(e[Uy]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function fd(e,n,t=process.env){return Gy(t)&&e===n}function md(e=Ft){let n=Bt("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(`
69
+ `).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function hd(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:ud,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 gd(e){return e.project_label.trim()!==""?e:{...e,project_label:ud,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 yd(e){if(e.unit!=null&&e.unit!==""){let n=Bt("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 Ky(e,n=50){if(_d(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 Vy(e,n={}){let t=n.batchSize??50;if(_d(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((s,a)=>({alias:`q${a}`,project:s}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...r.map(({alias:s,project:a})=>` ${s}: search(query: ${JSON.stringify(a.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
70
+ `),aliases:r}}function qy(e,n){let t=In(n),r=In(t.data),o=Array.isArray(t.errors)?t.errors.map(In):[],i=Qy(r.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=Yy(r[a]);if(d!=null)return{project_label:l.project_label,outcome:"counted",depth:d,detail:`project ${JSON.stringify(l.project_label)} has ${d} item(s) matching its selector`};let p=o.find(u=>zy(u.path,a));return i.exhausted||wd(p)?{project_label:l.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(l.project_label)} answered, so this queue has no depth rather than a depth of zero`+(i.reset_at==null?"":`; the quota resets at ${i.reset_at}`)}:{project_label:l.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(l.project_label)} could not be counted with the host token: ${qo(p?.message)||"the query returned no count for this selector"}`}}),rate_limit:i}}function Jy(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 bd(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 Rd(e){if(e.projects.length===0)return Jy(e.now);let n=e.batchSize??50,t=Ky(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let i of t){let s=Vy(i,{batchSize:n});try{let a=await e.transport(s.query),l=qy(s,a);r.push(...l.projects),o=kd(o,l.rate_limit)}catch(a){let l=a instanceof Error?a.message:String(a),d=/rate limit|secondary rate|429/i.test(l);o=kd(o,{remaining:null,reset_at:null,exhausted:d});for(let p of i)r.push({project_label:p.project_label,outcome:d?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(p.project_label)} answered: ${l}`})}}return{version:1,fetched_at:e.now,request_count:t.length,project_count:r.length,batch_size:n,rate_limit:o,projects:r}}function _d(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 kd(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 Qy(e,n){let t=In(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(wd)||r===0}}function wd(e){return e==null?!1:qo(e.type)==="RATE_LIMITED"||/rate limit/i.test(qo(e.message))}function zy(e,n){return Array.isArray(e)&&e.includes(n)}function Yy(e){let n=In(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function In(e){return Xy(e)?e:{}}function Xy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qo(e){return typeof e=="string"?e:""}import{randomUUID as vd}from"node:crypto";import{spawn as tk}from"node:child_process";import{closeSync as rk,mkdirSync as ok,openSync as ik}from"node:fs";import{dirname as sk}from"node:path";import{delimiter as xd,dirname as Zy}from"node:path";function ek(e,n=xd){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function nk(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=Zy(n);return t===""||t==="."?null:t}function Sd(e,n=process.execPath,t=xd){let r=ek(e,t),o=nk(n);return o==null?r.join(t):[o,...r.filter(i=>i!==o)].join(t)}var Nn=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},Ht=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function lk(e){if(e==null||e.trim()==="")return null;try{return ok(sk(e),{recursive:!0}),ik(e,"a")}catch{return null}}function ak(e){try{rk(e)}catch{}}function dk(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 Nn(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new Nn("redskilled worker spec args must be an array")}function ck(e){if(e==null)throw new Ht("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new Ht(e.reason,e)}function Pd(e){let{spec:n,admission:t}=e;ck(t),dk(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),i=(n.worker_id??e.workerId??vd()).trim()||vd(),s=e.probes??id(r),a=e.openLog===!1?null:lk(n.log_path),l={...n.env??{},PATH:Sd(n.env?.PATH??r.PATH,e.execPath??process.execPath)},d=ad({workerId:i,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:l,enabled:e.enabled??sd(r),probes:s,pipeOutput:a!==null}),u=(e.spawnFn??tk)(d.command,d.args,{...d.cwd!=null?{cwd:d.cwd}:{},detached:!0,stdio:a===null?"ignore":["ignore",a,a],env:d.backend==="transient-unit"?{...r}:{...r,...l,...d.environment}});if(a!==null&&ak(a),u.pid==null)throw u.once("error",()=>{}),new Nn(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${i}`);let f=d.job!=null?uk(d,s,u.pid):null;u.once("error",()=>{}),u.once("exit",(k,_)=>{try{f?.job?.close()}catch{}e.onExit?.(i,k,_)}),u.unref();let m=d.job!=null?f?.job!=null:d.isolated,h=[d.warning,f?.warning,d.budgetWarning].filter(k=>k!=null);return{worker:{worker_id:i,project_label:n.project_label,pid:u.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:h},admission:t,warnings:h,plan:d,child:u,...f?.job!=null?{job:f.job}:{}}}function uk(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 i;try{i=n.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(s){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${Ed(s)}. ${o}`}}try{i.assign(t)}catch(s){try{i.close()}catch{}return{warning:`Worker pid ${t} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${Ed(s)}. ${o}`}}return{job:i}}function Ed(e){return e instanceof Error?e.message:String(e)}import{open as pk,stat as fk}from"node:fs/promises";var mk=16*1024;async function jd(e,n=mk){let t;try{t=(await fk(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let i=await pk(e,"r");try{let s=Buffer.alloc(r);await i.read(s,0,r,t-r),o=s.toString("utf8")}finally{await i.close()}}catch{return null}return hk(o)}function hk(e){let n=e.split(`
71
+ `);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 Ok}from"node:child_process";import{existsSync as Ak,readdirSync as Tk}from"node:fs";import{dirname as $k,join as Ld,resolve as Lk}from"node:path";var gk="<version>";function we(e,n=[],t){let r=t&&t.trim().length>0?t.trim():gk;return[`npx -y -p ${Te}@${r}`,e,...n].join(" ")}function Z(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 Jo(e,n){let t=Z(e),r=Z(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var gv=4*60*60*1e3;pe();pe();import{spawnSync as yk}from"node:child_process";import{mkdir as kk,rm as bk,writeFile as Rk}from"node:fs/promises";import{existsSync as _k}from"node:fs";import{homedir as wk}from"node:os";import{dirname as xk,join as Qo}from"node:path";var on="redskilled.service",zo="REDSKILLED_SUPERVISED",Sk="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function vk(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||Qo(e.HOME?.trim()||wk(),".config");return Qo(n,"systemd","user")}function Yo(e=process.env){return Qo(vk(e),on)}function Dd(e,n={}){let t=n.env??process.env,r=Rt(n.override??{},n.entryLookup??{}),o=[...r.args,...Ae(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:on,unitPath:Yo(t),command:r.command,args:o,text:Ek(r.command,o,e)}}function Ek(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${Sk}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(Pk).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${zo}=1"`,`Environment="REDSKILLED_SESSION=${Od(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
72
+ `)}function Pk(e){return/[\s"'\\$%]/.test(e)?`"${Od(e)}"`:e}function Od(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function Ad(e,n={}){let t=n.writeFile??jk,r=n.run??Xo,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(Ut("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(Ut("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(i=>i.ok),steps:o}}async function Td(e={}){let n=e.removeFile??Dk,t=e.run??Xo,r=Yo(e.env??process.env),o=[Ut("disable",t,["systemctl","--user","disable","--now",on])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(Ut("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function $d(e={}){let n=e.exists??_k,t=e.run??Xo,r=Yo(e.env??process.env),o=n(r);return{unitName:on,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",on]).status===0,active:o&&t(["systemctl","--user","is-active",on]).status===0,floor:"auto-spawn"}}function Ut(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 jk(e,n){await kk(xk(e),{recursive:!0}),await Rk(e,n,{encoding:"utf8",mode:420})}async function Dk(e){await bk(e,{force:!0})}function Xo(e){let n=yk(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 Id=75,Cd=9e5,Nd="redskilled-replacement-entry-unresolved",Ik="REDSKILLED_NO_REGISTRY_PROBE",Md="REDSKILLED_BORN_BY_REPLACEMENT";function Wd(e=process.env){return e[Md]==="1"}function Fd(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function Bd(e){let n=e.running.trim();if(Cn(n))return null;let t=e.newest?.trim()??"",r=Z(t),o=Z(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:Nk(r.major,e.supervised)}}function Nk(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: ${we("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 Hd(e){let n=e.running.trim();if(Cn(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||Z(t)===null?{act:"hold",reason:"published-unknown"}:Jo(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function Cn(e){let n=e.trim();return Z(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function Ud(e=process.env){return e[zo]==="1"}var Zo=class extends Error{code=Nd;searched;constructor(n,t){super(`${Nd}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
73
73
  searched:
74
74
  ${t.map(r=>` ${r}`).join(`
75
- `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function sk(e,n={}){let t=n.env??process.env,r=n.exists??ek,o=n.execPath??process.execPath,i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,s=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[ad(mt(t),s),"bundle-cache"]];i&&l.push([ad(tk(rk(i)),s),"caller-sibling-bundle"]);for(let[d,p]of l)if(a.push(d),r(d))return{command:o,args:[d],version:e,source:p,searched:a};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new Io(e,a);return{command:t.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:a}}function kd(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>sk(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function Rd(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??ak)(dd),{...e,exitCode:dd};let o=[...e.entry.args,...Ae(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??lk(r.env))(e.entry,o),e}function lk(e){return(n,t)=>{let r=Zy(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[pd]:"1"}});r.on("error",()=>{}),r.unref()}}function ak(e){process.exitCode=e,process.exit(e)}async function bd(e,n=process.env,t=dk){let r=wd(n),o=xd(e,n);if(n[ok]==="1")return{version:o,newest:r};let i=Z(e)===null?"0.0.0":e;try{let s=await il({fetchText:t},i);return{version:s.sameMajor??o,newest:s.newest??r}}catch{return{version:o,newest:r}}}function _d(e,n=process.env,t){let r=t??To;return{version:xd(e,n,r),newest:wd(n,r)}}function wd(e=process.env,n=To){return vd(Sd(e,n))}function xd(e,n=process.env,t=To){let r=Z(e.trim())?.major;return r===void 0?null:vd(Sd(n,t).filter(o=>Z(o)?.major===r))}function Sd(e,n){let t=[];for(let r of n(mt(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||Z(o)===null||t.push(o)}return t}function vd(e){let n=null;for(let t of e)(n===null||Do(t,n)>0)&&(n=t);return n}function To(e){try{return nk(e)}catch{return[]}}async function dk(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 ck,readFile as uk,rename as pk,rm as No,writeFile as Ed}from"node:fs/promises";import{randomUUID as fk}from"node:crypto";import{dirname as mk}from"node:path";var It=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function In(e){let n;try{n=await uk(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=hk(n);return gk(t)?t:void 0}var Pd;function Dd(){return Pd??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Pd}function Od(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??U;async function i(){return await In(e)}async function s(l){let d=`${e}.${l.pid}.${fk()}.tmp`;await Ed(d,jd(l),{encoding:"utf8",mode:384}),await pk(d,e)}function a(l,d){return{version:1,pid:l.pid,start_time:l.startTime,session_key_hash:n.sessionKeyHash,machine_id_hash:n.machineIdHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}return{read:i,async acquire(l){await ck(mk(e),{recursive:!0,mode:448});let d=!1;for(;;){let p=r(),u=a(l,p);try{return await Ed(e,jd(u),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:u}}catch(m){if(m.code!=="EEXIST")throw m}let f=await i();if(!f){await No(e,{force:!0}),d=!0;continue}if(Co(f,l))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await No(e,{force:!0}),d=!0}},async renew(l){let d=await i();if(!d||!Co(d,l))throw new It(e);let p={...d,renewed_at:r()};return await s(p),p},async release(l){let d=await i();if(!d)return!1;if(!Co(d,l))throw new It(e);return await No(e,{force:!0}),!0}}}function Co(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function jd(e){return`${M(e,{keyedMapCollapse:!0})}
76
- `}function hk(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Y(n)}catch{return null}}}function gk(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 Mo=3e5,Sk=1e4,vk=6e4,Ek=15e3,Pk=3e4,Ad=16,tn=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},jk="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function $d(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??Mo,o=e.clock??(()=>new Date().toISOString()),i=e.launch??nd,s=e.ceiling??gl();e.repositoryActivity!=null&&mo(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??Dd(),l=e.leaseStore??Od(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??$l(),p={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},u=e.machineClaimStore??_t(n.machineClaimPath,p,{clock:o});await _k(xk(n.socketPath),{recursive:!0,mode:448});let f=await u.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new tn(n.socketPath):new be(u.claimPath,f.reason,f.claim);let m=await l.acquire(a);if(!m.acquired)throw await u.release(d).catch(()=>{}),new tn(n.socketPath,m.lease);let h;try{h=await Dk(n.socketPath)}catch(c){throw await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),c}let b=o(),k=e.eventLane??Rl(n.eventLanePath),w=e.liveness??Ca,j=e.stopWorker??Ka,ne=e.unitInventory??(()=>Ha(n.machineClaimPath,bt({machineIdHash:n.machineIdHash}))?Fa():[]),q=e.unitMainPid??Wa,we=e.treeSampler??zl,Ne=e.readLogTail??td,Cn=e.sampleMs??Ek,Xo=e.leaseRenewMs??Pk,Zo=e.publishedVersion??(c=>bd(c)),ei=e.replaceCheckMs??ud,ni=e.publishedProbeTimeoutMs??Sk,mc=e.localPublishedEvidence??(c=>_d(c,e.replacementIO?.env??process.env)),hc=e.bornByReplacement??fd(),ti=e.replaceBootCheckMs??vk,ri=e.supervised??yd(),oi=e.replacementIO??{},te=e.repositoryActivity,ii=te?.intervalMs??fo,xe=e.queueDiscovery,Mn=xe?.transport??te?.transport,Ct=xe?.unconfiguredReason??jk,Mt=xe?.intervalMs??15e3,si=e.demandMs??15e3,gc=e.demandBackoffMs??3e4,v=new Map,ge=new Set,Ce=new Map,Wn=new Map,Wt=[],Hn=[],I=new Map,Ht=new Set,li={},Ft=null,ai=null,Ut=null,di=!1,Bt=0,Kt=null,on="none",Vt=null,ci=null,qt=null,de=null,Fn=null,sn=[],ln=null,Un={},Gt=!1,Me,an,dn,cn,un,Bn,pn,Se,G=!1,Jt=!1,Kn=null,ui,Qt=new Promise(c=>{ui=c});function fn(c){pi(c);let g=Date.parse(c),y=Fl(I.values(),g);for(let _ of y.lapsed)I.delete(_.project_label),yc(_,g);return y.lapsed}function yc(c,g){let y=Number.isFinite(g)?new Date(g).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>Ad&&sn.splice(0,sn.length-Ad)}function pi(c){if(I.size===0)return;let g=Date.parse(c);if(!Number.isFinite(g))return;let y={};for(let x of v.values())y[x.project_label]=(y[x.project_label]??0)+1;let _=new Map((de?.projects??[]).map(x=>[x.project_label,x]));for(let x of[...I.values()]){let P=_.get(x.project_label),ue=Wl(x,{now:c,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:y[x.project_label]??0});ue.registration!==x&&I.set(x.project_label,ue.registration)}}function Vn(){let c=o();return fn(c),Ra({now:c,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:a.pid,startedAt:b,scope:Il(u.claimPath,p,d),workers:[...v.values()],hostCeilingBytes:s.memory_bytes,registrations:[...I.values()],lapses:sn,queue:de,published:{version:ai,checkedAt:Ut,newer:di,replacement:on,newest:Vt,majorHold:ci,checks:Bt,holdReason:Kt}})}function qn(){return ca({hostState:Vn(),ceiling:s,rss:li,sampledAt:Ft,logLines:Object.fromEntries(Ce),displays:Object.fromEntries(Wn),now:o(),reattachedWorkerIds:[...ge],repositoryActivity:qt,...e.deaths===void 0?{}:{deaths:e.deaths},metrics:Jl({observations:Wt,outcomes:Hn,now:o()})})}function kc(c,g){Wt=xt([...Wt,{worker_id:g,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 Rc(c){Hn=xt([...Hn,c],g=>g.ts,{now:o()})}async function zt(){return te==null||te.projects.length===0?null:(qt=await ia({projects:te.projects,hostTokenRef:te.hostTokenRef,transport:te.transport,closedWindowMs:te.closedWindowMs,now:o()}),qt)}function bc(){if(!(Mn!=null||xe?.armTransport==null))try{let c=xe.armTransport();if(c.transport!=null){Mn=c.transport;return}c.unconfiguredReason!=null&&(Ct=c.unconfiguredReason)}catch(c){Ct=`this host could not resolve a tracker credential: ${c instanceof Error?c.message:String(c)}`}}async function fi(){let c=o();fn(c);let g=[...I.values()].map(y=>({project_label:y.project_label,selector:y.selector})).sort((y,_)=>y.project_label.localeCompare(_.project_label));return g.length===0?null:(bc(),Mn==null?(de=qa(g,c,Ct),de):(de=await Ga({projects:g,transport:Mn,now:c,...xe?.batchSize==null?{}:{batchSize:xe.batchSize}}),pi(o()),de))}async function mi(){let c=o();if(Gt)return Fn??wl(c);Gt=!0;try{let g={};for(let O of v.values())g[O.project_label]=(g[O.project_label]??0)+1;let y={};for(let O of de?.projects??[])y[O.project_label]=O.depth;let _=Date.parse(c),x=_l({projects:[...I.values()].map(O=>({project_label:O.project_label,selector:O.selector,argv:O.argv,workspace_path:O.workspace_path,target:O.target})),queue:y,live:g,nowMs:Number.isFinite(_)?_:0,backoffUntilMs:ln,birthHaltUntilMs:Sl(Un,Number.isFinite(_)?_:0)}),P=[],ue=null;for(let O of x.births){let He,Uc=Tn(),Yn=I.get(O.project_label),ji=Nl({argv:O.argv,...Yn?.env==null?{}:{env:Yn.env},...Yn?.log_path==null?{}:{log_path:Yn.log_path}},{worker_id:Uc,slot:O.index,workspace_path:O.workspace_path},{project_label:O.project_label});try{He=Yt(ji)}catch(er){ue=er instanceof Error?er.message:String(er),ln=(Number.isFinite(_)?_:Date.now())+gc;break}P.push({project_label:O.project_label,worker_id:He.worker.worker_id,pid:He.worker.pid,warnings:ji.log_path==null?[...He.warnings,`project ${JSON.stringify(O.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(He.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:He.warnings})}return ue==null&&x.births.length>0&&(ln=null),Fn={version:1,at:c,requested:x.births.length,granted:P,shortfall:x.births.length-P.length,refusal:ue,retry_after:ln==null?null:new Date(ln).toISOString(),projects:x.intents},Fn}finally{Gt=!1}}function _c(c){return ua(qn(),{...$,mode:c?.mode??$.mode,project:c?.project??$.project,maxWorkers:c?.max_workers??$.maxWorkers,maxProjects:c?.max_projects??$.maxProjects,maxWidth:c?.max_width??$.maxWidth,verbose:c?.verbose??$.verbose})}function wc(c){return ga(qn(),{mode:c?.mode??Ze.mode,project:c?.project??Ze.project,maxWidth:c?.max_width??Ze.maxWidth,maxRows:c?.max_rows??Ze.maxRows})}function We(c,g,y){return Bl({op:c,sessionProject:g??null,targetProject:y})}async function xc(c){let g=v.get(c.worker_id),y=We(Ul(c.command),c.session_project,g?.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 _=g!=null&&await jc(g,c.detail??"stopped by its own project");return{version:1,command:c.command,worker_id:c.worker_id,applied:_,reach:y,detail:_?`redskilled stopped Worker ${JSON.stringify(c.worker_id)} of project ${JSON.stringify(g.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function Gn(c){v.delete(c),ge.delete(c),Ce.delete(c),Wn.delete(c)}function hi(c){let g=v.get(c.worker_id),y=We("worker-heartbeat",c.session_project,g?.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(g==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 _=o();Ce.set(c.worker_id,{line:c.last_log_line,published_at:_,source:"heartbeat"});let x=c.display===void 0?null:ma(c.display);if(x!=null){let P={display:x,published_at:_};Wn.set(c.worker_id,P),kc(P,c.worker_id)}return{version:1,worker_id:c.worker_id,accepted:!0,reach:y,published_at:_,detail:`redskilled stored a line for Worker ${JSON.stringify(c.worker_id)} without reading it`}}async function Sc(c,g,y){let _=`exit code=${g??"null"} signal=${y??"null"}`;if(c.unit!=null&&c.unit!==""&&await Ec(c)){Pc(c,`its launch client ended (${_}) 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}Gn(c.worker_id),ce("worker-death",c,_,{exitCode:g,signal:y}),T()}function vc(c,g){if(!Number.isFinite(g)||g<0){Un[c]=Rt;return}let y=Un[c]??Rt,_=xl(y,g,Date.parse(o()));Un[c]=_,_.haltUntilMs!=null&&y.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(c)} lost ${_.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(_.haltUntilMs).toISOString()}
77
- `)}async function Ec(c){try{return await w(c)===!0}catch{return!1}}function Pc(c,g){let y=c.unit==null?null:q(c.unit);v.set(c.worker_id,{...c,...y!=null&&y>0?{pid:y}:{},warnings:[...c.warnings,g]}),ge.add(c.worker_id),T()}function gi(c,g){let y=We("project-register",g,c.project_label);if(!y.permitted)throw new Error(y.reason);let _=o();fn(_);let x=Cl(c,{now:_,held:I.get(c.project_label)});return I.set(x.project_label,x),T(),{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 yi(c,g={}){let y=We("project-renew",g.sessionProject,c);if(!y.permitted)throw new Error(y.reason);let _=o();fn(_);let x=I.get(c);if(x==null)throw new wt(c);let P=Ml(x,{now:_,...g.renewWithinMs==null?{}:{renew_within_ms:g.renewWithinMs},...g.launch==null?{}:{launch:g.launch}});return I.set(P.project_label,P),T(),{version:1,registration:P,reach:y,detail:`redskilled renewed the registration for project ${JSON.stringify(P.project_label)}, which now stands until ${P.renew_by} after renewal ${P.renewals}`+(g.launch==null?"":`, carrying launch revision ${P.launch_revision} for its next Worker`)}}function ki(c,g){let y=We("project-deregister",g,c);if(!y.permitted)throw new Error(y.reason);let _=I.delete(c);return{version:1,project_label:c,released:_,reach:y,detail:_?`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 jc(c,g){try{await j(c)}catch{}return Gn(c.worker_id),ce("worker-death",c,g),T(),!0}function Ri(c){return ml({ceiling:s,workers:[...v.values()],budget:c.budget,projectLabel:c.project_label})}function Yt(c){let g=hl({ceiling:s,workers:[...v.values()],budget:c.budget}),y=i({spec:c,admission:Ri(c),memoryCeiling:g,clock:o,onExit:(_,x,P)=>{let ue=v.get(_);if(ue==null){T();return}Sc(ue,x,P).catch(()=>{})}});return v.set(y.worker.worker_id,y.worker),ce("worker-birth",y.worker,null),T(),y}function ce(c,g,y,_={}){if(G)return;let x=o();(c==="worker-death"||c==="worker-budget-kill")&&(Rc({worker_id:g.worker_id,ts:x,outcome:c}),vc(g.project_label,Date.parse(x)-Date.parse(g.started_at))),k.record({event:c,worker:g,ts:x,detail:y,..._.exitCode!==void 0?{exitCode:_.exitCode}:{},..._.signal!==void 0?{signal:_.signal}:{}}).catch(()=>{})}async function bi(){let c=[...ge].map(y=>v.get(y)).filter(y=>y!=null);if(c.length===0)return[];let{dead:g}=await Po(c,w);for(let y of g)Gn(y.worker_id),ce("worker-death",y,"the host no longer confirms this Worker");return g.length>0&&T(),g}async function _i(c,g){let y=v.get(c);if(!y)return!1;try{await j(y)}catch{}return Gn(c),ce("worker-budget-kill",y,g),T(),!0}async function wi(){let c=[...v.values()];if(c.length===0)return[];let g;try{g=await we(c)}catch{return[]}let y=g.rss;li=y,Ft=o(),Dc(g.cpu_seconds,Ft),Oc(g.sources);let{terminations:_}=Ql({workers:c,rss:y,...g.sources==null?{}:{sources:g.sources}}),x=[];for(let P of _)await _i(P.worker_id,P.reason)&&x.push(P);return x}function Dc(c,g){for(let[y,_]of Object.entries(c)){if(typeof _!="number"||!Number.isFinite(_))continue;let x=v.get(y);x&&v.set(y,{...x,cpu:{cpu_seconds:_,sampled_at:g}})}}function Oc(c){for(let[g,y]of Object.entries(c??{})){let _=v.get(g);_&&v.set(g,{..._,rss_source:y})}}async function Ac(){try{return ni<=0?await Zo(t):await new Promise(c=>{let g=setTimeout(()=>c(Xt()),ni);g.unref(),Zo(t).then(y=>{clearTimeout(g),c(y)},()=>{clearTimeout(g),c(Xt())})})}catch{return Xt()}}function Xt(){try{return mc(t)}catch{return null}}async function xi(){if($n(t))return Bt+=1,Ut=o(),Kt="local-build",{act:"hold",reason:"local-build"};let c=md(await Ac()),g=c.version;ai=g,Vt=c.newest??null,Ut=o(),ci=hd({running:t,newest:Vt,supervised:ri});let y=gd({running:t,published:g,supervised:ri});return di=y.act==="replace",Bt+=1,Kt=y.act==="hold"?y.reason:null,on!=="in-progress"&&(on=y.act==="replace"?"pending":"none"),y}async function Jn(){let c=await xi();if(c.act!=="replace"||on==="in-progress")return c;let g=kd(c,oi);return on="in-progress",await k.flush().catch(()=>{}),await zn({reason:"replaced"}),Rd(g,n,{...r==null?{}:{idleMs:r},io:oi}),c}function Lc(){G||un!=null||ei<=0||(!hc&&ti>0&&(Bn=setTimeout(()=>{Jn().catch(()=>{})},ti),Bn.unref()),un=setInterval(()=>{Jn().catch(()=>{})},ei),un.unref())}async function Si(){return await l.renew(a).catch(()=>null)}function $c(){G||dn!=null||Xo<=0||(dn=setInterval(()=>{Si()},Xo),dn.unref())}function Ic(){G||an!=null||Cn<=0||(an=setInterval(()=>{wi().catch(()=>{})},Cn),an.unref())}function Tc(){G||pn!=null||te==null||te.projects.length===0||ii<=0||(zt().catch(()=>{}),pn=setInterval(()=>{zt().catch(()=>{})},ii),pn.unref())}function Nc(){if(G||Se!=null||Mt<=0)return;let c=g=>{G||(Se=setTimeout(()=>{Se=void 0,fi().catch(()=>{}).finally(()=>c(za(de,Mt,Date.parse(o()))))},g),Se.unref())};c(Mt)}function Cc(){G||cn!=null||si<=0||(cn=setInterval(()=>{mi().catch(()=>{})},si),cn.unref())}function T(){G||(Me&&clearTimeout(Me),Me=setTimeout(()=>{bi().catch(()=>{}).then(()=>vi())},r),Me.unref())}function vi(){return v.size>0?(T(),"held-by-workers"):(fn(o()),I.size>0?(T(),"held-by-registrations"):(Mc(),"exited"))}async function Mc(){if(!$n(t)){if((await Jn().catch(()=>null))?.act==="replace"||Jt||G)return;if(v.size>0||I.size>0){T();return}}await zn({reason:"idle"})}function Qn(c){return El({reason:c,socketPath:n.socketPath,daemonVersion:t,pid:a.pid,workers:[...v.values()],projects:[...I.keys()]})}function Ei(c){if(Kn!=null)return Kn;let g=c.reason??"requested",y=c.note?.trim();return Kn=k.recordDaemonStop({ts:o(),pid:a.pid,socketPath:n.socketPath,reason:g,detail:y==null||y===""?Qn(g).detail:`${Qn(g).detail} \u2014 ${y}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),Kn}async function zn(c={}){if(Jt)return await Qt;Jt=!0,await Ei(c),G=!0,Me&&clearTimeout(Me),an&&clearInterval(an),dn&&clearInterval(dn),un&&clearInterval(un),Bn&&clearTimeout(Bn),pn&&clearInterval(pn),Se&&clearTimeout(Se),Se=void 0,cn&&clearInterval(cn),await k.flush().catch(()=>{}),h.close();for(let g of Ht)g.destroy();return await new Promise(g=>h.once("close",()=>g())),await Ld(n.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),ui(),await Qt}let Pi=await k.read().catch(()=>[]);Hn=xt(Pi.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 Wc=bl(Pi),Zt=await Po(Wc,w);for(let c of Zt.alive){let g=Ba(c),y=g.unit==null||U(g.pid)?null:q(g.unit);v.set(g.worker_id,y!=null&&y>0?{...g,pid:y}:g),ge.add(g.worker_id)}for(let c of Zt.dead)ce("worker-death",c,"the Worker ended while no daemon was watching");let Hc=Ua({units:await Promise.resolve(ne()).catch(()=>[]),held:[...v.values()],mainPid:q,now:b});for(let c of Hc)v.set(c.worker_id,c),ge.add(c.worker_id),ce("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of Zt.alive){if(c.log_path==null||Ce.has(c.worker_id))continue;let g=await Ne(c.log_path).catch(()=>null);g==null||g.trim()===""||Ce.set(c.worker_id,{line:g,published_at:o(),source:"rehydrated"})}h.on("connection",c=>{Ht.add(c),c.once("close",()=>Ht.delete(c)),T(),Ok(c,async(g,y)=>{T();let _=await Fc(g);y(_),g.op==="shutdown"&&setImmediate(()=>void zn({reason:"requested"}))})});async function Fc(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:jt,daemon_version:t,pid:a.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:Vn()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:qn()};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:_c(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:wc(c.dashboard)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:hi(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:gi(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:yi(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:ki(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await xc(c.command)};if(c.op==="worker-start"){let y=We("worker-start",c.session_project,c.spec.project_label);if(!y.permitted)return{id:c.id,ok:!1,error:y.reason};let _=Yt(c.spec);return await k.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:_.worker,admission:_.admission,warnings:_.warnings}}}if(c.op==="shutdown"){let y=Qn("requested");return await Ei({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:y}}let g=c;return{id:g.id??Tn(),ok:!1,error:`unsupported redskilled op: ${g.op??"unknown"}`}}catch(g){return{id:c.id??Tn(),ok:!1,error:g instanceof Error?g.message:String(g)}}}return T(),Ic(),$c(),Lc(),Tc(),Nc(),Cc(),{socketPath:n.socketPath,lease:m.lease,startedAt:b,closed:Qt,startWorker:Yt,admit:Ri,ceiling:()=>s,killWorkerOverBudget:_i,sampleMemoryBudgets:wi,renewLease:Si,pollRepositoryActivity:zt,pollQueueDiscovery:fi,queueDiscovery:()=>de,driveDemand:mi,demand:()=>Fn,sweepReattached:bi,publishWorkerHeartbeat:hi,reattached:()=>[...ge].map(c=>v.get(c)).filter(c=>c!=null),flushEvents:()=>k.flush(),trackWorker(c){v.set(c.worker_id,c),ce("worker-birth",c,null),T()},releaseWorker(c){let g=v.get(c),y=v.delete(c);return ge.delete(c),Ce.delete(c),Wn.delete(c),g&&ce("worker-death",g,"released by the daemon"),T(),y},workerCount:()=>v.size,registerProject:gi,renewProject:yi,deregisterProject:ki,registrations:()=>Vn().registrations??[],hostState:Vn,statuslinePayload:qn,evaluateIdle:vi,observePublishedVersion:xi,checkForReplacement:Jn,stopReport:Qn,stop:zn}}async function Dk(e){for(let n=0;n<2;n++){let t=wk();try{return await new Promise((r,o)=>{t.once("error",o),t.listen(e,()=>{t.off("error",o),r()})}),t}catch(r){if(t.close(),r.code!=="EADDRINUSE")throw r;if(await ee(e))throw new tn(e);await Ld(e,{force:!0})}}throw new tn(e)}async function ee(e,n=250){try{return(await ut({socketPath:e,timeoutMs:n},{id:Tn(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function Ok(e,n){el(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??Tn(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function Wo(e){let n=e.socketPath,t=Ak(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 ${Id(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 \`${_e("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 \`${_e("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function Ho(e){return`${e.reason} ${e.repair}`}function Ak(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:Lk(n.acquired_at,e.now??new Date().toISOString())}}function Lk(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 Id(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`}fe();var Cd=1e4,Te=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"?`. ${Ho(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},Fo=class extends Te{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}};async function Tt(e,n={}){let t=n.answers??await ee(e.socketPath),r=await In(e.leasePath).catch(()=>{});return Wo({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&U(r.pid)})}async function Uo(e,n={}){try{return await Ck(e,n)}catch(t){if(t instanceof be||t instanceof Te)throw t;let r=await Tt(e).catch(()=>{});throw new Te(e.socketPath,t,r)}}async function Ck(e,n){if(await Ik(Nk(e.socketPath),{recursive:!0,mode:448}),await ee(e.socketPath))return"already-running";await Wk(e);let t=await Mk(e,n);if(t!=null)return t;let r=await nl(e.lockPath);if(!r)return await Td(e,n),"joined";try{if(await ee(e.socketPath))return"already-running";let o=await Uk(e,n);return await Td(e,n,o),"spawned"}finally{await r.close(),await Tk(e.lockPath,{force:!0})}}async function Mk(e,n){let t=await Tt(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??Cd,o=Date.now()+r;for(;;){if(await ee(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(s=>setTimeout(s,25))}let i=await Tt(e).catch(()=>{});if(i==null||i.kind!=="held-unresponsive")return null;throw new Fo(e.socketPath,i,new Error(`it did not answer a ping within ${r}ms, and no second daemon was spawned because pid ${i.holder?.pid??"unknown"} still holds this socket`))}async function Wk(e){let t=await _t(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&U(t.pid))throw new be(e.machineClaimPath,"held",t)}async function Md(e,n,t={}){await Uo(e,t);let r;try{r=await On({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:Nd()})}catch(o){throw new Te(e.socketPath,o,await Tt(e).catch(()=>{}))}if(!r.ok)throw new Error(r.error);return r.value}async function Wd(e,n={},t={}){if(!await ee(e.socketPath))return Pl(e.socketPath);let r;try{r=await On({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Nd(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(s){throw new Te(e.socketPath,s)}if(!r.ok)throw new Error(r.error);if(!Zr(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await Hk(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 Hk(e,n){let t=Date.now()+n;for(;;){if(!await ee(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function Hd(e,n={}){let t=await Md(e,{op:"host-state"},n);if(!ba(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Fd(e,n=void 0,t={}){let r=await Md(e,{op:"statusline-string",...t.sessionProject!=null?{session_project:t.sessionProject}:{},...n==null?{}:{render:Fk(n)}},t);if(!ka(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function Fk(e){return{mode:e.mode,project:e.project,max_workers:e.maxWorkers,max_projects:e.maxProjects,max_width:e.maxWidth,verbose:e.verbose}}async function Td(e,n,t){let r=Date.now()+(n.readyTimeoutMs??Cd);for(;;){if(await ee(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()>=r){let o=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)}${o}`)}await new Promise(o=>setTimeout(o,25))}}async function Uk(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await dl({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},i=[...r.args,...Ae(e,n.idleMs==null?{}:{idleMs:n.idleMs})],s=$k(r.command,i,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return s.on("error",a=>{o.failure=a}),s.on("exit",(a,l)=>{o.exit=l?`died on ${l}`:`exited with code ${a??-1}`}),s.unref(),o}fe();import{chmod as Jd,mkdir as zd,readFile as Yd,stat as Zk,writeFile as eR}from"node:fs/promises";import{homedir as Vo}from"node:os";import{dirname as nR,join as qo}from"node:path";import{join as Bk}from"node:path";var Ud=["local","tmp","host"],Kk="local",Nn="plugins.dev.workspace.target";var Bo=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function Kd(e){let n=Qe(e,Nn),t=Gk(n??"").trim();return t===""?void 0:t}function Vd(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:Kk};let t=Ud.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 Bo(`${Nn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${Ud.join(", ")}) or an absolute parent directory for Workers.`)}function qd(e,n){return e.kind==="preset"?e.preset==="host":qk(Vk(e.parentDir,n),Oe(n))}function Vk(e,n){return e==="~"?Bd(n):e.startsWith("~/")?Bk(n,e.slice(2)):Bd(e)}function qk(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Bd(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function Gk(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}fe();import{createHash as Jk}from"node:crypto";import{hostname as Qk}from"node:os";import{join as Nt}from"node:path";var rn="redskilled.sock",zk="REDSKILLED_SESSION";function Yk(e={}){let n=e.env??process.env,t=n[zk]?.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 Xk(e={}){return Gd(e.host??Qk())}function he(e={}){let n=Yk(e),t=e.runtimeDir??pt({key:`redskilled:${n}`,socketFileName:rn,env:e.env,uid:e.uid}),r=Xk(e);return{sessionKey:n,sessionKeyHash:Gd(n),machineIdHash:r,runtimeDir:t,socketPath:Nt(t,rn),lockPath:Nt(t,"redskilled.spawn.lock"),leasePath:Nt(t,"redskilled.lease.toon"),eventLanePath:Nt(t,kl),machineClaimPath:e.machineClaimPath??bt({env:e.env,machineIdHash:r,platform:e.platform})}}function Gd(e){return Jk("sha256").update(e).digest("hex").slice(0,12)}var Ko=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${_e("red-skills-redskilled",["provision"])}\` directly`;async function Xd(e=Vo()){let n=Oe(e),t=await Jo(n);return t===void 0?(await zd(n,{recursive:!0,mode:se}),await Jd(n,se),{path:n,created:!0,tightened:!1,mode:se}):t===se?{path:n,created:!1,tightened:!1,mode:t}:(await Jd(n,se),{path:n,created:!1,tightened:!0,mode:se})}var Zd={needed:!1,declaredBy:`no ${Nn} in view`};async function Go(e={}){let n=e.homeDir??Vo(),t=e.declaredTarget?.trim();if(t)return Qd(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return Zd;let o=qo(r,".red","config.yaml"),i=await Yd(o,"utf8").catch(()=>{});if(i===void 0)return{needed:!1,declaredBy:`no ${o}`};let s=Kd(i);return s===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Qd(s,n,o)}function Qd(e,n,t){let r=`${Nn}: ${e} (${t})`;try{return{needed:qd(Vd(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function ec(e){let n=[tR(e),rR(e),oR(e),iR(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 tR(e){let n=e.homeNeed??Zd;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:Ko}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??se;return t!==se?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${se.toString(8)}`,fix:`${Ko} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function rR(e){return ae(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 \`${_e("red-skills-redskilled",["provision"])}\``}}function oR(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:`${Ko} \u2014 it starts the daemon and waits for the socket`}}function iR(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 nc(e={}){let n=e.env??process.env,t=e.homeDir??Vo(),r=e.paths??he({env:n}),o=Oe(t),[i,s,a]=await Promise.all([Jo(o),ee(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Go({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:i!==void 0,homeMode:i,homeNeed:a,entry:Re(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:s,supervisorUnit:await lR(aR(e,n,t),n)}}var sR="redskilled.service";function tc(e){return qo(e,"systemd","user",sR)}function rc(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(`
78
- `)}async function oc(e){let n=tc(e.configHome);return await Jo(n)!==void 0?{path:n,status:"already-present"}:(await zd(nR(n),{recursive:!0}),await eR(n,e.unit,"utf8"),{path:n,status:"installed"})}async function lR(e,n){if(process.platform!=="linux")return"unsupported";try{return await Yd(tc(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function aR(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??qo(t,".config")}async function Jo(e){try{return(await Zk(e)).mode&511}catch{return}}import{readdir as sc,rm as dR,stat as cR}from"node:fs/promises";import{dirname as uR,join as Qo}from"node:path";var pR=5*6e4,fR="redskilled.";function mR(e={}){let n=e.env??process.env,t=s=>uR(pt({key:"redskilled:reclaim-probe",socketFileName:rn,env:s,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=n,i=[t(n),t(o)];return[...new Set(i)]}async function lc(e={}){let n=e.roots??mR(e),t=e.graceMs??pR,r=e.now??Date.now,o=e.isPidAlive??U,i=e.answers??kR,s=e.dryRun===!0,a=[];for(let l of n){let d;try{d=(await sc(l,{withFileTypes:!0})).filter(p=>p.isDirectory()).map(p=>p.name)}catch{continue}for(let p of d.sort())a.push(await hR(Qo(l,p),{graceMs:t,now:r,pidAlive:o,answers:i,dryRun:s}))}return{roots:n,scanned:a.length,reclaimed:a.filter(l=>l.verdict==="reclaimed").length,dryRun:s,entries:a}}async function hR(e,n){let t;try{t=(await sc(e)).sort()}catch(s){return{dir:e,verdict:"failed",reason:ac(s),removed:[]}}let r=t.filter(s=>s.startsWith(fR));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await gR(Qo(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 ic(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(rn)&&await n.answers(Qo(e,rn)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let i=await yR(e,n.now);return i!==void 0&&i<n.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(i/1e3)}s ago`,removed:[]}:await ic(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function ic(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await dR(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:ac(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function gR(e){try{return await In(e)}catch{return}}async function yR(e,n){try{return Math.max(0,n()-(await cR(e)).mtimeMs)}catch{return}}async function kR(e){try{return(await On({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function ac(e){return e instanceof Error?e.message:String(e)}var RR="plugins.dev.statusline",bR="dev.statusline";function _R(e){let n=[],t=a=>{for(let l of[RR,bR]){let d=`${l}.${a}`,p=Qe(e,d)?.trim();if(p!=null&&p!=="")return{key:d,value:p}}},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 i=[{leaf:"max_workers",assign:a=>{o.maxWorkers=a}},{leaf:"max_projects",assign:a=>{o.maxProjects=a}},{leaf:"max_width",assign:a=>{o.maxWidth=a}}];for(let a of i){let l=t(a.leaf);if(l==null)continue;let d=Number(l.value);Number.isInteger(d)&&d>=0?a.assign(d):n.push({...l,reason:"expected a whole number of zero or more"})}let s=t("verbose");return s!=null&&(s.value==="true"||s.value==="false"?o.verbose=s.value==="true":n.push({...s,reason:"expected `true` or `false`"})),{config:o,warnings:n}}var wR={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 dc(e){let{values:n,positionals:t}=je(e,wR),r=[],o={},i=n.mode??t.find(a=>a==="global"||a==="local");i!=null&&(i==="local"||i==="global"?o.mode=i:r.push({key:"--mode",value:i,reason:"expected `local` or `global`"})),n.project!=null&&(o.project=n.project),n.verbose!==void 0&&(o.verbose=n.verbose===!0);let s=[{flag:"max-workers",assign:a=>{o.maxWorkers=a}},{flag:"max-projects",assign:a=>{o.maxProjects=a}},{flag:"max-width",assign:a=>{o.maxWidth=a}}];for(let a of s){let l=n[a.flag];if(l==null)continue;let d=Number(l);Number.isInteger(d)&&d>=0?a.assign(d):r.push({key:`--${a.flag}`,value:l,reason:"expected a whole number of zero or more"})}return{flags:o,warnings:r}}function cc(e={}){let n=e.configText==null?{config:{},warnings:[]}:_R(e.configText),t=e.flags??{};return{options:{...$,mode:t.mode??n.config.mode??$.mode,project:t.project!==void 0?t.project:e.project??$.project,maxWorkers:t.maxWorkers??n.config.maxWorkers??$.maxWorkers,maxProjects:t.maxProjects??n.config.maxProjects??$.maxProjects,maxWidth:t.maxWidth??n.config.maxWidth??$.maxWidth,verbose:t.verbose??n.config.verbose??$.verbose},warnings:n.warnings}}var SR=`Usage: redskilled <command> [options]
75
+ `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function Ck(e,n={}){let t=n.env??process.env,r=n.exists??Ak,o=n.execPath??process.execPath,i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,s=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[Ld(bt(t),s),"bundle-cache"]];i&&l.push([Ld($k(Lk(i)),s),"caller-sibling-bundle"]);for(let[d,p]of l)if(a.push(d),r(d))return{command:o,args:[d],version:e,source:p,searched:a};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new Zo(e,a);return{command:t.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:a}}function Gd(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>Ck(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function Kd(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??Wk)(Id),{...e,exitCode:Id};let o=[...e.entry.args,...Ae(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??Mk(r.env))(e.entry,o),e}function Mk(e){return(n,t)=>{let r=Ok(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[Md]:"1"}});r.on("error",()=>{}),r.unref()}}function Wk(e){process.exitCode=e,process.exit(e)}async function Vd(e,n=process.env,t=Fk){let r=Jd(n),o=Qd(e,n);if(n[Ik]==="1")return{version:o,newest:r};let i=Z(e)===null?"0.0.0":e;try{let s=await vl({fetchText:t},i);return{version:s.sameMajor??o,newest:s.newest??r}}catch{return{version:o,newest:r}}}function qd(e,n=process.env,t){let r=t??ei;return{version:Qd(e,n,r),newest:Jd(n,r)}}function Jd(e=process.env,n=ei){return Yd(zd(e,n))}function Qd(e,n=process.env,t=ei){let r=Z(e.trim())?.major;return r===void 0?null:Yd(zd(n,t).filter(o=>Z(o)?.major===r))}function zd(e,n){let t=[];for(let r of n(bt(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||Z(o)===null||t.push(o)}return t}function Yd(e){let n=null;for(let t of e)(n===null||Jo(t,n)>0)&&(n=t);return n}function ei(e){try{return Tk(e)}catch{return[]}}async function Fk(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 Bk,readFile as Hk,rename as Uk,rm as ni,writeFile as Xd}from"node:fs/promises";import{randomUUID as Gk}from"node:crypto";import{dirname as Kk}from"node:path";var Gt=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function Mn(e){let n;try{n=await Hk(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=Vk(n);return qk(t)?t:void 0}var Zd;function nc(){return Zd??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Zd}function tc(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??H;async function i(){return await Mn(e)}async function s(l){let d=`${e}.${l.pid}.${Gk()}.tmp`;await Xd(d,ec(l),{encoding:"utf8",mode:384}),await Uk(d,e)}function a(l,d){return{version:1,pid:l.pid,start_time:l.startTime,session_key_hash:n.sessionKeyHash,machine_id_hash:n.machineIdHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}return{read:i,async acquire(l){await Bk(Kk(e),{recursive:!0,mode:448});let d=!1;for(;;){let p=r(),u=a(l,p);try{return await Xd(e,ec(u),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:u}}catch(m){if(m.code!=="EEXIST")throw m}let f=await i();if(!f){await ni(e,{force:!0}),d=!0;continue}if(ti(f,l))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await ni(e,{force:!0}),d=!0}},async renew(l){let d=await i();if(!d||!ti(d,l))throw new Gt(e);let p={...d,renewed_at:r()};return await s(p),p},async release(l){let d=await i();if(!d)return!1;if(!ti(d,l))throw new Gt(e);return await ni(e,{force:!0}),!0}}}function ti(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function ec(e){return`${M(e,{keyedMapCollapse:!0})}
76
+ `}function Vk(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Y(n)}catch{return null}}}function qk(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 ri=3e5,nb=1e4,tb=6e4,rb=15e3,ob=3e4,rc=16,sn=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},ib="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function ic(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??ri,o=e.clock??(()=>new Date().toISOString()),i=e.launch??Pd,s=e.ceiling??Nl();e.repositoryActivity!=null&&Ao(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??nc(),l=e.leaseStore??tc(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??Zl(),p={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},u=e.machineClaimStore??Et(n.machineClaimPath,p,{clock:o});await Xk(eb(n.socketPath),{recursive:!0,mode:448});let f=await u.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new sn(n.socketPath):new _e(u.claimPath,f.reason,f.claim);let m=await l.acquire(a);if(!m.acquired)throw await u.release(d).catch(()=>{}),new sn(n.socketPath,m.lease);let h;try{h=await sb(n.socketPath)}catch(c){throw await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),c}let R=o(),k=e.eventLane??Wl(n.eventLanePath),_=e.liveness??cd,j=e.stopWorker??yd,ne=e.unitInventory??(()=>fd(n.machineClaimPath,vt({machineIdHash:n.machineIdHash}))?md():[]),q=e.unitMainPid??pd,xe=e.treeSampler??ja,Ne=e.readLogTail??jd,Bn=e.sampleMs??rb,gi=e.leaseRenewMs??ob,yi=e.publishedVersion??(c=>Vd(c)),ki=e.replaceCheckMs??Cd,bi=e.publishedProbeTimeoutMs??nb,Bc=e.localPublishedEvidence??(c=>qd(c,e.replacementIO?.env??process.env)),Hc=e.bornByReplacement??Wd(),Ri=e.replaceBootCheckMs??tb,_i=e.supervised??Ud(),wi=e.replacementIO??{},te=e.repositoryActivity,xi=te?.intervalMs??Oo,Hn=e.githubBalance,Se=e.queueDiscovery,Un=Se?.transport??te?.transport,Jt=Se?.unconfiguredReason??ib,Si=Se?.intervalMs??15e3,vi=e.demandMs??15e3,Uc=e.demandBackoffMs??3e4,v=new Map,ge=new Set,Ce=new Map,Gn=new Map,Qt=[],Kn=[],L=new Map,zt=new Set,Ei={},Yt=null,Pi=null,Xt=null,ji=!1,Zt=0,er=null,an="none",nr=null,Di=null,tr=null,dn=null,ye=null,Vn=null,cn=[],un=null,qn={},rr=!1,Me,pn,fn,mn,hn,Jn,gn,We,yn,U=!1,or=!1,Qn=null,Oi,ir=new Promise(c=>{Oi=c});function kn(c){Ai(c);let g=Date.parse(c),y=la(L.values(),g);for(let w of y.lapsed)L.delete(w.project_label),Gc(w,g);return y.lapsed}function Gc(c,g){let y=Number.isFinite(g)?new Date(g).toISOString():c.renew_by;cn.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`}),cn.length>rc&&cn.splice(0,cn.length-rc)}function Ai(c){if(L.size===0)return;let g=Date.parse(c);if(!Number.isFinite(g))return;let y={};for(let x of v.values())y[x.project_label]=(y[x.project_label]??0)+1;let w=new Map((ye?.projects??[]).map(x=>[x.project_label,x]));for(let x of[...L.values()]){let P=w.get(x.project_label),ce=ia(x,{now:c,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:y[x.project_label]??0});ce.registration!==x&&L.set(x.project_label,ce.registration)}}function zn(){let c=o();return kn(c),Va({now:c,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:a.pid,startedAt:R,scope:ea(u.claimPath,p,d),workers:[...v.values()],registrations:[...L.values()],lapses:cn,queue:ye,published:{version:Pi,checkedAt:Xt,newer:ji,replacement:an,newest:nr,majorHold:Di,checks:Zt,holdReason:er}})}function Yn(){return Ca({hostState:zn(),ceiling:s,rss:Ei,sampledAt:Yt,logLines:Object.fromEntries(Ce),displays:Object.fromEntries(Gn),now:o(),reattachedWorkerIds:[...ge],repositoryActivity:tr,githubBalance:dn,...e.deaths===void 0?{}:{deaths:e.deaths},metrics:Ea({observations:Qt,outcomes:Kn,now:o()})})}function Kc(c,g){Qt=Lt([...Qt,{worker_id:g,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 Vc(c){Kn=Lt([...Kn,c],g=>g.ts,{now:o()})}async function sr(){return te==null||te.projects.length===0?null:(tr=await Ta({projects:te.projects,hostTokenRef:te.hostTokenRef,transport:te.transport,closedWindowMs:te.closedWindowMs,now:o()}),tr)}async function Ti(){return Hn==null?null:(dn=await xo({transport:Hn.transport,now:o()}),dn)}function qc(){if(U||We!=null||Hn==null)return;let c=()=>{We=void 0,Ti().catch(()=>{}).then(()=>{if(U)return;let g=Hn.intervalMsOverride??$t(dn??Jc(),{now:o()});We=setTimeout(c,g),We.unref()})};c()}function Jc(){return Tt(o())}function Qc(){if(!(Un!=null||Se?.armTransport==null))try{let c=Se.armTransport();if(c.transport!=null){Un=c.transport;return}c.unconfiguredReason!=null&&(Jt=c.unconfiguredReason)}catch(c){Jt=`this host could not resolve a tracker credential: ${c instanceof Error?c.message:String(c)}`}}async function $i(){let c=o();kn(c);let g=[...L.values()].map(y=>({project_label:y.project_label,selector:y.selector})).sort((y,w)=>y.project_label.localeCompare(w.project_label));return g.length===0?null:(Qc(),Un==null?(ye=bd(g,c,Jt),ye):(ye=await Rd({projects:g,transport:Un,now:c,...Se?.batchSize==null?{}:{batchSize:Se.batchSize}}),Ai(o()),ye))}async function Li(){let c=o();if(rr)return Vn??Hl(c);rr=!0;try{let g={};for(let O of v.values())g[O.project_label]=(g[O.project_label]??0)+1;let y={};for(let O of ye?.projects??[])y[O.project_label]=O.depth;let w=Date.parse(c),x=Bl({projects:[...L.values()].map(O=>({project_label:O.project_label,selector:O.selector,argv:O.argv,workspace_path:O.workspace_path,target:O.target})),queue:y,live:g,nowMs:Number.isFinite(w)?w:0,backoffUntilMs:un,birthHaltUntilMs:Gl(qn,Number.isFinite(w)?w:0)}),P=[],ce=null;for(let O of x.births){let Be,gu=Wn(),tt=L.get(O.project_label),Ji=ta({argv:O.argv,...tt?.env==null?{}:{env:tt.env},...tt?.log_path==null?{}:{log_path:tt.log_path}},{worker_id:gu,slot:O.index,workspace_path:O.workspace_path},{project_label:O.project_label});try{Be=lr(Ji)}catch(cr){ce=cr instanceof Error?cr.message:String(cr),un=(Number.isFinite(w)?w:Date.now())+Uc;break}P.push({project_label:O.project_label,worker_id:Be.worker.worker_id,pid:Be.worker.pid,warnings:Ji.log_path==null?[...Be.warnings,`project ${JSON.stringify(O.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(Be.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:Be.warnings})}return ce==null&&x.births.length>0&&(un=null),Vn={version:1,at:c,requested:x.births.length,granted:P,shortfall:x.births.length-P.length,refusal:ce,retry_after:un==null?null:new Date(un).toISOString(),projects:x.intents},Vn}finally{rr=!1}}function zc(c){return Ma(Yn(),{...$,mode:c?.mode??$.mode,project:c?.project??$.project,maxWorkers:c?.max_workers??$.maxWorkers,maxProjects:c?.max_projects??$.maxProjects,maxWidth:c?.max_width??$.maxWidth,verbose:c?.verbose??$.verbose})}function Yc(c){return Ua(Yn(),{mode:c?.mode??tn.mode,project:c?.project??tn.project,maxWidth:c?.max_width??tn.maxWidth,maxRows:c?.max_rows??tn.maxRows})}function Fe(c,g,y){return da({op:c,sessionProject:g??null,targetProject:y})}async function Xc(c){let g=v.get(c.worker_id),y=Fe(aa(c.command),c.session_project,g?.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 w=g!=null&&await ru(g,c.detail??"stopped by its own project");return{version:1,command:c.command,worker_id:c.worker_id,applied:w,reach:y,detail:w?`redskilled stopped Worker ${JSON.stringify(c.worker_id)} of project ${JSON.stringify(g.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function Xn(c){v.delete(c),ge.delete(c),Ce.delete(c),Gn.delete(c)}function Ii(c){let g=v.get(c.worker_id),y=Fe("worker-heartbeat",c.session_project,g?.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(g==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 w=o();Ce.set(c.worker_id,{line:c.last_log_line,published_at:w,source:"heartbeat"});let x=c.display===void 0?null:Ba(c.display);if(x!=null){let P={display:x,published_at:w};Gn.set(c.worker_id,P),Kc(P,c.worker_id)}return{version:1,worker_id:c.worker_id,accepted:!0,reach:y,published_at:w,detail:`redskilled stored a line for Worker ${JSON.stringify(c.worker_id)} without reading it`}}async function Zc(c,g,y){let w=`exit code=${g??"null"} signal=${y??"null"}`;if(c.unit!=null&&c.unit!==""&&await nu(c)){tu(c,`its launch client ended (${w}) 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}Xn(c.worker_id),de("worker-death",c,w,{exitCode:g,signal:y}),I()}function eu(c,g){if(!Number.isFinite(g)||g<0){qn[c]=St;return}let y=qn[c]??St,w=Ul(y,g,Date.parse(o()));qn[c]=w,w.haltUntilMs!=null&&y.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(c)} lost ${w.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(w.haltUntilMs).toISOString()}
77
+ `)}async function nu(c){try{return await _(c)===!0}catch{return!1}}function tu(c,g){let y=c.unit==null?null:q(c.unit);v.set(c.worker_id,{...c,...y!=null&&y>0?{pid:y}:{},warnings:[...c.warnings,g]}),ge.add(c.worker_id),I()}function Ni(c,g){let y=Fe("project-register",g,c.project_label);if(!y.permitted)throw new Error(y.reason);let w=o();kn(w);let x=ra(c,{now:w,held:L.get(c.project_label)});return L.set(x.project_label,x),I(),{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 Ci(c,g={}){let y=Fe("project-renew",g.sessionProject,c);if(!y.permitted)throw new Error(y.reason);let w=o();kn(w);let x=L.get(c);if(x==null)throw new Pt(c);let P=oa(x,{now:w,...g.renewWithinMs==null?{}:{renew_within_ms:g.renewWithinMs},...g.launch==null?{}:{launch:g.launch}});return L.set(P.project_label,P),I(),{version:1,registration:P,reach:y,detail:`redskilled renewed the registration for project ${JSON.stringify(P.project_label)}, which now stands until ${P.renew_by} after renewal ${P.renewals}`+(g.launch==null?"":`, carrying launch revision ${P.launch_revision} for its next Worker`)}}function Mi(c,g){let y=Fe("project-deregister",g,c);if(!y.permitted)throw new Error(y.reason);let w=L.delete(c);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`}}async function ru(c,g){try{await j(c)}catch{}return Xn(c.worker_id),de("worker-death",c,g),I(),!0}function Wi(c){return Ll({ceiling:s,workers:[...v.values()],budget:c.budget,projectLabel:c.project_label})}function lr(c){let g=Il({ceiling:s,workers:[...v.values()],budget:c.budget}),y=i({spec:c,admission:Wi(c),memoryCeiling:g,clock:o,onExit:(w,x,P)=>{let ce=v.get(w);if(ce==null){I();return}Zc(ce,x,P).catch(()=>{})}});return v.set(y.worker.worker_id,y.worker),de("worker-birth",y.worker,null),I(),y}function de(c,g,y,w={}){if(U)return;let x=o();(c==="worker-death"||c==="worker-budget-kill")&&(Vc({worker_id:g.worker_id,ts:x,outcome:c}),eu(g.project_label,Date.parse(x)-Date.parse(g.started_at))),k.record({event:c,worker:g,ts:x,detail:y,...w.exitCode!==void 0?{exitCode:w.exitCode}:{},...w.signal!==void 0?{signal:w.signal}:{}}).catch(()=>{})}async function Fi(){let c=[...ge].map(y=>v.get(y)).filter(y=>y!=null);if(c.length===0)return[];let{dead:g}=await Vo(c,_);for(let y of g)Xn(y.worker_id),de("worker-death",y,"the host no longer confirms this Worker");return g.length>0&&I(),g}async function Bi(c,g){let y=v.get(c);if(!y)return!1;try{await j(y)}catch{}return Xn(c),de("worker-budget-kill",y,g),I(),!0}async function Hi(){let c=[...v.values()];if(c.length===0)return[];let g;try{g=await xe(c)}catch{return[]}let y=g.rss;Ei=y,Yt=o(),ou(g.cpu_seconds,Yt);let{terminations:w}=Pa({workers:c,rss:y}),x=[];for(let P of w)await Bi(P.worker_id,P.reason)&&x.push(P);return x}function ou(c,g){for(let[y,w]of Object.entries(c)){if(typeof w!="number"||!Number.isFinite(w))continue;let x=v.get(y);x&&v.set(y,{...x,cpu:{cpu_seconds:w,sampled_at:g}})}}async function iu(){try{return bi<=0?await yi(t):await new Promise(c=>{let g=setTimeout(()=>c(ar()),bi);g.unref(),yi(t).then(y=>{clearTimeout(g),c(y)},()=>{clearTimeout(g),c(ar())})})}catch{return ar()}}function ar(){try{return Bc(t)}catch{return null}}async function Ui(){if(Cn(t))return Zt+=1,Xt=o(),er="local-build",{act:"hold",reason:"local-build"};let c=Fd(await iu()),g=c.version;Pi=g,nr=c.newest??null,Xt=o(),Di=Bd({running:t,newest:nr,supervised:_i});let y=Hd({running:t,published:g,supervised:_i});return ji=y.act==="replace",Zt+=1,er=y.act==="hold"?y.reason:null,an!=="in-progress"&&(an=y.act==="replace"?"pending":"none"),y}async function Zn(){let c=await Ui();if(c.act!=="replace"||an==="in-progress")return c;let g=Gd(c,wi);return an="in-progress",await k.flush().catch(()=>{}),await nt({reason:"replaced"}),Kd(g,n,{...r==null?{}:{idleMs:r},io:wi}),c}function su(){U||hn!=null||ki<=0||(!Hc&&Ri>0&&(Jn=setTimeout(()=>{Zn().catch(()=>{})},Ri),Jn.unref()),hn=setInterval(()=>{Zn().catch(()=>{})},ki),hn.unref())}async function Gi(){return await l.renew(a).catch(()=>null)}function lu(){U||fn!=null||gi<=0||(fn=setInterval(()=>{Gi()},gi),fn.unref())}function au(){U||pn!=null||Bn<=0||(pn=setInterval(()=>{Hi().catch(()=>{})},Bn),pn.unref())}function du(){U||gn!=null||te==null||te.projects.length===0||xi<=0||(sr().catch(()=>{}),gn=setInterval(()=>{sr().catch(()=>{})},xi),gn.unref())}function cu(){U||yn!=null||Si<=0||(yn=setInterval(()=>{$i().catch(()=>{})},Si),yn.unref())}function uu(){U||mn!=null||vi<=0||(mn=setInterval(()=>{Li().catch(()=>{})},vi),mn.unref())}function I(){U||(Me&&clearTimeout(Me),Me=setTimeout(()=>{Fi().catch(()=>{}).then(()=>Ki())},r),Me.unref())}function Ki(){return v.size>0?(I(),"held-by-workers"):(kn(o()),L.size>0?(I(),"held-by-registrations"):(pu(),"exited"))}async function pu(){if(!Cn(t)){if((await Zn().catch(()=>null))?.act==="replace"||or||U)return;if(v.size>0||L.size>0){I();return}}await nt({reason:"idle"})}function et(c){return Vl({reason:c,socketPath:n.socketPath,daemonVersion:t,pid:a.pid,workers:[...v.values()],projects:[...L.keys()]})}function Vi(c){if(Qn!=null)return Qn;let g=c.reason??"requested",y=c.note?.trim();return Qn=k.recordDaemonStop({ts:o(),pid:a.pid,socketPath:n.socketPath,reason:g,detail:y==null||y===""?et(g).detail:`${et(g).detail} \u2014 ${y}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),Qn}async function nt(c={}){if(or)return await ir;or=!0,await Vi(c),U=!0,Me&&clearTimeout(Me),pn&&clearInterval(pn),fn&&clearInterval(fn),hn&&clearInterval(hn),Jn&&clearTimeout(Jn),gn&&clearInterval(gn),We&&clearTimeout(We),yn&&clearInterval(yn),mn&&clearInterval(mn),await k.flush().catch(()=>{}),h.close();for(let g of zt)g.destroy();return await new Promise(g=>h.once("close",()=>g())),await oc(n.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),Oi(),await ir}let qi=await k.read().catch(()=>[]);Kn=Lt(qi.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 fu=Fl(qi),dr=await Vo(fu,_);for(let c of dr.alive){let g=gd(c),y=g.unit==null||H(g.pid)?null:q(g.unit);v.set(g.worker_id,y!=null&&y>0?{...g,pid:y}:g),ge.add(g.worker_id)}for(let c of dr.dead)de("worker-death",c,"the Worker ended while no daemon was watching");let mu=hd({units:await Promise.resolve(ne()).catch(()=>[]),held:[...v.values()],mainPid:q,now:R});for(let c of mu)v.set(c.worker_id,c),ge.add(c.worker_id),de("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of dr.alive){if(c.log_path==null||Ce.has(c.worker_id))continue;let g=await Ne(c.log_path).catch(()=>null);g==null||g.trim()===""||Ce.set(c.worker_id,{line:g,published_at:o(),source:"rehydrated"})}h.on("connection",c=>{zt.add(c),c.once("close",()=>zt.delete(c)),I(),lb(c,async(g,y)=>{I();let w=await hu(g);y(w),g.op==="shutdown"&&setImmediate(()=>void nt({reason:"requested"}))})});async function hu(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:Mt,daemon_version:t,pid:a.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:zn()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:Yn()};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:zc(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:Yc(c.dashboard)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:Ii(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:Ni(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:Ci(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:Mi(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await Xc(c.command)};if(c.op==="worker-start"){let y=Fe("worker-start",c.session_project,c.spec.project_label);if(!y.permitted)return{id:c.id,ok:!1,error:y.reason};let w=lr(c.spec);return await k.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:w.worker,admission:w.admission,warnings:w.warnings}}}if(c.op==="shutdown"){let y=et("requested");return await Vi({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:y}}let g=c;return{id:g.id??Wn(),ok:!1,error:`unsupported redskilled op: ${g.op??"unknown"}`}}catch(g){return{id:c.id??Wn(),ok:!1,error:g instanceof Error?g.message:String(g)}}}return I(),au(),lu(),su(),du(),qc(),cu(),uu(),{socketPath:n.socketPath,lease:m.lease,startedAt:R,closed:ir,startWorker:lr,admit:Wi,ceiling:()=>s,killWorkerOverBudget:Bi,sampleMemoryBudgets:Hi,renewLease:Gi,pollRepositoryActivity:sr,pollGithubBalance:Ti,githubBalance:()=>dn,pollQueueDiscovery:$i,queueDiscovery:()=>ye,driveDemand:Li,demand:()=>Vn,sweepReattached:Fi,publishWorkerHeartbeat:Ii,reattached:()=>[...ge].map(c=>v.get(c)).filter(c=>c!=null),flushEvents:()=>k.flush(),trackWorker(c){v.set(c.worker_id,c),de("worker-birth",c,null),I()},releaseWorker(c){let g=v.get(c),y=v.delete(c);return ge.delete(c),Ce.delete(c),Gn.delete(c),g&&de("worker-death",g,"released by the daemon"),I(),y},workerCount:()=>v.size,registerProject:Ni,renewProject:Ci,deregisterProject:Mi,registrations:()=>zn().registrations??[],hostState:zn,statuslinePayload:Yn,evaluateIdle:Ki,observePublishedVersion:Ui,checkForReplacement:Zn,stopReport:et,stop:nt}}async function sb(e){for(let n=0;n<2;n++){let t=Zk();try{return await new Promise((r,o)=>{t.once("error",o),t.listen(e,()=>{t.off("error",o),r()})}),t}catch(r){if(t.close(),r.code!=="EADDRINUSE")throw r;if(await ee(e))throw new sn(e);await oc(e,{force:!0})}}throw new sn(e)}async function ee(e,n=250){try{return(await gt({socketPath:e,timeoutMs:n},{id:Wn(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function lb(e,n){Rl(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??Wn(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function oi(e){let n=e.socketPath,t=ab(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 ${sc(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 \`${we("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 \`${we("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function ii(e){return`${e.reason} ${e.repair}`}function ab(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:db(n.acquired_at,e.now??new Date().toISOString())}}function db(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 sc(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`}pe();var dc=1e4,Ie=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"?`. ${ii(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},si=class extends Ie{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}};async function Kt(e,n={}){let t=n.answers??await ee(e.socketPath),r=await Mn(e.leasePath).catch(()=>{});return oi({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&H(r.pid)})}async function li(e,n={}){try{return await mb(e,n)}catch(t){if(t instanceof _e||t instanceof Ie)throw t;let r=await Kt(e).catch(()=>{});throw new Ie(e.socketPath,t,r)}}async function mb(e,n){if(await ub(fb(e.socketPath),{recursive:!0,mode:448}),await ee(e.socketPath))return"already-running";await gb(e);let t=await hb(e,n);if(t!=null)return t;let r=await _l(e.lockPath);if(!r)return await lc(e,n),"joined";try{if(await ee(e.socketPath))return"already-running";let o=await bb(e,n);return await lc(e,n,o),"spawned"}finally{await r.close(),await pb(e.lockPath,{force:!0})}}async function hb(e,n){let t=await Kt(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??dc,o=Date.now()+r;for(;;){if(await ee(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(s=>setTimeout(s,25))}let i=await Kt(e).catch(()=>{});if(i==null||i.kind!=="held-unresponsive")return null;throw new si(e.socketPath,i,new Error(`it did not answer a ping within ${r}ms, and no second daemon was spawned because pid ${i.holder?.pid??"unknown"} still holds this socket`))}async function gb(e){let t=await Et(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 _e(e.machineClaimPath,"held",t)}async function cc(e,n,t={}){await li(e,t);let r;try{r=await Ln({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:ac()})}catch(o){throw new Ie(e.socketPath,o,await Kt(e).catch(()=>{}))}if(!r.ok)throw new Error(r.error);return r.value}async function uc(e,n={},t={}){if(!await ee(e.socketPath))return ql(e.socketPath);let r;try{r=await Ln({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:ac(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(s){throw new Ie(e.socketPath,s)}if(!r.ok)throw new Error(r.error);if(!co(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await yb(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 yb(e,n){let t=Date.now()+n;for(;;){if(!await ee(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function pc(e,n={}){let t=await cc(e,{op:"host-state"},n);if(!qa(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function fc(e,n=void 0,t={}){let r=await cc(e,{op:"statusline-string",...t.sessionProject!=null?{session_project:t.sessionProject}:{},...n==null?{}:{render:kb(n)}},t);if(!Ka(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function kb(e){return{mode:e.mode,project:e.project,max_workers:e.maxWorkers,max_projects:e.maxProjects,max_width:e.maxWidth,verbose:e.verbose}}async function lc(e,n,t){let r=Date.now()+(n.readyTimeoutMs??dc);for(;;){if(await ee(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()>=r){let o=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)}${o}`)}await new Promise(o=>setTimeout(o,25))}}async function bb(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await Dl({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},i=[...r.args,...Ae(e,n.idleMs==null?{}:{idleMs:n.idleMs})],s=cb(r.command,i,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return s.on("error",a=>{o.failure=a}),s.on("exit",(a,l)=>{o.exit=l?`died on ${l}`:`exited with code ${a??-1}`}),s.unref(),o}pe();import{chmod as Rc,mkdir as wc,readFile as xc,stat as Ob,writeFile as Ab}from"node:fs/promises";import{homedir as ci}from"node:os";import{dirname as Tb,join as ui}from"node:path";import{join as Rb}from"node:path";var mc=["local","tmp","host"],_b="local",Fn="plugins.dev.workspace.target";var ai=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function gc(e){let n=ze(e,Fn),t=Sb(n??"").trim();return t===""?void 0:t}function yc(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:_b};let t=mc.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 ai(`${Fn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${mc.join(", ")}) or an absolute parent directory for Workers.`)}function kc(e,n){return e.kind==="preset"?e.preset==="host":xb(wb(e.parentDir,n),Oe(n))}function wb(e,n){return e==="~"?hc(n):e.startsWith("~/")?Rb(n,e.slice(2)):hc(e)}function xb(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function hc(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function Sb(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}pe();import{createHash as vb}from"node:crypto";import{hostname as Eb}from"node:os";import{join as Vt}from"node:path";var ln="redskilled.sock",Pb="REDSKILLED_SESSION";function jb(e={}){let n=e.env??process.env,t=n[Pb]?.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 Db(e={}){return bc(e.host??Eb())}function he(e={}){let n=jb(e),t=e.runtimeDir??yt({key:`redskilled:${n}`,socketFileName:ln,env:e.env,uid:e.uid}),r=Db(e);return{sessionKey:n,sessionKeyHash:bc(n),machineIdHash:r,runtimeDir:t,socketPath:Vt(t,ln),lockPath:Vt(t,"redskilled.spawn.lock"),leasePath:Vt(t,"redskilled.lease.toon"),eventLanePath:Vt(t,Ml),machineClaimPath:e.machineClaimPath??vt({env:e.env,machineIdHash:r,platform:e.platform})}}function bc(e){return vb("sha256").update(e).digest("hex").slice(0,12)}var di=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${we("red-skills-redskilled",["provision"])}\` directly`;async function Sc(e=ci()){let n=Oe(e),t=await fi(n);return t===void 0?(await wc(n,{recursive:!0,mode:se}),await Rc(n,se),{path:n,created:!0,tightened:!1,mode:se}):t===se?{path:n,created:!1,tightened:!1,mode:t}:(await Rc(n,se),{path:n,created:!1,tightened:!0,mode:se})}var vc={needed:!1,declaredBy:`no ${Fn} in view`};async function pi(e={}){let n=e.homeDir??ci(),t=e.declaredTarget?.trim();if(t)return _c(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return vc;let o=ui(r,".red","config.yaml"),i=await xc(o,"utf8").catch(()=>{});if(i===void 0)return{needed:!1,declaredBy:`no ${o}`};let s=gc(i);return s===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:_c(s,n,o)}function _c(e,n,t){let r=`${Fn}: ${e} (${t})`;try{return{needed:kc(yc(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function Ec(e){let n=[$b(e),Lb(e),Ib(e),Nb(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 $b(e){let n=e.homeNeed??vc;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:di}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??se;return t!==se?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${se.toString(8)}`,fix:`${di} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function Lb(e){return ae(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 \`${we("red-skills-redskilled",["provision"])}\``}}function Ib(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:`${di} \u2014 it starts the daemon and waits for the socket`}}function Nb(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 Pc(e={}){let n=e.env??process.env,t=e.homeDir??ci(),r=e.paths??he({env:n}),o=Oe(t),[i,s,a]=await Promise.all([fi(o),ee(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):pi({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:i!==void 0,homeMode:i,homeNeed:a,entry:Re(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:s,supervisorUnit:await Mb(Wb(e,n,t),n)}}var Cb="redskilled.service";function jc(e){return ui(e,"systemd","user",Cb)}function Dc(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(`
78
+ `)}async function Oc(e){let n=jc(e.configHome);return await fi(n)!==void 0?{path:n,status:"already-present"}:(await wc(Tb(n),{recursive:!0}),await Ab(n,e.unit,"utf8"),{path:n,status:"installed"})}async function Mb(e,n){if(process.platform!=="linux")return"unsupported";try{return await xc(jc(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function Wb(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??ui(t,".config")}async function fi(e){try{return(await Ob(e)).mode&511}catch{return}}import{readdir as Tc,rm as Fb,stat as Bb}from"node:fs/promises";import{dirname as Hb,join as mi}from"node:path";var Ub=5*6e4,Gb="redskilled.";function Kb(e={}){let n=e.env??process.env,t=s=>Hb(yt({key:"redskilled:reclaim-probe",socketFileName:ln,env:s,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=n,i=[t(n),t(o)];return[...new Set(i)]}async function $c(e={}){let n=e.roots??Kb(e),t=e.graceMs??Ub,r=e.now??Date.now,o=e.isPidAlive??H,i=e.answers??Qb,s=e.dryRun===!0,a=[];for(let l of n){let d;try{d=(await Tc(l,{withFileTypes:!0})).filter(p=>p.isDirectory()).map(p=>p.name)}catch{continue}for(let p of d.sort())a.push(await Vb(mi(l,p),{graceMs:t,now:r,pidAlive:o,answers:i,dryRun:s}))}return{roots:n,scanned:a.length,reclaimed:a.filter(l=>l.verdict==="reclaimed").length,dryRun:s,entries:a}}async function Vb(e,n){let t;try{t=(await Tc(e)).sort()}catch(s){return{dir:e,verdict:"failed",reason:Lc(s),removed:[]}}let r=t.filter(s=>s.startsWith(Gb));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await qb(mi(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 Ac(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(ln)&&await n.answers(mi(e,ln)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let i=await Jb(e,n.now);return i!==void 0&&i<n.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(i/1e3)}s ago`,removed:[]}:await Ac(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function Ac(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await Fb(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:Lc(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function qb(e){try{return await Mn(e)}catch{return}}async function Jb(e,n){try{return Math.max(0,n()-(await Bb(e)).mtimeMs)}catch{return}}async function Qb(e){try{return(await Ln({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function Lc(e){return e instanceof Error?e.message:String(e)}var zb="plugins.dev.statusline",Yb="dev.statusline";function Xb(e){let n=[],t=a=>{for(let l of[zb,Yb]){let d=`${l}.${a}`,p=ze(e,d)?.trim();if(p!=null&&p!=="")return{key:d,value:p}}},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 i=[{leaf:"max_workers",assign:a=>{o.maxWorkers=a}},{leaf:"max_projects",assign:a=>{o.maxProjects=a}},{leaf:"max_width",assign:a=>{o.maxWidth=a}}];for(let a of i){let l=t(a.leaf);if(l==null)continue;let d=Number(l.value);Number.isInteger(d)&&d>=0?a.assign(d):n.push({...l,reason:"expected a whole number of zero or more"})}let s=t("verbose");return s!=null&&(s.value==="true"||s.value==="false"?o.verbose=s.value==="true":n.push({...s,reason:"expected `true` or `false`"})),{config:o,warnings:n}}var Zb={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 Ic(e){let{values:n,positionals:t}=je(e,Zb),r=[],o={},i=n.mode??t.find(a=>a==="global"||a==="local");i!=null&&(i==="local"||i==="global"?o.mode=i:r.push({key:"--mode",value:i,reason:"expected `local` or `global`"})),n.project!=null&&(o.project=n.project),n.verbose!==void 0&&(o.verbose=n.verbose===!0);let s=[{flag:"max-workers",assign:a=>{o.maxWorkers=a}},{flag:"max-projects",assign:a=>{o.maxProjects=a}},{flag:"max-width",assign:a=>{o.maxWidth=a}}];for(let a of s){let l=n[a.flag];if(l==null)continue;let d=Number(l);Number.isInteger(d)&&d>=0?a.assign(d):r.push({key:`--${a.flag}`,value:l,reason:"expected a whole number of zero or more"})}return{flags:o,warnings:r}}function Nc(e={}){let n=e.configText==null?{config:{},warnings:[]}:Xb(e.configText),t=e.flags??{};return{options:{...$,mode:t.mode??n.config.mode??$.mode,project:t.project!==void 0?t.project:e.project??$.project,maxWorkers:t.maxWorkers??n.config.maxWorkers??$.maxWorkers,maxProjects:t.maxProjects??n.config.maxProjects??$.maxProjects,maxWidth:t.maxWidth??n.config.maxWidth??$.maxWidth,verbose:t.verbose??n.config.verbose??$.verbose},warnings:n.warnings}}var nR=`Usage: redskilled <command> [options]
79
79
 
80
80
  Commands:
81
81
  host-state (default) print the host's state as JSON
@@ -87,7 +87,7 @@ Commands:
87
87
 
88
88
  Run \`redskilled <command> --help\` for a command's own usage.
89
89
  \`--version\` (\`-v\`) prints the build stamp; both answer offline.
90
- `,vR={serve:`Usage: redskilled serve [options]
90
+ `,tR={serve:`Usage: redskilled serve [options]
91
91
 
92
92
  Runs the daemon in this process. Every path is a flag and none is derived
93
93
  (ADR 0130 rule 3); what is absent falls back to the session derivation.
@@ -151,19 +151,19 @@ Reports every session runtime dir it looked at and why it kept or removed it.
151
151
 
152
152
  --dry-run the same report with nothing removed
153
153
  --grace-ms <n> how long a dir must be idle before it is reclaimed
154
- `};function ER(e){return e==="--help"||e==="-h"||e==="help"}var PR={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)}},fc="REDSKILLED_HOST_TOKEN";function Yo(){try{let n=xR("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function jR(e=process.env,n=Yo){let t=(e[fc]??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 DR(e,n=process.env,t=Yo){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...uc(e,n,t),armTransport:()=>uc(e,n,t)}}function uc(e,n=process.env,t=Yo){let r=jR(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${fc}, 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:la({token:r.token,...o?{endpoint:o}:{}})}}async function OR(e){if(e[0]==="--version"||e[0]==="-v"){let o=br("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
155
- `:`${ps(o)}
156
- `),0}if(ER(e[0]))return process.stdout.write(SR),0;let{command:n,args:t}=gs(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(vR[n]),0;if(n==="serve"){let{values:o}=je(t,PR),i=DR(o),s=pc(Oe(zo()),"state"),a=Ns({stateRoot:s});process.stderr.write(`${Cs(a)}
157
- `);let l=As({lanePath:bn(s),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),d=await $d({paths:FR(o),idleMs:o["idle-ms"]??Mo,daemonVersion:o["daemon-version"]??br("redskilled").version,deaths:a.attributions,queueDiscovery:i,...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let p of["SIGTERM","SIGINT"])process.once(p,()=>void d.stop({reason:"signal",signal:p}).catch(()=>{}));return await d.closed,l.phase("closed"),0}if(n==="stop")return await LR(t);if(n==="statusline")return await IR(t);if(n==="unit")return await $R(t);if(n==="provision")return await NR(t);if(n==="reclaim")return await MR(t);let r=await Hd(he());return process.stdout.write(`${JSON.stringify(r,null,2)}
158
- `),0}var AR={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function LR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),{values:r}=je(e,AR),o=await Wd(n.paths??he(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${M({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(i=>({worker_id:i.worker_id,project_label:i.project_label,pid:i.pid,unit:i.unit,isolated:i.isolated,survives:i.survives})),detail:o.detail})}
159
- `),o.running&&!o.stopped?1:0}async function $R(e,n={}){let t=n.write??(i=>process.stdout.write(i)),r=n.paths??he(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(ld(n.unitIO??{}),null,2)}
160
- `),0;if(o==="install"){let i=await id(rd(r),n.unitIO??{});return t(`${JSON.stringify(i,null,2)}
161
- `),i.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await sd(n.unitIO??{}),null,2)}
162
- `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function IR(e,n={}){let t=n.write??(l=>process.stdout.write(l)),r=n.warn??(l=>process.stderr.write(l)),o=dc(e),i=HR(n.cwd??process.cwd()),s=cc({...i.configText==null?{}:{configText:i.configText},project:i.label,flags:o.flags});for(let l of[...s.warnings,...o.warnings])r(`redskilled statusline: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
163
- `);let a;try{a=await Fd(n.paths??he(),s.options,{...n.client??{},...s.options.project==null?{}:{sessionProject:s.options.project}})}catch(l){r(`redskilled statusline: ${l instanceof Error?l.message:String(l)}
164
- `),a=pa({options:s.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${a.lines.join(`
154
+ `};function rR(e){return e==="--help"||e==="-h"||e==="help"}var oR={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)}},Wc="REDSKILLED_HOST_TOKEN";function qt(){try{let n=eR("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function Fc(e=process.env,n=qt){let t=(e[Wc]??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 iR(e,n=process.env,t=qt){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...Cc(e,n,t),armTransport:()=>Cc(e,n,t)}}function sR(e,n=process.env,t=qt){let r=Fc(n,t);if(r==null)return null;let o=n.GITHUB_API_URL;return{transport:Po({token:r.token,...o?{origin:o}:{}})}}function Cc(e,n=process.env,t=qt){let r=Fc(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${Wc}, 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:La({token:r.token,...o?{endpoint:o}:{}})}}async function lR(e){if(e[0]==="--version"||e[0]==="-v"){let o=Or("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
155
+ `:`${Ts(o)}
156
+ `),0}if(rR(e[0]))return process.stdout.write(nR),0;let{command:n,args:t}=Ns(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(tR[n]),0;if(n==="serve"){let{values:o}=je(t,oR),i=iR(o),s=sR(o),a=Mc(Oe(hi()),"state"),l=tl({stateRoot:a});process.stderr.write(`${rl(l)}
157
+ `);let d=Ys({lanePath:vn(a),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),p=await ic({paths:kR(o),idleMs:o["idle-ms"]??ri,daemonVersion:o["daemon-version"]??Or("redskilled").version,deaths:l.attributions,queueDiscovery:i,...s==null?{}:{githubBalance:s},...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let u of["SIGTERM","SIGINT"])process.once(u,()=>void p.stop({reason:"signal",signal:u}).catch(()=>{}));return await p.closed,d.phase("closed"),0}if(n==="stop")return await dR(t);if(n==="statusline")return await uR(t);if(n==="unit")return await cR(t);if(n==="provision")return await fR(t);if(n==="reclaim")return await hR(t);let r=await pc(he());return process.stdout.write(`${JSON.stringify(r,null,2)}
158
+ `),0}var aR={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function dR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),{values:r}=je(e,aR),o=await uc(n.paths??he(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${M({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(i=>({worker_id:i.worker_id,project_label:i.project_label,pid:i.pid,unit:i.unit,isolated:i.isolated,survives:i.survives})),detail:o.detail})}
159
+ `),o.running&&!o.stopped?1:0}async function cR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),r=n.paths??he(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify($d(n.unitIO??{}),null,2)}
160
+ `),0;if(o==="install"){let i=await Ad(Dd(r),n.unitIO??{});return t(`${JSON.stringify(i,null,2)}
161
+ `),i.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await Td(n.unitIO??{}),null,2)}
162
+ `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function uR(e,n={}){let t=n.write??(l=>process.stdout.write(l)),r=n.warn??(l=>process.stderr.write(l)),o=Ic(e),i=yR(n.cwd??process.cwd()),s=Nc({...i.configText==null?{}:{configText:i.configText},project:i.label,flags:o.flags});for(let l of[...s.warnings,...o.warnings])r(`redskilled statusline: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
163
+ `);let a;try{a=await fc(n.paths??he(),s.options,{...n.client??{},...s.options.project==null?{}:{sessionProject:s.options.project}})}catch(l){r(`redskilled statusline: ${l instanceof Error?l.message:String(l)}
164
+ `),a=Wa({options:s.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${a.lines.join(`
165
165
  `)}
166
- `),0}var TR={"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 NR(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=je(e,TR),o=n.paths??he(),i=n.homeDir??zo(),s=await Go({homeDir:i,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),a=r.check||!s.needed?void 0:await Xd(i),l;if(!r.check&&!r["no-start"])try{await Uo(o,n.client??{})}catch(f){l=f instanceof Error?f.message:String(f)}let d=await nc({paths:o,homeNeed:s,...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}}}),p=r["install-unit"]&&ae(d.entry)?await oc({configHome:n.configHome??WR(),unit:rc({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=ec(d);return t(`${M({verdict:u.verdict,home:{path:a?.path??d.homePath,created:a?.created??!1,tightened:a?.tightened??!1,needed:s.needed,needed_by:s.declaredBy},socket:d.socketPath,...l==null?{}:{start_error:l},...p==null?{}:{unit:{path:p.path,status:p.status}},checks:u.rows.map(f=>({check:f.check,verdict:f.verdict,evidence:f.evidence})),fixes:u.findings.map(f=>({check:f.check,fix:f.fix}))})}
167
- `),u.verdict==="ok"?0:1}var CR={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function MR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),{values:r}=je(e,CR),o=await lc({...n.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return t(`${M({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(i=>({dir:i.dir,verdict:i.verdict,reason:i.reason,removed:[...i.removed]}))})}
168
- `),o.entries.some(i=>i.verdict==="failed")?1:0}function WR(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:pc(zo(),".config")}function HR(e){let n=Wr(e);return n.configText==null?{label:null}:{configText:n.configText,label:Vs(e)}}function FR(e){let n=he();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 UR=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;UR&&OR(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
169
- `),process.exitCode=1});export{fc as REDSKILLED_HOST_TOKEN_ENV,SR as REDSKILLED_USAGE,uc as armRedskilledQueueTransport,jR as resolveRedskilledHostToken,DR as resolveServeQueueDiscovery,NR as runProvision,MR as runReclaim,OR as runRedskilledCli,IR as runStatusline,LR as runStop,$R as runUnit};
166
+ `),0}var pR={"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 fR(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=je(e,pR),o=n.paths??he(),i=n.homeDir??hi(),s=await pi({homeDir:i,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),a=r.check||!s.needed?void 0:await Sc(i),l;if(!r.check&&!r["no-start"])try{await li(o,n.client??{})}catch(f){l=f instanceof Error?f.message:String(f)}let d=await Pc({paths:o,homeNeed:s,...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}}}),p=r["install-unit"]&&ae(d.entry)?await Oc({configHome:n.configHome??gR(),unit:Dc({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=Ec(d);return t(`${M({verdict:u.verdict,home:{path:a?.path??d.homePath,created:a?.created??!1,tightened:a?.tightened??!1,needed:s.needed,needed_by:s.declaredBy},socket:d.socketPath,...l==null?{}:{start_error:l},...p==null?{}:{unit:{path:p.path,status:p.status}},checks:u.rows.map(f=>({check:f.check,verdict:f.verdict,evidence:f.evidence})),fixes:u.findings.map(f=>({check:f.check,fix:f.fix}))})}
167
+ `),u.verdict==="ok"?0:1}var mR={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function hR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),{values:r}=je(e,mR),o=await $c({...n.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return t(`${M({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(i=>({dir:i.dir,verdict:i.verdict,reason:i.reason,removed:[...i.removed]}))})}
168
+ `),o.entries.some(i=>i.verdict==="failed")?1:0}function gR(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:Mc(hi(),".config")}function yR(e){let n=Qr(e);return n.configText==null?{label:null}:{configText:n.configText,label:ul(e)}}function kR(e){let n=he();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 bR=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;bR&&lR(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
169
+ `),process.exitCode=1});export{Wc as REDSKILLED_HOST_TOKEN_ENV,nR as REDSKILLED_USAGE,Cc as armRedskilledQueueTransport,Fc as resolveRedskilledHostToken,sR as resolveServeGithubBalance,iR as resolveServeQueueDiscovery,fR as runProvision,hR as runReclaim,lR as runRedskilledCli,uR as runStatusline,dR as runStop,cR as runUnit};