@reddb-io/red-skills 3.3.10 → 3.3.11

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 Uc=Object.defineProperty;var Bc=(e,n)=>()=>(e&&(n=e(e=0)),n);var Vc=(e,n)=>{for(var t in n)Uc(e,t,{get:n[t],enumerable:!0})};var ol={};Vc(ol,{REDSKILLED_BIN_ENV:()=>qr,REDSKILLED_BUNDLE_ASSET:()=>le,REDSKILLED_ENTRY_UNRESOLVED:()=>xn,RedskilledDaemonEntryError:()=>Sn,isRedskilledEntryPath:()=>Gr,isResolvedRedskilledEntry:()=>ae,redskilledBundleCacheRoot:()=>mt,redskilledServeArgv:()=>Oe,requireRedskilledEntry:()=>ht,resolveRedskilledEntry:()=>Re});import{existsSync as Uf,readdirSync as Bf}from"node:fs";import{homedir as Vf}from"node:os";import{basename as Kr,dirname as Vr,join as K,resolve as ft}from"node:path";function ae(e){return"command"in e}function Oe(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??Uf,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[qr];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(s&&Gr(s))return a(ft(s),"caller-entry");let d=[];for(let[p,u]of Gf(s,n.rootDir,t,n.listDir??Yf))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 Gr(e){let n=Kr(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(Kr(n)==="redskilled")return!0;let r=Vr(n);if(r===n)return!1;n=r}return!1}function*Gf(e,n,t,r){if(e){let i=Vr(ft(e));yield[K(i,le),"caller-sibling-bundle"];let s=Kf.exec(Kr(e));s&&(yield[K(i,`redskilled-${s[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[K(i,"..","dist",le),"caller-sibling-bundle"]}for(let i of qf){let s=t[i];s&&(yield[K(s,"dist",le),"plugin-root-bundle"],yield[K(s,"..","..","dist",le),"plugin-root-bundle"])}n&&(yield[K(n,"dist",le),"repo-bundle"],yield[K(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[K(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=rl(t);yield[K(o,le),"bundle-cache"];for(let i of Qf(o,r))yield[K(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||K(e.HOME||Vf(),".cache");return K(n,"red-skills","bundles")}function Qf(e,n){return n(e).filter(t=>Jr.test(t)).sort((t,r)=>zf(tl(r),tl(t)))}function tl(e){return Jr.exec(e)?.[1]??""}function zf(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 Yf(e){try{return Bf(e)}catch{return[]}}var le,xn,qr,Sn,Kf,Jr,qf,pe=Bc(()=>{"use strict";le="redskilled.bundle.min.mjs",xn="redskilled-daemon-entry-unresolved",qr="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 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)`:""}
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)}};Kf=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Jr=/^redskilled-(.+)\.bundle\.min\.mjs$/,qf=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as RR}from"node:child_process";import{homedir as Qo}from"node:os";import{join as uc}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}},Se=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 He(e,n)}function S(e,n){return new Se(e,n)}function Fe(e){return e instanceof Se?e:e instanceof He?new Se(e.line,e.reason):new Se(0,String(e&&e.message?e.message:e))}var Di=["type","kind","event"],ve="|",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:Kc(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 G(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 Kc(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function qc(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 Qc(e,n);throw R(0,"not a primitive")}function Gc(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function N(e){return Gc(e)?e:Zn(e)}function Qc(e,n){return er(e,n)?Zn(e):e}function er(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||qc(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 Q(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=zc(r,1);if(o===void 0)return e;Q(n,t,o)}return n}function zc(e,n){if(!A(e)||!Yc(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=Xc(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 nr(n);let h=d.get(u)??0,b=m[h];if(b===void 0)throw nr(n);return d.set(u,h+1),Zc(r,u,a[f],b,n)});for(let[u,f]of l)if((d.get(u)??0)!==f.length)throw nr(n);return p}function Yc(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function Xc(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=>ru(p,t));if(a.some(p=>p===""))throw C(t);let l=tu(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 Zc(e,n,t,r,o){let i={};Q(i,e,n);for(let[s,a]of Object.entries(t??{})){if(s===e||Object.prototype.hasOwnProperty.call(i,s))throw C(o);Q(i,s,a)}for(let[s,a]of Object.entries(eu(r,o))){if(s===e||Object.prototype.hasOwnProperty.call(i,s))throw C(o);Q(i,s,a)}return i}function eu(e,n){let t={};for(let[r,o]of Object.entries(e))nu(t,r.split("."),o,n);return et(t,n)}function nu(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 tu(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 ru(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 nr(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=ou(i);if(s===void 0)return;t.push([o,s])}let r=[];for(let[o,i]of t)au(r,o,i);return r.join("")}function ou(e){if(!Array.isArray(e)||e.length===0||!e.every(A))return;let n=iu(e);if(n===void 0)return;let t=e.map(a=>a[n]),r=su(t);if(r===void 0)return;let o=lu(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)&&!tr(u,p,d))return;i.get(l).push(d)}let s=[];for(let a of r.cycle){let l=i.get(a),d=cu(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 iu(e){return Di.find(n=>e.every(t=>typeof t[n]=="string"))}function su(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 lu(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(!du(i)||!e.every(s=>Object.prototype.hasOwnProperty.call(s,i))||!e.every(s=>oe(s[i])))break;t.push(i)}return t}function au(e,n,t){e.push(N(n),`:
9
- `),e.push(" order: ",H(t.order.encoded,ve),`
10
- `),e.push(" discriminator: ",H(t.discriminator,ve),`
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),`
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),ve,"]{",t.map(N).join(ve),`}:
13
- `);for(let o of r)e.push(" ",t.map(i=>H(o[i],ve)).join(ve),`
14
- `)}function du(e){return e!==""&&rr(e)}function tr(e,n,t,r=new Set){if(!rr(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)=>tr(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(".")&&tr(s,`${n}.${i}`,t,r));return r.delete(e),o}return!1}function cu(e){let n=Object.keys(e[0]??{});if(e.every(t=>uu(Object.keys(t),n)))return n.every(rr)?n:void 0}function uu(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function rr(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function Ue(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=fu(f.slice(1,-1),u),m=ir(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=pu(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 pu(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(Vi(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 fu(e,n){if(n!==D&&e.includes(D)&&(e.includes("[")||e.includes("{")))return or(e,D,n);try{return or(e,n,n)}catch(t){if(n!==D&&t.reason!=="duplicate key")return or(e,D,n);throw t}}function or(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=mu(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=ir(s);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(Vi(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 mu(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 ir(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?ir(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function tt(e,n,t){return e.listDelimiter===void 0?B(n,t):G(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 Vi(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 z(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 yu(d,r,t)}if(i&&W(o.content,":",o.number)===-1)return B(o.content.trim(),o.number);let s={index:0},a=lr(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 lr(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}=hu(e,n,t,r);Yi(o,s,a,l,r,i.number)}return o}function hu(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=sr(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=gu(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=sr(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=ar(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=sr(e,n,t,l,o.number,r);return{key:u,quoted:f,value:m}}function sr(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?lr(e,n,t+1,i):{}}function gu(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=G(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 yu(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=ar(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 ar(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 ku(e,e.fields,t,r,o+1,i)}if(a!==""){let l=G(a,e.delimiter,s).map(d=>B(d,s));if(l.length!==e.len)throw R(s,"array length mismatch");return l}return vu(e,t,r,o+1,i)}function ku(e,n,t,r,o,i){if(e.fieldTree!==void 0&&xu(e.fieldTree))return Ru(e,t,r,o,i);let s=[];for(;s.length<e.len;){let l=t[r.index];if(l===void 0)throw Ue(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(!Be(l.content,e.delimiter,l.number))break;let d=G(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 Ue(t,r.index);let a=t[r.index];if(a!==void 0&&a.depth>=o&&Be(a.content,e.delimiter,a.number))throw R(a.number,"array length mismatch");return s}function Ru(e,n,t,r,o){return Ki(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function Ki(e,n,t,r,o,i,s,a){let l=[],d=Ji(e,n,t,r,o.index,i,s);for(;l.length<e;){let u=r[o.index];if(u===void 0)throw Ue(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(!Be(u.content,t,u.number))break;let f=G(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(wu(n,h,a)),o.index=m.nextIndex}if(l.length!==e)throw Ue(r,o.index);let p=r[o.index];if(p!==void 0&&p.depth>=i&&Be(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=bu(d,u,n,t,r,o,i,s,a);Ve(l,[d.key],f,a,t)}),l}function bu(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+Su(n)):k){if(f===void 0)throw R(r,"array row length mismatch");return i.cellIndex+=1,Ki(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 Ji(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=Gi(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 Gi(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||!Be(f.content,r,f.number))return;let m=G(f.content,r,f.number),h=_u(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&&Be(p.content,r,p.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function _u(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=Ji(f,u.children,r,o,d,s,a);if(m===void 0)return;let h=Gi(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 wu(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 xu(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 Su(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+zi(t),0)}function Be(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 vu(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 Ue(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(Eu(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 Eu(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 ar(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 lr(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(Pu)){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");Q(e,i,t);return}if(s&&!A(e[i])){if(r.strict)throw R(o,"path expansion conflict");Q(e,i,{})}else s||Q(e,i,{});Ve(e[i],n.slice(1),t,r,o)}function Pu(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)?pr(i,void 0,e,0,!1,o):A(e)?Xi(i,e,0,o):i.push(H(e,r)),i.join("")}function Ke(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))Ke(e,t),cr(e,o,i,t,r)}function cr(e,n,t,r,o){if(ie(r,0,o),Array.isArray(t)){pr(e,n,t,r,!1,o);return}if(A(t)){let i=o.keyedMapCollapse?Du(t,o,r+1):void 0;if(i!==void 0){e.push(N(n),"{",fr(o.delimiter),i.fields.map(s=>gr(s,o.delimiter)).join(o.delimiter),`}:
15
- `);for(let[s,a]of Object.entries(t)){Ke(e,r+1);let l=[];e.push(N(s),": ",i.paths.map(d=>yr(hr(a,d.path),d,o.delimiter,o,l,r+2)).join(o.delimiter),`
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),`
16
16
  `),e.push(...l)}return}e.push(N(n),`:
17
17
  `),Xi(e,t,r+1,o);return}e.push(N(n),": ",H(t,o.delimiter),`
18
- `)}function pr(e,n,t,r,o,i){if(ie(r,0,i),t.length===0){n!==void 0?e.push(N(n),`: []
18
+ `)}function fr(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)){dr(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){dr(e,n,t.length,s.fields,i.delimiter),e.push(`
23
- `);for(let a of t){Ke(e,r+1);let l=[];e.push(s.paths.map(d=>yr(hr(a,d.path),d,i.delimiter,i,l,r+2)).join(i.delimiter)),e.push(`
24
- `),e.push(...l)}return}dr(e,n,t.length,void 0,i.delimiter),e.push(`
25
- `);for(let a of t)Ke(e,r+1),ju(e,a,r+1,i)}function ju(e,n,t,r){if(ie(t,0,r),Array.isArray(n)){e.push("- "),pr(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("- "),cr(e,o[0][0],o[0][1],t+1,r);for(let[i,s]of o.slice(1))Ke(e,t+1),cr(e,i,s,t+1,r);return}e.push("- ",H(n,r.delimiter),`
27
- `)}function dr(e,n,t,r,o){n!==void 0&&e.push(N(n)),e.push("[",String(t),fr(o),"]"),r!==void 0&&e.push("{",r.map(i=>gr(i,o)).join(o),"}"),e.push(":")}function fr(e){return e===D?"":e}function Zi(e,n,t){let r=Ou(e,n);if(r!==void 0)return r;let o=ur(e.map(i=>({value:i})),n,t);return o===void 0?void 0:{fields:o,paths:mr(o)}}function Du(e,n,t){let r=Object.values(e);if(!(r.length<2))return Zi(r,n,t)}function ur(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=ur(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=ur(s,n,t+1);if(a===void 0)return;i.children=a}return o}}function Ou(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 mr(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}]:mr(t.children,r)})}function hr(e,n){let t=e;for(let r of n)t=t[r];return t}function gr(e,n){return e.listDelimiter!==void 0?`${N(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${N(e.key)}[${e.fixedLength}${fr(n)}]`:e.children===void 0?N(e.key):`${N(e.key)}{${e.children.map(t=>gr(t,n)).join(n)}}`}function yr(e,n,t,r,o,i){return n.childFields!==void 0?(Au(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=>Lu(s,t,n.listDelimiter)).join(n.listDelimiter)}function Au(e,n,t,r,o){for(let i of n){Ke(e,o);let s=[];e.push(mr(t).map(a=>yr(hr(i,a.path),a,r.delimiter,r,s,o+1)).join(r.delimiter)),e.push(`
28
- `),e.push(...s)}}function Lu(e,n,t){return typeof e!="string"?H(e,n):er(e,n)||e.includes(t)?Zn(e):e}var as=[D,"|"," "];var ds=8,cs=/^[A-Za-z0-9_-]+$/,Nb=new TextEncoder,Cb=new TextDecoder;function Nu(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 Cu(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 Mu(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=G(p,a,n).map(f=>J(f,n)[0])}catch(f){throw Fe(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 Wu(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=G(e,n,r)}catch(i){throw Fe(i)}if(o.length!==t)throw S(r,"row arity mismatch");for(let i of o)try{B(i,r)}catch(s){throw Fe(s)}return o}function Hu(e,n,t){let r={};return e.forEach((o,i)=>{try{Q(r,o,B(n[i],t))}catch(s){throw Fe(s)}}),r}function Fu(e,n,t){if(e.startsWith("- "))throw S(n,"reserved line prefix");let r=Nu(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=Mu(e,n);if(o!==null)return o.continuation?(Wu(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let i=Cu(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 Uu(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=Fu(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 Uu(e).flatMap(n=>n.rows.map(t=>Hu(n.fields,t,0)))}function Bu(e){if(!as.includes(e))throw S(0,"invalid header delimiter")}function ts(e,n,t=!1){return`[${`${t?"~":""}${e===D?"":e}`}]{${n}}:
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
29
  `}function rs(e,n){return`[]<${e}>{${n}}:
30
- `}function kr(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 Fe(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 Ku(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 qu(e){return JSON.stringify([...e].sort())}function ls(e,n){let t=qu(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}={}){Bu(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=()=>Ku(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,Te)=>we!==w[Te]))&&(j+=m(),o=w,i=kr(e,o),a=0,l=0,d=0,j+=ts(e,i));let ee=o.map(we=>H(k[we],e));j+=h();let q=`${ee.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),ee=kr(D,j),q=b(k);return os(q.fields,j)?"":(q.fields=j,rs(k,ee))},pushTagged(k,w){if(u)throw S(0,"TOONL encoder is closed");let j=b(k),ee=ls(ss(w),j.fieldsByShape),q=kr(D,ee),we=ee.map(Cn=>H(w[Cn],D)),Te="";return os(j.fields,ee)||(j.fields=ee,Te+=rs(k,q)),`${Te}${k}:${we.join(D)}
33
- `},end(){return u?"":(u=!0,m())}}}function Rr(e){let n={app:e,version:Ju(qe("__RED_BUILD_VERSION__",()=>"3.3.10")??"0.0.0-dev"),gitSha:qe("__RED_BUILD_GIT_SHA__",()=>"efacf48c6512520601e438c4e755e96b51509e23")??"unknown",buildTime:qe("__RED_BUILD_TIME__",()=>"2026-08-02T23:09:28-03:00")??"unknown",bundleAsset:qe("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=qe("__REDDB_SDK_VERSION__",()=>""),r=qe("__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 qe(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"},Gu=/^[a-z][a-z0-9+.-]*:\/\//i;function Qu(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 zu(e=fs){return Object.entries(e).map(([n,t])=>Qu(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function Yu(e){return/^-\d+(\.\d+)?$/.test(e)}function kn(e){return!(!e||e.startsWith("-")&&!Yu(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 Ee(e,n){switch(n){case"boolean":return Xu(e);case"number":return Zu(e);case"array":return e.split(",").map(t=>it(t.trim()));case"string":default:return e}}function Xu(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function Zu(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 ep(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 np(e){let n=[],t=rp(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
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",`
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=op(e.options);n.push(...r)}return n}function tp(e,n){let t=np(e);return ep(t,n)}function rp(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 op(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=up(e.options??{},e.autoShort??!1),t=zu(e.separators??fs);return{schema:e,parse(r){return ip(r,e,n,t)},help(){return tp(e,e.formatter)}}}function ip(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?Ee(h,f.type):h),l++}o.positional[f.name]=m,s++}else{let m=f.type?Ee(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=dp(p,l,e,o,t,n);continue}if(p.startsWith("-")&&p.length>1&&!gp(p)){l=cp(p,l,e,o,t,n);continue}let u=sp(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?Ee(b,f.type):b),l++}o.positional[f.name]=h,s++;continue}let m=f.type?Ee(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 fp(o,n,t),mp(o,n,a),hp(o,n,t),o}function sp(e,n){if(Gu.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(lp(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(ap(o,i,t))return{key:o,value:i,config:t}}}return null}function lp(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function ap(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 dp(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 cp(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=br(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=br(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=br(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?Ee(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?Ee(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 up(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=pp(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 pp(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 br(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function fp(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?Ee(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 mp(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 hp(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 gp(e){return/^-\d+(\.\d+)?$/.test(e)}var _r=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 yp(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 kp(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 Pe(e,n,t={}){let o=hs({options:yp(n),separators:{},allowUnknown:!0}).parse([...e]),i={},s=kp(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 _r(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 wr=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 wr(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as Dp,mkdirSync as Op,readFileSync as Es,statSync as Ap}from"node:fs";import{dirname as js,join as Lp}from"node:path";var ys="RED_WORKER_SCOPE",ks="RED_WORKER_MEMORY_CEILING",Rs="RED_WORKER_SCOPE_DEGRADATION",Sr={scope:null,memory_ceiling:null,scope_degradation:null};function vr(e){return{scope:xr(e[ys]),memory_ceiling:xr(e[ks]),scope_degradation:xr(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 xr(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as _p,readdirSync as wp,readFileSync as xs,rmSync as xp,writeFileSync as Sp}from"node:fs";import{basename as vp,join as Je}from"node:path";import{isAbsolute as g_,join as lt,resolve as y_}from"node:path";function Rp(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var bs="deaths",_s="deaths.toonl";function at(e){return lt(Rp(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 Er(e){return lt(at(e),ws)}var jr=Je("sys","kernel","random","boot_id"),Ss=1;function Dr(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,jr)),cgroup:Ep(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 Ep(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 Or(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function Ar(e,n){let t=Je(e,Or(n));try{return _p(e,{recursive:!0,mode:448}),Sp(t,ue({trailer:!1}).push(jp(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function je(e,n){try{xp(Je(e,Or(n)),{force:!0})}catch{}}function Lr(e,n){let t;try{t=wp(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(Pp(a))}catch(s){n?.(vp(i),s instanceof Error?s.message:String(s))}}return r}function Pp(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:Pr(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:Pr(e.pid),ppid:Pr(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 Pr(e){return typeof e=="number"?e:Number(e)}function jp(e){return{...e}}var $p=1,Ip=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Tp(e){return typeof e=="string"&&Ip.has(e)}var Np="startup";function Cp(e,n){return{...e.scope??Sr,version:$p,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 Mp(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 Ir={mkdir(e){Op(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=Ap(e).size}catch{return!0}if(n===0)return!0;try{return Es(e,"utf8").endsWith(`
43
- `)}catch{return!0}},append(e,n){Dp(e,n,{encoding:"utf8",mode:384})},read(e){return Es(e,"utf8")}};function Wp(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function Hp(e,n,t=Ir){let r=ue({trailer:!1}).push(Wp(n));return t.mkdir(js(e)),t.endsClean(e)||t.append(e,`
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
44
  `),t.append(e,r),n}function Ds(e){let n=e.endsWith(`
45
45
  `)?e:e.slice(0,e.lastIndexOf(`
46
- `)+1);return n===""?[]:ye(n).map(Fp)}function Fp(e){let n=e.exit_path;if(!Tp(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:V(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:V(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:V(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:V(e.uptime_s),rss_kb:V(e.rss_kb),max_rss_kb:V(e.max_rss_kb),user_cpu_us:V(e.user_cpu_us),system_cpu_us:V(e.system_cpu_us),minor_page_faults:V(e.minor_page_faults),major_page_faults:V(e.major_page_faults),voluntary_ctx_switches:V(e.voluntary_ctx_switches),involuntary_ctx_switches:V(e.involuntary_ctx_switches)}}function V(e){return typeof e=="number"?e:Number(e)}function Os(e,n=Ir){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return Ds(t)}var Up=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],$r=null;function As(e){let n=e.host??process,t=e.io??Ir,r=e.clock??(()=>new Date().toISOString()),o=n.pid,i=e.scope??vr(process.env),s=e.phase??Np,a=null,l=e.presenceDir===void 0?Lp(js(e.lanePath),_n):e.presenceDir,d=null,p=()=>{l!==null&&(d=Dr({kind:e.kind,id:e.id,last_phase:s,pid:o},{procRoot:e.procRoot}),Ar(l,d))},u=k=>{if(!a){try{a=Hp(e.lanePath,Cp({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:s,scope:i,...k},Mp(n)),t)}catch{}l!==null&&d!==null&&je(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??Up).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&&je(l,d),$r===b&&($r=null)},handlers:f};return e.setActive!==!1&&($r=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 Bp,readdirSync as Vp,readFileSync as ct,statSync as Kp,writeFileSync as qp}from"node:fs";import{join as Ts}from"node:path";var Jp=1,Gp=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],Qp=512*1024;function zp(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??Gp,r=[],o=Ts(n,jr),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:Tr(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:Tr(l),detail:null})}let a=[];for(let l of t)try{let p=Yp(l,e.tailBytes??Qp).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:Tr(d),detail:null})}return{boot_id:i,live_pids:s,journal:a,probes:r}}function Tr(e){return e.code==="ENOENT"?"absent":"unreadable"}function Yp(e,n){let t=Kp(e).size,r=ct(e,"utf8");return t<=n?r:r.slice(r.length-n)}var Xp=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,Zp=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,ef=/Killed (\/\S*) due to memory pressure/,nf=/\bopid=(\d+)\b/,Ls=/\bsig=(\d+)\b/,tf=/\buid=(\d+)\b/,rf=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,of={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function sf(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,Xp)||$s(u,e.pid,Zp));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=ef.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(nf.exec(u)?.[1])===e.pid&&Ls.test(u));if(d!==void 0){let u=Number(Ls.exec(d)?.[1]),f=tf.exec(d)?.[1];return s("user-signal",o?"medium":"high",of[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=>rf.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 lf=" | ";function Is(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(lf)}function af(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 df(e){let n=ue({trailer:!1});return e.map(t=>n.push(af(t))).join("")}function Ns(e){let n=dt(e.stateRoot),t=Er(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??zp({procRoot:e.procRoot,journalPaths:e.journalPaths}),i=[],s=Lr(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),je(n,u);continue}l.push(sf(u,o,a,r())),je(n,u)}return l.length>0&&cf(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 cf(e,n){try{Bp(Ts(e,".."),{recursive:!0,mode:448});let t=uf(e),r=t===""||t.endsWith(`
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(`
48
48
  `)?"":`
49
- `;qp(e,`${t}${r}${df(n)}`,{encoding:"utf8",mode:384})}catch{}}function uf(e){try{return ct(e,"utf8")}catch{return""}}import{join as pf}from"node:path";var ff=[".red","redskilled"],se=448;function De(e){return pf(e,...ff)}import{execFileSync as Pf}from"node:child_process";import{readFileSync as jf}from"node:fs";import{dirname as Vs,join as Df}from"node:path";import{existsSync as mf,readFileSync as G_}from"node:fs";import{dirname as hf,join as gf}from"node:path";function Ms(e,n){let t=e;for(let r=0;r<16;r++){let o=gf(t,n);if(mf(o))return o;let i=hf(t);if(i===t)break;t=i}return null}function yf(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function Ge(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 yf(d)}}import{createHash as kf}from"node:crypto";var Rf="project.name";function Hs(e){let n=Ge(e,Rf)?.trim();return n===void 0||n===""?void 0:n}var bf=8,Fs="project";function Us(e){let n=vf(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:_f(e.remoteUrl)??{name:wf(e.checkoutPath,n),source:"basename"},o=Sf(n??Nr(e.checkoutPath));return{name:r.name,slug:`${xf(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 _f(e){let n=Bs(e);return n===void 0?void 0:{name:n,source:"remote"}}function wf(e,n){let t=n===void 0?"":Ws(Ef(n));if(t!=="")return t;let r=Ws(Nr(e));return r===""?Fs: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===""?Fs:t}function Sf(e){return kf("sha256").update(e).digest("hex").slice(0,bf)}function vf(e){let n=Nr(e??"");return n===""?void 0:n}function Nr(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 Ef(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var Of=2e3;function Ks(e){return Af(e).name}function Af(e){let n=Mr(e),t=Cr(e,["rev-parse","--absolute-git-dir"])??Cr(e,["rev-parse","--git-common-dir"]),r=Cr(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 Mr(e){let n=Ms(e,Df(".red","config.yaml"));if(n==null)return{};let t;try{t=jf(n,"utf8")}catch{return{}}let r=Hs(t),o=Vs(Vs(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function Cr(e,n){try{let t=Pf("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Of}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as Td}from"node:crypto";import{spawn as Dk}from"node:child_process";import{mkdir as Ok,rm as Ak}from"node:fs/promises";import{dirname as Lk}from"node:path";import{createHash as If}from"node:crypto";import{constants as Br}from"node:fs";import{mkdir as Tf,open as Nf}from"node:fs/promises";import{createConnection as Cf}from"node:net";import{tmpdir as Mf}from"node:os";import{dirname as Wf,join as wn}from"node:path";var Lf="toon";function Gs(e){return e.trimStart().startsWith("{")?"json":"toon"}function Hr(e){let n=0;for(;e[n]===`
51
- `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=Gs(t);if(r==="json"){let i=t.indexOf(`
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(`
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 Fr(e){let n=Gs(e)==="json"?Wr:qs,t=n===Wr?qs:Wr;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function Wr(e){return JSON.parse(e)}function qs(e){return z(e)}function Ur(e,n){if(n==="toon"){let t=$f(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 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(`
55
55
  `)?`${t}
56
56
  `:`${t}
57
57
 
58
58
  `}return`${JSON.stringify(e)}
59
- `}function $f(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!Js(e)||!Js(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function Js(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zs=new Set;function Ys(e){return zs.has(e)?"json":Lf}function Xs(e){zs.add(e)}var Hf=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=Cf(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(Ur(n,r))}),a.on("data",f=>{d+=f.toString("utf8");let m=Hr(d);m&&(d=m.rest,u(()=>{try{i(Fr(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=Hr(r);if(!i)return;r=i.rest,e.pause();let s=a=>{if(!(e.destroyed||!e.writable))try{e.write(Ur(a,i.dialect))}catch{}};(async()=>{let a;try{a=Fr(i.frame),await n(a,s)}catch(l){t(l,a,s)}finally{e.end()}})()})}async function nl(e){await Tf(Wf(e),{recursive:!0,mode:448});try{return await Nf(e,Br.O_CREAT|Br.O_EXCL|Br.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 Ff="/tmp";function pt(e){let n=e.env??process.env,t=If("sha256").update(e.key).digest("hex").slice(0,20),r=l=>wn(l,e.socketFileName).length<Hf,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(Mf(),s);return r(a)||process.platform==="win32"?a:wn(Ff,s)}pe();import{homedir as cm}from"node:os";import{join as Yr}from"node:path";import{spawnSync as um}from"node:child_process";import{createHash as pm}from"node:crypto";import{existsSync as fm}from"node:fs";import{mkdir as al,readFile as mm,writeFile as hm}from"node:fs/promises";import{dirname as gm}from"node:path";var Ae="@reddb-io/red-skills",Xf="https://registry.npmjs.org",Zf="canary",Qe=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function em(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,em(n,t,o))}function nm(e){return e==="dev"?["rsp","redskilled"]:[]}function tm(e){return`${e}.bundle.min.mjs`}function rm(e){return yt("dist",tm(e))}function om(e,n="stable"){return`${Ae}@${n==="canary"?Zf:e}`}function im(e=Ae){return`${Xf}/${e.replace("/","%2F")}`}async function zr(e,n){let{plugin:t,version:r,cacheDir:o,channel:i="stable"}=n,s=gt({plugin:t,version:r,cacheDir:o,channel:i}),a=nm(t),l=a.map(f=>gt({plugin:f,version:r,cacheDir:o,channel:i}));if(i!=="canary"&&await e.exists(s)&&await sm(e,l))return s;let d=om(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=rm(f),h=yt(u,m);if(!await e.exists(h))throw new Qe("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 sm(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function il(e,n,t=Ae){let r;try{r=await e.fetchText(im(t))}catch(i){throw ll(i,t)}let o=lm(r);return{sameMajor:am(o,n),newest:dm(o)}}function lm(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 am(e,n){let t=Qr(n);if(t===null)return null;let r=null;for(let o of e)Qr(o)===t&&(r===null||sl(o,r)>0)&&(r=o);return r}function dm(e){let n=null;for(let t of e){let r=String(t).trim();Qr(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||sl(r,n)>0)&&(n=r)}return n}function Qr(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 Qe("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Qe("package-missing",`npm could not resolve ${n}: ${t}`,e):new Qe("network",`failed to resolve ${n}: ${t}`,e)}function yt(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}pe();var ym={async materialize(e,n){await al(n,{recursive:!0});let t=um("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 Yr(n,"node_modules",...Ae.split("/"))},async readFile(e){return new Uint8Array(await mm(e))},async writeFile(e,n){await al(gm(e),{recursive:!0}),await hm(e,n)},async exists(e){return fm(e)},sha256(e){return pm("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()}},km="redskilled";function Rm(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Yr(e.HOME||cm(),".cache");return Yr(n,"red-skills","bundles")}async function bm(e={},n={},t={}){let r=Re(e,n);if(ae(r))return r;let o=t.env??n.env??process.env;try{await zr(t.bundleIO??ym,{plugin:km,version:t.version??"",cacheDir:Rm(o)})}catch{return r}return Re(e,n)}async function dl(e={},n={},t={}){let r=await bm(e,n,t);if(ae(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(pe(),ol));throw new o(r)}import{randomUUID as Tn}from"node:crypto";import{mkdir as yk,rm as Ad}from"node:fs/promises";import{createServer as kk}from"node:net";import{dirname as Rk}from"node:path";import{totalmem as wm}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=ze(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:_m(e.length,r,a,l)}}function _m(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 ze(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 xm="REDSKILLED_MEMORY_CEILING",pl="REDSKILLED_WORKER_CEILING",Sm=.7;function fl(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return ze(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=wm()){let t=(e[xm]??"").trim(),r=(e[pl]??"").trim(),o=Em(r);if(t!==""){let i=vm(t,n);if(i!==void 0)return{memory_bytes:i,worker_count:o,source:"declared"}}return{memory_bytes:Math.floor(n*Sm),worker_count:o,source:r!==""?"declared":"host-fraction"}}function vm(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)):ze(e)??void 0}function Em(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 Pm,mkdir as jm,open as Dm,readFile as Om,stat as Am,truncate as yl}from"node:fs/promises";import{dirname as Lm}from"node:path";var kl="redskilled.events.toonl";function $m(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 Im="daemon:";function Tm(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${Im}${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=ue({trailer:!1}),t=Promise.resolve();async function r(o){let i=t.then(async()=>{await jm(Lm(e),{recursive:!0,mode:448}),await Nm(e),await Pm(e,n.push(Hm(o)),{encoding:"utf8",mode:384})});return t=i.catch(()=>{}),await i,o}return{path:e,record:o=>r($m(o)),recordDaemonStop:o=>r(Tm(o)),read:()=>Cm(e),flush:async()=>{await t}}}async function Nm(e){let n;try{n=(await Am(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await Dm(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 Cm(e){let n;try{n=await Om(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return Mm(n)}function Mm(e){let n=e.split(`
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
60
  `);return n.pop(),n.length===0?[]:ye(`${n.join(`
61
61
  `)}
62
- `).filter(Fm).map(Um)}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,Wm(t)):n.delete(t.worker_id));return[...n.values()]}function Wm(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 Hm(e){return{...e}}function Fm(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 Um(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 _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(Bm),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:Km({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 Bm(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 Km(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 Xr(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 qm,mkdir as Jm,readFile as Gm,rm as Qm,writeFile as zm}from"node:fs/promises";import{dirname as jl,join as Ll}from"node:path";import{tmpdir as Dl}from"node:os";var Ym="redskilled.machine.claim.toon",Xm="REDSKILLED_MACHINE_DIR",Zm=8,be=class extends Error{constructor(t,r,o){super(nh(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 eh(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[Xm]?.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(eh(e),Ym)}function _t(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??U;async function i(){let l;try{l=await Gm(e,"utf8")}catch(p){if(p.code==="ENOENT"||Zr(p))return;throw p}let d=rh(l);return oh(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 Qm(e,{force:!0}),!0}catch(l){if(Zr(l))return!1;throw l}}return{claimPath:e,read:i,async claim(l){await Jm(jl(e),{recursive:!0,mode:1023})!=null&&await qm(jl(e),1023).catch(()=>{});let p=!1;for(let u=0;u<Zm;u+=1){let f=s(l,r());try{return await zm(e,th(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:p,claim:f}}catch(h){if(h.code!=="EEXIST"){if(Zr(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 nh(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 Zr(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 th(e){return`${M(e,{keyedMapCollapse:!0})}
63
- `}function rh(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return z(n)}catch{return null}}}function oh(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 ih=["worker_id","slot","workspace_path","log_path"],eo=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${ih.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},sh=/\{\{([a-z_]+)\}\}/g;function lh(e,n){let t=(s,a)=>s.replace(sh,(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 eo(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=lh(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 no(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 to(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 ro(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 ah=3e5,dh=.5,io=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 io(n.held);let t=oo(e.project_label,"a project label"),r=oo(e.selector,"a selector"),o=no(e.argv,t),i=ro(e.env,t),s=to(e.log_path,t),a=oo(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??ah;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:no(n.launch.argv,e.project_label),env:ro(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},i=n.launch==null?e.log_path:to(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 ch(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*dh;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)(ch(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function so(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||uh(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 uh(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function oo(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var ph={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=ph[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 Gl(e){return{generated_at:e.now,hour:Vl("hour",36e5,e),day:Vl("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 Vl(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&&Jl(u.at,o,r)).sort((u,f)=>u.at-f.at),a=t.outcomes.map(u=>En(u.ts)).filter(u=>u!=null&&Jl(u,o,r)),l=Kl(s,u=>u.tokens,"tokens",i),d=Kl(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:fh(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 Kl(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 fh(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 Jl(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 mh}from"node:child_process";import{existsSync as hh,readFileSync as St,readdirSync as gh}from"node:fs";import{dirname as yh,join as Le}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=ze(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(kh(r,o,i))}}return{terminations:n,unenforceable:t}}function kh(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 Rh=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=_h(e,t,n);for(let[u,f]of a){let m=Sh(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=Ph(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 bh="/sys/fs/cgroup";function _h(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let i=t.cgroupRoot??bh,s=e.filter(l=>l.unit!=null&&l.unit!=="");if(s.length===0)return r;let a=wh(i,t);for(let l of s)for(let d of a){let p=Le(d,l.unit);if(hh(Le(p,"memory.current"))){r.set(l.worker_id,p);break}}return r}function wh(e,n){let t=n.selfCgroupPath??xh(),r=[],o=a=>{r.includes(a)||r.push(a)},i=t;for(;i!=null&&i!==""&&i!=="/"&&i!==".";){o(Le(e,i));let a=yh(i);if(a===i)break;i=a}o(e);let s=n.uid??process.getuid?.();return s!=null&&o(Le(e,"user.slice",`user-${s}.slice`,`user@${s}.service`,"app.slice")),r}function xh(){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 Sh(e){let n;try{n=St(Le(e,"memory.current"),"utf8")}catch{return null}let t=Number(n.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:vh(e)}}function vh(e){let n;try{n=St(Le(e,"cpu.stat"),"utf8")}catch{return null}return Eh(n)}function Eh(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 Ph(e,n){return n.procRoot!=null||e==="linux"?$h(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?Ah(jh(n.psTable)):new Map}function jh(e){try{return(e??Dh)()}catch{return""}}function Dh(){return mh("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Oh=1024;function Ah(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=Lh(r[3]);a!=null&&n.set(o,{pid:o,ppid:i,rssBytes:s*Oh,cpuSeconds:a})}return n}function Lh(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 $h(e){let n=new Map,t;try{t=gh(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=St(Le(e,r,"stat"),"utf8")}catch{continue}let i=Th(o);i&&n.set(i.pid,{pid:i.pid,ppid:i.ppid,rssBytes:i.rssPages*Rh,cpuSeconds:i.cpuTicks/Ih})}return n}var Ih=100;function Th(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")],Nh=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 lo(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=lo(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 Nh.get(lo(e))??null}function na(e){let n=ea(e);if(!n)throw new vt(e);return n}function ao(e){return na(e).surface}var Ch=["api","graphql"],Mh=ao(Ch);function Wh(e,n="https://api.github.com"){return e==="graphql"?`${n}/graphql`:n}var ta=100,po=6e4,Hh=2*po,Fh=7*24*60*60*1e3,co=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 fo(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new co(t.project_label,t.token_ref,n)}function Uh(e,n={now:new Date(0).toISOString()}){Kh(e);let t=n.closedWindowMs??Fh,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 Bh(e,n,t){let r=Ye(n),o=Ye(r.data),i=Array.isArray(r.errors)?r.errors.map(Ye):[],s=qh(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: ${uo(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);fo(e.projects,e.hostTokenRef);let n=Uh(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return Bh(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??Hh,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??Wh(Mh),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 Kh(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 qh(e,n){let t=Ye(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=uo(e.type),t=uo(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=Ye(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function Jh(e){let n=Ye(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Ye(e){return da(e)?e:{}}function da(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function uo(e){return typeof e=="string"?e:""}var Gh=3e4,Qh=4;function ca(e){let n=e.stalenessMs??Gh,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=>Xh(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:tg({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:ng(a),known_projects:eg(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:zh(e.deaths,e.recentDeathLimit??Qh)},engine:Yh(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function zh(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 Yh(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 Xh(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:Zh(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function Zh(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 eg(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 ng(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 tg(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=dg(e,n),r=lg(e,n),o=ag(e,n),i=cg(e,n,r,t),s=ig(n,r,o),a={detail:"host",line:i};for(let u of s){let f=bg(i,sg(u,n,r,o),n.separator);if(a={detail:u,line:f},_g(f)<=n.maxWidth)break}let l=yo(a.line,n.maxWidth),d=n.verbose&&a.detail==="workers"?gg(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=yo(og,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 rg="!unregistered",ho="\u21E1",Et="\u2020",og="redskilled unreachable \u2014 Worker state unknown";function ig(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 sg(e,n,t,r){return e==="workers"?t.map(o=>hg(o,n)):e==="projects"?r.map(Rg):[]}function lg(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function ag(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function dg(e,n){return go(e,n.project)}function go(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 cg(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(mo(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(mo(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(mo(e,n)),o.push(rg)):o.push(fg(n.project,r)),o.push(ug(e));let i=pg(e);return i!=null&&o.push(i),e.staleness.stale&&o.push(mg(e)),o.join(" ")}function ug(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${ho}`}function pg(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Et}${n.count} ${n.latest.sender_class}`}function fg(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 mo(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?`${Y(t)}/${Y(r)}`:Y(t)}function mg(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function hg(e,n){let t=fa(e,n),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?Y(r):`${Y(r)}/${Y(e.budget.bytes)}`;return`${t} ${o}`}function gg(e,n){let t=[];for(let r of e){let o=kg(r.log.last_line);o!=null&&t.push(yo(` ${yg} ${fa(r,n)}: ${o}`,n.maxWidth))}return t}var yg="\u21B3";function kg(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 Rg(e){return`${e.project_label} ${e.worker_count}w ${Y(e.observed_rss_bytes)}`}function bg(e,n,t){return[e,...n].join(t)}function _g(e){return[...e].length}function yo(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 Y(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 ko={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},wg=["runner","model","effort","origin","issue","phase","step","heartbeat"],xg=["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={...ko};for(let r of wg){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of xg){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"],Xe={mode:"local",project:null,maxWidth:200,maxRows:16};var Sg=" ",ha="\u2588",vg="\u25B6",Eg="\u2717",Pg="\u2591";function ga(e,n=Xe){let t=go(e,n.project),r=jg(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),i=o.map(u=>Dg(u,n)),s=Mg(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(Wg(i[f],s),n.maxWidth)})),l=Ag(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(...$g(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 jg(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Dg(e,n){let t=e.display??ko,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:Og(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:Cg(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:Ng(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 Og(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?Eg:vg;return`${ha.repeat(r)}${o}${Pg.repeat(Math.floor(n)-r-1)}`}function Ag(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=Tg(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?ho:""}`];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(Ig(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:Lg(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&&bo(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 Lg(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${Ro(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${Ro(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${Ro(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 $g(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 Ig(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${Y(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${Y(e.memory_used_bytes)}/${Y(e.memory_ceiling_bytes)}${n}`}function Tg(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 Ng(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 Ro(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 Cg(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 Mg(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],bo(t[r]));return n}function Wg(e,n){return Pt.filter(r=>n[r]>0).map(r=>Hg(e[r],n[r])).join(Sg).replace(/\s+$/,"")}function Hg(e,n){return e+" ".repeat(Math.max(0,n-bo(e)))}function bo(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:Bg(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:cl(n,{hostCeilingBytes:e.hostCeilingBytes??null}),upgrade:Vg(e)}}function Bg(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(so))&&(n.upgrade===void 0||Kg(n.upgrade))}function Kg(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||qg(n.major_hold))}function qg(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 vo}from"node:fs";import{delimiter as ny,join as Oa}from"node:path";import{join as _a}from"node:path";import{existsSync as Jg}from"node:fs";import{createRequire as Gg}from"node:module";var wa="redskilled-job-object.node",$e=100;function Ze(e){return{available:!1,reason:e}}function Qg(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 Ze(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??Yg(),o=e.exists??Jg,i=Qg(n,t,r),s=i.find(d=>o(d));if(s==null)return Ze(`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??Gg(import.meta.url),l;try{l=a(s)}catch(d){return Ze(`the Job Object addon at ${s} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return zg(l)?{available:!0,binding:l}:Ze(`the Job Object addon at ${s} does not export createJobObject, so it cannot be the native reach`)}function zg(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Yg(){return new URL("..",import.meta.url).pathname}function Sa(e){let n=e??{},t=[],r=Xg(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<$e?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 ${$e}, 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 Xg(e){return Pn({budget:e})}var Dt=5,va=19;function _o(e){return{available:!1,reason:e}}var Zg="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<$e){let a=Math.round(va*($e-t.cpu_weight)/$e);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 ${$e}, 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:Zg,...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 ${ey(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 wo(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 ey(e){return`'${e.replace(/'/g,"'\\''")}'`}var Aa="REDSKILLED_PLACEMENT",Ot="red-worker",xo="/bin/sh";function La(e=process.env,n=process.platform){let t=_o(`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=Ze(`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:ty(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),i=o!==""&&vo(Oa(o,"systemd","private"));return{platform:n,systemdRun:Na("systemd-run",e),userSession:i,jobObjects:r,posix:t}}function ty(e){return vo(xo)?{available:!0,shell:xo,nice:Na("nice",e)}:_o(`no POSIX shell was found at ${xo}, 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 ry(e,n,t=Ot){return Ia(e,n,t).replace(/\.service$/,"")}function Ia(e,n,t=Ot){return`${So(t,"red-worker",24)}-${So(e,"project",32)}-${So(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 iy(e,n,t,r,o,s);if(e.probes.platform==="darwin")return oy(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=wo(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 oy(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 iy(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=ry(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}),...sy(o&&a.note!=null?`${a.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,wo(e.budget))}}function sy(...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(ny)){if(!t)continue;let r=Oa(t,e);if(vo(r))return r}return null}function So(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function Eo(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!==""?ly(e.unit):U(e.pid)}function ly(e){let n=At("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var ay="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 dy(e=process.env){let n=(e[ay]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Ha(e,n,t=process.env){return dy(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 Va(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 cy(e,n=50){if(Ga(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 uy(e,n={}){let t=n.batchSize??50;if(Ga(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 py(e,n){let t=An(n),r=An(t.data),o=Array.isArray(t.errors)?t.errors.map(An):[],i=my(r.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=gy(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=>hy(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: ${Po(p?.message)||"the query returned no count for this selector"}`}}),rate_limit:i}}function fy(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 Ja(e){if(e.projects.length===0)return fy(e.now);let n=e.batchSize??50,t=cy(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let i of t){let s=uy(i,{batchSize:n});try{let a=await e.transport(s.query),l=py(s,a);r.push(...l.projects),o=Ka(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=Ka(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 Ga(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 Ka(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 my(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:Po(e.type)==="RATE_LIMITED"||/rate limit/i.test(Po(e.message))}function hy(e,n){return Array.isArray(e)&&e.includes(n)}function gy(e){let n=An(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function An(e){return yy(e)?e:{}}function yy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Po(e){return typeof e=="string"?e:""}import{randomUUID as Xa}from"node:crypto";import{spawn as _y}from"node:child_process";import{closeSync as wy,mkdirSync as xy,openSync as Sy}from"node:fs";import{dirname as vy}from"node:path";import{delimiter as za,dirname as ky}from"node:path";function Ry(e,n=za){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function by(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=ky(n);return t===""||t==="."?null:t}function Ya(e,n=process.execPath,t=za){let r=Ry(e,t),o=by(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 Ey(e){if(e==null||e.trim()==="")return null;try{return xy(vy(e),{recursive:!0}),Sy(e,"a")}catch{return null}}function Py(e){try{wy(e)}catch{}}function jy(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 Dy(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 ed(e){let{spec:n,admission:t}=e;Dy(t),jy(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),i=(n.worker_id??e.workerId??Xa()).trim()||Xa(),s=e.probes??La(r),a=e.openLog===!1?null:Ey(n.log_path),l={...n.env??{},PATH:Ya(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??_y)(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&&Py(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?Oy(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 Oy(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: ${Za(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)}: ${Za(s)}. ${o}`}}return{job:i}}function Za(e){return e instanceof Error?e.message:String(e)}import{open as Ay,stat as Ly}from"node:fs/promises";var $y=16*1024;async function nd(e,n=$y){let t;try{t=(await Ly(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let i=await Ay(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 Iy(o)}function Iy(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 Qy}from"node:child_process";import{existsSync as zy,readdirSync as Yy}from"node:fs";import{dirname as Xy,join as ld,resolve as Zy}from"node:path";var Ty="<version>";function _e(e,n=[],t){let r=t&&t.trim().length>0?t.trim():Ty;return[`npx -y -p ${Ae}@${r}`,e,...n].join(" ")}function X(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=X(e),r=X(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var KS=4*60*60*1e3;pe();pe();import{spawnSync as Ny}from"node:child_process";import{mkdir as Cy,rm as My,writeFile as Wy}from"node:fs/promises";import{existsSync as Hy}from"node:fs";import{homedir as Fy}from"node:os";import{dirname as Uy,join as Do}from"node:path";var en="redskilled.service",Oo="REDSKILLED_SUPERVISED",By="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function Vy(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||Do(e.HOME?.trim()||Fy(),".config");return Do(n,"systemd","user")}function Ao(e=process.env){return Do(Vy(e),en)}function td(e,n={}){let t=n.env??process.env,r=ht(n.override??{},n.entryLookup??{}),o=[...r.args,...Oe(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:en,unitPath:Ao(t),command:r.command,args:o,text:Ky(r.command,o,e)}}function Ky(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${By}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(qy).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Oo}=1"`,`Environment="REDSKILLED_SESSION=${rd(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
72
- `)}function qy(e){return/[\s"'\\$%]/.test(e)?`"${rd(e)}"`:e}function rd(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function od(e,n={}){let t=n.writeFile??Jy,r=n.run??Lo,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 id(e={}){let n=e.removeFile??Gy,t=e.run??Lo,r=Ao(e.env??process.env),o=[$t("disable",t,["systemctl","--user","disable","--now",en])];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 sd(e={}){let n=e.exists??Hy,t=e.run??Lo,r=Ao(e.env??process.env),o=n(r);return{unitName:en,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",en]).status===0,active:o&&t(["systemctl","--user","is-active",en]).status===0,floor:"auto-spawn"}}function $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 Jy(e,n){await Cy(Uy(e),{recursive:!0}),await Wy(e,n,{encoding:"utf8",mode:420})}async function Gy(e){await My(e,{force:!0})}function Lo(e){let n=Ny(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 ad=75,cd=9e5,dd="redskilled-replacement-entry-unresolved",ek="REDSKILLED_NO_REGISTRY_PROBE",ud="REDSKILLED_BORN_BY_REPLACEMENT";function pd(e=process.env){return e[ud]==="1"}function fd(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function md(e){let n=e.running.trim();if($n(n))return null;let t=e.newest?.trim()??"",r=X(t),o=X(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: ${_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 hd(e){let n=e.running.trim();if($n(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||X(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 $n(e){let n=e.trim();return X(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function gd(e=process.env){return e[Oo]==="1"}var $o=class extends Error{code=dd;searched;constructor(n,t){super(`${dd}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
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
73
73
  searched:
74
74
  ${t.map(r=>` ${r}`).join(`
75
- `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function tk(e,n={}){let t=n.env??process.env,r=n.exists??zy,o=n.execPath??process.execPath,i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,s=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[ld(mt(t),s),"bundle-cache"]];i&&l.push([ld(Xy(Zy(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 $o(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 yd(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>tk(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??ok)(ad),{...e,exitCode:ad};let o=[...e.entry.args,...Oe(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??rk(r.env))(e.entry,o),e}function rk(e){return(n,t)=>{let r=Qy(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[ud]:"1"}});r.on("error",()=>{}),r.unref()}}function ok(e){process.exitCode=e,process.exit(e)}async function Rd(e,n=process.env,t=ik){let r=_d(n),o=wd(e,n);if(n[ek]==="1")return{version:o,newest:r};let i=X(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 bd(e,n=process.env,t){let r=t??Io;return{version:wd(e,n,r),newest:_d(n,r)}}function _d(e=process.env,n=Io){return Sd(xd(e,n))}function wd(e,n=process.env,t=Io){let r=X(e.trim())?.major;return r===void 0?null:Sd(xd(n,t).filter(o=>X(o)?.major===r))}function xd(e,n){let t=[];for(let r of n(mt(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||X(o)===null||t.push(o)}return t}function Sd(e){let n=null;for(let t of e)(n===null||jo(t,n)>0)&&(n=t);return n}function Io(e){try{return Yy(e)}catch{return[]}}async function ik(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 sk,readFile as lk,rename as ak,rm as To,writeFile as vd}from"node:fs/promises";import{randomUUID as dk}from"node:crypto";import{dirname as ck}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 lk(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=uk(n);return pk(t)?t:void 0}var Ed;function jd(){return Ed??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Ed}function Dd(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}.${dk()}.tmp`;await vd(d,Pd(l),{encoding:"utf8",mode:384}),await ak(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 sk(ck(e),{recursive:!0,mode:448});let d=!1;for(;;){let p=r(),u=a(l,p);try{return await vd(e,Pd(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 To(e,{force:!0}),d=!0;continue}if(No(f,l))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await To(e,{force:!0}),d=!0}},async renew(l){let d=await i();if(!d||!No(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(!No(d,l))throw new It(e);return await To(e,{force:!0}),!0}}}function No(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function Pd(e){return`${M(e,{keyedMapCollapse:!0})}
76
- `}function uk(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return z(n)}catch{return null}}}function pk(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 Co=3e5,bk=1e4,_k=6e4,wk=15e3,xk=3e4,Od=16,nn=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},Sk="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Ld(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??Co,o=e.clock??(()=>new Date().toISOString()),i=e.launch??ed,s=e.ceiling??gl();e.repositoryActivity!=null&&fo(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??jd(),l=e.leaseStore??Dd(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 yk(Rk(n.socketPath),{recursive:!0,mode:448});let f=await u.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new nn(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 nn(n.socketPath,m.lease);let h;try{h=await vk(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??Va,ee=e.unitInventory??(()=>Ha(n.machineClaimPath,bt({machineIdHash:n.machineIdHash}))?Fa():[]),q=e.unitMainPid??Wa,we=e.treeSampler??zl,Te=e.readLogTail??nd,Cn=e.sampleMs??wk,Yo=e.leaseRenewMs??xk,Xo=e.publishedVersion??(c=>Rd(c)),Zo=e.replaceCheckMs??cd,ei=e.publishedProbeTimeoutMs??bk,fc=e.localPublishedEvidence??(c=>bd(c,e.replacementIO?.env??process.env)),mc=e.bornByReplacement??pd(),ni=e.replaceBootCheckMs??_k,ti=e.supervised??gd(),ri=e.replacementIO??{},ne=e.repositoryActivity,oi=ne?.intervalMs??po,xe=e.queueDiscovery,Mn=xe?.transport??ne?.transport,Ct=xe?.unconfiguredReason??Sk,ii=xe?.intervalMs??15e3,si=e.demandMs??15e3,hc=e.demandBackoffMs??3e4,v=new Map,he=new Set,Ne=new Map,Wn=new Map,Mt=[],Hn=[],I=new Map,Wt=new Set,li={},Ht=null,ai=null,Ft=null,di=!1,Ut=0,Bt=null,rn="none",Vt=null,ci=null,Kt=null,ge=null,Fn=null,on=[],sn=null,Un={},qt=!1,Ce,ln,an,dn,cn,Bn,un,pn,te=!1,Jt=!1,Vn=null,ui,Gt=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),gc(_,g);return y.lapsed}function gc(c,g){let y=Number.isFinite(g)?new Date(g).toISOString():c.renew_by;on.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`}),on.length>Od&&on.splice(0,on.length-Od)}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((ge?.projects??[]).map(x=>[x.project_label,x]));for(let x of[...I.values()]){let P=_.get(x.project_label),ce=Wl(x,{now:c,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:y[x.project_label]??0});ce.registration!==x&&I.set(x.project_label,ce.registration)}}function Kn(){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:on,queue:ge,published:{version:ai,checkedAt:Ft,newer:di,replacement:rn,newest:Vt,majorHold:ci,checks:Ut,holdReason:Bt}})}function qn(){return ca({hostState:Kn(),ceiling:s,rss:li,sampledAt:Ht,logLines:Object.fromEntries(Ne),displays:Object.fromEntries(Wn),now:o(),reattachedWorkerIds:[...he],repositoryActivity:Kt,...e.deaths===void 0?{}:{deaths:e.deaths},metrics:Gl({observations:Mt,outcomes:Hn,now:o()})})}function yc(c,g){Mt=xt([...Mt,{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 kc(c){Hn=xt([...Hn,c],g=>g.ts,{now:o()})}async function Qt(){return ne==null||ne.projects.length===0?null:(Kt=await ia({projects:ne.projects,hostTokenRef:ne.hostTokenRef,transport:ne.transport,closedWindowMs:ne.closedWindowMs,now:o()}),Kt)}function Rc(){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:(Rc(),Mn==null?(ge=qa(g,c,Ct),ge):(ge=await Ja({projects:g,transport:Mn,now:c,...xe?.batchSize==null?{}:{batchSize:xe.batchSize}}),pi(o()),ge))}async function mi(){let c=o();if(qt)return Fn??wl(c);qt=!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 ge?.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:sn,birthHaltUntilMs:Sl(Un,Number.isFinite(_)?_:0)}),P=[],ce=null;for(let O of x.births){let We,Fc=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:Fc,slot:O.index,workspace_path:O.workspace_path},{project_label:O.project_label});try{We=zt(ji)}catch(Zt){ce=Zt instanceof Error?Zt.message:String(Zt),sn=(Number.isFinite(_)?_:Date.now())+hc;break}P.push({project_label:O.project_label,worker_id:We.worker.worker_id,pid:We.worker.pid,warnings:ji.log_path==null?[...We.warnings,`project ${JSON.stringify(O.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(We.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:We.warnings})}return ce==null&&x.births.length>0&&(sn=null),Fn={version:1,at:c,requested:x.births.length,granted:P,shortfall:x.births.length-P.length,refusal:ce,retry_after:sn==null?null:new Date(sn).toISOString(),projects:x.intents},Fn}finally{qt=!1}}function bc(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 _c(c){return ga(qn(),{mode:c?.mode??Xe.mode,project:c?.project??Xe.project,maxWidth:c?.max_width??Xe.maxWidth,maxRows:c?.max_rows??Xe.maxRows})}function Me(c,g,y){return Bl({op:c,sessionProject:g??null,targetProject:y})}async function wc(c){let g=v.get(c.worker_id),y=Me(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 Pc(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 Jn(c){v.delete(c),he.delete(c),Ne.delete(c),Wn.delete(c)}function hi(c){let g=v.get(c.worker_id),y=Me("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();Ne.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),yc(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 xc(c,g,y){let _=`exit code=${g??"null"} signal=${y??"null"}`;if(c.unit!=null&&c.unit!==""&&await vc(c)){Ec(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}Jn(c.worker_id),de("worker-death",c,_,{exitCode:g,signal:y}),T()}function Sc(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 vc(c){try{return await w(c)===!0}catch{return!1}}function Ec(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]}),he.add(c.worker_id),T()}function gi(c,g){let y=Me("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=Me("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=Me("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 Pc(c,g){try{await j(c)}catch{}return Jn(c.worker_id),de("worker-death",c,g),T(),!0}function Ri(c){return ml({ceiling:s,workers:[...v.values()],budget:c.budget,projectLabel:c.project_label})}function zt(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 ce=v.get(_);if(ce==null){T();return}xc(ce,x,P).catch(()=>{})}});return v.set(y.worker.worker_id,y.worker),de("worker-birth",y.worker,null),T(),y}function de(c,g,y,_={}){if(te)return;let x=o();(c==="worker-death"||c==="worker-budget-kill")&&(kc({worker_id:g.worker_id,ts:x,outcome:c}),Sc(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=[...he].map(y=>v.get(y)).filter(y=>y!=null);if(c.length===0)return[];let{dead:g}=await Eo(c,w);for(let y of g)Jn(y.worker_id),de("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 Jn(c),de("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,Ht=o(),jc(g.cpu_seconds,Ht),Dc(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 jc(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 Dc(c){for(let[g,y]of Object.entries(c??{})){let _=v.get(g);_&&v.set(g,{..._,rss_source:y})}}async function Oc(){try{return ei<=0?await Xo(t):await new Promise(c=>{let g=setTimeout(()=>c(Yt()),ei);g.unref(),Xo(t).then(y=>{clearTimeout(g),c(y)},()=>{clearTimeout(g),c(Yt())})})}catch{return Yt()}}function Yt(){try{return fc(t)}catch{return null}}async function xi(){if($n(t))return Ut+=1,Ft=o(),Bt="local-build",{act:"hold",reason:"local-build"};let c=fd(await Oc()),g=c.version;ai=g,Vt=c.newest??null,Ft=o(),ci=md({running:t,newest:Vt,supervised:ti});let y=hd({running:t,published:g,supervised:ti});return di=y.act==="replace",Ut+=1,Bt=y.act==="hold"?y.reason:null,rn!=="in-progress"&&(rn=y.act==="replace"?"pending":"none"),y}async function Gn(){let c=await xi();if(c.act!=="replace"||rn==="in-progress")return c;let g=yd(c,ri);return rn="in-progress",await k.flush().catch(()=>{}),await zn({reason:"replaced"}),kd(g,n,{...r==null?{}:{idleMs:r},io:ri}),c}function Ac(){te||cn!=null||Zo<=0||(!mc&&ni>0&&(Bn=setTimeout(()=>{Gn().catch(()=>{})},ni),Bn.unref()),cn=setInterval(()=>{Gn().catch(()=>{})},Zo),cn.unref())}async function Si(){return await l.renew(a).catch(()=>null)}function Lc(){te||an!=null||Yo<=0||(an=setInterval(()=>{Si()},Yo),an.unref())}function $c(){te||ln!=null||Cn<=0||(ln=setInterval(()=>{wi().catch(()=>{})},Cn),ln.unref())}function Ic(){te||un!=null||ne==null||ne.projects.length===0||oi<=0||(Qt().catch(()=>{}),un=setInterval(()=>{Qt().catch(()=>{})},oi),un.unref())}function Tc(){te||pn!=null||ii<=0||(pn=setInterval(()=>{fi().catch(()=>{})},ii),pn.unref())}function Nc(){te||dn!=null||si<=0||(dn=setInterval(()=>{mi().catch(()=>{})},si),dn.unref())}function T(){te||(Ce&&clearTimeout(Ce),Ce=setTimeout(()=>{bi().catch(()=>{}).then(()=>vi())},r),Ce.unref())}function vi(){return v.size>0?(T(),"held-by-workers"):(fn(o()),I.size>0?(T(),"held-by-registrations"):(Cc(),"exited"))}async function Cc(){if(!$n(t)){if((await Gn().catch(()=>null))?.act==="replace"||Jt||te)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(Vn!=null)return Vn;let g=c.reason??"requested",y=c.note?.trim();return Vn=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(()=>{}),Vn}async function zn(c={}){if(Jt)return await Gt;Jt=!0,await Ei(c),te=!0,Ce&&clearTimeout(Ce),ln&&clearInterval(ln),an&&clearInterval(an),cn&&clearInterval(cn),Bn&&clearTimeout(Bn),un&&clearInterval(un),pn&&clearInterval(pn),dn&&clearInterval(dn),await k.flush().catch(()=>{}),h.close();for(let g of Wt)g.destroy();return await new Promise(g=>h.once("close",()=>g())),await Ad(n.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),ui(),await Gt}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 Mc=bl(Pi),Xt=await Eo(Mc,w);for(let c of Xt.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),he.add(g.worker_id)}for(let c of Xt.dead)de("worker-death",c,"the Worker ended while no daemon was watching");let Wc=Ua({units:await Promise.resolve(ee()).catch(()=>[]),held:[...v.values()],mainPid:q,now:b});for(let c of Wc)v.set(c.worker_id,c),he.add(c.worker_id),de("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of Xt.alive){if(c.log_path==null||Ne.has(c.worker_id))continue;let g=await Te(c.log_path).catch(()=>null);g==null||g.trim()===""||Ne.set(c.worker_id,{line:g,published_at:o(),source:"rehydrated"})}h.on("connection",c=>{Wt.add(c),c.once("close",()=>Wt.delete(c)),T(),Ek(c,async(g,y)=>{T();let _=await Hc(g);y(_),g.op==="shutdown"&&setImmediate(()=>void zn({reason:"requested"}))})});async function Hc(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:Kn()};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:bc(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:_c(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 wc(c.command)};if(c.op==="worker-start"){let y=Me("worker-start",c.session_project,c.spec.project_label);if(!y.permitted)return{id:c.id,ok:!1,error:y.reason};let _=zt(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(),$c(),Lc(),Ac(),Ic(),Tc(),Nc(),{socketPath:n.socketPath,lease:m.lease,startedAt:b,closed:Gt,startWorker:zt,admit:Ri,ceiling:()=>s,killWorkerOverBudget:_i,sampleMemoryBudgets:wi,renewLease:Si,pollRepositoryActivity:Qt,pollQueueDiscovery:fi,queueDiscovery:()=>ge,driveDemand:mi,demand:()=>Fn,sweepReattached:bi,publishWorkerHeartbeat:hi,reattached:()=>[...he].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),T()},releaseWorker(c){let g=v.get(c),y=v.delete(c);return he.delete(c),Ne.delete(c),Wn.delete(c),g&&de("worker-death",g,"released by the daemon"),T(),y},workerCount:()=>v.size,registerProject:gi,renewProject:yi,deregisterProject:ki,registrations:()=>Kn().registrations??[],hostState:Kn,statuslinePayload:qn,evaluateIdle:vi,observePublishedVersion:xi,checkForReplacement:Gn,stopReport:Qn,stop:zn}}async function vk(e){for(let n=0;n<2;n++){let t=kk();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 Z(e))throw new nn(e);await Ad(e,{force:!0})}}throw new nn(e)}async function Z(e,n=250){try{return(await ut({socketPath:e,timeoutMs:n},{id:Tn(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function Ek(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 Mo(e){let n=e.socketPath,t=Pk(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 ${$d(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 Wo(e){return`${e.reason} ${e.repair}`}function Pk(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:jk(n.acquired_at,e.now??new Date().toISOString())}}function jk(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 $d(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 Nd=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"?`. ${Wo(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},Ho=class extends Ie{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}};async function Tt(e,n={}){let t=n.answers??await Z(e.socketPath),r=await In(e.leasePath).catch(()=>{});return Mo({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&U(r.pid)})}async function Fo(e,n={}){try{return await $k(e,n)}catch(t){if(t instanceof be||t instanceof Ie)throw t;let r=await Tt(e).catch(()=>{});throw new Ie(e.socketPath,t,r)}}async function $k(e,n){if(await Ok(Lk(e.socketPath),{recursive:!0,mode:448}),await Z(e.socketPath))return"already-running";await Tk(e);let t=await Ik(e,n);if(t!=null)return t;let r=await nl(e.lockPath);if(!r)return await Id(e,n),"joined";try{if(await Z(e.socketPath))return"already-running";let o=await Mk(e,n);return await Id(e,n,o),"spawned"}finally{await r.close(),await Ak(e.lockPath,{force:!0})}}async function Ik(e,n){let t=await Tt(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??Nd,o=Date.now()+r;for(;;){if(await Z(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 Ho(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 Tk(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 Cd(e,n,t={}){await Fo(e,t);let r;try{r=await On({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:Td()})}catch(o){throw new Ie(e.socketPath,o,await Tt(e).catch(()=>{}))}if(!r.ok)throw new Error(r.error);return r.value}async function Md(e,n={},t={}){if(!await Z(e.socketPath))return Pl(e.socketPath);let r;try{r=await On({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Td(),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(!Xr(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await Nk(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 Nk(e,n){let t=Date.now()+n;for(;;){if(!await Z(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function Wd(e,n={}){let t=await Cd(e,{op:"host-state"},n);if(!ba(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Hd(e,n=void 0,t={}){let r=await Cd(e,{op:"statusline-string",...t.sessionProject!=null?{session_project:t.sessionProject}:{},...n==null?{}:{render:Ck(n)}},t);if(!ka(r))throw new Error("redskilled daemon returned a malformed statusline render");return r}function Ck(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 Id(e,n,t){let r=Date.now()+(n.readyTimeoutMs??Nd);for(;;){if(await Z(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 Mk(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,...Oe(e,n.idleMs==null?{}:{idleMs:n.idleMs})],s=Dk(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 Jd,mkdir as Qd,readFile as zd,stat as Qk,writeFile as zk}from"node:fs/promises";import{homedir as Vo}from"node:os";import{dirname as Yk,join as Ko}from"node:path";import{join as Wk}from"node:path";var Fd=["local","tmp","host"],Hk="local",Nn="plugins.dev.workspace.target";var Uo=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function Bd(e){let n=Ge(e,Nn),t=Bk(n??"").trim();return t===""?void 0:t}function Vd(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:Hk};let t=Fd.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 Uo(`${Nn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${Fd.join(", ")}) or an absolute parent directory for Workers.`)}function Kd(e,n){return e.kind==="preset"?e.preset==="host":Uk(Fk(e.parentDir,n),De(n))}function Fk(e,n){return e==="~"?Ud(n):e.startsWith("~/")?Wk(n,e.slice(2)):Ud(e)}function Uk(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Ud(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function Bk(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}pe();import{createHash as Vk}from"node:crypto";import{hostname as Kk}from"node:os";import{join as Nt}from"node:path";var tn="redskilled.sock",qk="REDSKILLED_SESSION";function Jk(e={}){let n=e.env??process.env,t=n[qk]?.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 Gk(e={}){return qd(e.host??Kk())}function me(e={}){let n=Jk(e),t=e.runtimeDir??pt({key:`redskilled:${n}`,socketFileName:tn,env:e.env,uid:e.uid}),r=Gk(e);return{sessionKey:n,sessionKeyHash:qd(n),machineIdHash:r,runtimeDir:t,socketPath:Nt(t,tn),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 qd(e){return Vk("sha256").update(e).digest("hex").slice(0,12)}var Bo=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${_e("red-skills-redskilled",["provision"])}\` directly`;async function Yd(e=Vo()){let n=De(e),t=await Jo(n);return t===void 0?(await Qd(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 Xd={needed:!1,declaredBy:`no ${Nn} in view`};async function qo(e={}){let n=e.homeDir??Vo(),t=e.declaredTarget?.trim();if(t)return Gd(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return Xd;let o=Ko(r,".red","config.yaml"),i=await zd(o,"utf8").catch(()=>{});if(i===void 0)return{needed:!1,declaredBy:`no ${o}`};let s=Bd(i);return s===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Gd(s,n,o)}function Gd(e,n,t){let r=`${Nn}: ${e} (${t})`;try{return{needed:Kd(Vd(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function Zd(e){let n=[Xk(e),Zk(e),eR(e),nR(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 Xk(e){let n=e.homeNeed??Xd;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:Bo}:{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:`${Bo} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function Zk(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 eR(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:`${Bo} \u2014 it starts the daemon and waits for the socket`}}function nR(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 ec(e={}){let n=e.env??process.env,t=e.homeDir??Vo(),r=e.paths??me({env:n}),o=De(t),[i,s,a]=await Promise.all([Jo(o),Z(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):qo({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 rR(oR(e,n,t),n)}}var tR="redskilled.service";function nc(e){return Ko(e,"systemd","user",tR)}function tc(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 rc(e){let n=nc(e.configHome);return await Jo(n)!==void 0?{path:n,status:"already-present"}:(await Qd(Yk(n),{recursive:!0}),await zk(n,e.unit,"utf8"),{path:n,status:"installed"})}async function rR(e,n){if(process.platform!=="linux")return"unsupported";try{return await zd(nc(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function oR(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??Ko(t,".config")}async function Jo(e){try{return(await Qk(e)).mode&511}catch{return}}import{readdir as ic,rm as iR,stat as sR}from"node:fs/promises";import{dirname as lR,join as Go}from"node:path";var aR=5*6e4,dR="redskilled.";function cR(e={}){let n=e.env??process.env,t=s=>lR(pt({key:"redskilled:reclaim-probe",socketFileName:tn,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 sc(e={}){let n=e.roots??cR(e),t=e.graceMs??aR,r=e.now??Date.now,o=e.isPidAlive??U,i=e.answers??mR,s=e.dryRun===!0,a=[];for(let l of n){let d;try{d=(await ic(l,{withFileTypes:!0})).filter(p=>p.isDirectory()).map(p=>p.name)}catch{continue}for(let p of d.sort())a.push(await uR(Go(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 uR(e,n){let t;try{t=(await ic(e)).sort()}catch(s){return{dir:e,verdict:"failed",reason:lc(s),removed:[]}}let r=t.filter(s=>s.startsWith(dR));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await pR(Go(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 oc(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(tn)&&await n.answers(Go(e,tn)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let i=await fR(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 oc(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function oc(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await iR(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 pR(e){try{return await In(e)}catch{return}}async function fR(e,n){try{return Math.max(0,n()-(await sR(e)).mtimeMs)}catch{return}}async function mR(e){try{return(await On({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 hR="plugins.dev.statusline",gR="dev.statusline";function yR(e){let n=[],t=a=>{for(let l of[hR,gR]){let d=`${l}.${a}`,p=Ge(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 kR={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 ac(e){let{values:n,positionals:t}=Pe(e,kR),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 dc(e={}){let n=e.configText==null?{config:{},warnings:[]}:yR(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 bR=`Usage: redskilled <command> [options]
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]
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
- `,_R={serve:`Usage: redskilled serve [options]
90
+ `,vR={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 wR(e){return e==="--help"||e==="-h"||e==="help"}var xR={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)}},pc="REDSKILLED_HOST_TOKEN";function zo(){try{let n=RR("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function SR(e=process.env,n=zo){let t=(e[pc]??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 vR(e,n=process.env,t=zo){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...cc(e,n,t),armTransport:()=>cc(e,n,t)}}function cc(e,n=process.env,t=zo){let r=SR(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${pc}, 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 ER(e){if(e[0]==="--version"||e[0]==="-v"){let o=Rr("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
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
155
  `:`${ps(o)}
156
- `),0}if(wR(e[0]))return process.stdout.write(bR),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(_R[n]),0;if(n==="serve"){let{values:o}=Pe(t,xR),i=vR(o),s=uc(De(Qo()),"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 Ld({paths:CR(o),idleMs:o["idle-ms"]??Co,daemonVersion:o["daemon-version"]??Rr("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 jR(t);if(n==="statusline")return await OR(t);if(n==="unit")return await DR(t);if(n==="provision")return await LR(t);if(n==="reclaim")return await IR(t);let r=await Wd(me());return process.stdout.write(`${JSON.stringify(r,null,2)}
158
- `),0}var PR={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function jR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),{values:r}=Pe(e,PR),o=await Md(n.paths??me(),{...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 DR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),r=n.paths??me(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(sd(n.unitIO??{}),null,2)}
160
- `),0;if(o==="install"){let i=await od(td(r),n.unitIO??{});return t(`${JSON.stringify(i,null,2)}
161
- `),i.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await id(n.unitIO??{}),null,2)}
162
- `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function OR(e,n={}){let t=n.write??(l=>process.stdout.write(l)),r=n.warn??(l=>process.stderr.write(l)),o=ac(e),i=NR(n.cwd??process.cwd()),s=dc({...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 Hd(n.paths??me(),s.options,{...n.client??{},...s.options.project==null?{}:{sessionProject:s.options.project}})}catch(l){r(`redskilled statusline: ${l instanceof Error?l.message:String(l)}
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
164
  `),a=pa({options:s.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${a.lines.join(`
165
165
  `)}
166
- `),0}var AR={"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 LR(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=Pe(e,AR),o=n.paths??me(),i=n.homeDir??Qo(),s=await qo({homeDir:i,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),a=r.check||!s.needed?void 0:await Yd(i),l;if(!r.check&&!r["no-start"])try{await Fo(o,n.client??{})}catch(f){l=f instanceof Error?f.message:String(f)}let d=await ec({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 rc({configHome:n.configHome??TR(),unit:tc({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=Zd(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 $R={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function IR(e,n={}){let t=n.write??(i=>process.stdout.write(i)),{values:r}=Pe(e,$R),o=await sc({...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 TR(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:uc(Qo(),".config")}function NR(e){let n=Mr(e);return n.configText==null?{label:null}:{configText:n.configText,label:Ks(e)}}function CR(e){let n=me();return{...n,socketPath:e.socket??n.socketPath,leasePath:e.lease??n.leasePath,eventLanePath:e.events??n.eventLanePath,sessionKeyHash:e["session-key-hash"]??n.sessionKeyHash,machineIdHash:e["machine-id-hash"]??n.machineIdHash,machineClaimPath:e["machine-claim"]??n.machineClaimPath}}var MR=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;MR&&ER(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{pc as REDSKILLED_HOST_TOKEN_ENV,bR as REDSKILLED_USAGE,cc as armRedskilledQueueTransport,SR as resolveRedskilledHostToken,vR as resolveServeQueueDiscovery,LR as runProvision,IR as runReclaim,ER as runRedskilledCli,OR as runStatusline,jR as runStop,DR as runUnit};
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};