@reddb-io/red-skills 3.3.16 → 3.3.18

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,97 +1,98 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var Ku=Object.defineProperty;var Vu=(e,n)=>()=>(e&&(n=e(e=0)),n);var qu=(e,n)=>{for(var t in n)Ku(e,t,{get:n[t],enumerable:!0})};var Ql={};qu(Ql,{REDSKILLED_BIN_ENV:()=>Ro,REDSKILLED_BUNDLE_ASSET:()=>le,REDSKILLED_ENTRY_UNRESOLVED:()=>$n,RedskilledDaemonEntryError:()=>In,isRedskilledEntryPath:()=>_o,isResolvedRedskilledEntry:()=>ae,redskilledBundleCacheRoot:()=>jt,redskilledServeArgv:()=>Te,requireRedskilledEntry:()=>Dt,resolveRedskilledEntry:()=>we});import{existsSync as Xm,readdirSync as Zm}from"node:fs";import{homedir as eh}from"node:os";import{basename as ko,dirname as go,join as Q,resolve as Pt}from"node:path";function ae(e){return"command"in e}function Te(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 jt(e=process.env){return Jl(e)}function we(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??Xm,o=n.execPath??process.execPath,s=n.execArgv??[],i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,a=(c,u)=>({command:o,args:[...s,c],source:u,entry:c}),l=t[Ro];if(l)return{command:l,args:[],source:"env-redskilled-bin",entry:l};if(i&&_o(i))return a(Pt(i),"caller-entry");let d=[];for(let[c,u]of oh(i,n.rootDir,t,n.listDir??lh))if(d.push(c),r(c))return a(c,u);return{diagnostic:$n,searched:d,...i?{callerEntry:Pt(i)}:{}}}function Dt(e={},n={}){let t=we(e,n);if(ae(t))return t;throw new In(t)}function _o(e){let n=ko(e);return n===le||bo.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:rh(Pt(e))}function rh(e){let n=go(e);for(let t=0;t<4;t++){if(ko(n)==="redskilled")return!0;let r=go(n);if(r===n)return!1;n=r}return!1}function*oh(e,n,t,r){if(e){let s=go(Pt(e));yield[Q(s,le),"caller-sibling-bundle"];let i=nh.exec(ko(e));i&&(yield[Q(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[Q(s,"..","dist",le),"caller-sibling-bundle"]}for(let s of th){let i=t[s];i&&(yield[Q(i,"dist",le),"plugin-root-bundle"],yield[Q(i,"..","..","dist",le),"plugin-root-bundle"])}n&&(yield[Q(n,"dist",le),"repo-bundle"],yield[Q(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[Q(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=Jl(t);yield[Q(o,le),"bundle-cache"];for(let s of sh(o,r))yield[Q(o,s),"bundle-cache"]}function Jl(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Q(e.HOME||eh(),".cache");return Q(n,"red-skills","bundles")}function sh(e,n){return n(e).filter(t=>bo.test(t)).sort((t,r)=>ih(ql(r),ql(t)))}function ql(e){return bo.exec(e)?.[1]??""}function ih(e,n){let t=s=>s.split(".").map(i=>Number.parseInt(i,10)),[r,o]=[t(e),t(n)];for(let s=0;s<Math.max(r.length,o.length);s++){let[i,a]=[r[s],o[s]];if(Number.isNaN(i)||i===void 0)return Number.isNaN(a)||a===void 0?e.localeCompare(n):-1;if(Number.isNaN(a)||a===void 0)return 1;if(i!==a)return i-a}return 0}function lh(e){try{return Zm(e)}catch{return[]}}var le,$n,Ro,In,nh,bo,th,me=Vu(()=>{"use strict";le="redskilled.bundle.min.mjs",$n="redskilled-daemon-entry-unresolved",Ro="REDSKILLED_BIN";In=class extends Error{code=$n;searched;callerEntry;constructor(n){super(`${$n}: 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 Qu=Object.defineProperty;var zu=(e,n)=>()=>(e&&(n=e(e=0)),n);var Yu=(e,n)=>{for(var t in n)Qu(e,t,{get:n[t],enumerable:!0})};var Xl={};Yu(Xl,{REDSKILLED_BIN_ENV:()=>Ro,REDSKILLED_BUNDLE_ASSET:()=>le,REDSKILLED_ENTRY_UNRESOLVED:()=>In,RedskilledDaemonEntryError:()=>Nn,isRedskilledEntryPath:()=>_o,isResolvedRedskilledEntry:()=>ae,redskilledBundleCacheRoot:()=>At,redskilledServeArgv:()=>Te,requireRedskilledEntry:()=>Lt,resolveRedskilledEntry:()=>xe});import{existsSync as th,readdirSync as rh}from"node:fs";import{homedir as oh}from"node:os";import{basename as ko,dirname as yo,join as Q,resolve as Ot}from"node:path";function ae(e){return"command"in e}function Te(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 At(e=process.env){return Yl(e)}function xe(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??th,o=n.execPath??process.execPath,s=n.execArgv??[],i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,l=(c,u)=>({command:o,args:[...s,c],source:u,entry:c}),a=t[Ro];if(a)return{command:a,args:[],source:"env-redskilled-bin",entry:a};if(i&&_o(i))return l(Ot(i),"caller-entry");let d=[];for(let[c,u]of ah(i,n.rootDir,t,n.listDir??uh))if(d.push(c),r(c))return l(c,u);return{diagnostic:In,searched:d,...i?{callerEntry:Ot(i)}:{}}}function Lt(e={},n={}){let t=xe(e,n);if(ae(t))return t;throw new Nn(t)}function _o(e){let n=ko(e);return n===le||bo.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:lh(Ot(e))}function lh(e){let n=yo(e);for(let t=0;t<4;t++){if(ko(n)==="redskilled")return!0;let r=yo(n);if(r===n)return!1;n=r}return!1}function*ah(e,n,t,r){if(e){let s=yo(Ot(e));yield[Q(s,le),"caller-sibling-bundle"];let i=sh.exec(ko(e));i&&(yield[Q(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[Q(s,"..","dist",le),"caller-sibling-bundle"]}for(let s of ih){let i=t[s];i&&(yield[Q(i,"dist",le),"plugin-root-bundle"],yield[Q(i,"..","..","dist",le),"plugin-root-bundle"])}n&&(yield[Q(n,"dist",le),"repo-bundle"],yield[Q(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[Q(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=Yl(t);yield[Q(o,le),"bundle-cache"];for(let s of dh(o,r))yield[Q(o,s),"bundle-cache"]}function Yl(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Q(e.HOME||oh(),".cache");return Q(n,"red-skills","bundles")}function dh(e,n){return n(e).filter(t=>bo.test(t)).sort((t,r)=>ch(zl(r),zl(t)))}function zl(e){return bo.exec(e)?.[1]??""}function ch(e,n){let t=s=>s.split(".").map(i=>Number.parseInt(i,10)),[r,o]=[t(e),t(n)];for(let s=0;s<Math.max(r.length,o.length);s++){let[i,l]=[r[s],o[s]];if(Number.isNaN(i)||i===void 0)return Number.isNaN(l)||l===void 0?e.localeCompare(n):-1;if(Number.isNaN(l)||l===void 0)return 1;if(i!==l)return i-l}return 0}function uh(e){try{return rh(e)}catch{return[]}}var le,In,Ro,Nn,sh,bo,ih,ge=zu(()=>{"use strict";le="redskilled.bundle.min.mjs",In="redskilled-daemon-entry-unresolved",Ro="REDSKILLED_BIN";Nn=class extends Error{code=In;searched;callerEntry;constructor(n){super(`${In}: 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)}};nh=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,bo=/^redskilled-(.+)\.bundle\.min\.mjs$/,th=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as Eb}from"node:child_process";import{homedir as $s}from"node:os";import{join as pu}from"node:path";var qe=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},Pe=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 qe(e,n)}function S(e,n){return new Pe(e,n)}function Je(e){return e instanceof Pe?e:e instanceof qe?new Pe(e.line,e.reason):new Pe(0,String(e&&e.message?e.message:e))}var mi=["type","kind","event"],je="|",hi=new Set(["order","discriminator","rows","common"]);var O=",";function pt(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 V(e,n){if(e==="")return"";if(e.startsWith('"'))return ki(e,n);if(e.includes('"'))throw re(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:Ju(e)?Number(e):e}function Y(e,n){let t=e.trim();if(t.startsWith('"'))return[ki(t,n),!0];if(t.includes('"')||/\s/.test(t))throw R(n,"expected non-empty field name");return[t,!1]}var yi=/["\\\u0000-\u0008\u000a-\u001f]/g;function ki(e,n){if(e.charCodeAt(0)!==34)throw re(n);let t="",r=1;for(;r<e.length;){yi.lastIndex=r;let o=yi.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(r,o.index);throw re(n)}if(o[0]!=="\\")throw re(n);t+=e.slice(r,o.index);let s=e[o.index+1];switch(r=o.index+2,s){case'"':t+='"';break;case"\\":t+="\\";break;case"n":t+=`
8
- `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let i=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(i))throw re(n);let a=Number.parseInt(i,16);if(a>=55296&&a<=57343)throw re(n);t+=String.fromCharCode(a),r+=4;break}default:throw re(n)}}throw re(n)}function Ri(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 X(e,n,t){if(e==="")return[];let r=[],o=0,s=0;for(;s<e.length;){let i=e.indexOf('"',s),a=e.indexOf(n,s);if(a!==-1&&(i===-1||a<i))r.push(e.slice(o,a).trim()),o=a+1,s=a+1;else if(i!==-1)s=Ri(e,i+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),s=e.indexOf(n,r);if(s!==-1&&(o===-1||s<o))return s;if(o===-1)return-1;r=Ri(e,o+1,t)}return-1}function Ju(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Qu(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function zu(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 F(e,n){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return zu(e);if(typeof e=="string")return Xu(e,n);throw R(0,"not a primitive")}function Yu(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function N(e){return Yu(e)?e:ft(e)}function Xu(e,n){return Er(e,n)?ft(e):e}function Er(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Qu(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}var gi=/["\\\u0000-\u001f]/g;function ft(e){let n='"',t=0;gi.lastIndex=0;let r;for(;(r=gi.exec(e))!==null;){let o=e.charCodeAt(r.index),s;o===34?s='\\"':o===92?s="\\\\":o===10?s="\\n":o===13?s="\\r":o===9?s="\\t":s=`\\u${o.toString(16).padStart(4,"0")}`,n+=e.slice(t,r.index)+s,t=r.index+1}return`${n}${e.slice(t)}"`}function Z(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bi(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 _i(e,n){let t=[],r=!1;return pt(e).forEach((o,s)=>{let i=s+1;if(o.trim()===""){r=!0;return}let a=o.length-o.replace(/^ +/,"").length;if(o[a]===" ")throw R(i,"invalid indentation");if(n.strict&&a%n.indent!==0)throw R(i,"invalid indentation");let l=Math.floor(a/n.indent);se(l,i,n),t.push({number:i,depth:l,content:o.slice(a),blankBefore:r}),r=!1}),t}function se(e,n,t){if(t.maxDepth!==0&&e>t.maxDepth)throw R(n,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function Pn(e,n,t){if(t.maxDepth===0)return;let r=0,o=!1,s=!1;for(let i of e){if(s){s=!1;continue}if(o&&i==="\\"){s=!0;continue}if(i==='"'){o=!o;continue}o||(i==="{"?(r+=1,se(r,n,t)):i==="}"&&(r=Math.max(0,r-1)))}}function Si(e){if(!L(e)||Object.keys(e).length===0)return e;let n={};for(let[t,r]of Object.entries(e)){let o=Zu(r,1);if(o===void 0)return e;Z(n,t,o)}return n}function Zu(e,n){if(!L(e)||!ep(e))return;let{order:t,discriminator:r,rows:o}=e;if(typeof t!="string"||typeof r!="string"||!Number.isSafeInteger(o)||o<0)throw M(n);let s=np(t,o,n),i=e.common,a=i===void 0?Array.from({length:o},()=>({})):i;if(!Array.isArray(a)||a.length!==o||!a.every(L))throw vi(n);let l=new Map;for(let[u,f]of Object.entries(e))if(!hi.has(u)){if(!Array.isArray(f)||!f.every(L))throw M(n);l.set(u,f)}if(l.size===0)throw M(n);let d=new Map,c=s.map((u,f)=>{let m=l.get(u);if(m===void 0)throw Pr(n);let h=d.get(u)??0,b=m[h];if(b===void 0)throw Pr(n);return d.set(u,h+1),tp(r,u,a[f],b,n)});for(let[u,f]of l)if((d.get(u)??0)!==f.length)throw Pr(n);return c}function ep(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function np(e,n,t){if(!e.startsWith("cycle("))throw M(t);let r=e.slice(6),o=r.indexOf(")*");if(o===-1)throw M(t);let s=r.slice(0,o),i=r.slice(o+2);if(s===""||i.includes("+tail("))throw M(t);let a=s.split(",").map(c=>ip(c,t));if(a.some(c=>c===""))throw M(t);let l=sp(i,t),d=a.length*l;if(!Number.isSafeInteger(d))throw M(t);if(d!==n)throw vi(t);return Array.from({length:d},(c,u)=>a[u%a.length])}function tp(e,n,t,r,o){let s={};Z(s,e,n);for(let[i,a]of Object.entries(t??{})){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw M(o);Z(s,i,a)}for(let[i,a]of Object.entries(rp(r,o))){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw M(o);Z(s,i,a)}return s}function rp(e,n){let t={};for(let[r,o]of Object.entries(e))op(t,r.split("."),o,n);return mt(t,n)}function op(e,n,t,r){if(n.some(s=>s===""))throw M(r);let o=e;for(let s=0;s<n.length;s+=1){let i=n[s];if(s===n.length-1){o[i]=t;return}if(o[i]??={},o=o[i],!L(o))throw M(r)}}function mt(e,n){return Array.isArray(e)?e.map(t=>mt(t,n)):L(e)?Number.isSafeInteger(e.length)&&e.length>=0?Array.from({length:e.length},(t,r)=>{if(!Object.prototype.hasOwnProperty.call(e,String(r)))throw M(n);return mt(e[String(r)],n)}):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,mt(r,n)])):e}function sp(e,n){if(e===""||e.length>1&&e.startsWith("0")||!/^[0-9]+$/.test(e))throw M(n);let t=Number(e);if(!Number.isSafeInteger(t))throw M(n);return t}function ip(e,n){try{return decodeURIComponent(e)}catch{throw M(n)}}function wi(e){return encodeURIComponent(e)}function M(e){return R(e,"invalid cyclic array wire")}function vi(e){return R(e,"cyclic array length mismatch")}function Pr(e){return R(e,"cyclic array group length mismatch")}function Ei(e){if(!L(e))return;let n=Object.entries(e);if(n.length===0)return;let t=[];for(let[o,s]of n){let i=lp(s);if(i===void 0)return;t.push([o,i])}let r=[];for(let[o,s]of t)up(r,o,s);return r.join("")}function lp(e){if(!Array.isArray(e)||e.length===0||!e.every(L))return;let n=ap(e);if(n===void 0)return;let t=e.map(a=>a[n]),r=dp(t);if(r===void 0)return;let o=cp(e,n),s=new Map;for(let a of e){let l=a[n];s.has(l)||s.set(l,[]);let d={};for(let[c,u]of Object.entries(a))if(c!==n&&!o.includes(c)&&!jr(u,c,d))return;s.get(l).push(d)}let i=[];for(let a of r.cycle){let l=s.get(a),d=fp(l);if(d===void 0||d.length===0)return;i.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:i,order:r,rows:e}}function ap(e){return mi.find(n=>e.every(t=>typeof t[n]=="string"))}function dp(e){if(!(e.length<12))for(let n=2;n<=Math.min(8,Math.floor(e.length/3));n+=1){if(e.length%n!==0)continue;let t=e.slice(0,n);if(new Set(t).size<2||!e.every((i,a)=>i===t[a%n]))continue;let r=e.length/n;if(r<3)continue;let o=e.map(wi).join(","),s=`cycle(${t.map(wi).join(",")})*${r}`;if(s.length<=o.length*.4)return{cycle:t,encoded:s,repeats:r}}}function cp(e,n){let t=[],r=Object.keys(e[0]),o=r.indexOf(n)+1;for(let s of r.slice(o).filter(i=>i!==n)){if(!pp(s)||!e.every(i=>Object.prototype.hasOwnProperty.call(i,s))||!e.every(i=>oe(i[s])))break;t.push(s)}return t}function up(e,n,t){e.push(N(n),`:
6
+ `)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};sh=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,bo=/^redskilled-(.+)\.bundle\.min\.mjs$/,ih=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as Db}from"node:child_process";import{homedir as Ms}from"node:os";import{join as hu}from"node:path";var qe=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},Pe=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 qe(e,n)}function S(e,n){return new Pe(e,n)}function Je(e){return e instanceof Pe?e:e instanceof qe?new Pe(e.line,e.reason):new Pe(0,String(e&&e.message?e.message:e))}var yi=["type","kind","event"],je="|",ki=new Set(["order","discriminator","rows","common"]);var O=",";function ht(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 V(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:Xu(e)?Number(e):e}function Y(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 Ri=/["\\\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;){Ri.lastIndex=r;let o=Ri.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 s=e[o.index+1];switch(r=o.index+2,s){case'"':t+='"';break;case"\\":t+="\\";break;case"n":t+=`
8
+ `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let i=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(i))throw re(n);let l=Number.parseInt(i,16);if(l>=55296&&l<=57343)throw re(n);t+=String.fromCharCode(l),r+=4;break}default:throw re(n)}}throw re(n)}function wi(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 X(e,n,t){if(e==="")return[];let r=[],o=0,s=0;for(;s<e.length;){let i=e.indexOf('"',s),l=e.indexOf(n,s);if(l!==-1&&(i===-1||l<i))r.push(e.slice(o,l).trim()),o=l+1,s=l+1;else if(i!==-1)s=wi(e,i+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),s=e.indexOf(n,r);if(s!==-1&&(o===-1||s<o))return s;if(o===-1)return-1;r=wi(e,o+1,t)}return-1}function Xu(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Zu(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function ep(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 F(e,n){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return ep(e);if(typeof e=="string")return tp(e,n);throw R(0,"not a primitive")}function np(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function N(e){return np(e)?e:gt(e)}function tp(e,n){return Er(e,n)?gt(e):e}function Er(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Zu(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}var bi=/["\\\u0000-\u001f]/g;function gt(e){let n='"',t=0;bi.lastIndex=0;let r;for(;(r=bi.exec(e))!==null;){let o=e.charCodeAt(r.index),s;o===34?s='\\"':o===92?s="\\\\":o===10?s="\\n":o===13?s="\\r":o===9?s="\\t":s=`\\u${o.toString(16).padStart(4,"0")}`,n+=e.slice(t,r.index)+s,t=r.index+1}return`${n}${e.slice(t)}"`}function Z(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xi(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 Si(e,n){let t=[],r=!1;return ht(e).forEach((o,s)=>{let i=s+1;if(o.trim()===""){r=!0;return}let l=o.length-o.replace(/^ +/,"").length;if(o[l]===" ")throw R(i,"invalid indentation");if(n.strict&&l%n.indent!==0)throw R(i,"invalid indentation");let a=Math.floor(l/n.indent);se(a,i,n),t.push({number:i,depth:a,content:o.slice(l),blankBefore:r}),r=!1}),t}function se(e,n,t){if(t.maxDepth!==0&&e>t.maxDepth)throw R(n,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function jn(e,n,t){if(t.maxDepth===0)return;let r=0,o=!1,s=!1;for(let i of e){if(s){s=!1;continue}if(o&&i==="\\"){s=!0;continue}if(i==='"'){o=!o;continue}o||(i==="{"?(r+=1,se(r,n,t)):i==="}"&&(r=Math.max(0,r-1)))}}function Pi(e){if(!L(e)||Object.keys(e).length===0)return e;let n={};for(let[t,r]of Object.entries(e)){let o=rp(r,1);if(o===void 0)return e;Z(n,t,o)}return n}function rp(e,n){if(!L(e)||!op(e))return;let{order:t,discriminator:r,rows:o}=e;if(typeof t!="string"||typeof r!="string"||!Number.isSafeInteger(o)||o<0)throw M(n);let s=sp(t,o,n),i=e.common,l=i===void 0?Array.from({length:o},()=>({})):i;if(!Array.isArray(l)||l.length!==o||!l.every(L))throw ji(n);let a=new Map;for(let[u,f]of Object.entries(e))if(!ki.has(u)){if(!Array.isArray(f)||!f.every(L))throw M(n);a.set(u,f)}if(a.size===0)throw M(n);let d=new Map,c=s.map((u,f)=>{let m=a.get(u);if(m===void 0)throw Pr(n);let h=d.get(u)??0,b=m[h];if(b===void 0)throw Pr(n);return d.set(u,h+1),ip(r,u,l[f],b,n)});for(let[u,f]of a)if((d.get(u)??0)!==f.length)throw Pr(n);return c}function op(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function sp(e,n,t){if(!e.startsWith("cycle("))throw M(t);let r=e.slice(6),o=r.indexOf(")*");if(o===-1)throw M(t);let s=r.slice(0,o),i=r.slice(o+2);if(s===""||i.includes("+tail("))throw M(t);let l=s.split(",").map(c=>cp(c,t));if(l.some(c=>c===""))throw M(t);let a=dp(i,t),d=l.length*a;if(!Number.isSafeInteger(d))throw M(t);if(d!==n)throw ji(t);return Array.from({length:d},(c,u)=>l[u%l.length])}function ip(e,n,t,r,o){let s={};Z(s,e,n);for(let[i,l]of Object.entries(t??{})){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw M(o);Z(s,i,l)}for(let[i,l]of Object.entries(lp(r,o))){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw M(o);Z(s,i,l)}return s}function lp(e,n){let t={};for(let[r,o]of Object.entries(e))ap(t,r.split("."),o,n);return yt(t,n)}function ap(e,n,t,r){if(n.some(s=>s===""))throw M(r);let o=e;for(let s=0;s<n.length;s+=1){let i=n[s];if(s===n.length-1){o[i]=t;return}if(o[i]??={},o=o[i],!L(o))throw M(r)}}function yt(e,n){return Array.isArray(e)?e.map(t=>yt(t,n)):L(e)?Number.isSafeInteger(e.length)&&e.length>=0?Array.from({length:e.length},(t,r)=>{if(!Object.prototype.hasOwnProperty.call(e,String(r)))throw M(n);return yt(e[String(r)],n)}):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,yt(r,n)])):e}function dp(e,n){if(e===""||e.length>1&&e.startsWith("0")||!/^[0-9]+$/.test(e))throw M(n);let t=Number(e);if(!Number.isSafeInteger(t))throw M(n);return t}function cp(e,n){try{return decodeURIComponent(e)}catch{throw M(n)}}function vi(e){return encodeURIComponent(e)}function M(e){return R(e,"invalid cyclic array wire")}function ji(e){return R(e,"cyclic array length mismatch")}function Pr(e){return R(e,"cyclic array group length mismatch")}function Di(e){if(!L(e))return;let n=Object.entries(e);if(n.length===0)return;let t=[];for(let[o,s]of n){let i=up(s);if(i===void 0)return;t.push([o,i])}let r=[];for(let[o,s]of t)hp(r,o,s);return r.join("")}function up(e){if(!Array.isArray(e)||e.length===0||!e.every(L))return;let n=pp(e);if(n===void 0)return;let t=e.map(l=>l[n]),r=fp(t);if(r===void 0)return;let o=mp(e,n),s=new Map;for(let l of e){let a=l[n];s.has(a)||s.set(a,[]);let d={};for(let[c,u]of Object.entries(l))if(c!==n&&!o.includes(c)&&!jr(u,c,d))return;s.get(a).push(d)}let i=[];for(let l of r.cycle){let a=s.get(l),d=yp(a);if(d===void 0||d.length===0)return;i.push({fields:d,label:l,rows:a})}return{common:o,commonRows:e.map(l=>Object.fromEntries(o.map(a=>[a,l[a]]))),discriminator:n,groups:i,order:r,rows:e}}function pp(e){return yi.find(n=>e.every(t=>typeof t[n]=="string"))}function fp(e){if(!(e.length<12))for(let n=2;n<=Math.min(8,Math.floor(e.length/3));n+=1){if(e.length%n!==0)continue;let t=e.slice(0,n);if(new Set(t).size<2||!e.every((i,l)=>i===t[l%n]))continue;let r=e.length/n;if(r<3)continue;let o=e.map(vi).join(","),s=`cycle(${t.map(vi).join(",")})*${r}`;if(s.length<=o.length*.4)return{cycle:t,encoded:s,repeats:r}}}function mp(e,n){let t=[],r=Object.keys(e[0]),o=r.indexOf(n)+1;for(let s of r.slice(o).filter(i=>i!==n)){if(!gp(s)||!e.every(i=>Object.prototype.hasOwnProperty.call(i,s))||!e.every(i=>oe(i[s])))break;t.push(s)}return t}function hp(e,n,t){e.push(N(n),`:
9
9
  `),e.push(" order: ",F(t.order.encoded,je),`
10
10
  `),e.push(" discriminator: ",F(t.discriminator,je),`
11
11
  `),e.push(" rows: ",String(t.rows.length),`
12
- `),t.common.length>0&&xi(e,"common",t.common,t.commonRows);for(let r of t.groups)xi(e,r.label,r.fields,r.rows)}function xi(e,n,t,r){e.push(" ",N(n),"[",String(r.length),je,"]{",t.map(N).join(je),`}:
12
+ `),t.common.length>0&&Ei(e,"common",t.common,t.commonRows);for(let r of t.groups)Ei(e,r.label,r.fields,r.rows)}function Ei(e,n,t,r){e.push(" ",N(n),"[",String(r.length),je,"]{",t.map(N).join(je),`}:
13
13
  `);for(let o of r)e.push(" ",t.map(s=>F(o[s],je)).join(je),`
14
- `)}function pp(e){return e!==""&&Dr(e)}function jr(e,n,t,r=new Set){if(!Dr(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((s,i)=>jr(s,`${n}.${i}`,t,r));return r.delete(e),o}if(L(e)){if(r.has(e))return!1;r.add(e);let o=Object.entries(e).every(([s,i])=>!s.includes(".")&&jr(i,`${n}.${s}`,t,r));return r.delete(e),o}return!1}function fp(e){let n=Object.keys(e[0]??{});if(e.every(t=>mp(Object.keys(t),n)))return n.every(Dr)?n:void 0}function mp(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function Dr(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function Qe(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function ht(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,s;try{[o,s]=Y(t.slice(0,r),0)}catch{throw R(0,"invalid array header")}let i=t.slice(r+1),a=i.indexOf("]");if(a===-1)throw R(0,"invalid array header");let l=i.slice(0,a),d=/^[0-9]*/.exec(l)[0];if(d===""||d.length>1&&d.startsWith("0"))throw R(0,"invalid array header");let c=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=i.slice(a+1),m,h;if(f==="")m=void 0,h=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{h=yp(f.slice(1,-1),u),m=Ar(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:s,len:c,delimiter:u,fields:m,fieldTree:h}}function Pi(e){let n=W(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=Y(e.slice(0,n),0)}catch{throw R(0,"invalid keyed map header")}if(t===""&&!r)throw R(0,"expected non-empty field name");let o=e.slice(n+1,-1),s=O;(o.startsWith("|")||o.startsWith(" "))&&(s=o[0],o=o.slice(1));let i;try{i=hp(o,s,s)}catch(a){throw R(0,a.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:s,fields:i}}function hp(e,n,t){let r=[],o=0;function s(l,d){let c=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==='"'){i();continue}if(h===n||h==="{"||h==="}"||h==="[")break;o+=1}let[f,m]=Y(e.slice(u,o),0);if(f===""&&!m)throw R(0,"invalid array header");if(c+=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(!ji(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(s([...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(c===0)throw R(0,"invalid array header")}function i(){for(o+=1;o<e.length;){let l=e[o];if(o+=1,l==="\\")o+=1;else if(l==='"')return}}if(s([],!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(Di(r[l].path,r[d].path)||jn(r[l].path,r[d].path)||jn(r[d].path,r[l].path))throw R(0,"duplicate key");for(let l of r){let c=l.path.join("\0");if(a.has(c))throw R(0,"duplicate key");a.add(c)}return r}function yp(e,n){if(n!==O&&e.includes(O)&&(e.includes("[")||e.includes("{")))return Or(e,O,n);try{return Or(e,n,n)}catch(t){if(n!==O&&t.reason!=="duplicate key")return Or(e,O,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 c=r;for(;r<e.length;){let h=e[r];if(h==='"'){s();continue}if(h===n||h==="{"||h==="}"||h==="[")break;r+=1}let[u,f]=Y(e.slice(c,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=gp(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(ji(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 s(){for(r+=1;r<e.length;){let l=e[r];if(r+=1,l==="\\")r+=1;else if(l==='"')return}}let i=o(!1);if(r!==e.length)throw R(0,"invalid array header");let a=Ar(i);for(let l=0;l<a.length;l+=1)for(let d=l+1;d<a.length;d+=1)if(Di(a[l].path,a[d].path)||jn(a[l].path,a[d].path)||jn(a[d].path,a[l].path))throw R(0,"duplicate key");return i}function gp(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=O;break;case" ":r=" ";break;case"|":r="|";break;default:return}return{len:Number.parseInt(n,10),delimiter:r}}function Ar(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?Ar(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function yt(e,n,t){return e.listDelimiter===void 0?V(n,t):X(n,e.listDelimiter,t).map(r=>V(r,t))}function ji(e,n){return e.length===1&&e!==n&&!/[ \t\r\n"[\]{}:]/.test(e)}function Di(e,n){return e.length===n.length&&jn(e,n)}function jn(e,n){return n.every((t,r)=>e[r]===t)}function gt(e,n){return R(n,e.reason??String(e.message))}function q(e,n){let t=bi(n),r=_i(e,t),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw R(o.number,"invalid indentation");let s=r.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){Pn(o.content,o.number,t);let d;try{d=ht(o.content,W(o.content,":",o.number))}catch(c){if(t.strict)throw gt(c,o.number);d=void 0}if(d!==void 0)return bp(d,r,t)}if(s&&W(o.content,":",o.number)===-1)return V(o.content.trim(),o.number);let i={index:0},a=Tr(r,i,0,t),l=r[i.index];if(l!==void 0)throw R(l.number,"expected end of document");return t.cyclicDiscriminatedArrays?Si(a):a}function Tr(e,n,t,r){let o={};for(;n.index<e.length;){let s=e[n.index];if(s.depth<t)break;if(s.depth>t)throw R(s.number,"invalid indentation");let{key:i,quoted:a,value:l}=kp(e,n,t,r);Ni(o,i,a,l,r,s.number)}return o}function kp(e,n,t,r){let o=e[n.index],s=o.content,i=W(s,":",o.number);if(i===-1)throw R(o.number,"expected `key: value`");let a=s.slice(0,i),l=s.slice(i+1),d=W(a,"[",o.number),c=W(a,"{",o.number);if(c!==-1&&(d===-1||c<d)){Pn(a,o.number,r);let h;try{h=Pi(a)}catch(k){if(r.strict)throw gt(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=Rp(h,e,n,t+1,r);return{key:h.key,quoted:h.keyQuoted,value:b}}if(d!==-1){Pn(a,o.number,r);let h;try{h=ht(a,i)}catch(k){if(r.strict)throw gt(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=$r(h,l,e,n,t,r);return{key:h.key,quoted:h.keyQuoted,value:b}}let[u,f]=Y(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,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return V(i,o);let a=e[n.index];return a!==void 0&&a.depth>t?Tr(e,n,t+1,s):{}}function Rp(e,n,t,r,o){let s={};for(t.index+=1;t.index<n.length;){let i=n[t.index];if(i.depth<r)break;if(i.depth>r)throw R(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw R(i.number,"blank line inside keyed map");let a=W(i.content,":",i.number);if(a===-1)throw R(i.number,"expected `key: value`");let[l,d]=Y(i.content.slice(0,a),i.number);if(l===""&&!d)throw R(i.number,"expected non-empty field name");let c=X(i.content.slice(a+1).trim(),e.delimiter,i.number);if(c.length!==e.fields.length)throw R(i.number,"keyed map row length mismatch");let u={};e.fields.forEach((f,m)=>{Ye(u,f.path,yt(f,c[m],i.number),o,i.number)}),Ni(s,l,d,u,o,i.number),t.index+=1}return s}function bp(e,n,t){let r=n[0],o=W(r.content,":",r.number);if(o===-1)throw R(r.number,"expected `key: value`");let s=r.content.slice(o+1),i={index:0},a=$r(e,s,n,i,0,t),l=n[i.index];if(l!==void 0)throw R(l.number,"expected end of document");return a}function $r(e,n,t,r,o,s){let i=t[r.index].number,a=n.trim();if(r.index+=1,e.fields!==void 0){if(a!=="")throw R(i,"expected tabular rows");return _p(e,e.fields,t,r,o+1,s)}if(a!==""){let l=X(a,e.delimiter,i).map(d=>V(d,i));if(l.length!==e.len)throw R(i,"array length mismatch");return l}return jp(e,t,r,o+1,s)}function _p(e,n,t,r,o,s){if(e.fieldTree!==void 0&&Ep(e.fieldTree))return wp(e,t,r,o,s);let i=[];for(;i.length<e.len;){let l=t[r.index];if(l===void 0)throw Qe(t,r.index);if(l.depth<o)break;if(l.depth>o)throw R(l.number,"invalid indentation");if(l.blankBefore&&s.strict)throw R(l.number,"blank line inside array");if(!ze(l.content,e.delimiter,l.number))break;let d=X(l.content,e.delimiter,l.number);if(d.length!==n.length)throw R(l.number,"array row length mismatch");let c={};n.forEach((u,f)=>{Ye(c,u.path,yt(u,d[f],l.number),s,l.number)}),i.push(c),r.index+=1}if(i.length!==e.len)throw Qe(t,r.index);let a=t[r.index];if(a!==void 0&&a.depth>=o&&ze(a.content,e.delimiter,a.number))throw R(a.number,"array length mismatch");return i}function wp(e,n,t,r,o){return Oi(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function Oi(e,n,t,r,o,s,i,a){let l=[],d=Li(e,n,t,r,o.index,s,i);for(;l.length<e;){let u=r[o.index];if(u===void 0)throw Qe(r,o.index);if(u.depth<s)break;if(u.depth>s)throw R(u.number,"invalid indentation");if(u.blankBefore&&i.strict)throw R(u.number,"blank line inside array");if(!ze(u.content,t,u.number))break;let f=X(u.content,t,u.number),m={cellIndex:0,nextIndex:o.index+1,flatWidth:kt(n),childTableFields:d},h=Ai(n,f,u.number,r,m,s+1,t,i);if(m.cellIndex!==f.length)throw R(u.number,"array row length mismatch");l.push(vp(n,h,a)),o.index=m.nextIndex}if(l.length!==e)throw Qe(r,o.index);let c=r[o.index];if(c!==void 0&&c.depth>=s&&ze(c.content,t,c.number))throw R(c.number,"array length mismatch");return l}function Ai(e,n,t,r,o,s,i,a){let l={};return e.forEach((d,c)=>{let u=e.slice(c+1),f=xp(d,u,n,t,r,o,s,i,a);Ye(l,[d.key],f,a,t)}),l}function xp(e,n,t,r,o,s,i,a,l){if(e.fixedLength!==void 0){if(s.cellIndex+e.fixedLength>t.length)throw R(r,"array row length mismatch");let c=t.slice(s.cellIndex,s.cellIndex+e.fixedLength).map(u=>V(u,r));return s.cellIndex+=e.fixedLength,c}if(e.children!==void 0){let c=kt(e.children),u=t[s.cellIndex],f=$i(u),m=t.length-s.cellIndex-1,h=o[s.nextIndex],b=h!==void 0&&h.depth===i,k=s.childTableFields===void 0?void 0:s.childTableFields.has(e);if(k===void 0?f!==void 0&&(b||t.length!==s.flatWidth&&m<c+Pp(n)):k){if(f===void 0)throw R(r,"array row length mismatch");return s.cellIndex+=1,Oi(f,e.children,a,o,{get index(){return s.nextIndex},set index(D){s.nextIndex=D}},i,l,!1)}return Ai(e.children,t,r,o,s,i,a,l)}let d=t[s.cellIndex];if(d===void 0)throw R(r,"array row length mismatch");return s.cellIndex+=1,yt(e,d,r)}function Li(e,n,t,r,o,s,i){let a=n.filter(c=>c.children!==void 0);if(a.length===0)return new Set;if(a.length>12)return;let l,d=1<<a.length;for(let c=0;c<d;c+=1){let u=new Set;a.forEach((m,h)=>{c&1<<h&&u.add(m)});let f=Ti(e,n,u,t,r,o,s,i);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 Ti(e,n,t,r,o,s,i,a){let l=s,d=0;try{for(let u=0;u<e;u+=1){let f=o[l];if(f===void 0||f.depth!==i||f.blankBefore&&a.strict||!ze(f.content,r,f.number))return;let m=X(f.content,r,f.number),h=Sp(n,t,m,r,o,l+1,i+1,a);if(h===void 0||o[h.nextIndex]?.depth>i)return;d+=h.consumedChildRows,l=h.nextIndex}let c=o[l];if(c!==void 0&&c.depth>=i&&ze(c.content,r,c.number))return}catch{return}return{nextIndex:l,consumedChildRows:d}}function Sp(e,n,t,r,o,s,i,a){let l=0,d=s,c=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=$i(t[l]);if(f===void 0)return;l+=1;let m=Li(f,u.children,r,o,d,i,a);if(m===void 0)return;let h=Ti(f,u.children,m,r,o,d,i,a);if(h===void 0)return;d=h.nextIndex,c+=f+h.consumedChildRows}else l+=kt(u.children);else l+=1;if(l>t.length)return}if(l===t.length)return{nextIndex:d,consumedChildRows:c}}function vp(e,n,t){return t&&e.length===1&&e[0].fixedLength!==void 0?n[e[0].key]:n}function $i(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function Ep(e){return e.some(n=>n.fixedLength!==void 0||n.children!==void 0)}function kt(e){return e.reduce((n,t)=>n+Ii(t),0)}function Ii(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?kt(e.children):1}function Pp(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+Ii(t),0)}function ze(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 jp(e,n,t,r,o){let s=[];for(;s.length<e.len;){let a=n[t.index];if(a===void 0||a.depth<r)throw Qe(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");s.push(Dp(n,t,r,o))}let i=n[t.index];if(i!==void 0&&i.depth>=r)throw R(i.number,"array length mismatch");return s}function Dp(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw R(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return n.index+=1,{};if(s.startsWith("[")){let i=W(s,":",o.number);Pn(s,o.number,r);let a;try{a=ht(s,i)}catch{a=void 0}if(a!==void 0){let l=s.slice(i+1);return $r(a,l,e,n,t,r)}}if(W(s,":",o.number)!==-1){let i=[{number:o.number,depth:t+1,content:s,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let a=e[n.index];if(a.depth<=t)break;i.push(a),n.index+=1}return Tr(i,{index:0},t+1,r)}return n.index+=1,V(s,o.number)}function Ni(e,n,t,r,o,s){if(o.expandPaths&&!t&&n.includes(".")){let i=n.split(".");if(i.every(Op)){Ye(e,i,r,o,s);return}}Ye(e,[n],r,o,s)}function Ye(e,n,t,r,o){se(n.length-1,o,r);let s=n[0],i=Object.prototype.hasOwnProperty.call(e,s);if(n.length===1){if(i&&r.strict)throw R(o,"duplicate key");Z(e,s,t);return}if(i&&!L(e[s])){if(r.strict)throw R(o,"path expansion conflict");Z(e,s,{})}else i||Z(e,s,{});Ye(e[s],n.slice(1),t,r,o)}function Op(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function C(e,n={}){let t=n.maxDepth??1e3,r=n.delimiter??O;if(![O,"|"," "].includes(r))throw R(0,"invalid array header");let o={nestedTabularHeaders:n.nestedTabularHeaders===!0,keyedMapCollapse:n.keyedMapCollapse===!0,primitiveArrayColumns:n.primitiveArrayColumns===!0,objectArrayColumns:n.objectArrayColumns===!0,cyclicDiscriminatedArrays:n.cyclicDiscriminatedArrays===!0,delimiter:r,maxDepth:t===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(t))};if(o.cyclicDiscriminatedArrays){let i=Ei(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?Cr(s,void 0,e,0,!1,o):L(e)?Mi(s,e,0,o):s.push(F(e,r)),s.join("")}function Xe(e,n){e.push(" ".repeat(n*2))}function Mi(e,n,t,r){se(t,0,r);for(let[o,s]of Object.entries(n))Xe(e,t),Nr(e,o,s,t,r)}function Nr(e,n,t,r,o){if(se(r,0,o),Array.isArray(t)){Cr(e,n,t,r,!1,o);return}if(L(t)){let s=o.keyedMapCollapse?Lp(t,o,r+1):void 0;if(s!==void 0){e.push(N(n),"{",Wr(o.delimiter),s.fields.map(i=>Hr(i,o.delimiter)).join(o.delimiter),`}:
15
- `);for(let[i,a]of Object.entries(t)){Xe(e,r+1);let l=[];e.push(N(i),": ",s.paths.map(d=>Ur(Br(a,d.path),d,o.delimiter,o,l,r+2)).join(o.delimiter),`
16
- `),e.push(...l)}return}e.push(N(n),`:
17
- `),Mi(e,t,r+1,o);return}e.push(N(n),": ",F(t,o.delimiter),`
14
+ `)}function gp(e){return e!==""&&Dr(e)}function jr(e,n,t,r=new Set){if(!Dr(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((s,i)=>jr(s,`${n}.${i}`,t,r));return r.delete(e),o}if(L(e)){if(r.has(e))return!1;r.add(e);let o=Object.entries(e).every(([s,i])=>!s.includes(".")&&jr(i,`${n}.${s}`,t,r));return r.delete(e),o}return!1}function yp(e){let n=Object.keys(e[0]??{});if(e.every(t=>kp(Object.keys(t),n)))return n.every(Dr)?n:void 0}function kp(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function Dr(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function Qe(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function kt(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,s;try{[o,s]=Y(t.slice(0,r),0)}catch{throw R(0,"invalid array header")}let i=t.slice(r+1),l=i.indexOf("]");if(l===-1)throw R(0,"invalid array header");let a=i.slice(0,l),d=/^[0-9]*/.exec(a)[0];if(d===""||d.length>1&&d.startsWith("0"))throw R(0,"invalid array header");let c=Number.parseInt(d,10),u;switch(a.slice(d.length)){case"":u=",";break;case" ":u=" ";break;case"|":u="|";break;default:throw R(0,"invalid array header")}let f=i.slice(l+1),m,h;if(f==="")m=void 0,h=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{h=bp(f.slice(1,-1),u),m=Ar(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:s,len:c,delimiter:u,fields:m,fieldTree:h}}function Oi(e){let n=W(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=Y(e.slice(0,n),0)}catch{throw R(0,"invalid keyed map header")}if(t===""&&!r)throw R(0,"expected non-empty field name");let o=e.slice(n+1,-1),s=O;(o.startsWith("|")||o.startsWith(" "))&&(s=o[0],o=o.slice(1));let i;try{i=Rp(o,s,s)}catch(l){throw R(0,l.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:s,fields:i}}function Rp(e,n,t){let r=[],o=0;function s(a,d){let c=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==='"'){i();continue}if(h===n||h==="{"||h==="}"||h==="[")break;o+=1}let[f,m]=Y(e.slice(u,o),0);if(f===""&&!m)throw R(0,"invalid array header");if(c+=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(!Ai(b,t))throw R(0,"invalid array header");o+=1,r.push({path:[...a,f],listDelimiter:b})}else if(e[o]==="{"){o+=1;let h=r.length;if(s([...a,f],!0),e[o]!=="}"||r.length===h)throw R(0,"invalid array header");o+=1}else r.push({path:[...a,f],listDelimiter:void 0});if(e[o]===n){if(o+=1,o>=e.length||e[o]==="}")throw R(0,"invalid array header");continue}if(d?e[o]==="}":o===e.length)break;throw R(0,"invalid array header")}if(c===0)throw R(0,"invalid array header")}function i(){for(o+=1;o<e.length;){let a=e[o];if(o+=1,a==="\\")o+=1;else if(a==='"')return}}if(s([],!1),o!==e.length)throw R(0,"invalid array header");let l=new Set;for(let a=0;a<r.length;a+=1)for(let d=a+1;d<r.length;d+=1)if(Li(r[a].path,r[d].path)||Dn(r[a].path,r[d].path)||Dn(r[d].path,r[a].path))throw R(0,"duplicate key");for(let a of r){let c=a.path.join("\0");if(l.has(c))throw R(0,"duplicate key");l.add(c)}return r}function bp(e,n){if(n!==O&&e.includes(O)&&(e.includes("[")||e.includes("{")))return Or(e,O,n);try{return Or(e,n,n)}catch(t){if(n!==O&&t.reason!=="duplicate key")return Or(e,O,n);throw t}}function Or(e,n,t){let r=0;function o(a){let d=[];for(;r<e.length&&!(a&&e[r]==="}");){if(e[r]===n||e[r]==="}")throw R(0,"invalid array header");let c=r;for(;r<e.length;){let h=e[r];if(h==='"'){s();continue}if(h===n||h==="{"||h==="}"||h==="[")break;r+=1}let[u,f]=Y(e.slice(c,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=_p(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(Ai(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(a?e[r]==="}":r===e.length)break;throw R(0,"invalid array header")}if(d.length===0)throw R(0,"invalid array header");return d}function s(){for(r+=1;r<e.length;){let a=e[r];if(r+=1,a==="\\")r+=1;else if(a==='"')return}}let i=o(!1);if(r!==e.length)throw R(0,"invalid array header");let l=Ar(i);for(let a=0;a<l.length;a+=1)for(let d=a+1;d<l.length;d+=1)if(Li(l[a].path,l[d].path)||Dn(l[a].path,l[d].path)||Dn(l[d].path,l[a].path))throw R(0,"duplicate key");return i}function _p(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=O;break;case" ":r=" ";break;case"|":r="|";break;default:return}return{len:Number.parseInt(n,10),delimiter:r}}function Ar(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?Ar(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function Rt(e,n,t){return e.listDelimiter===void 0?V(n,t):X(n,e.listDelimiter,t).map(r=>V(r,t))}function Ai(e,n){return e.length===1&&e!==n&&!/[ \t\r\n"[\]{}:]/.test(e)}function Li(e,n){return e.length===n.length&&Dn(e,n)}function Dn(e,n){return n.every((t,r)=>e[r]===t)}function bt(e,n){return R(n,e.reason??String(e.message))}function q(e,n){let t=xi(n),r=Si(e,t),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw R(o.number,"invalid indentation");let s=r.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){jn(o.content,o.number,t);let d;try{d=kt(o.content,W(o.content,":",o.number))}catch(c){if(t.strict)throw bt(c,o.number);d=void 0}if(d!==void 0)return Sp(d,r,t)}if(s&&W(o.content,":",o.number)===-1)return V(o.content.trim(),o.number);let i={index:0},l=Tr(r,i,0,t),a=r[i.index];if(a!==void 0)throw R(a.number,"expected end of document");return t.cyclicDiscriminatedArrays?Pi(l):l}function Tr(e,n,t,r){let o={};for(;n.index<e.length;){let s=e[n.index];if(s.depth<t)break;if(s.depth>t)throw R(s.number,"invalid indentation");let{key:i,quoted:l,value:a}=wp(e,n,t,r);Wi(o,i,l,a,r,s.number)}return o}function wp(e,n,t,r){let o=e[n.index],s=o.content,i=W(s,":",o.number);if(i===-1)throw R(o.number,"expected `key: value`");let l=s.slice(0,i),a=s.slice(i+1),d=W(l,"[",o.number),c=W(l,"{",o.number);if(c!==-1&&(d===-1||c<d)){jn(l,o.number,r);let h;try{h=Oi(l)}catch(k){if(r.strict)throw bt(k,o.number);n.index+=1;let w=Lr(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:w}}if(a.trim()!=="")throw R(o.number,"expected keyed map rows");let b=xp(h,e,n,t+1,r);return{key:h.key,quoted:h.keyQuoted,value:b}}if(d!==-1){jn(l,o.number,r);let h;try{h=kt(l,i)}catch(k){if(r.strict)throw bt(k,o.number);n.index+=1;let w=Lr(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:w}}if(h.key===""&&!h.keyQuoted)throw R(o.number,"expected non-empty field name");let b=$r(h,a,e,n,t,r);return{key:h.key,quoted:h.keyQuoted,value:b}}let[u,f]=Y(l,o.number);if(u===""&&!f)throw R(o.number,"expected non-empty field name");n.index+=1;let m=Lr(e,n,t,a,o.number,r);return{key:u,quoted:f,value:m}}function Lr(e,n,t,r,o,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return V(i,o);let l=e[n.index];return l!==void 0&&l.depth>t?Tr(e,n,t+1,s):{}}function xp(e,n,t,r,o){let s={};for(t.index+=1;t.index<n.length;){let i=n[t.index];if(i.depth<r)break;if(i.depth>r)throw R(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw R(i.number,"blank line inside keyed map");let l=W(i.content,":",i.number);if(l===-1)throw R(i.number,"expected `key: value`");let[a,d]=Y(i.content.slice(0,l),i.number);if(a===""&&!d)throw R(i.number,"expected non-empty field name");let c=X(i.content.slice(l+1).trim(),e.delimiter,i.number);if(c.length!==e.fields.length)throw R(i.number,"keyed map row length mismatch");let u={};e.fields.forEach((f,m)=>{Ye(u,f.path,Rt(f,c[m],i.number),o,i.number)}),Wi(s,a,d,u,o,i.number),t.index+=1}return s}function Sp(e,n,t){let r=n[0],o=W(r.content,":",r.number);if(o===-1)throw R(r.number,"expected `key: value`");let s=r.content.slice(o+1),i={index:0},l=$r(e,s,n,i,0,t),a=n[i.index];if(a!==void 0)throw R(a.number,"expected end of document");return l}function $r(e,n,t,r,o,s){let i=t[r.index].number,l=n.trim();if(r.index+=1,e.fields!==void 0){if(l!=="")throw R(i,"expected tabular rows");return vp(e,e.fields,t,r,o+1,s)}if(l!==""){let a=X(l,e.delimiter,i).map(d=>V(d,i));if(a.length!==e.len)throw R(i,"array length mismatch");return a}return Lp(e,t,r,o+1,s)}function vp(e,n,t,r,o,s){if(e.fieldTree!==void 0&&Op(e.fieldTree))return Ep(e,t,r,o,s);let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0)throw Qe(t,r.index);if(a.depth<o)break;if(a.depth>o)throw R(a.number,"invalid indentation");if(a.blankBefore&&s.strict)throw R(a.number,"blank line inside array");if(!ze(a.content,e.delimiter,a.number))break;let d=X(a.content,e.delimiter,a.number);if(d.length!==n.length)throw R(a.number,"array row length mismatch");let c={};n.forEach((u,f)=>{Ye(c,u.path,Rt(u,d[f],a.number),s,a.number)}),i.push(c),r.index+=1}if(i.length!==e.len)throw Qe(t,r.index);let l=t[r.index];if(l!==void 0&&l.depth>=o&&ze(l.content,e.delimiter,l.number))throw R(l.number,"array length mismatch");return i}function Ep(e,n,t,r,o){return Ti(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function Ti(e,n,t,r,o,s,i,l){let a=[],d=Ii(e,n,t,r,o.index,s,i);for(;a.length<e;){let u=r[o.index];if(u===void 0)throw Qe(r,o.index);if(u.depth<s)break;if(u.depth>s)throw R(u.number,"invalid indentation");if(u.blankBefore&&i.strict)throw R(u.number,"blank line inside array");if(!ze(u.content,t,u.number))break;let f=X(u.content,t,u.number),m={cellIndex:0,nextIndex:o.index+1,flatWidth:_t(n),childTableFields:d},h=$i(n,f,u.number,r,m,s+1,t,i);if(m.cellIndex!==f.length)throw R(u.number,"array row length mismatch");a.push(Dp(n,h,l)),o.index=m.nextIndex}if(a.length!==e)throw Qe(r,o.index);let c=r[o.index];if(c!==void 0&&c.depth>=s&&ze(c.content,t,c.number))throw R(c.number,"array length mismatch");return a}function $i(e,n,t,r,o,s,i,l){let a={};return e.forEach((d,c)=>{let u=e.slice(c+1),f=Pp(d,u,n,t,r,o,s,i,l);Ye(a,[d.key],f,l,t)}),a}function Pp(e,n,t,r,o,s,i,l,a){if(e.fixedLength!==void 0){if(s.cellIndex+e.fixedLength>t.length)throw R(r,"array row length mismatch");let c=t.slice(s.cellIndex,s.cellIndex+e.fixedLength).map(u=>V(u,r));return s.cellIndex+=e.fixedLength,c}if(e.children!==void 0){let c=_t(e.children),u=t[s.cellIndex],f=Mi(u),m=t.length-s.cellIndex-1,h=o[s.nextIndex],b=h!==void 0&&h.depth===i,k=s.childTableFields===void 0?void 0:s.childTableFields.has(e);if(k===void 0?f!==void 0&&(b||t.length!==s.flatWidth&&m<c+Ap(n)):k){if(f===void 0)throw R(r,"array row length mismatch");return s.cellIndex+=1,Ti(f,e.children,l,o,{get index(){return s.nextIndex},set index(D){s.nextIndex=D}},i,a,!1)}return $i(e.children,t,r,o,s,i,l,a)}let d=t[s.cellIndex];if(d===void 0)throw R(r,"array row length mismatch");return s.cellIndex+=1,Rt(e,d,r)}function Ii(e,n,t,r,o,s,i){let l=n.filter(c=>c.children!==void 0);if(l.length===0)return new Set;if(l.length>12)return;let a,d=1<<l.length;for(let c=0;c<d;c+=1){let u=new Set;l.forEach((m,h)=>{c&1<<h&&u.add(m)});let f=Ni(e,n,u,t,r,o,s,i);f!==void 0&&(a===void 0||f.consumedChildRows>a.consumedChildRows||f.consumedChildRows===a.consumedChildRows&&u.size<a.childTableFields.size)&&(a={childTableFields:u,consumedChildRows:f.consumedChildRows})}return a?.childTableFields}function Ni(e,n,t,r,o,s,i,l){let a=s,d=0;try{for(let u=0;u<e;u+=1){let f=o[a];if(f===void 0||f.depth!==i||f.blankBefore&&l.strict||!ze(f.content,r,f.number))return;let m=X(f.content,r,f.number),h=jp(n,t,m,r,o,a+1,i+1,l);if(h===void 0||o[h.nextIndex]?.depth>i)return;d+=h.consumedChildRows,a=h.nextIndex}let c=o[a];if(c!==void 0&&c.depth>=i&&ze(c.content,r,c.number))return}catch{return}return{nextIndex:a,consumedChildRows:d}}function jp(e,n,t,r,o,s,i,l){let a=0,d=s,c=0;for(let u of e){if(u.fixedLength!==void 0)a+=u.fixedLength;else if(u.children!==void 0)if(n.has(u)){let f=Mi(t[a]);if(f===void 0)return;a+=1;let m=Ii(f,u.children,r,o,d,i,l);if(m===void 0)return;let h=Ni(f,u.children,m,r,o,d,i,l);if(h===void 0)return;d=h.nextIndex,c+=f+h.consumedChildRows}else a+=_t(u.children);else a+=1;if(a>t.length)return}if(a===t.length)return{nextIndex:d,consumedChildRows:c}}function Dp(e,n,t){return t&&e.length===1&&e[0].fixedLength!==void 0?n[e[0].key]:n}function Mi(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function Op(e){return e.some(n=>n.fixedLength!==void 0||n.children!==void 0)}function _t(e){return e.reduce((n,t)=>n+Ci(t),0)}function Ci(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?_t(e.children):1}function Ap(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+Ci(t),0)}function ze(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 Lp(e,n,t,r,o){let s=[];for(;s.length<e.len;){let l=n[t.index];if(l===void 0||l.depth<r)throw Qe(n,t.index);if(l.depth>r)throw R(l.number,"invalid indentation");if(l.blankBefore&&o.strict)throw R(l.number,"blank line inside array");s.push(Tp(n,t,r,o))}let i=n[t.index];if(i!==void 0&&i.depth>=r)throw R(i.number,"array length mismatch");return s}function Tp(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw R(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return n.index+=1,{};if(s.startsWith("[")){let i=W(s,":",o.number);jn(s,o.number,r);let l;try{l=kt(s,i)}catch{l=void 0}if(l!==void 0){let a=s.slice(i+1);return $r(l,a,e,n,t,r)}}if(W(s,":",o.number)!==-1){let i=[{number:o.number,depth:t+1,content:s,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let l=e[n.index];if(l.depth<=t)break;i.push(l),n.index+=1}return Tr(i,{index:0},t+1,r)}return n.index+=1,V(s,o.number)}function Wi(e,n,t,r,o,s){if(o.expandPaths&&!t&&n.includes(".")){let i=n.split(".");if(i.every($p)){Ye(e,i,r,o,s);return}}Ye(e,[n],r,o,s)}function Ye(e,n,t,r,o){se(n.length-1,o,r);let s=n[0],i=Object.prototype.hasOwnProperty.call(e,s);if(n.length===1){if(i&&r.strict)throw R(o,"duplicate key");Z(e,s,t);return}if(i&&!L(e[s])){if(r.strict)throw R(o,"path expansion conflict");Z(e,s,{})}else i||Z(e,s,{});Ye(e[s],n.slice(1),t,r,o)}function $p(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function C(e,n={}){let t=n.maxDepth??1e3,r=n.delimiter??O;if(![O,"|"," "].includes(r))throw R(0,"invalid array header");let o={nestedTabularHeaders:n.nestedTabularHeaders===!0,keyedMapCollapse:n.keyedMapCollapse===!0,primitiveArrayColumns:n.primitiveArrayColumns===!0,objectArrayColumns:n.objectArrayColumns===!0,cyclicDiscriminatedArrays:n.cyclicDiscriminatedArrays===!0,delimiter:r,maxDepth:t===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(t))};if(o.cyclicDiscriminatedArrays){let i=Di(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?Cr(s,void 0,e,0,!1,o):L(e)?Fi(s,e,0,o):s.push(F(e,r)),s.join("")}function Xe(e,n){e.push(" ".repeat(n*2))}function Fi(e,n,t,r){se(t,0,r);for(let[o,s]of Object.entries(n))Xe(e,t),Nr(e,o,s,t,r)}function Nr(e,n,t,r,o){if(se(r,0,o),Array.isArray(t)){Cr(e,n,t,r,!1,o);return}if(L(t)){let s=o.keyedMapCollapse?Np(t,o,r+1):void 0;if(s!==void 0){e.push(N(n),"{",Wr(o.delimiter),s.fields.map(i=>Hr(i,o.delimiter)).join(o.delimiter),`}:
15
+ `);for(let[i,l]of Object.entries(t)){Xe(e,r+1);let a=[];e.push(N(i),": ",s.paths.map(d=>Ur(Br(l,d.path),d,o.delimiter,o,a,r+2)).join(o.delimiter),`
16
+ `),e.push(...a)}return}e.push(N(n),`:
17
+ `),Fi(e,t,r+1,o);return}e.push(N(n),": ",F(t,o.delimiter),`
18
18
  `)}function Cr(e,n,t,r,o,s){if(se(r,0,s),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)){Ir(e,n,t.length,void 0,s.delimiter),e.push(" "),e.push(t.map(a=>F(a,s.delimiter)).join(s.delimiter)),e.push(`
22
- `);return}let i=o?void 0:Ci(t,s,r+1);if(i!==void 0){Ir(e,n,t.length,i.fields,s.delimiter),e.push(`
23
- `);for(let a of t){Xe(e,r+1);let l=[];e.push(i.paths.map(d=>Ur(Br(a,d.path),d,s.delimiter,s,l,r+2)).join(s.delimiter)),e.push(`
24
- `),e.push(...l)}return}Ir(e,n,t.length,void 0,s.delimiter),e.push(`
25
- `);for(let a of t)Xe(e,r+1),Ap(e,a,r+1,s)}function Ap(e,n,t,r){if(se(t,0,r),Array.isArray(n)){e.push("- "),Cr(e,void 0,n,t,!0,r);return}if(L(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
21
+ `);return}if(t.every(oe)){Ir(e,n,t.length,void 0,s.delimiter),e.push(" "),e.push(t.map(l=>F(l,s.delimiter)).join(s.delimiter)),e.push(`
22
+ `);return}let i=o?void 0:Bi(t,s,r+1);if(i!==void 0){Ir(e,n,t.length,i.fields,s.delimiter),e.push(`
23
+ `);for(let l of t){Xe(e,r+1);let a=[];e.push(i.paths.map(d=>Ur(Br(l,d.path),d,s.delimiter,s,a,r+2)).join(s.delimiter)),e.push(`
24
+ `),e.push(...a)}return}Ir(e,n,t.length,void 0,s.delimiter),e.push(`
25
+ `);for(let l of t)Xe(e,r+1),Ip(e,l,r+1,s)}function Ip(e,n,t,r){if(se(t,0,r),Array.isArray(n)){e.push("- "),Cr(e,void 0,n,t,!0,r);return}if(L(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
26
26
  `);return}e.push("- "),Nr(e,o[0][0],o[0][1],t+1,r);for(let[s,i]of o.slice(1))Xe(e,t+1),Nr(e,s,i,t+1,r);return}e.push("- ",F(n,r.delimiter),`
27
- `)}function Ir(e,n,t,r,o){n!==void 0&&e.push(N(n)),e.push("[",String(t),Wr(o),"]"),r!==void 0&&e.push("{",r.map(s=>Hr(s,o)).join(o),"}"),e.push(":")}function Wr(e){return e===O?"":e}function Ci(e,n,t){let r=Tp(e,n);if(r!==void 0)return r;let o=Mr(e.map(s=>({value:s})),n,t);return o===void 0?void 0:{fields:o,paths:Fr(o)}}function Lp(e,n,t){let r=Object.values(e);if(!(r.length<2))return Ci(r,n,t)}function Mr(e,n,t){se(t,0,n);let r=e[0]?.value;if(!L(r))return;let o=Object.keys(r).map(s=>({key:s}));if(o.length!==0){for(let{value:s}of e)if(!L(s)||Object.keys(s).length!==o.length||o.some(a=>!Object.prototype.hasOwnProperty.call(s,a.key)))return;for(let s of o){let i=e.map(({value:l})=>({value:l[s.key]}));if(i.every(({value:l})=>oe(l)))continue;if(n.primitiveArrayColumns&&i.every(({value:l})=>Array.isArray(l)&&l.every(oe))){s.listDelimiter=";";continue}if(n.objectArrayColumns&&i.every(({value:l})=>Array.isArray(l))){let l=Wi(i.map(({value:c})=>c));if(l!==void 0){s.fixedLength=l.fixedLength,s.fixedDelimiter=n.delimiter;continue}let d=Mr(i.flatMap(({value:c})=>c.map(u=>({value:u}))),n,t+1);if(d!==void 0){s.children=d,s.childTable=!0;continue}}if(!n.nestedTabularHeaders)return;let a=Mr(i,n,t+1);if(a===void 0)return;s.children=a}return o}}function Tp(e,n){if(!n.objectArrayColumns)return;let t=Wi(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:n.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function Wi(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 Fr(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}]:Fr(t.children,r)})}function Br(e,n){let t=e;for(let r of n)t=t[r];return t}function Hr(e,n){return e.listDelimiter!==void 0?`${N(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${N(e.key)}[${e.fixedLength}${Wr(n)}]`:e.children===void 0?N(e.key):`${N(e.key)}{${e.children.map(t=>Hr(t,n)).join(n)}}`}function Ur(e,n,t,r,o,s){return n.childFields!==void 0?($p(o,e,n.childFields,r,s),String(e.length)):n.fixedLength!==void 0?e.map(i=>F(i,t)).join(t):n.listDelimiter===void 0?F(e,t):e.map(i=>Ip(i,t,n.listDelimiter)).join(n.listDelimiter)}function $p(e,n,t,r,o){for(let s of n){Xe(e,o);let i=[];e.push(Fr(t).map(a=>Ur(Br(s,a.path),a,r.delimiter,r,i,o+1)).join(r.delimiter)),e.push(`
28
- `),e.push(...i)}}function Ip(e,n,t){return typeof e!="string"?F(e,n):Er(e,n)||e.includes(t)?ft(e):e}var qi=[O,"|"," "];var Ji=8,Qi=/^[A-Za-z0-9_-]+$/,U_=new TextEncoder,G_=new TextDecoder;function Wp(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 zi(e,n){if(!Qi.test(e))throw S(n,"invalid tag")}function Fp(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!Qi.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 Bp(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),s=o.startsWith("~"),i=s?o.slice(1):o;if(!s&&i.startsWith("="))return null;if(!qi.includes(i)&&i!=="")throw S(n,"invalid header delimiter");let a=i===""?O:i,l=t.slice(r+1),d=null;if(!s&&l.startsWith("<")){let f=l.indexOf(">");if(f===-1)throw S(n,"invalid tag");if(d=l.slice(1,f),zi(d,n),i!=="")throw S(n,"invalid header delimiter");l=l.slice(f+1)}if(!l.startsWith("{")||!l.endsWith("}:"))throw S(n,"invalid header");let c=l.slice(1,-2),u;try{u=X(c,a,n).map(f=>Y(f,n)[0])}catch(f){throw Je(f)}if(u.length===0||u.some(f=>f===""))throw S(n,"invalid header fields");return{delimiter:a,fields:u,fieldText:c,continuation:s,tag:d}}function Hp(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 Fi(e,n,t,r){let o;try{o=X(e,n,r)}catch(s){throw Je(s)}if(o.length!==t)throw S(r,"row arity mismatch");for(let s of o)try{V(s,r)}catch(i){throw Je(i)}return o}function Up(e,n,t){let r={};return e.forEach((o,s)=>{try{Z(r,o,V(n[s],t))}catch(i){throw Je(i)}}),r}function Gp(e,n,t){if(e.startsWith("- "))throw S(n,"reserved line prefix");let r=Wp(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=Bp(e,n);if(o!==null)return o.continuation?(Hp(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=Fp(e,n);if(s!==null){let i=t?.taggedLanes?.get(s.tag);if(i===void 0)throw S(n,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:Fi(s.cellsText,i.delimiter,i.fields.length,n)}}if(t===null||t.delimiter===void 0)throw S(n,"row before header");return{kind:"row",cells:Fi(e,t.delimiter,t.fields.length,n)}}function Kp(e,n={}){let t=[],r=new Map,o=[],s=[],i=null,a=!1,l=!1;function d(m,h){let b=s.at(-1);if(b!==void 0&&b.lane===m.lane&&b.delimiter===m.delimiter&&b.fieldText===m.fieldText){b.rows.push(h);return}s.push({lane:m.lane,delimiter:m.delimiter,fields:m.fields,fieldText:m.fieldText,rows:[h]})}function c(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function u(m,h,b){let k=r.get(m);if(k===void 0){if(r.size>=Ji)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(pt(e).forEach((m,h)=>{let b=h+1;if(m==="")return;let k=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},w=Gp(m,b,k);if(w.kind==="trailer"){c(),i=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"){c(),a||(t.push(null),a=!0),i={lane:null,delimiter:w.header.delimiter,fields:w.header.fields,fieldText:w.header.fieldText,rows:[]};return}if(w.kind==="tagged-row"){l=!0;let D=r.get(w.tag).current;D.rows.push(w.cells),d(D,w.cells);return}if(i===null)throw S(b,"row before header");i.rows.push(w.cells),d(i,w.cells)}}),!l)return c(),n.preserveInterleaving===!0,o;let f=[];c();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?s:f}function be(e){return Kp(e).flatMap(n=>n.rows.map(t=>Up(n.fields,t,0)))}function Vp(e){if(!qi.includes(e))throw S(0,"invalid header delimiter")}function Bi(e,n,t=!1){return`[${`${t?"~":""}${e===O?"":e}`}]{${n}}:
29
- `}function Hi(e,n){return`[]<${e}>{${n}}:
30
- `}function Gr(e,n){return n.map(N).join(e)}function qp(e){if(!Array.isArray(e)||e.length===0)throw S(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=Y(String(n),0)}catch(r){throw Je(r)}if(t==="")throw S(0,"TOONL header requires fields");return t})}function Ui(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function Gi(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw S(0,"TOONL continuation cadence must be positive")}function Jp(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function Ki(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 Qp(e){return JSON.stringify([...e].sort())}function Vi(e,n){let t=Qp(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function fe({delimiter:e=O,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){Vp(e),Gi(t),Gi(r);let o=null,s="",i=new Map,a=0,l=0,d=0,c=new Map,u=!1,f={continuationEveryRows:t,continuationEveryBytes:r},m=()=>o===null||!n?"":`[=${a}]
31
- `,h=()=>Jp(f,l,d)?(l=0,d=0,Bi(e,s,!0)):"",b=k=>{zi(k,0);let w=c.get(k);if(w===void 0){if(c.size>=Ji)throw S(0,"too many tagged lanes");w={fields:null,fieldsByShape:new Map},c.set(k,w)}return w};return{push(k){if(u)throw S(0,"TOONL encoder is closed");let w=Vi(Ki(k),i),D="";(o===null||o.length!==w.length||o.some((ce,Be)=>ce!==w[Be]))&&(D+=m(),o=w,s=Gr(e,o),a=0,l=0,d=0,D+=Bi(e,s));let z=o.map(ce=>F(k[ce],e));D+=h();let de=`${z.join(e)}
32
- `;return D+=de,a+=1,l+=1,d+=de.length,D},declareLane(k,w){if(u)throw S(0,"TOONL encoder is closed");let D=qp(w),z=Gr(O,D),de=b(k);return Ui(de.fields,D)?"":(de.fields=D,Hi(k,z))},pushTagged(k,w){if(u)throw S(0,"TOONL encoder is closed");let D=b(k),z=Vi(Ki(w),D.fieldsByShape),de=Gr(O,z),ce=z.map(lr=>F(w[lr],O)),Be="";return Ui(D.fields,z)||(D.fields=z,Be+=Hi(k,de)),`${Be}${k}:${ce.join(O)}
33
- `},end(){return u?"":(u=!0,m())}}}function Kr(e){let n={app:e,version:zp(Ze("__RED_BUILD_VERSION__",()=>"3.3.16")??"0.0.0-dev"),gitSha:Ze("__RED_BUILD_GIT_SHA__",()=>"70c21664a46ca24f83835ef2c389dd0c788e1dcf")??"unknown",buildTime:Ze("__RED_BUILD_TIME__",()=>"2026-08-03T03:52:27-03:00")??"unknown",bundleAsset:Ze("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=Ze("__REDDB_SDK_VERSION__",()=>""),r=Ze("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function zp(e){return e.startsWith("v")?e.slice(1):e}function Yi(e){return`${e.app} ${e.version} ${e.gitSha}`}function Ze(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var Xi={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Yp=/^[a-z][a-z0-9+.-]*:\/\//i;function Xp(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 Zp(e=Xi){return Object.entries(e).map(([n,t])=>Xp(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function ef(e){return/^-\d+(\.\d+)?$/.test(e)}function Dn(e){return!(!e||e.startsWith("-")&&!ef(e))}function Rt(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 Zi(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=>Zi(t.trim())):e}function De(e,n){switch(n){case"boolean":return nf(e);case"number":return tf(e);case"array":return e.split(",").map(t=>Rt(t.trim()));case"string":default:return e}}function nf(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function tf(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 _e(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function rf(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 of(e){let n=[],t=lf(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
27
+ `)}function Ir(e,n,t,r,o){n!==void 0&&e.push(N(n)),e.push("[",String(t),Wr(o),"]"),r!==void 0&&e.push("{",r.map(s=>Hr(s,o)).join(o),"}"),e.push(":")}function Wr(e){return e===O?"":e}function Bi(e,n,t){let r=Mp(e,n);if(r!==void 0)return r;let o=Mr(e.map(s=>({value:s})),n,t);return o===void 0?void 0:{fields:o,paths:Fr(o)}}function Np(e,n,t){let r=Object.values(e);if(!(r.length<2))return Bi(r,n,t)}function Mr(e,n,t){se(t,0,n);let r=e[0]?.value;if(!L(r))return;let o=Object.keys(r).map(s=>({key:s}));if(o.length!==0){for(let{value:s}of e)if(!L(s)||Object.keys(s).length!==o.length||o.some(l=>!Object.prototype.hasOwnProperty.call(s,l.key)))return;for(let s of o){let i=e.map(({value:a})=>({value:a[s.key]}));if(i.every(({value:a})=>oe(a)))continue;if(n.primitiveArrayColumns&&i.every(({value:a})=>Array.isArray(a)&&a.every(oe))){s.listDelimiter=";";continue}if(n.objectArrayColumns&&i.every(({value:a})=>Array.isArray(a))){let a=Hi(i.map(({value:c})=>c));if(a!==void 0){s.fixedLength=a.fixedLength,s.fixedDelimiter=n.delimiter;continue}let d=Mr(i.flatMap(({value:c})=>c.map(u=>({value:u}))),n,t+1);if(d!==void 0){s.children=d,s.childTable=!0;continue}}if(!n.nestedTabularHeaders)return;let l=Mr(i,n,t+1);if(l===void 0)return;s.children=l}return o}}function Mp(e,n){if(!n.objectArrayColumns)return;let t=Hi(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:n.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function Hi(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 Fr(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}]:Fr(t.children,r)})}function Br(e,n){let t=e;for(let r of n)t=t[r];return t}function Hr(e,n){return e.listDelimiter!==void 0?`${N(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${N(e.key)}[${e.fixedLength}${Wr(n)}]`:e.children===void 0?N(e.key):`${N(e.key)}{${e.children.map(t=>Hr(t,n)).join(n)}}`}function Ur(e,n,t,r,o,s){return n.childFields!==void 0?(Cp(o,e,n.childFields,r,s),String(e.length)):n.fixedLength!==void 0?e.map(i=>F(i,t)).join(t):n.listDelimiter===void 0?F(e,t):e.map(i=>Wp(i,t,n.listDelimiter)).join(n.listDelimiter)}function Cp(e,n,t,r,o){for(let s of n){Xe(e,o);let i=[];e.push(Fr(t).map(l=>Ur(Br(s,l.path),l,r.delimiter,r,i,o+1)).join(r.delimiter)),e.push(`
28
+ `),e.push(...i)}}function Wp(e,n,t){return typeof e!="string"?F(e,n):Er(e,n)||e.includes(t)?gt(e):e}var zi=[O,"|"," "];var Yi=8,Xi=/^[A-Za-z0-9_-]+$/,V_=new TextEncoder,q_=new TextDecoder;function Up(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw S(n,"invalid trailer count");return Number.parseInt(t,10)}function Zi(e,n){if(!Xi.test(e))throw S(n,"invalid tag")}function Gp(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!Xi.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 Kp(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),s=o.startsWith("~"),i=s?o.slice(1):o;if(!s&&i.startsWith("="))return null;if(!zi.includes(i)&&i!=="")throw S(n,"invalid header delimiter");let l=i===""?O:i,a=t.slice(r+1),d=null;if(!s&&a.startsWith("<")){let f=a.indexOf(">");if(f===-1)throw S(n,"invalid tag");if(d=a.slice(1,f),Zi(d,n),i!=="")throw S(n,"invalid header delimiter");a=a.slice(f+1)}if(!a.startsWith("{")||!a.endsWith("}:"))throw S(n,"invalid header");let c=a.slice(1,-2),u;try{u=X(c,l,n).map(f=>Y(f,n)[0])}catch(f){throw Je(f)}if(u.length===0||u.some(f=>f===""))throw S(n,"invalid header fields");return{delimiter:l,fields:u,fieldText:c,continuation:s,tag:d}}function Vp(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 Ui(e,n,t,r){let o;try{o=X(e,n,r)}catch(s){throw Je(s)}if(o.length!==t)throw S(r,"row arity mismatch");for(let s of o)try{V(s,r)}catch(i){throw Je(i)}return o}function qp(e,n,t){let r={};return e.forEach((o,s)=>{try{Z(r,o,V(n[s],t))}catch(i){throw Je(i)}}),r}function Jp(e,n,t){if(e.startsWith("- "))throw S(n,"reserved line prefix");let r=Up(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw S(n,"trailer without header");if(t.rowCount!==r)throw S(n,"trailer count mismatch");return{kind:"trailer"}}let o=Kp(e,n);if(o!==null)return o.continuation?(Vp(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=Gp(e,n);if(s!==null){let i=t?.taggedLanes?.get(s.tag);if(i===void 0)throw S(n,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:Ui(s.cellsText,i.delimiter,i.fields.length,n)}}if(t===null||t.delimiter===void 0)throw S(n,"row before header");return{kind:"row",cells:Ui(e,t.delimiter,t.fields.length,n)}}function Qp(e,n={}){let t=[],r=new Map,o=[],s=[],i=null,l=!1,a=!1;function d(m,h){let b=s.at(-1);if(b!==void 0&&b.lane===m.lane&&b.delimiter===m.delimiter&&b.fieldText===m.fieldText){b.rows.push(h);return}s.push({lane:m.lane,delimiter:m.delimiter,fields:m.fields,fieldText:m.fieldText,rows:[h]})}function c(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function u(m,h,b){let k=r.get(m);if(k===void 0){if(r.size>=Yi)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(ht(e).forEach((m,h)=>{let b=h+1;if(m==="")return;let k=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},w=Jp(m,b,k);if(w.kind==="trailer"){c(),i=null;return}if(w.kind!=="continuation"){if(w.kind==="tag-header"){a=!0,u(w.header.tag,w.header,b);return}if(w.kind==="header"){c(),l||(t.push(null),l=!0),i={lane:null,delimiter:w.header.delimiter,fields:w.header.fields,fieldText:w.header.fieldText,rows:[]};return}if(w.kind==="tagged-row"){a=!0;let D=r.get(w.tag).current;D.rows.push(w.cells),d(D,w.cells);return}if(i===null)throw S(b,"row before header");i.rows.push(w.cells),d(i,w.cells)}}),!a)return c(),n.preserveInterleaving===!0,o;let f=[];c();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?s:f}function _e(e){return Qp(e).flatMap(n=>n.rows.map(t=>qp(n.fields,t,0)))}function zp(e){if(!zi.includes(e))throw S(0,"invalid header delimiter")}function Gi(e,n,t=!1){return`[${`${t?"~":""}${e===O?"":e}`}]{${n}}:
29
+ `}function Ki(e,n){return`[]<${e}>{${n}}:
30
+ `}function Gr(e,n){return n.map(N).join(e)}function Yp(e){if(!Array.isArray(e)||e.length===0)throw S(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=Y(String(n),0)}catch(r){throw Je(r)}if(t==="")throw S(0,"TOONL header requires fields");return t})}function Vi(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function qi(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw S(0,"TOONL continuation cadence must be positive")}function Xp(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function Ji(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 Zp(e){return JSON.stringify([...e].sort())}function Qi(e,n){let t=Zp(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function he({delimiter:e=O,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){zp(e),qi(t),qi(r);let o=null,s="",i=new Map,l=0,a=0,d=0,c=new Map,u=!1,f={continuationEveryRows:t,continuationEveryBytes:r},m=()=>o===null||!n?"":`[=${l}]
31
+ `,h=()=>Xp(f,a,d)?(a=0,d=0,Gi(e,s,!0)):"",b=k=>{Zi(k,0);let w=c.get(k);if(w===void 0){if(c.size>=Yi)throw S(0,"too many tagged lanes");w={fields:null,fieldsByShape:new Map},c.set(k,w)}return w};return{push(k){if(u)throw S(0,"TOONL encoder is closed");let w=Qi(Ji(k),i),D="";(o===null||o.length!==w.length||o.some((pe,Be)=>pe!==w[Be]))&&(D+=m(),o=w,s=Gr(e,o),l=0,a=0,d=0,D+=Gi(e,s));let z=o.map(pe=>F(k[pe],e));D+=h();let ue=`${z.join(e)}
32
+ `;return D+=ue,l+=1,a+=1,d+=ue.length,D},declareLane(k,w){if(u)throw S(0,"TOONL encoder is closed");let D=Yp(w),z=Gr(O,D),ue=b(k);return Vi(ue.fields,D)?"":(ue.fields=D,Ki(k,z))},pushTagged(k,w){if(u)throw S(0,"TOONL encoder is closed");let D=b(k),z=Qi(Ji(w),D.fieldsByShape),ue=Gr(O,z),pe=z.map(lr=>F(w[lr],O)),Be="";return Vi(D.fields,z)||(D.fields=z,Be+=Ki(k,ue)),`${Be}${k}:${pe.join(O)}
33
+ `},end(){return u?"":(u=!0,m())}}}function Kr(e){let n={app:e,version:ef(Ze("__RED_BUILD_VERSION__",()=>"3.3.18")??"0.0.0-dev"),gitSha:Ze("__RED_BUILD_GIT_SHA__",()=>"db32a54b878943e1fe09550db39087f663cc084d")??"unknown",buildTime:Ze("__RED_BUILD_TIME__",()=>"2026-08-03T08:06:58-03:00")??"unknown",bundleAsset:Ze("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=Ze("__REDDB_SDK_VERSION__",()=>""),r=Ze("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function ef(e){return e.startsWith("v")?e.slice(1):e}function el(e){return`${e.app} ${e.version} ${e.gitSha}`}function Ze(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var nl={"=":"data",":=":{to:"data",typed:!0},":":"meta"},nf=/^[a-z][a-z0-9+.-]*:\/\//i;function tf(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 rf(e=nl){return Object.entries(e).map(([n,t])=>tf(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function of(e){return/^-\d+(\.\d+)?$/.test(e)}function On(e){return!(!e||e.startsWith("-")&&!of(e))}function wt(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 tl(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=>tl(t.trim())):e}function De(e,n){switch(n){case"boolean":return sf(e);case"number":return lf(e);case"array":return e.split(",").map(t=>wt(t.trim()));case"string":default:return e}}function sf(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function lf(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 we(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function af(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 df(e){let n=[],t=uf(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=af(e.options);n.push(...r)}return n}function sf(e,n){let t=of(e);return rf(t,n)}function lf(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 af(e,n=!1){let t=[],r=[],o=n?"global-option-flag":"option-flag",s=n?"global-option-type":"option-type",i=n?"global-option-default":"option-default",a=n?"global-option-description":"option-description";for(let[d,c]of Object.entries(e)){if(c.hidden)continue;let u=[],f=b=>{u.includes(b)||u.push(b)};c.short&&f(`-${c.short}`),f(`--${d}`);for(let b of c.aliases??[])b.length===1?f(`-${b}`):f(`--${b}`);let m=u.join(", "),h=c.type&&c.type!=="boolean"?`<${c.type}>`:void 0;r.push({flags:m,type:h,desc:c.description??"",default:c.default!==void 0?String(c.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 c=d.flags.length+(d.type?d.type.length+1:0),u=" ".repeat(l-c+2);t.push(E("indent"," ")),t.push(E(o,d.flags)),d.type&&(t.push(E("text"," ")),t.push(E(s,d.type))),t.push(E("text",u)),t.push(E(a,d.desc)),d.default!==void 0&&(t.push(E("text"," ")),t.push(E(i,`(default: ${d.default})`))),t.push(E("newline",`
41
- `))}return t}function el(e){let n=hf(e.options??{},e.autoShort??!1),t=Zp(e.separators??Xi);return{schema:e,parse(r){return df(r,e,n,t)},help(){return sf(e,e.formatter)}}}function df(e,n,t,r){let o={positional:{},options:{},errors:[],rest:[]},s=new Set(r.map(c=>c.to));for(let c of s)o[c]={};let i=0,a=n.positional??[],l=0,d=!1;for(;l<e.length;){let c=e[l];if(n.stopEarly&&i>0){o.rest=e.slice(l);break}if(c==="--"&&!d){d=!0,l++;continue}if(d){if(i<a.length){let f=a[i];if(f.variadic){let m=[];for(;l<e.length;){let h=e[l];m.push(f.type?De(h,f.type):h),l++}o.positional[f.name]=m,i++}else{let m=f.type?De(c,f.type):c;o.positional[f.name]=m,i++,l++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(c)),l++;continue}if(c.startsWith("--")){l=ff(c,l,e,o,t,n);continue}if(c.startsWith("-")&&c.length>1&&!bf(c)){l=mf(c,l,e,o,t,n);continue}let u=cf(c,r);if(u){let{key:f,value:m,config:h}=u,b=o,k=b[h.to]??(b[h.to]={});k[f]=h.typed?Zi(m):_e(m),l++;continue}if(i<a.length){let f=a[i];if(f.variadic){let h=[];for(;l<e.length&&!e[l].startsWith("-");){let b=e[l];h.push(f.type?De(b,f.type):b),l++}o.positional[f.name]=h,i++;continue}let m=f.type?De(c,f.type):c;o.positional[f.name]=m,i++}else n.allowUnknown!==!1?o.rest.push(c):o.errors.push(`Unexpected positional argument: ${c}`);l++}return gf(o,n,t),kf(o,n,a),Rf(o,n,t),o}function cf(e,n){if(Yp.test(e))return null;for(let t of n){if(t.prefix&&e.startsWith(t.separator)){let o=e.slice(t.separator.length),s=o.indexOf(":");if(s>0){let i=o.slice(0,s),a=o.slice(s+1);if(uf(i))return{key:i,value:a,config:t}}continue}let r=e.indexOf(t.separator);if(r>0){let o=e.slice(0,r),s=e.slice(r+t.separator.length);if(pf(o,s,t))return{key:o,value:s,config:t}}}return null}function uf(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function pf(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 ff(e,n,t,r,o,s){let i=e.slice(2);if(i.startsWith("no-")){let l=i.slice(3),d=o.get(l);if(d?.negatable!==!1&&d?.type==="boolean")return r.options[d.name]=!1,n+1}if(i.includes("=")){let l=i.indexOf("="),d=i.slice(0,l),c=i.slice(l+1);return bt(d,c,n+1,r,o,s)}let a=o.get(i);if(a){if(a.type!=="boolean"){let l=t[n+1];return Dn(l)?bt(a.name,l,n+2,r,o,s):(r.errors.push(`Option --${i} requires a value`),n+1)}return r.options[a.name]=!0,n+1}return s.strict?r.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(r.options[i]=!0),n+1}function mf(e,n,t,r,o,s){let i=e.slice(1);if(i.includes("=")){let a=i.indexOf("="),l=i.slice(0,a),d=i.slice(a+1),c=Vr(l,o);return c?bt(c.name,d,n+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${l}`):s.allowUnknown!==!1&&(r.options[l]=Rt(_e(d))),n+1)}if(i.length===1){let a=Vr(i,o);if(a){if(a.type!=="boolean"){let l=t[n+1];return Dn(l)?bt(a.name,l,n+2,r,o,s):(r.errors.push(`Option -${i} requires a value`),n+1)}return r.options[a.name]=!0,n+1}if(s.strict)r.errors.push(`Unknown option: -${i}`);else if(s.allowUnknown!==!1){let l=t[n+1];if(Dn(l))return r.options[i]=Rt(_e(l)),n+2;r.options[i]=!0}return n+1}for(let a of i){let l=Vr(a,o);l?l.type==="boolean"?r.options[l.name]=!0:r.errors.push(`Option -${a} requires a value`):s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=!0)}return n+1}function bt(e,n,t,r,o,s){let i=o.get(e);if(i){if(i.choices){let l=i.type?De(_e(n),i.type):_e(n);if(!i.choices.includes(l))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${i.choices.join(", ")}`),t}let a=i.type?De(_e(n),i.type):_e(n);if(i.type==="array"){let l=r.options[e];Array.isArray(l)?l.push(...a):r.options[e]=a}else r.options[e]=a}else s.strict?r.errors.push(`Unknown option: --${e}`):s.allowUnknown!==!1&&(r.options[e]=Rt(_e(n)));return t}function hf(e,n=!1){let t=new Map,r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i)),o=new Set;for(let[,s]of r)s.short&&o.add(s.short);for(let[s,i]of r){let a=i.short??"";n&&!a&&(a=yf(s,o),a&&o.add(a));let l={name:s,short:a,aliases:i.aliases??[],type:i.type??"string",description:i.description??"",required:i.required??!1,hidden:i.hidden??!1,negatable:i.negatable??!0,default:i.default,choices:i.choices,env:i.env,validate:i.validate};t.set(s,l);for(let d of l.aliases)t.set(d,l)}return t}function yf(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 Vr(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function gf(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?De(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 kf(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 Rf(e,n,t){for(let r of t.values()){let o=e.options[r.name];if(r.validate&&o!==void 0){let s=r.validate(o);s!==!0&&e.errors.push(s)}}for(let r of n.positional??[]){let o=e.positional[r.name];if(r.validate&&o!==void 0){let s=r.validate(o);s!==!0&&e.errors.push(s)}}}function bf(e){return/^-\d+(\.\d+)?$/.test(e)}var qr=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 _f(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 wf(e,n){let t=new Map;for(let[o,s]of Object.entries(n))if(!(s.kind!=="value"||s.type!=="array")){t.set(o,o);for(let i of s.aliases??[])t.set(i,o)}let r=new Map;for(let o=0;o<e.length;o+=1){let s=e[o];if(s==="--")break;let i=s.match(/^--([^=]+)(?:=(.*))?$/)??s.match(/^-([^=])(?:=(.*))?$/);if(i===null)continue;let a=t.get(i[1]);if(a===void 0)continue;let l=i[2];if(l===void 0&&Dn(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 Oe(e,n,t={}){let o=el({options:_f(n),separators:{},allowUnknown:!0}).parse([...e]),s={},i=wf(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 qr(d.length===1?`-${d}`:`--${d}`,Object.keys(n).map(c=>c.length===1?`-${c}`:`--${c}`))}for(let[l,d]of Object.entries(n)){let c=o.options[l];c!==void 0&&(d.kind==="boolean"?s[l]=c:d.type==="array"?s[l]=(i.get(l)??[]).map(u=>d.coerce(u)):s[l]=d.coerce(String(c)))}return{values:s,positionals:o.rest}}var Jr=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 nl(e,n){let[t,...r]=e;if(t!==void 0){for(let[s,i]of Object.entries(n.commands))if(t===s||(i.aliases??[]).includes(t))return{command:s,args:r};if(n.errorOnUnknownCommand&&!t.startsWith("-"))throw new Jr(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as Tf,mkdirSync as $f,readFileSync as ul,statSync as If}from"node:fs";import{dirname as fl,join as Nf}from"node:path";var tl="RED_WORKER_SCOPE",rl="RED_WORKER_MEMORY_CEILING",ol="RED_WORKER_SCOPE_DEGRADATION",zr={scope:null,memory_ceiling:null,scope_degradation:null};function Yr(e){return{scope:Qr(e[tl]),memory_ceiling:Qr(e[rl]),scope_degradation:Qr(e[ol])}}function On(e){let n={};return e.scope!=null&&e.scope!==""&&(n[tl]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[rl]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[ol]=e.scope_degradation),n}function Qr(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as vf,readdirSync as Ef,readFileSync as al,rmSync as Pf,writeFileSync as jf}from"node:fs";import{basename as Df,join as en}from"node:path";import{isAbsolute as xw,join as _t,resolve as Sw}from"node:path";function xf(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var sl="deaths",il="deaths.toonl";function wt(e){return _t(xf(e),sl)}function An(e){return _t(wt(e),il)}var Ln="live",ll="attributions.toonl";function xt(e){return _t(wt(e),Ln)}function Xr(e){return _t(wt(e),ll)}var eo=en("sys","kernel","random","boot_id"),dl=1;function no(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:dl,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:cl(en(t,eo)),cgroup:Of(t,r),last_phase:e.last_phase}}function cl(e){try{let n=al(e,"utf8").trim();return n===""?null:n}catch{return null}}function Of(e,n){let t=cl(en(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
42
- `),o=r.find(i=>i.startsWith("0::"));if(o)return o.slice(3)||null;let s=r[0]?.split(":").slice(2).join(":");return s===void 0||s===""?null:s}function to(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function ro(e,n){let t=en(e,to(n));try{return vf(e,{recursive:!0,mode:448}),jf(t,fe({trailer:!1}).push(Lf(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function Ae(e,n){try{Pf(en(e,to(n)),{force:!0})}catch{}}function oo(e,n){let t;try{t=Ef(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=en(e,o);try{let a=be(al(s,"utf8"))[0];if(a===void 0)throw new Error("anchor holds no record");r.push(Af(a))}catch(i){n?.(Df(s),i instanceof Error?i.message:String(i))}}return r}function Af(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:Zr(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:Zr(e.pid),ppid:Zr(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 Zr(e){return typeof e=="number"?e:Number(e)}function Lf(e){return{...e}}var Mf=1,Cf=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Wf(e){return typeof e=="string"&&Cf.has(e)}var Ff="startup";function Bf(e,n){return{...e.scope??zr,version:Mf,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 Hf(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 io={mkdir(e){$f(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=If(e).size}catch{return!0}if(n===0)return!0;try{return ul(e,"utf8").endsWith(`
43
- `)}catch{return!0}},append(e,n){Tf(e,n,{encoding:"utf8",mode:384})},read(e){return ul(e,"utf8")}};function Uf(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function Gf(e,n,t=io){let r=fe({trailer:!1}).push(Uf(n));return t.mkdir(fl(e)),t.endsClean(e)||t.append(e,`
44
- `),t.append(e,r),n}function ml(e){let n=e.endsWith(`
40
+ `));let r=pf(e.options);n.push(...r)}return n}function cf(e,n){let t=df(e);return af(t,n)}function uf(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 pf(e,n=!1){let t=[],r=[],o=n?"global-option-flag":"option-flag",s=n?"global-option-type":"option-type",i=n?"global-option-default":"option-default",l=n?"global-option-description":"option-description";for(let[d,c]of Object.entries(e)){if(c.hidden)continue;let u=[],f=b=>{u.includes(b)||u.push(b)};c.short&&f(`-${c.short}`),f(`--${d}`);for(let b of c.aliases??[])b.length===1?f(`-${b}`):f(`--${b}`);let m=u.join(", "),h=c.type&&c.type!=="boolean"?`<${c.type}>`:void 0;r.push({flags:m,type:h,desc:c.description??"",default:c.default!==void 0?String(c.default):void 0})}let a=Math.max(...r.map(d=>d.flags.length+(d.type?d.type.length+1:0)),20);for(let d of r){let c=d.flags.length+(d.type?d.type.length+1:0),u=" ".repeat(a-c+2);t.push(E("indent"," ")),t.push(E(o,d.flags)),d.type&&(t.push(E("text"," ")),t.push(E(s,d.type))),t.push(E("text",u)),t.push(E(l,d.desc)),d.default!==void 0&&(t.push(E("text"," ")),t.push(E(i,`(default: ${d.default})`))),t.push(E("newline",`
41
+ `))}return t}function rl(e){let n=Rf(e.options??{},e.autoShort??!1),t=rf(e.separators??nl);return{schema:e,parse(r){return ff(r,e,n,t)},help(){return cf(e,e.formatter)}}}function ff(e,n,t,r){let o={positional:{},options:{},errors:[],rest:[]},s=new Set(r.map(c=>c.to));for(let c of s)o[c]={};let i=0,l=n.positional??[],a=0,d=!1;for(;a<e.length;){let c=e[a];if(n.stopEarly&&i>0){o.rest=e.slice(a);break}if(c==="--"&&!d){d=!0,a++;continue}if(d){if(i<l.length){let f=l[i];if(f.variadic){let m=[];for(;a<e.length;){let h=e[a];m.push(f.type?De(h,f.type):h),a++}o.positional[f.name]=m,i++}else{let m=f.type?De(c,f.type):c;o.positional[f.name]=m,i++,a++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(c)),a++;continue}if(c.startsWith("--")){a=yf(c,a,e,o,t,n);continue}if(c.startsWith("-")&&c.length>1&&!Sf(c)){a=kf(c,a,e,o,t,n);continue}let u=mf(c,r);if(u){let{key:f,value:m,config:h}=u,b=o,k=b[h.to]??(b[h.to]={});k[f]=h.typed?tl(m):we(m),a++;continue}if(i<l.length){let f=l[i];if(f.variadic){let h=[];for(;a<e.length&&!e[a].startsWith("-");){let b=e[a];h.push(f.type?De(b,f.type):b),a++}o.positional[f.name]=h,i++;continue}let m=f.type?De(c,f.type):c;o.positional[f.name]=m,i++}else n.allowUnknown!==!1?o.rest.push(c):o.errors.push(`Unexpected positional argument: ${c}`);a++}return _f(o,n,t),wf(o,n,l),xf(o,n,t),o}function mf(e,n){if(nf.test(e))return null;for(let t of n){if(t.prefix&&e.startsWith(t.separator)){let o=e.slice(t.separator.length),s=o.indexOf(":");if(s>0){let i=o.slice(0,s),l=o.slice(s+1);if(hf(i))return{key:i,value:l,config:t}}continue}let r=e.indexOf(t.separator);if(r>0){let o=e.slice(0,r),s=e.slice(r+t.separator.length);if(gf(o,s,t))return{key:o,value:s,config:t}}}return null}function hf(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function gf(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 yf(e,n,t,r,o,s){let i=e.slice(2);if(i.startsWith("no-")){let a=i.slice(3),d=o.get(a);if(d?.negatable!==!1&&d?.type==="boolean")return r.options[d.name]=!1,n+1}if(i.includes("=")){let a=i.indexOf("="),d=i.slice(0,a),c=i.slice(a+1);return xt(d,c,n+1,r,o,s)}let l=o.get(i);if(l){if(l.type!=="boolean"){let a=t[n+1];return On(a)?xt(l.name,a,n+2,r,o,s):(r.errors.push(`Option --${i} requires a value`),n+1)}return r.options[l.name]=!0,n+1}return s.strict?r.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(r.options[i]=!0),n+1}function kf(e,n,t,r,o,s){let i=e.slice(1);if(i.includes("=")){let l=i.indexOf("="),a=i.slice(0,l),d=i.slice(l+1),c=Vr(a,o);return c?xt(c.name,d,n+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=wt(we(d))),n+1)}if(i.length===1){let l=Vr(i,o);if(l){if(l.type!=="boolean"){let a=t[n+1];return On(a)?xt(l.name,a,n+2,r,o,s):(r.errors.push(`Option -${i} requires a value`),n+1)}return r.options[l.name]=!0,n+1}if(s.strict)r.errors.push(`Unknown option: -${i}`);else if(s.allowUnknown!==!1){let a=t[n+1];if(On(a))return r.options[i]=wt(we(a)),n+2;r.options[i]=!0}return n+1}for(let l of i){let a=Vr(l,o);a?a.type==="boolean"?r.options[a.name]=!0:r.errors.push(`Option -${l} requires a value`):s.strict?r.errors.push(`Unknown option: -${l}`):s.allowUnknown!==!1&&(r.options[l]=!0)}return n+1}function xt(e,n,t,r,o,s){let i=o.get(e);if(i){if(i.choices){let a=i.type?De(we(n),i.type):we(n);if(!i.choices.includes(a))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${i.choices.join(", ")}`),t}let l=i.type?De(we(n),i.type):we(n);if(i.type==="array"){let a=r.options[e];Array.isArray(a)?a.push(...l):r.options[e]=l}else r.options[e]=l}else s.strict?r.errors.push(`Unknown option: --${e}`):s.allowUnknown!==!1&&(r.options[e]=wt(we(n)));return t}function Rf(e,n=!1){let t=new Map,r=Object.entries(e).sort(([s],[i])=>s.localeCompare(i)),o=new Set;for(let[,s]of r)s.short&&o.add(s.short);for(let[s,i]of r){let l=i.short??"";n&&!l&&(l=bf(s,o),l&&o.add(l));let a={name:s,short:l,aliases:i.aliases??[],type:i.type??"string",description:i.description??"",required:i.required??!1,hidden:i.hidden??!1,negatable:i.negatable??!0,default:i.default,choices:i.choices,env:i.env,validate:i.validate};t.set(s,a);for(let d of a.aliases)t.set(d,a)}return t}function bf(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 Vr(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function _f(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?De(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 wf(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 xf(e,n,t){for(let r of t.values()){let o=e.options[r.name];if(r.validate&&o!==void 0){let s=r.validate(o);s!==!0&&e.errors.push(s)}}for(let r of n.positional??[]){let o=e.positional[r.name];if(r.validate&&o!==void 0){let s=r.validate(o);s!==!0&&e.errors.push(s)}}}function Sf(e){return/^-\d+(\.\d+)?$/.test(e)}var qr=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 vf(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 Ef(e,n){let t=new Map;for(let[o,s]of Object.entries(n))if(!(s.kind!=="value"||s.type!=="array")){t.set(o,o);for(let i of s.aliases??[])t.set(i,o)}let r=new Map;for(let o=0;o<e.length;o+=1){let s=e[o];if(s==="--")break;let i=s.match(/^--([^=]+)(?:=(.*))?$/)??s.match(/^-([^=])(?:=(.*))?$/);if(i===null)continue;let l=t.get(i[1]);if(l===void 0)continue;let a=i[2];if(a===void 0&&On(e[o+1])&&(a=e[o+1],o+=1),a===void 0)continue;let d=r.get(l)??[];d.push(a),r.set(l,d)}return r}function Oe(e,n,t={}){let o=rl({options:vf(n),separators:{},allowUnknown:!0}).parse([...e]),s={},i=Ef(e,n),l=o.errors.find(a=>/^Option --?\S+ requires a value$/.test(a));if(l!==void 0)throw new Error(l.replace(/^Option /,""));if(o.errors.length>0)throw new Error(o.errors[0]);if(t.unknownFlags==="error"){let a=new Set(Object.keys(n));for(let d of Object.keys(o.options))if(!a.has(d))throw new qr(d.length===1?`-${d}`:`--${d}`,Object.keys(n).map(c=>c.length===1?`-${c}`:`--${c}`))}for(let[a,d]of Object.entries(n)){let c=o.options[a];c!==void 0&&(d.kind==="boolean"?s[a]=c:d.type==="array"?s[a]=(i.get(a)??[]).map(u=>d.coerce(u)):s[a]=d.coerce(String(c)))}return{values:s,positionals:o.rest}}var Jr=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 ol(e,n){let[t,...r]=e;if(t!==void 0){for(let[s,i]of Object.entries(n.commands))if(t===s||(i.aliases??[]).includes(t))return{command:s,args:r};if(n.errorOnUnknownCommand&&!t.startsWith("-"))throw new Jr(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as Mf,mkdirSync as Cf,readFileSync as ml,statSync as Wf}from"node:fs";import{dirname as gl,join as Ff}from"node:path";var sl="RED_WORKER_SCOPE",il="RED_WORKER_MEMORY_CEILING",ll="RED_WORKER_SCOPE_DEGRADATION",zr={scope:null,memory_ceiling:null,scope_degradation:null};function Yr(e){return{scope:Qr(e[sl]),memory_ceiling:Qr(e[il]),scope_degradation:Qr(e[ll])}}function An(e){let n={};return e.scope!=null&&e.scope!==""&&(n[sl]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[il]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[ll]=e.scope_degradation),n}function Qr(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as Df,readdirSync as Of,readFileSync as ul,rmSync as Af,writeFileSync as Lf}from"node:fs";import{basename as Tf,join as en}from"node:path";import{isAbsolute as Ew,join as St,resolve as Pw}from"node:path";function Pf(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var al="deaths",dl="deaths.toonl";function vt(e){return St(Pf(e),al)}function Ln(e){return St(vt(e),dl)}var Tn="live",cl="attributions.toonl";function Et(e){return St(vt(e),Tn)}function Xr(e){return St(vt(e),cl)}var eo=en("sys","kernel","random","boot_id"),pl=1;function no(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:pl,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:fl(en(t,eo)),cgroup:$f(t,r),last_phase:e.last_phase}}function fl(e){try{let n=ul(e,"utf8").trim();return n===""?null:n}catch{return null}}function $f(e,n){let t=fl(en(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
42
+ `),o=r.find(i=>i.startsWith("0::"));if(o)return o.slice(3)||null;let s=r[0]?.split(":").slice(2).join(":");return s===void 0||s===""?null:s}function to(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function ro(e,n){let t=en(e,to(n));try{return Df(e,{recursive:!0,mode:448}),Lf(t,he({trailer:!1}).push(Nf(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function Ae(e,n){try{Af(en(e,to(n)),{force:!0})}catch{}}function oo(e,n){let t;try{t=Of(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=en(e,o);try{let l=_e(ul(s,"utf8"))[0];if(l===void 0)throw new Error("anchor holds no record");r.push(If(l))}catch(i){n?.(Tf(s),i instanceof Error?i.message:String(i))}}return r}function If(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:Zr(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:Zr(e.pid),ppid:Zr(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 Zr(e){return typeof e=="number"?e:Number(e)}function Nf(e){return{...e}}var Bf=1,Hf=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Uf(e){return typeof e=="string"&&Hf.has(e)}var Gf="startup";function Kf(e,n){return{...e.scope??zr,version:Bf,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 Vf(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 io={mkdir(e){Cf(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=Wf(e).size}catch{return!0}if(n===0)return!0;try{return ml(e,"utf8").endsWith(`
43
+ `)}catch{return!0}},append(e,n){Mf(e,n,{encoding:"utf8",mode:384})},read(e){return ml(e,"utf8")}};function qf(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function Jf(e,n,t=io){let r=he({trailer:!1}).push(qf(n));return t.mkdir(gl(e)),t.endsClean(e)||t.append(e,`
44
+ `),t.append(e,r),n}function yl(e){let n=e.endsWith(`
45
45
  `)?e:e.slice(0,e.lastIndexOf(`
46
- `)+1);return n===""?[]:be(n).map(Kf)}function Kf(e){let n=e.exit_path;if(!Wf(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:J(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:J(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:J(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:J(e.uptime_s),rss_kb:J(e.rss_kb),max_rss_kb:J(e.max_rss_kb),user_cpu_us:J(e.user_cpu_us),system_cpu_us:J(e.system_cpu_us),minor_page_faults:J(e.minor_page_faults),major_page_faults:J(e.major_page_faults),voluntary_ctx_switches:J(e.voluntary_ctx_switches),involuntary_ctx_switches:J(e.involuntary_ctx_switches)}}function J(e){return typeof e=="number"?e:Number(e)}function hl(e,n=io){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return ml(t)}var Vf=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],so=null;function yl(e){let n=e.host??process,t=e.io??io,r=e.clock??(()=>new Date().toISOString()),o=n.pid,s=e.scope??Yr(process.env),i=e.phase??Ff,a=null,l=e.presenceDir===void 0?Nf(fl(e.lanePath),Ln):e.presenceDir,d=null,c=()=>{l!==null&&(d=no({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),ro(l,d))},u=k=>{if(!a){try{a=Gf(e.lanePath,Bf({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...k},Hf(n)),t)}catch{}l!==null&&d!==null&&Ae(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:pl(k)})},unhandledRejection(k){u({exit_path:"unhandled-rejection",detail:pl(k)})}},h=[...(e.signals??Vf).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){i=k,a||c()},currentPhase:()=>i,written:()=>a,uninstall(){for(let[k,w]of h)n.off(k,w);l!==null&&d!==null&&Ae(l,d),so===b&&(so=null)},handlers:f};return e.setActive!==!1&&(so=b),c(),b}function pl(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as qf,readdirSync as Jf,readFileSync as St,statSync as Qf,writeFileSync as zf}from"node:fs";import{join as bl}from"node:path";var Yf=1,Xf=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],Zf=512*1024;function em(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??Xf,r=[],o=bl(n,eo),s=null;try{let l=St(o,"utf8").trim();s=l===""?null:l,r.push({source:o,result:s?"read":"empty",detail:s})}catch(l){r.push({source:o,result:lo(l),detail:null})}let i=new Set;try{for(let l of Jf(n))/^\d+$/.test(l)&&i.add(Number(l));r.push({source:n,result:"read",detail:`${i.size} live pids`})}catch(l){r.push({source:n,result:lo(l),detail:null})}let a=[];for(let l of t)try{let c=nm(l,e.tailBytes??Zf).split(`
47
- `).filter(u=>u.trim()!=="");a.push(...c),r.push({source:l,result:c.length===0?"empty":"read",detail:`${c.length} lines`})}catch(d){r.push({source:l,result:lo(d),detail:null})}return{boot_id:s,live_pids:i,journal:a,probes:r}}function lo(e){return e.code==="ENOENT"?"absent":"unreadable"}function nm(e,n){let t=Qf(e).size,r=St(e,"utf8");return t<=n?r:r.slice(r.length-n)}var tm=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,rm=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,om=/Killed (\/\S*) due to memory pressure/,sm=/\bopid=(\d+)\b/,gl=/\bsig=(\d+)\b/,im=/\buid=(\d+)\b/,lm=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,am={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function dm(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,s=[...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"}`],i=(u,f,m,h)=>({version:Yf,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:s}),a=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],l=n.journal.find(u=>kl(u,e.pid,tm)||kl(u,e.pid,rm));if(l!==void 0)return i("oomd",o?"medium":"high","SIGKILL",[l,...a]);if(e.cgroup!==null)for(let u of n.journal){let f=om.exec(u)?.[1];if(f!==void 0){if(f===e.cgroup)return i("oomd",o?"medium":"high","SIGKILL",[u,...a]);if(e.cgroup.startsWith(`${f}/`))return i("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(sm.exec(u)?.[1])===e.pid&&gl.test(u));if(d!==void 0){let u=Number(gl.exec(d)?.[1]),f=im.exec(d)?.[1];return i("user-signal",o?"medium":"high",am[u]??null,[d,...f===void 0?[]:[`sent by uid ${f}`],...a])}let c=t.find(u=>u.pid===e.ppid);if(c!==void 0&&!n.live_pids.has(e.ppid))return i("parent-death","medium",null,[`parent pid ${e.ppid} (${c.kind} ${c.id}) recorded its own death at ${c.ts} via ${c.exit_path}${c.signal?` ${c.signal}`:""}`]);if(o){let u=n.journal.find(f=>lm.test(f));return u!==void 0?i("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,u]):i("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,"no shutdown record on any journal read: the host stopped without announcing it (a freeze or a power loss, not an orderly teardown)"])}return i("unknown","none",null,[])}function kl(e,n,t){return Number(t.exec(e)?.[1])===n}var cm=" | ";function Rl(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(cm)}function um(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:Rl(e.evidence),checked:Rl(e.checked)}}function pm(e){let n=fe({trailer:!1});return e.map(t=>n.push(um(t))).join("")}function _l(e){let n=xt(e.stateRoot),t=Xr(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??em({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=oo(n,u=>s.push(u)),a=hl(An(e.stateRoot)),l=[],d=[],c=[];for(let u of i){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){c.push(u),Ae(n,u);continue}l.push(dm(u,o,a,r())),Ae(n,u)}return l.length>0&&fm(t,l),{attributions:l,alive:d,self_recorded:c,skipped:s,laneText:()=>{try{return St(t,"utf8")}catch{return""}}}}function wl(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 fm(e,n){try{qf(bl(e,".."),{recursive:!0,mode:448});let t=mm(e),r=t===""||t.endsWith(`
46
+ `)+1);return n===""?[]:_e(n).map(Qf)}function Qf(e){let n=e.exit_path;if(!Uf(n))throw new Error(`death record has unknown exit_path ${JSON.stringify(n)}`);let t=e.kind;if(t!=="launcher"&&t!=="worker"&&t!=="daemon")throw new Error(`death record has unknown kind ${JSON.stringify(t)}`);return{version:J(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:J(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:J(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:J(e.uptime_s),rss_kb:J(e.rss_kb),max_rss_kb:J(e.max_rss_kb),user_cpu_us:J(e.user_cpu_us),system_cpu_us:J(e.system_cpu_us),minor_page_faults:J(e.minor_page_faults),major_page_faults:J(e.major_page_faults),voluntary_ctx_switches:J(e.voluntary_ctx_switches),involuntary_ctx_switches:J(e.involuntary_ctx_switches)}}function J(e){return typeof e=="number"?e:Number(e)}function kl(e,n=io){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return yl(t)}var zf=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],so=null;function Rl(e){let n=e.host??process,t=e.io??io,r=e.clock??(()=>new Date().toISOString()),o=n.pid,s=e.scope??Yr(process.env),i=e.phase??Gf,l=null,a=e.presenceDir===void 0?Ff(gl(e.lanePath),Tn):e.presenceDir,d=null,c=()=>{a!==null&&(d=no({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),ro(a,d))},u=k=>{if(!l){try{l=Jf(e.lanePath,Kf({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...k},Vf(n)),t)}catch{}a!==null&&d!==null&&Ae(a,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:hl(k)})},unhandledRejection(k){u({exit_path:"unhandled-rejection",detail:hl(k)})}},h=[...(e.signals??zf).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){i=k,l||c()},currentPhase:()=>i,written:()=>l,uninstall(){for(let[k,w]of h)n.off(k,w);a!==null&&d!==null&&Ae(a,d),so===b&&(so=null)},handlers:f};return e.setActive!==!1&&(so=b),c(),b}function hl(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as Yf,readdirSync as Xf,readFileSync as Pt,statSync as Zf,writeFileSync as em}from"node:fs";import{join as xl}from"node:path";var nm=1,tm=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],rm=512*1024;function om(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??tm,r=[],o=xl(n,eo),s=null;try{let a=Pt(o,"utf8").trim();s=a===""?null:a,r.push({source:o,result:s?"read":"empty",detail:s})}catch(a){r.push({source:o,result:lo(a),detail:null})}let i=new Set;try{for(let a of Xf(n))/^\d+$/.test(a)&&i.add(Number(a));r.push({source:n,result:"read",detail:`${i.size} live pids`})}catch(a){r.push({source:n,result:lo(a),detail:null})}let l=[];for(let a of t)try{let c=sm(a,e.tailBytes??rm).split(`
47
+ `).filter(u=>u.trim()!=="");l.push(...c),r.push({source:a,result:c.length===0?"empty":"read",detail:`${c.length} lines`})}catch(d){r.push({source:a,result:lo(d),detail:null})}return{boot_id:s,live_pids:i,journal:l,probes:r}}function lo(e){return e.code==="ENOENT"?"absent":"unreadable"}function sm(e,n){let t=Zf(e).size,r=Pt(e,"utf8");return t<=n?r:r.slice(r.length-n)}var im=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,lm=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,am=/Killed (\/\S*) due to memory pressure/,dm=/\bopid=(\d+)\b/,bl=/\bsig=(\d+)\b/,cm=/\buid=(\d+)\b/,um=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,pm={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function fm(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,s=[...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"}`],i=(u,f,m,h)=>({version:nm,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:s}),l=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],a=n.journal.find(u=>_l(u,e.pid,im)||_l(u,e.pid,lm));if(a!==void 0)return i("oomd",o?"medium":"high","SIGKILL",[a,...l]);if(e.cgroup!==null)for(let u of n.journal){let f=am.exec(u)?.[1];if(f!==void 0){if(f===e.cgroup)return i("oomd",o?"medium":"high","SIGKILL",[u,...l]);if(e.cgroup.startsWith(`${f}/`))return i("oomd","medium","SIGKILL",[u,`the killed scope ${f} is an ancestor of this process's ${e.cgroup}`,...l])}}let d=n.journal.find(u=>Number(dm.exec(u)?.[1])===e.pid&&bl.test(u));if(d!==void 0){let u=Number(bl.exec(d)?.[1]),f=cm.exec(d)?.[1];return i("user-signal",o?"medium":"high",pm[u]??null,[d,...f===void 0?[]:[`sent by uid ${f}`],...l])}let c=t.find(u=>u.pid===e.ppid);if(c!==void 0&&!n.live_pids.has(e.ppid))return i("parent-death","medium",null,[`parent pid ${e.ppid} (${c.kind} ${c.id}) recorded its own death at ${c.ts} via ${c.exit_path}${c.signal?` ${c.signal}`:""}`]);if(o){let u=n.journal.find(f=>um.test(f));return u!==void 0?i("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,u]):i("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,"no shutdown record on any journal read: the host stopped without announcing it (a freeze or a power loss, not an orderly teardown)"])}return i("unknown","none",null,[])}function _l(e,n,t){return Number(t.exec(e)?.[1])===n}var mm=" | ";function wl(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(mm)}function hm(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:wl(e.evidence),checked:wl(e.checked)}}function gm(e){let n=he({trailer:!1});return e.map(t=>n.push(hm(t))).join("")}function Sl(e){let n=Et(e.stateRoot),t=Xr(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??om({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=oo(n,u=>s.push(u)),l=kl(Ln(e.stateRoot)),a=[],d=[],c=[];for(let u of i){if(o.live_pids.has(u.pid)){d.push(u);continue}if(l.find(m=>m.pid===u.pid&&m.id===u.id)!==void 0){c.push(u),Ae(n,u);continue}a.push(fm(u,o,l,r())),Ae(n,u)}return a.length>0&&ym(t,a),{attributions:a,alive:d,self_recorded:c,skipped:s,laneText:()=>{try{return Pt(t,"utf8")}catch{return""}}}}function vl(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 ym(e,n){try{Yf(xl(e,".."),{recursive:!0,mode:448});let t=km(e),r=t===""||t.endsWith(`
48
48
  `)?"":`
49
- `;zf(e,`${t}${r}${pm(n)}`,{encoding:"utf8",mode:384})}catch{}}function mm(e){try{return St(e,"utf8")}catch{return""}}import{join as hm}from"node:path";var ym=[".red","redskilled"],ie=448;function Le(e){return hm(e,...ym)}import{execFileSync as Om}from"node:child_process";import{readFileSync as Am}from"node:fs";import{dirname as Dl,join as Lm}from"node:path";import{existsSync as gm,readFileSync as nx}from"node:fs";import{dirname as km,join as Rm}from"node:path";function xl(e,n){let t=e;for(let r=0;r<16;r++){let o=Rm(t,n);if(gm(o))return o;let s=km(t);if(s===t)break;t=s}return null}function bm(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function nn(e,n){let t=[];for(let r of e.split(`
50
- `)){let o=r.replace(/\r$/,""),s=o.trim();if(!s||s.startsWith("#"))continue;let i=o.indexOf(":");if(i<0)continue;let a=o.length-o.trimStart().length,l=o.slice(0,i).trim();if(!l)continue;let d=o.slice(i+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 bm(d)}}import{createHash as _m}from"node:crypto";var wm="project.name";function vl(e){let n=nn(e,wm)?.trim();return n===void 0||n===""?void 0:n}var xm=8,El="project";function Pl(e){let n=jm(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:Sm(e.remoteUrl)??{name:vm(e.checkoutPath,n),source:"basename"},o=Pm(n??ao(e.checkoutPath));return{name:r.name,slug:`${Em(r.name)}-${o}`,hash:o,source:r.source}}function jl(e){let n=(e??"").trim();if(n==="")return;let t=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),r=/^[^/]*?:(?!\d)(.+)$/.exec(t),s=(r?r[1]:t.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(i=>i.trim()).filter(i=>i!=="");if(s.length!==0)return s.slice(-2).join("/")}function Sm(e){let n=jl(e);return n===void 0?void 0:{name:n,source:"remote"}}function vm(e,n){let t=n===void 0?"":Sl(Dm(n));if(t!=="")return t;let r=Sl(ao(e));return r===""?El:r}function Em(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?El:t}function Pm(e){return _m("sha256").update(e).digest("hex").slice(0,xm)}function jm(e){let n=ao(e??"");return n===""?void 0:n}function ao(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function Sl(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function Dm(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var Tm=2e3;function Ol(e){return $m(e).name}function $m(e){let n=uo(e),t=co(e,["rev-parse","--absolute-git-dir"])??co(e,["rev-parse","--git-common-dir"]),r=co(e,["remote","get-url","origin"]);return Pl({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function uo(e){let n=xl(e,Lm(".red","config.yaml"));if(n==null)return{};let t;try{t=Am(n,"utf8")}catch{return{}}let r=vl(t),o=Dl(Dl(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function co(e,n){try{let t=Om("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Tm}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as Nc}from"node:crypto";import{spawn as NR}from"node:child_process";import{mkdir as MR}from"node:fs/promises";import{dirname as CR}from"node:path";import{createHash as Mm}from"node:crypto";import{constants as yo}from"node:fs";import{mkdir as Wl,open as Cm,readFile as Wm,rm as Fl,stat as Fm}from"node:fs/promises";import{createConnection as Bm}from"node:net";import{tmpdir as Hm}from"node:os";import{dirname as Bl,join as Tn}from"node:path";var Im="toon";function Tl(e){return e.trimStart().startsWith("{")?"json":"toon"}function fo(e){let n=0;for(;e[n]===`
51
- `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=Tl(t);if(r==="json"){let s=t.indexOf(`
49
+ `;em(e,`${t}${r}${gm(n)}`,{encoding:"utf8",mode:384})}catch{}}function km(e){try{return Pt(e,"utf8")}catch{return""}}import{join as Rm}from"node:path";var bm=[".red","redskilled"],ie=448;function Le(e){return Rm(e,...bm)}import{execFileSync as $m}from"node:child_process";import{readFileSync as Im}from"node:fs";import{dirname as Ll,join as Nm}from"node:path";import{existsSync as _m,readFileSync as ox}from"node:fs";import{dirname as wm,join as xm}from"node:path";function El(e,n){let t=e;for(let r=0;r<16;r++){let o=xm(t,n);if(_m(o))return o;let s=wm(t);if(s===t)break;t=s}return null}function Sm(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function nn(e,n){let t=[];for(let r of e.split(`
50
+ `)){let o=r.replace(/\r$/,""),s=o.trim();if(!s||s.startsWith("#"))continue;let i=o.indexOf(":");if(i<0)continue;let l=o.length-o.trimStart().length,a=o.slice(0,i).trim();if(!a)continue;let d=o.slice(i+1).trim();for(;t.length&&t[t.length-1].indent>=l;)t.pop();if(t.push({indent:l,key:a}),d&&t.map(u=>u.key).join(".")===n)return Sm(d)}}import{createHash as vm}from"node:crypto";var Em="project.name";function jl(e){let n=nn(e,Em)?.trim();return n===void 0||n===""?void 0:n}var Pm=8,Dl="project";function Ol(e){let n=Lm(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:jm(e.remoteUrl)??{name:Dm(e.checkoutPath,n),source:"basename"},o=Am(n??ao(e.checkoutPath));return{name:r.name,slug:`${Om(r.name)}-${o}`,hash:o,source:r.source}}function Al(e){let n=(e??"").trim();if(n==="")return;let t=n.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,""),r=/^[^/]*?:(?!\d)(.+)$/.exec(t),s=(r?r[1]:t.replace(/^[^/]*/,"")).replace(/\.git$/,"").split("/").map(i=>i.trim()).filter(i=>i!=="");if(s.length!==0)return s.slice(-2).join("/")}function jm(e){let n=Al(e);return n===void 0?void 0:{name:n,source:"remote"}}function Dm(e,n){let t=n===void 0?"":Pl(Tm(n));if(t!=="")return t;let r=Pl(ao(e));return r===""?Dl:r}function Om(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?Dl:t}function Am(e){return vm("sha256").update(e).digest("hex").slice(0,Pm)}function Lm(e){let n=ao(e??"");return n===""?void 0:n}function ao(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function Pl(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function Tm(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var Mm=2e3;function Tl(e){return Cm(e).name}function Cm(e){let n=uo(e),t=co(e,["rev-parse","--absolute-git-dir"])??co(e,["rev-parse","--git-common-dir"]),r=co(e,["remote","get-url","origin"]);return Ol({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function uo(e){let n=El(e,Nm(".red","config.yaml"));if(n==null)return{};let t;try{t=Im(n,"utf8")}catch{return{}}let r=jl(t),o=Ll(Ll(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function co(e,n){try{let t=$m("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Mm}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as Wc}from"node:crypto";import{spawn as FR}from"node:child_process";import{mkdir as BR}from"node:fs/promises";import{dirname as HR}from"node:path";import{createHash as Bm}from"node:crypto";import{constants as go}from"node:fs";import{mkdir as Hl,open as Hm,readFile as Um,rm as Ul,stat as Gm}from"node:fs/promises";import{createConnection as Km}from"node:net";import{tmpdir as Vm}from"node:os";import{dirname as Gl,join as $n}from"node:path";var Wm="toon";function Nl(e){return e.trimStart().startsWith("{")?"json":"toon"}function fo(e){let n=0;for(;e[n]===`
51
+ `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=Nl(t);if(r==="json"){let s=t.indexOf(`
52
52
  `);return s<0?null:{frame:t.slice(0,s),dialect:r,rest:t.slice(s+1)}}let o=t.indexOf(`
53
53
 
54
- `);return o<0?null:{frame:t.slice(0,o+1),dialect:r,rest:t.slice(o+2)}}function mo(e){let n=Tl(e)==="json"?po:Al,t=n===po?Al:po;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function po(e){return JSON.parse(e)}function Al(e){return q(e)}function ho(e,n){if(n==="toon"){let t=Nm(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 mo(e){let n=Nl(e)==="json"?po:$l,t=n===po?$l:po;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function po(e){return JSON.parse(e)}function $l(e){return q(e)}function ho(e,n){if(n==="toon"){let t=Fm(e);if(t!==null)return t.endsWith(`
55
55
  `)?`${t}
56
56
  `:`${t}
57
57
 
58
58
  `}return`${JSON.stringify(e)}
59
- `}function Nm(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=C(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function $l(e,n){return!Ll(e)||!Ll(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function Ll(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Il=new Set;function Nl(e){return Il.has(e)?"json":Im}function Ml(e){Il.add(e)}var Um=108;async function vt(e,n,t="resident server"){let r=e.wire,o=r??Nl(e.socketPath),s=await Cl(e,n,t,o);return r||o==="json"||!$l(n,s)?s:(Ml(e.socketPath),await Cl(e,n,t,"json"))}async function Cl(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let a=Bm(e.socketPath),l=!1,d="",c=setTimeout(()=>{u(()=>i(new Error(`${t} timed out`))),a.destroy()},o);function u(f){l||(l=!0,clearTimeout(c),f())}a.on("connect",()=>{a.write(ho(n,r))}),a.on("data",f=>{d+=f.toString("utf8");let m=fo(d);m&&(d=m.rest,u(()=>{try{s(mo(m.frame))}catch(h){i(h)}}),a.end())}),a.on("error",f=>u(()=>i(f))),a.on("close",()=>{l||u(()=>i(new Error(`${t} closed without response`)))})})}function Hl(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=fo(r);if(!s)return;r=s.rest,e.pause();let i=a=>{if(!(e.destroyed||!e.writable))try{e.write(ho(a,s.dialect))}catch{}};(async()=>{let a;try{a=mo(s.frame),await n(a,i)}catch(l){t(l,a,i)}finally{e.end()}})()})}async function Gm(e){await Wl(Bl(e),{recursive:!0,mode:448});try{return await Cm(e,yo.O_CREAT|yo.O_EXCL|yo.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}var Km=6e4,Ul="resident-spawn-lock v1",Vm=3;async function Gl(e,n={}){let t=n.maxAgeMs??Km,r=n.now??Date.now,o=n.pid??process.pid,s=n.isPidAlive??B;await Wl(Bl(e),{recursive:!0,mode:448});let i=[];for(let a=0;;a+=1){let l=await Gm(e);if(l)return await l.writeFile(`${Ul} pid=${o} taken=${new Date(r()).toISOString()}
60
- `).catch(()=>{}),{acquired:!0,lockPath:e,handle:l,reaped:i};let d=await Jm(e),c=await zm(e,d,r());if(a>=Vm||c==null)return{acquired:!1,lockPath:e,holder:d,ageMs:c};let u=qm(d,c,t,s);if(u==null)return{acquired:!1,lockPath:e,holder:d,ageMs:c};let f={lockPath:e,reason:u,holder:d,ageMs:c};await Fl(e,{force:!0}),i.push(f),n.onReap?.(f)}}async function Kl(e){await e.handle.close().catch(()=>{}),await Fl(e.lockPath,{force:!0})}function qm(e,n,t,r){return e==null?n>t?"unattributed":null:r(e.pid)?n>t?"aged-out":null:"holder-dead"}function Vl(e){let n=e.ageMs==null?"of unknown age":`taken ${Math.round(e.ageMs/1e3)}s ago`,t=e.holder==null?"an owner it does not name":`pid ${e.holder.pid} (at ${e.holder.takenAt})`;return`no spawn was attempted: the spawn lock ${JSON.stringify(e.lockPath)} is held by ${t}, ${n}. If that process is gone, remove the file to clear it`}async function Jm(e){try{return Qm(await Wm(e,"utf8"))}catch{return null}}function Qm(e){let n=e.split(`
61
- `,1)[0]?.trim()??"";if(!n.startsWith(Ul))return null;let t=Number(/\bpid=(\d+)\b/.exec(n)?.[1]??""),r=/\btaken=(\S+)/.exec(n)?.[1]??"";return!Number.isInteger(t)||t<=0||!Number.isFinite(Date.parse(r))?null:{pid:t,takenAt:r}}async function zm(e,n,t){let r=n==null?Number.NaN:Date.parse(n.takenAt);if(Number.isFinite(r))return Math.max(0,t-r);try{return Math.max(0,t-(await Fm(e)).mtimeMs)}catch{return null}}function B(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var Ym="/tmp";function Et(e){let n=e.env??process.env,t=Mm("sha256").update(e.key).digest("hex").slice(0,20),r=l=>Tn(l,e.socketFileName).length<Um,o=n.XDG_RUNTIME_DIR;if(o){let l=Tn(o,"red-skills",t);if(r(l))return l}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=Tn(`red-skills-${s}`,t),a=Tn(Hm(),i);return r(a)||process.platform==="win32"?a:Tn(Ym,i)}me();import{homedir as bh}from"node:os";import{join as So}from"node:path";import{spawnSync as _h}from"node:child_process";import{createHash as wh}from"node:crypto";import{existsSync as xh}from"node:fs";import{mkdir as Zl,readFile as Sh,writeFile as vh}from"node:fs/promises";import{dirname as Eh}from"node:path";var $e="@reddb-io/red-skills",ah="https://registry.npmjs.org",dh="canary",tn=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function ch(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function Ot(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return At(r,ch(n,t,o))}function uh(e){return e==="dev"?["rsp","redskilled"]:[]}function ph(e){return`${e}.bundle.min.mjs`}function fh(e){return At("dist",ph(e))}function mh(e,n="stable"){return`${$e}@${n==="canary"?dh:e}`}function hh(e=$e){return`${ah}/${e.replace("/","%2F")}`}async function xo(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=Ot({plugin:t,version:r,cacheDir:o,channel:s}),a=uh(t),l=a.map(f=>Ot({plugin:f,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await yh(e,l))return i;let d=mh(r,s),c=At(o,`.staging-${t}-${s==="canary"?"canary":r}`),u;try{u=await e.materialize(d,c)}catch(f){throw Xl(f,d)}for(let f of[t,...a]){let m=fh(f),h=At(u,m);if(!await e.exists(h))throw new tn("bundle-missing",`npm package ${d} has no ${m}`);let b=f===t?i:Ot({plugin:f,version:r,cacheDir:o,channel:s});await e.writeFile(b,await e.readFile(h))}return i}async function yh(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function zl(e,n,t=$e){let r;try{r=await e.fetchText(hh(t))}catch(s){throw Xl(s,t)}let o=gh(r);return{sameMajor:kh(o,n),newest:Rh(o)}}function gh(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 kh(e,n){let t=wo(n);if(t===null)return null;let r=null;for(let o of e)wo(o)===t&&(r===null||Yl(o,r)>0)&&(r=o);return r}function Rh(e){let n=null;for(let t of e){let r=String(t).trim();wo(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||Yl(r,n)>0)&&(n=r)}return n}function wo(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function Yl(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 Xl(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new tn("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new tn("package-missing",`npm could not resolve ${n}: ${t}`,e):new tn("network",`failed to resolve ${n}: ${t}`,e)}function At(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}me();var Ph={async materialize(e,n){await Zl(n,{recursive:!0});let t=_h("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 So(n,"node_modules",...$e.split("/"))},async readFile(e){return new Uint8Array(await Sh(e))},async writeFile(e,n){await Zl(Eh(e),{recursive:!0}),await vh(e,n)},async exists(e){return xh(e)},sha256(e){return wh("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()}},jh="redskilled";function Dh(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||So(e.HOME||bh(),".cache");return So(n,"red-skills","bundles")}async function Oh(e={},n={},t={}){let r=we(e,n);if(ae(r))return r;let o=t.env??n.env??process.env;try{await xo(t.bundleIO??Ph,{plugin:jh,version:t.version??"",cacheDir:Dh(o)})}catch{return r}return we(e,n)}async function ea(e={},n={},t={}){let r=await Oh(e,n,t);if(ae(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(me(),Ql));throw new o(r)}import{randomUUID as Qn}from"node:crypto";import{mkdir as SR,rm as Lc}from"node:fs/promises";import{createServer as vR}from"node:net";import{dirname as ER}from"node:path";import{totalmem as Lh}from"node:os";function Nn(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 na(e,n={}){let t=0,r=0,o=0,s=[],i=[];for(let d of e){let c=Nn(d),u=!1;for(let[f,m]of[[c.memory_high,h=>t+=h],[c.memory_max,h=>r+=h]]){if(f==null)continue;let h=rn(f);h==null?u=!0:m(h)}c.cpu_weight!=null&&(o+=c.cpu_weight),u&&s.push(d.worker_id),d.isolated||i.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:s.sort(),unisolated_workers:i.sort(),memory_ceiling_bytes:a,over_committed_bytes:l,over_commitment_reason:l===0?null:Ah(e.length,r,a,l)}}function Ah(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 rn(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 ta(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 ra="REDSKILLED_MEMORY_CEILING",vo="REDSKILLED_WORKER_CEILING",oa=.7;function ia(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return rn(n)}function Lt(e){let n=0,t=[];for(let r of e){let o=ia(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 la(e){let{ceiling:n}=e,t=Lt(e.workers),r=ia(e.budget),o=r===void 0?null:r,s=t.memory_bytes+(r??0),i=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=(c,u)=>({version:1,admitted:!1,verdict:c,reason:u,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s});return n.worker_count!=null&&i>n.worker_count?d("refused-over-worker-ceiling",`redskilled refused this Worker${a}: it would be Worker ${i} 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&&s>n.memory_bytes?d("refused-over-memory-ceiling",`redskilled refused this Worker${a}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${n.memory_bytes} bytes, and ${l}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${a}: ${s} 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:i,projected_memory_bytes:s}}function aa(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=Lt(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,s=o==null?r:Math.floor(e.ceiling.memory_bytes/o),i=Math.min(r,s);if(i<=0)return{memory_max:null,reason:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes is already fully committed to ${t.worker_count} Worker(s), so no positive per-Worker ceiling can be derived; the daemon's RSS sampling floor is the only remaining ceiling`};let a=o==null?`the headroom under this host's memory ceiling of ${e.ceiling.memory_bytes} bytes; this host declares no Worker slot count (${vo} is unset), so this ceiling is a per-Worker wall and not memory the host sets aside \u2014 N Workers may carry N such walls, and the host ceiling is not enforced host-wide. Declare a slot count to make it divide into shares that sum to it`:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes shared across its ${o} Worker slot(s)`;return{memory_max:String(i),reason:`derived from ${a} (ceiling source: ${e.ceiling.source})`}}function da(e=process.env,n=Lh()){let t=(e[ra]??"").trim(),r=(e[vo]??"").trim(),o=Ih(r);if(t!==""){let s=$h(t,n);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"};sa(`redskilled: ${ra}=${JSON.stringify(t)} is not a memory ceiling this host can read; using ${oa*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return r!==""&&o===null&&!Th(r)&&sa(`redskilled: ${vo}=${JSON.stringify(r)} is not a positive integer; this host admits an unbounded number of Workers instead.`),{memory_bytes:Math.floor(n*oa),worker_count:o,source:"host-fraction"}}function Th(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var sa=e=>process.stderr.write(`${e}
62
- `);function $h(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)):rn(e)??void 0}function Ih(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 Nh,mkdir as Mh,open as Ch,readFile as Wh,stat as Fh,truncate as ca}from"node:fs/promises";import{dirname as Bh}from"node:path";var ua="redskilled.events.toonl";function Hh(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 Uh="daemon:";function Gh(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${Uh}${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 pa(e){let n=fe({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await Mh(Bh(e),{recursive:!0,mode:448}),await Kh(e),await Nh(e,n.push(Qh(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(Hh(o)),recordDaemonStop:o=>r(Gh(o)),read:()=>Vh(e),flush:async()=>{await t}}}async function Kh(e){let n;try{n=(await Fh(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await Ch(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let s=n;s>0;s-=t){let i=Math.min(t,s),a=Buffer.alloc(i);await r.read(a,0,i,s-i);let l=a.lastIndexOf(10);if(l>=0){await ca(e,s-i+l+1);return}}await ca(e,0)}finally{await r.close()}}async function Vh(e){let n;try{n=await Wh(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return qh(n)}function qh(e){let n=e.split(`
63
- `);return n.pop(),n.length===0?[]:be(`${n.join(`
59
+ `}function Fm(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=C(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function Ml(e,n){return!Il(e)||!Il(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function Il(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Cl=new Set;function Wl(e){return Cl.has(e)?"json":Wm}function Fl(e){Cl.add(e)}var qm=108;async function jt(e,n,t="resident server"){let r=e.wire,o=r??Wl(e.socketPath),s=await Bl(e,n,t,o);return r||o==="json"||!Ml(n,s)?s:(Fl(e.socketPath),await Bl(e,n,t,"json"))}async function Bl(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=Km(e.socketPath),a=!1,d="",c=setTimeout(()=>{u(()=>i(new Error(`${t} timed out`))),l.destroy()},o);function u(f){a||(a=!0,clearTimeout(c),f())}l.on("connect",()=>{l.write(ho(n,r))}),l.on("data",f=>{d+=f.toString("utf8");let m=fo(d);m&&(d=m.rest,u(()=>{try{s(mo(m.frame))}catch(h){i(h)}}),l.end())}),l.on("error",f=>u(()=>i(f))),l.on("close",()=>{a||u(()=>i(new Error(`${t} closed without response`)))})})}function Kl(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=fo(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(ho(l,s.dialect))}catch{}};(async()=>{let l;try{l=mo(s.frame),await n(l,i)}catch(a){t(a,l,i)}finally{e.end()}})()})}async function Jm(e){await Hl(Gl(e),{recursive:!0,mode:448});try{return await Hm(e,go.O_CREAT|go.O_EXCL|go.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}var Qm=6e4,Vl="resident-spawn-lock v1",zm=3;async function ql(e,n={}){let t=n.maxAgeMs??Qm,r=n.now??Date.now,o=n.pid??process.pid,s=n.isPidAlive??B;await Hl(Gl(e),{recursive:!0,mode:448});let i=[];for(let l=0;;l+=1){let a=await Jm(e);if(a)return await a.writeFile(`${Vl} pid=${o} taken=${new Date(r()).toISOString()}
60
+ `).catch(()=>{}),{acquired:!0,lockPath:e,handle:a,reaped:i};let d=await Xm(e),c=await eh(e,d,r());if(l>=zm||c==null)return{acquired:!1,lockPath:e,holder:d,ageMs:c};let u=Ym(d,c,t,s);if(u==null)return{acquired:!1,lockPath:e,holder:d,ageMs:c};let f={lockPath:e,reason:u,holder:d,ageMs:c};await Ul(e,{force:!0}),i.push(f),n.onReap?.(f)}}async function Jl(e){await e.handle.close().catch(()=>{}),await Ul(e.lockPath,{force:!0})}function Ym(e,n,t,r){return e==null?n>t?"unattributed":null:r(e.pid)?n>t?"aged-out":null:"holder-dead"}function Ql(e){let n=e.ageMs==null?"of unknown age":`taken ${Math.round(e.ageMs/1e3)}s ago`,t=e.holder==null?"an owner it does not name":`pid ${e.holder.pid} (at ${e.holder.takenAt})`;return`no spawn was attempted: the spawn lock ${JSON.stringify(e.lockPath)} is held by ${t}, ${n}. If that process is gone, remove the file to clear it`}async function Xm(e){try{return Zm(await Um(e,"utf8"))}catch{return null}}function Zm(e){let n=e.split(`
61
+ `,1)[0]?.trim()??"";if(!n.startsWith(Vl))return null;let t=Number(/\bpid=(\d+)\b/.exec(n)?.[1]??""),r=/\btaken=(\S+)/.exec(n)?.[1]??"";return!Number.isInteger(t)||t<=0||!Number.isFinite(Date.parse(r))?null:{pid:t,takenAt:r}}async function eh(e,n,t){let r=n==null?Number.NaN:Date.parse(n.takenAt);if(Number.isFinite(r))return Math.max(0,t-r);try{return Math.max(0,t-(await Gm(e)).mtimeMs)}catch{return null}}function B(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var nh="/tmp";function Dt(e){let n=e.env??process.env,t=Bm("sha256").update(e.key).digest("hex").slice(0,20),r=a=>$n(a,e.socketFileName).length<qm,o=n.XDG_RUNTIME_DIR;if(o){let a=$n(o,"red-skills",t);if(r(a))return a}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=$n(`red-skills-${s}`,t),l=$n(Vm(),i);return r(l)||process.platform==="win32"?l:$n(nh,i)}ge();import{homedir as Sh}from"node:os";import{join as So}from"node:path";import{spawnSync as vh}from"node:child_process";import{createHash as Eh}from"node:crypto";import{existsSync as Ph}from"node:fs";import{mkdir as ta,readFile as jh,writeFile as Dh}from"node:fs/promises";import{dirname as Oh}from"node:path";var $e="@reddb-io/red-skills",ph="https://registry.npmjs.org",fh="canary",tn=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}};function mh(e,n,t="stable"){return`${e}-${t==="canary"?"canary":n}.bundle.min.mjs`}function Tt(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return $t(r,mh(n,t,o))}function hh(e){return e==="dev"?["rsp","redskilled"]:[]}function gh(e){return`${e}.bundle.min.mjs`}function yh(e){return $t("dist",gh(e))}function kh(e,n="stable"){return`${$e}@${n==="canary"?fh:e}`}function Rh(e=$e){return`${ph}/${e.replace("/","%2F")}`}async function xo(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=Tt({plugin:t,version:r,cacheDir:o,channel:s}),l=hh(t),a=l.map(f=>Tt({plugin:f,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await bh(e,a))return i;let d=kh(r,s),c=$t(o,`.staging-${t}-${s==="canary"?"canary":r}`),u;try{u=await e.materialize(d,c)}catch(f){throw na(f,d)}for(let f of[t,...l]){let m=yh(f),h=$t(u,m);if(!await e.exists(h))throw new tn("bundle-missing",`npm package ${d} has no ${m}`);let b=f===t?i:Tt({plugin:f,version:r,cacheDir:o,channel:s});await e.writeFile(b,await e.readFile(h))}return i}async function bh(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function Zl(e,n,t=$e){let r;try{r=await e.fetchText(Rh(t))}catch(s){throw na(s,t)}let o=_h(r);return{sameMajor:wh(o,n),newest:xh(o)}}function _h(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 wh(e,n){let t=wo(n);if(t===null)return null;let r=null;for(let o of e)wo(o)===t&&(r===null||ea(o,r)>0)&&(r=o);return r}function xh(e){let n=null;for(let t of e){let r=String(t).trim();wo(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||ea(r,n)>0)&&(n=r)}return n}function wo(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function ea(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 na(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new tn("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new tn("package-missing",`npm could not resolve ${n}: ${t}`,e):new tn("network",`failed to resolve ${n}: ${t}`,e)}function $t(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}ge();var Ah={async materialize(e,n){await ta(n,{recursive:!0});let t=vh("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 So(n,"node_modules",...$e.split("/"))},async readFile(e){return new Uint8Array(await jh(e))},async writeFile(e,n){await ta(Oh(e),{recursive:!0}),await Dh(e,n)},async exists(e){return Ph(e)},sha256(e){return Eh("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()}},Lh="redskilled";function Th(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||So(e.HOME||Sh(),".cache");return So(n,"red-skills","bundles")}async function $h(e={},n={},t={}){let r=xe(e,n);if(ae(r))return r;let o=t.env??n.env??process.env;try{await xo(t.bundleIO??Ah,{plugin:Lh,version:t.version??"",cacheDir:Th(o)})}catch{return r}return xe(e,n)}async function ra(e={},n={},t={}){let r=await $h(e,n,t);if(ae(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(ge(),Xl));throw new o(r)}import{randomUUID as Xn}from"node:crypto";import{mkdir as jR,rm as Ic}from"node:fs/promises";import{createServer as DR}from"node:net";import{dirname as OR}from"node:path";import{totalmem as Nh}from"node:os";function Mn(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 oa(e,n={}){let t=0,r=0,o=0,s=[],i=[];for(let d of e){let c=Mn(d),u=!1;for(let[f,m]of[[c.memory_high,h=>t+=h],[c.memory_max,h=>r+=h]]){if(f==null)continue;let h=rn(f);h==null?u=!0:m(h)}c.cpu_weight!=null&&(o+=c.cpu_weight),u&&s.push(d.worker_id),d.isolated||i.push(d.worker_id)}let l=n.hostCeilingBytes??null,a=l==null?0:Math.max(0,r-l);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:r,cpu_weight_total:o,unaccounted_workers:s.sort(),unisolated_workers:i.sort(),memory_ceiling_bytes:l,over_committed_bytes:a,over_commitment_reason:a===0?null:Ih(e.length,r,l,a)}}function Ih(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 rn(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 sa(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 ia="REDSKILLED_MEMORY_CEILING",vo="REDSKILLED_WORKER_CEILING",la=.7;function da(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return rn(n)}function It(e){let n=0,t=[];for(let r of e){let o=da(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 ca(e){let{ceiling:n}=e,t=It(e.workers),r=da(e.budget),o=r===void 0?null:r,s=t.memory_bytes+(r??0),i=t.worker_count+1,l=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",a=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,d=(c,u)=>({version:1,admitted:!1,verdict:c,reason:u,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s});return n.worker_count!=null&&i>n.worker_count?d("refused-over-worker-ceiling",`redskilled refused this Worker${l}: it would be Worker ${i} past a host ceiling of ${n.worker_count} Worker(s), and ${a}`):n.memory_bytes!=null&&r===null?d("refused-unaccountable-budget",`redskilled refused this Worker${l}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${n.memory_bytes} bytes, and ${a}`):n.memory_bytes!=null&&s>n.memory_bytes?d("refused-over-memory-ceiling",`redskilled refused this Worker${l}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${n.memory_bytes} bytes, and ${a}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${l}: ${s} bytes of declared Worker memory against a host ceiling of ${n.memory_bytes??"unbounded"} bytes, and ${a}`,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function ua(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=It(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,s=o==null?r:Math.floor(e.ceiling.memory_bytes/o),i=Math.min(r,s);if(i<=0)return{memory_max:null,reason:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes is already fully committed to ${t.worker_count} Worker(s), so no positive per-Worker ceiling can be derived; the daemon's RSS sampling floor is the only remaining ceiling`};let l=o==null?`the headroom under this host's memory ceiling of ${e.ceiling.memory_bytes} bytes; this host declares no Worker slot count (${vo} is unset), so this ceiling is a per-Worker wall and not memory the host sets aside \u2014 N Workers may carry N such walls, and the host ceiling is not enforced host-wide. Declare a slot count to make it divide into shares that sum to it`:`this host's memory ceiling of ${e.ceiling.memory_bytes} bytes shared across its ${o} Worker slot(s)`;return{memory_max:String(i),reason:`derived from ${l} (ceiling source: ${e.ceiling.source})`}}function pa(e=process.env,n=Nh()){let t=(e[ia]??"").trim(),r=(e[vo]??"").trim(),o=Wh(r);if(t!==""){let s=Ch(t,n);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"};aa(`redskilled: ${ia}=${JSON.stringify(t)} is not a memory ceiling this host can read; using ${la*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return r!==""&&o===null&&!Mh(r)&&aa(`redskilled: ${vo}=${JSON.stringify(r)} is not a positive integer; this host admits an unbounded number of Workers instead.`),{memory_bytes:Math.floor(n*la),worker_count:o,source:"host-fraction"}}function Mh(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var aa=e=>process.stderr.write(`${e}
62
+ `);function Ch(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)):rn(e)??void 0}function Wh(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 Fh,mkdir as Bh,open as Hh,readFile as Uh,stat as Gh,truncate as fa}from"node:fs/promises";import{dirname as Kh}from"node:path";var ma="redskilled.events.toonl";function Vh(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 qh="daemon:";function Jh(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${qh}${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 ha(e){let n=he({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await Bh(Kh(e),{recursive:!0,mode:448}),await Qh(e),await Fh(e,n.push(Zh(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(Vh(o)),recordDaemonStop:o=>r(Jh(o)),read:()=>zh(e),flush:async()=>{await t}}}async function Qh(e){let n;try{n=(await Gh(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await Hh(e,"r");try{let o=Buffer.alloc(1);if(await r.read(o,0,1,n-1),o[0]===10)return;for(let s=n;s>0;s-=t){let i=Math.min(t,s),l=Buffer.alloc(i);await r.read(l,0,i,s-i);let a=l.lastIndexOf(10);if(a>=0){await fa(e,s-i+a+1);return}}await fa(e,0)}finally{await r.close()}}async function zh(e){let n;try{n=await Uh(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return Yh(n)}function Yh(e){let n=e.split(`
63
+ `);return n.pop(),n.length===0?[]:_e(`${n.join(`
64
64
  `)}
65
- `).filter(zh).map(Yh)}function fa(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,Jh(t)):n.delete(t.worker_id));return[...n.values()]}function Jh(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 Qh(e){return{...e}}function zh(e){return e.version===1&&typeof e.ts=="string"&&typeof e.worker_id=="string"&&(e.event==="worker-birth"||e.event==="worker-death"||e.event==="worker-budget-kill"||e.event==="daemon-stop")}function Yh(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:he(e.project_label)??"",pid:Number(e.pid??0),workspace_path:he(e.workspace_path)??"",log_path:he(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:he(e.unit),memory_high:he(e.memory_high),memory_max:he(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:he(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:he(e.signal),reason:he(e.reason)}}function he(e){return e==null||e===""?null:String(e)}function ma(e){let n=[...e.projects].sort((i,a)=>i.project_label.localeCompare(a.project_label)),t=e.backoffUntilMs??null,r=t!=null&&e.nowMs<t,o=[],s=[];for(let i of n){let a=Math.max(0,e.live[i.project_label]??0),l=Object.prototype.hasOwnProperty.call(e.queue,i.project_label),d=l?e.queue[i.project_label]??null:null,c={project_label:i.project_label,queue_depth:d,target:i.target,live:a};if(r){o.push({...c,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?.[i.project_label];if(u!=null&&e.nowMs<u){o.push({...c,outcome:"birth-halted",wanted:0,detail:`project ${JSON.stringify(i.project_label)} lost 3 Workers in a row inside 60000ms of birth, so it is not asked for another before ${new Date(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({...c,outcome:"queue-unknown",wanted:0,detail:l?`the last poll produced no depth for project ${JSON.stringify(i.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(i.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...c,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(i.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,i.target),d)-a);if(f===0){o.push({...c,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(i.project_label)} holds ${a} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for none`});continue}o.push({...c,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(i.project_label)} holds ${a} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for ${f} more`});for(let m=0;m<f;m+=1)(s[m]??(s[m]=[])).push({project_label:i.project_label,index:a+m,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function ha(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}var Tt={shortLifeStreak:0,haltUntilMs:null};function ya(e,n,t){if(n>=6e4)return Tt;let r=e.shortLifeStreak+1;return r<3?{shortLifeStreak:r,haltUntilMs:null}:{shortLifeStreak:r,haltUntilMs:t+6e5}}function ga(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 Ra(e){let n=e.workers.map(Xh),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:ey({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function ba(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 Xh(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 Zh(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 ey(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Zh(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${ka(e.held,"Worker")} across ${ka(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 ka(e,n){return`${e} ${n}${e===1?"":"s"}`}function Eo(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 ny,mkdir as ty,readFile as ry,rm as oy,writeFile as sy}from"node:fs/promises";import{dirname as _a,join as va}from"node:path";import{tmpdir as wa}from"node:os";var iy="redskilled.machine.claim.toon",ly="REDSKILLED_MACHINE_DIR",ay=8,xe=class extends Error{constructor(t,r,o){super(cy(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},xa;function Ea(){return xa??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},xa}function dy(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[ly]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||wa():wa();return va(o,`redskilled-${e.machineIdHash}`)}function $t(e){return va(dy(e),iy)}function It(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??B;async function s(){let l;try{l=await ry(e,"utf8")}catch(c){if(c.code==="ENOENT"||Po(c))return;throw c}let d=py(l);return fy(d)?d:void 0}function i(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 oy(e,{force:!0}),!0}catch(l){if(Po(l))return!1;throw l}}return{claimPath:e,read:s,async claim(l){await ty(_a(e),{recursive:!0,mode:1023})!=null&&await ny(_a(e),1023).catch(()=>{});let c=!1;for(let u=0;u<ay;u+=1){let f=i(l,r());try{return await sy(e,uy(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:c,claim:f}}catch(h){if(h.code!=="EEXIST"){if(Po(h))return{claimed:!1,reason:"stale-claim-not-reapable"};throw h}}let m=await s();if(!m){if(!await a())return{claimed:!1,reason:"stale-claim-not-reapable"};c=!0;continue}if(Sa(m,l,n.socketPath))return{claimed:!0,reaped:c,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};c=!0}return{claimed:!1,reason:"contended"}},async release(l){let d=await s();return!d||!Sa(d,l,n.socketPath)?!1:await a()}}}function Pa(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 ja(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 cy(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 Po(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function Sa(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function uy(e){return`${C(e,{keyedMapCollapse:!0})}
66
- `}function py(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return q(n)}catch{return null}}}function fy(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 my=["worker_id","slot","workspace_path","log_path"],jo=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${my.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},hy=/\{\{([a-z_]+)\}\}/g;function yy(e,n){let t=(i,a)=>i.replace(hy,(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 jo(d,a)}}),r=e.argv.map((i,a)=>t(i,`argv word ${a}`)),o={};for(let[i,a]of Object.entries(e.env??{}))o[i]=t(a,`env entry ${JSON.stringify(i)}`);let s=e.log_path==null?void 0:t(e.log_path,"the log path");return{argv:r,env:o,...s==null||s===""?{}:{log_path:s}}}function Da(e,n,t){let r=yy(e,n),o=r.log_path??n.log_path,[s,...i]=r.argv;if(s===void 0||s==="")throw new Error(`redskilled cannot start a Worker for project ${JSON.stringify(t.project_label)}: its launch expanded to an argv with no command`);return{worker_id:n.worker_id,project_label:t.project_label,workspace_path:n.workspace_path,...o==null||o===""?{}:{log_path:o},command:s,args:i,env:r.env}}function Do(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 Oo(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 Ao(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 gy=3e5,ky=.5,To=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 Oa(e,n){if(n.held!=null)throw new To(n.held);let t=Lo(e.project_label,"a project label"),r=Lo(e.selector,"a selector"),o=Do(e.argv,t),s=Ao(e.env,t),i=Oo(e.log_path,t),a=Lo(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??gy;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:s,...i==null?{}:{log_path:i},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 Nt=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 Aa(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:Do(n.launch.argv,e.project_label),env:Ao(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=n.launch==null?e.log_path:Oo(n.launch.log_path,e.project_label),{log_path:i,...a}=e;return{...a,...s==null?{}:{log_path:s},...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1}}function La(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(n.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,n.liveWorkers??0),s=n.queue,i=s!=null&&s.outcome==="counted"?s.depth:null,a=i!=null&&i>0?"open-work":o>0?"live-worker":null;if(a==null){let l=i===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 ${i} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function Ry(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function Ta(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*ky;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 $a(e,n){let t=[],r=[];for(let o of e)(Ry(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function $o(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||by(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 by(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function Lo(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var _y={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 Ia(e){return`worker-${e}`}function Na(e){let n=_y[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 Ma(e){return e==="single-object"?"rest":"graphql"}function T(e,n,t,r,o){return{key:e,kind:"read",cardinality:n,surface:o??Ma(n),budget:t,...o?{only:o}:{},why:r}}function H(e,n,t,r){return{key:e,kind:"write",cardinality:"single-object",surface:n,budget:t,why:r}}var Ca=[T("issue view","single-object","rest","one issue by number; REST answers it in one request against the idle pool"),T("pr view","single-object","rest","one pull request by number, polled per Worker per iteration"),T("repo view","single-object","rest","one repository's own metadata"),T("run view","single-object","rest","one Actions run; the Actions API has no GraphQL surface either way"),T("release view","single-object","rest","one release by tag"),T("pr diff","single-object","rest","one pull request's diff, served by a REST media type"),T("issue list","multi-node","graphql","a connection of issues; one GraphQL query beats N REST pages"),T("pr list","multi-node","graphql","a connection of pull requests; one GraphQL query beats N REST pages"),T("pr checks","multi-node","graphql","every check context on one commit, which is a connection, not an object"),T("release list","multi-node","rest","Releases have no GraphQL connection gh reads; REST pages them","rest"),T("run list","multi-node","rest","the Actions API has no GraphQL surface, so a listing draws the request pool","rest"),T("label list","multi-node","graphql","a connection of labels inside one repository"),T("issue list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),T("pr list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),T("search issues","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("search prs","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("search repos","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("api graphql","multi-node","graphql","the caller wrote the query; `gh api graphql` is GraphQL by construction"),T("api rest","single-object","rest","any `gh api <path>` that is not `graphql` is a REST request"),H("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),H("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),H("issue close","graphql","graphql","gh closes with the closeIssue mutation"),H("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),H("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),H("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),H("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),H("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),H("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),H("pr close","graphql","graphql","gh closes with a GraphQL mutation"),H("pr edit","graphql","graphql","gh edits with GraphQL mutations"),H("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),H("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),H("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],wy=new Map(Ca.map(e=>[e.key,e]));function Wa(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 Io(e){let n=Wa(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 Mt=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(n){let t=Io(n);super(`unclassified GitHub operation ${JSON.stringify(t||"(empty argv)")}: add an entry to GITHUB_OPERATIONS in packages/github/surface.ts stating its cardinality. Defaulting to GraphQL is what sent every single-object poll to the node-point pool (ADR 0132 decision 4).`),this.operation=t,this.args=[...n]}};function Fa(e){return wy.get(Io(e))??null}function Ba(e){let n=Fa(e);if(!n)throw new Mt(e);return n}function No(e){return Ba(e).surface}var Ua="rate_limit",Ga={rest:"core",graphql:"graphql",search:"search"},ye=["rest","graphql","search"];function Bt(e,n){return{version:1,origin:"asked",outcome:"unanswered",source:"GET /rate_limit",asked_at:e,request_count:0,pools:{rest:null,graphql:null,search:null},unreported_pools:[...ye],detail:n??"no balance has been asked for yet, so none is known"}}var Co=15e3,on=.15,Wt=[{at_or_below_fraction:0,every_ms:Co,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:on,every_ms:3e4,why:"inside the reserved band: the posture can change between two calls"},{at_or_below_fraction:.5,every_ms:12e4,why:"below half: tightening, because the band is now reachable inside one window"},{at_or_below_fraction:1,every_ms:6e5,why:"above half: rare, because nothing this balance decides is anywhere close"}],Mo=2;function Ka(e,n){let t=Ha(e),r=Ha(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let a of ye){let l=Ga[a],d=r[l],c=vy(a,l,d);o[a]=c,c==null&&s.push(a)}let i=ye.length-s.length;return{version:1,origin:"asked",outcome:i>0?"asked":"unanswered",source:"GET /rate_limit",asked_at:n.askedAt,request_count:1,pools:o,unreported_pools:s,detail:i>0?`the token's own answer for ${i} of ${ye.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function Wo(e){try{let n=await e.transport();return Ka(n,{askedAt:e.now})}catch(n){let t=n instanceof Error?n.message:String(n);return{...Bt(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function Fo(e){let n=null;for(let t of ye){let r=e.pools[t];r!=null&&(n==null||r.fraction<n.fraction)&&(n=r)}return n}function Ht(e,n){let t=Fo(e);if(t==null)return Ft(on).every_ms;let r=Ft(t.fraction);if(t.remaining>0)return r.every_ms;let o=qa(n.now,t.reset_at);return o==null?r.every_ms:Math.max(Co,Math.min(r.every_ms,o))}function Bo(e,n=on){return Math.ceil(e.limit*n)}function Va(e,n,t=on){let r=e.pools[n];return r==null?"unknown":r.remaining<=0?"spent":r.remaining<Bo(r,t)?"reserved":"open"}function Ho(e){let n=e.reservedFraction??on,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:Ft(n).every_ms*Mo,stale:!1,posture:"unknown",reserved_fraction:n,next_poll_ms:Ft(n).every_ms,pools:[],unreported_pools:[...ye],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let r=Ht(t,{now:e.now}),o=e.stalenessMs??r*Mo,s=qa(t.asked_at,e.now),i=t.outcome==="asked"&&(s==null||s>o),a=ye.map(c=>t.pools[c]).filter(c=>c!=null),l=Sy(t,n),d=Fo(t);return{version:1,origin:"asked",outcome:t.outcome,asked_at:t.asked_at,age_ms:s,threshold_ms:o,stale:i,posture:l,reserved_fraction:n,next_poll_ms:r,pools:a,unreported_pools:t.unreported_pools,reason:i?`this balance is stale: asked ${s==null?"at an unreadable instant":`${s}ms ago`}, past the ${o}ms window, so the posture below is the last one the token confirmed and not the current one`:xy(l,d,t,n)}}function Uo(e){if(!Ko(e))return!1;let n=e;return n.version===1&&n.origin==="asked"&&(n.outcome==="asked"||n.outcome==="unanswered")&&(n.asked_at===null||typeof n.asked_at=="string")&&(n.age_ms===null||typeof n.age_ms=="number")&&typeof n.threshold_ms=="number"&&typeof n.stale=="boolean"&&typeof n.posture=="string"&&typeof n.reserved_fraction=="number"&&typeof n.next_poll_ms=="number"&&Array.isArray(n.pools)&&Array.isArray(n.unreported_pools)&&typeof n.reason=="string"}function xy(e,n,t,r){if(n==null)return t.detail;let o=Bo(n,r);switch(e){case"spent":return`the ${n.pool} pool is spent and resets at ${n.reset_at}: work is not queued, it is refused`;case"reserved":return`the ${n.pool} pool has ${n.remaining} of ${n.limit} left, inside the reserved band of ${o}: convenience reads are refused and the claim, a landing and a closing comment still pass`;default:return`the ${n.pool} pool is the tightest at ${n.remaining} of ${n.limit}, above the reserved band of ${o}`}}function Sy(e,n){let t="unknown";for(let r of ye){if(e.pools[r]==null)continue;let o=Va(e,r,n);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function Ft(e){for(let n of Wt)if(e<=n.at_or_below_fraction)return n;return Wt[Wt.length-1]}function vy(e,n,t){if(!Ko(t))return null;let r=Ct(t.limit),o=Ct(t.remaining),s=Ct(t.used),i=Ct(t.reset);return r==null||r<=0||o==null?null:{pool:e,resource:n,limit:r,remaining:o,used:s??0,reset_at:i==null?"":new Date(i*1e3).toISOString(),fraction:o/r}}function Go(e){let n=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let r=await t(`${n}/${Ua}`,{method:"GET",headers:{authorization:`bearer ${e.token}`,accept:"application/vnd.github+json"}});if(!r.ok)throw new Error(`the balance ask was refused with HTTP ${r.status}`);return await r.json()}}function qa(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 Ct(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function Ha(e){return Ko(e)?e:{}}function Ko(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Za(e){return{generated_at:e.now,hour:Ja("hour",36e5,e),day:Ja("day",864e5,e)}}function Ut(e,n,t){let r=Mn(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(a=>{let l=Mn(n(a));return l==null?!1:r==null||r-l<=o});return i.length<=s?i:i.slice(i.length-s)}function Ja(e,n,t){let r=Mn(t.now),o=r==null?null:r-n,s=e==="hour"?"1h":"24h",i=t.observations.map(u=>({observation:u,at:Mn(u.observed_at)})).filter(u=>u.at!=null&&Ya(u.at,o,r)).sort((u,f)=>u.at-f.at),a=t.outcomes.map(u=>Mn(u.ts)).filter(u=>u!=null&&Ya(u,o,r)),l=Qa(i,u=>u.tokens,"tokens",s),d=Qa(i,u=>u.tools,"tools",s),c=[];return i.length===0?c.push("worker-vitals"):(l.samples===0&&c.push("worker-vitals.tokens"),d.samples===0&&c.push("worker-vitals.tools")),a.length===0&&c.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:Ey(a.length,n,s),runner_share:za("runner",i,u=>u.runner,s),model_share:za("model",i,u=>u.model,s),unavailable:c}}function Qa(e,n,t,r){let o=new Map,s=0;for(let d of e){let c=n(d.observation);if(c==null||!Number.isFinite(c))continue;s+=1;let u=o.get(d.observation.worker_id)??[];u.push({at:d.at,count:c}),o.set(d.observation.worker_id,u)}if(s===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${r}`,samples:0};let i=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||(i+=Math.max(0,h.count-m.count))}let c=d[0],u=d[d.length-1];c!=null&&(a=a==null?c.at:Math.min(a,c.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:s}:{value:i/((l-a)/6e4),absent_reason:null,samples:s}}function Ey(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 za(e,n,t,r){let o=new Map;for(let d of n){let c=t(d.observation);c!=null?o.set(d.observation.worker_id,c):o.has(d.observation.worker_id)||o.set(d.observation.worker_id,null)}let s=new Map,i=0,a=0;for(let d of o.values()){if(d==null){a+=1;continue}i+=1,s.set(d,(s.get(d)??0)+1)}let l=[...s.entries()].map(([d,c])=>({key:d,worker_count:c,share:c/i})).sort((d,c)=>c.worker_count-d.worker_count||d.key.localeCompare(c.key));return{dimension:e,attributed_workers:i,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 Ya(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function Mn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function ed(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.generated_at=="string"&&Xa(n.hour)&&Xa(n.day)}function Xa(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.window=="string"&&typeof n.window_ms=="number"&&Vo(n.tokens_per_min)&&Vo(n.tools_per_min)&&Vo(n.issues_per_hour)&&Array.isArray(n.unavailable)}function Vo(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return(n.value===null||typeof n.value=="number")&&(n.absent_reason===null||typeof n.absent_reason=="string")&&Number.isInteger(n.samples)}import{execFileSync as Py}from"node:child_process";import{existsSync as jy,readFileSync as Gt,readdirSync as Dy}from"node:fs";import{dirname as Oy,join as Ie}from"node:path";function Cn(e){let n=Nn(e),t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let s=rn(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function nd(e){let n=[],t=[];for(let r of e.workers){let o=Cn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(Nn(r).memory_max??Nn(r).memory_high)==null?"this Worker declared no memory budget and the host derived no ceiling for it, so the sampler has none to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let s=e.rss[r.worker_id];if(typeof s!="number"||!Number.isFinite(s)){t.push({worker_id:r.worker_id,reason:"the host produced no RSS reading for this Worker on this tick, and an unmeasured Worker is never killed on suspicion"});continue}if(!(s<=o.bytes)){if(e.sources?.[r.worker_id]==="cgroup"&&o.name==="MemoryMax"){t.push({worker_id:r.worker_id,reason:`this Worker's ${o.name} of ${o.declared} is held by the kernel on its own cgroup, and the reading is memory.current \u2014 which counts reclaimable page cache the kernel drops before it kills anything, so the daemon does not duplicate an enforcement that can tell cache from anonymous memory`});continue}n.push(Ay(r,o,s))}}return{terminations:n,unenforceable:t}}function Ay(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 Ly=4096;function td(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return r;let o={},s={},i={},a=$y(e,t,n);for(let[u,f]of a){let m=My(f);m!=null&&(o[u]=m.memoryBytes,m.cpuSeconds!=null&&(s[u]=m.cpuSeconds),i[u]="cgroup")}let l=e.filter(u=>i[u.worker_id]==null);if(l.length===0)return{rss:o,cpu_seconds:s,sources:i};let d=Fy(t,n);if(d.size===0)return{rss:o,cpu_seconds:s,sources:i};let c=new Map;for(let u of d.values()){let f=c.get(u.ppid);f?f.push(u.pid):c.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 D of c.get(k)??[])h.push(D)}}o[u.worker_id]=f,s[u.worker_id]=m,i[u.worker_id]="process-tree"}return{rss:o,cpu_seconds:s,sources:i}}var Ty="/sys/fs/cgroup";function $y(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let s=t.cgroupRoot??Ty,i=e.filter(l=>l.unit!=null&&l.unit!=="");if(i.length===0)return r;let a=Iy(s,t);for(let l of i)for(let d of a){let c=Ie(d,l.unit);if(jy(Ie(c,"memory.current"))){r.set(l.worker_id,c);break}}return r}function Iy(e,n){let t=n.selfCgroupPath??Ny(),r=[],o=a=>{r.includes(a)||r.push(a)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(Ie(e,s));let a=Oy(s);if(a===s)break;s=a}o(e);let i=n.uid??process.getuid?.();return i!=null&&o(Ie(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),r}function Ny(){try{for(let e of Gt("/proc/self/cgroup","utf8").split(`
67
- `))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function My(e){let n;try{n=Gt(Ie(e,"memory.current"),"utf8")}catch{return null}let t=Number(n.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:Cy(e)}}function Cy(e){let n;try{n=Gt(Ie(e,"cpu.stat"),"utf8")}catch{return null}return Wy(n)}function Wy(e){for(let n of e.split(`
68
- `)){let[t,r]=n.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(r);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function Fy(e,n){return n.procRoot!=null||e==="linux"?Vy(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?Gy(By(n.psTable)):new Map}function By(e){try{return(e??Hy)()}catch{return""}}function Hy(){return Py("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Uy=1024;function Gy(e){let n=new Map;for(let t of e.split(`
69
- `)){let r=t.trim().split(/\s+/);if(r.length!==4)continue;let[o,s,i]=r.slice(0,3).map(Number);if(![o,s,i].every(l=>l!=null&&Number.isSafeInteger(l)&&l>=0))continue;let a=Ky(r[3]);a!=null&&n.set(o,{pid:o,ppid:s,rssBytes:i*Uy,cpuSeconds:a})}return n}function Ky(e){let n=e.indexOf("-"),t=n<0?0:Number(e.slice(0,n));if(!Number.isFinite(t)||t<0)return null;let r=e.slice(n+1).split(":"),o=t*86400,s=1;for(let i=r.length-1;i>=0;i--){let a=Number(r[i]);if(!Number.isFinite(a)||a<0||r[i]==="")return null;o+=a*s,s*=60}return o}function Vy(e){let n=new Map,t;try{t=Dy(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=Gt(Ie(e,r,"stat"),"utf8")}catch{continue}let s=Jy(o);s&&n.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*Ly,cpuSeconds:s.cpuTicks/qy})}return n}var qy=100;function Jy(e){let n=e.lastIndexOf(")");if(n<0)return null;let t=Number(e.slice(0,e.indexOf(" "))),r=e.slice(n+1).trim().split(/\s+/),o=Number(r[1]),s=Number(r[11]),i=Number(r[12]),a=Number(r[21]);return!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||!Number.isFinite(a)||!Number.isFinite(s)||!Number.isFinite(i)?null:{pid:t,ppid:o,rssPages:Math.max(0,a),cpuTicks:Math.max(0,s)+Math.max(0,i)}}var Qy=["api","graphql"],zy=No(Qy);function Yy(e,n="https://api.github.com"){return e==="graphql"?`${n}/graphql`:n}var rd=100,Qo=6e4,Xy=2*Qo,Zy=7*24*60*60*1e3,qo=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 zo(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new qo(t.project_label,t.token_ref,n)}function eg(e,n={now:new Date(0).toISOString()}){rg(e);let t=n.closedWindowMs??Zy,r=Date.parse(n.now);if(!Number.isFinite(r))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(n.now)}`);let o=new Date(r-Math.max(0,t)).toISOString(),s=e.map((l,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:l}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { cost remaining resetAt }",...s.flatMap(({alias:l,search_alias:d,project:c})=>{let u=JSON.stringify(c.owner),f=JSON.stringify(c.name),m=JSON.stringify(`repo:${c.owner}/${c.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(`
70
- `),aliases:s,closed_since:o}}function ng(e,n,t){let r=sn(n),o=sn(r.data),s=Array.isArray(r.errors)?r.errors.map(sn):[],i=og(o.rateLimit,s),a=e.aliases.map(({alias:l,search_alias:d,project:c})=>{let u=c.owner+"/"+c.name,f=o[l],m=s.find(h=>od(h.path,l)||od(h.path,d));if(Kt(f)){let h=sd(f.open_pull_requests),b=sd(f.open_issues),k=sg(o[d]);if(h!=null&&b!=null&&k!=null)return{project_label:c.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:h,open_issues:b,recently_closed:k},detail:`counted ${u} for project ${JSON.stringify(c.project_label)}`}}return i.exhausted||cd(m)?{project_label:c.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${i.reset_at==null?"":`; the quota resets at ${i.reset_at}`}`}:{project_label:c.project_label,repository:u,outcome:"unreachable",counts:null,detail:`${u} is not reachable with the host token: ${Jo(m?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:a.length,rate_limit:i,projects:a}}function tg(e){return{version:1,fetched_at:e,request_count:0,project_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1,point_cost:null},projects:[]}}async function id(e){if(e.projects.length===0)return tg(e.now);zo(e.projects,e.hostTokenRef);let n=eg(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return ng(n,t,{fetchedAt:e.now})}catch(t){let r=t instanceof Error?t.message:String(t),o=/rate limit|secondary rate|429/i.test(r);return{version:1,fetched_at:e.now,request_count:1,project_count:e.projects.length,rate_limit:{remaining:null,reset_at:null,exhausted:o,point_cost:null},projects:e.projects.map(s=>({project_label:s.project_label,repository:`${s.owner}/${s.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${s.owner}/${s.name} answered: ${r}`}))}}}function ld(e){let n=e.stalenessMs??Xy,t=e.activity;if(t==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:n,stale:!1,request_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1,point_cost:null},projects:[],reason:"the daemon polls no repository, so there are no counts to age"};let r=Date.parse(e.now),o=Date.parse(t.fetched_at),s=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,i=s==null||s>n;return{version:1,fetched_at:t.fetched_at,age_ms:s,threshold_ms:n,stale:t.projects.length>0&&i,request_count:t.request_count,rate_limit:t.rate_limit,projects:t.projects.map(a=>({...a,fetched_at:t.fetched_at,age_ms:s,stale:i})),reason:t.projects.length===0?"the daemon polls no repository, so there are no counts to age":s==null?"these counts carry no readable instant, so they cannot be presented as current":i?`these counts are ${s}ms old, past the ${n}ms window`:`fetched ${s}ms ago, within the ${n}ms window`}}function ad(e){if(!Kt(e))return!1;let n=e;return n.version===1&&(n.fetched_at===null||typeof n.fetched_at=="string")&&(n.age_ms===null||typeof n.age_ms=="number")&&typeof n.threshold_ms=="number"&&typeof n.stale=="boolean"&&Number.isInteger(n.request_count)&&Kt(n.rate_limit)&&Array.isArray(n.projects)&&typeof n.reason=="string"}function dd(e){let n=e.endpoint??Yy(zy),t=e.fetchImpl??fetch;return async r=>{let o=await t(n,{method:"POST",headers:{authorization:`bearer ${e.token}`,"content-type":"application/json",accept:"application/vnd.github+json"},body:JSON.stringify({query:r})});if(!o.ok){let s=o.headers.get("x-ratelimit-remaining"),i=o.status===429||s==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(i?": the host token's rate limit is spent":""))}return await o.json()}}function rg(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>rd)throw new Error(`redskilled activity fetch spans at most ${rd} 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 og(e,n){let t=sn(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(cd),i=typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:null;return{remaining:r,reset_at:o,exhausted:s||r===0,point_cost:i}}function cd(e){if(e==null)return!1;let n=Jo(e.type),t=Jo(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function od(e,n){return Array.isArray(e)&&e.includes(n)}function sd(e){let n=sn(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function sg(e){let n=sn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function sn(e){return Kt(e)?e:{}}function Kt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jo(e){return typeof e=="string"?e:""}var ig=3e4,lg=4,ag=["logs","vitals","display"];function ud(e,n){if(n===void 0)return e;let t=ag.filter(o=>n[o]!==!0);if(t.length===0)return e;let r=o=>n[o]===!0;return{...e,workers:e.workers.map(o=>({...o,...r("vitals")?{}:{vitals:dg,budget:{...o.budget,used_bytes:null,used_fraction:null}},...r("logs")?{}:{log:cg},...r("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var dg={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},cg={last_line:null,published_at:null,source:null};function pd(e){let n=e.stalenessMs??ig,t=Wn(e.now),r=e.sampledAt==null?null:Wn(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),s=o!=null&&o<=n,i=new Set(e.reattachedWorkerIds??[]),a=e.hostState.workers.map(f=>fg(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:i.has(f.worker_id)?"reattached":"running"})),l=a.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=a.length-l.length,c=a.reduce((f,m)=>f+(m.vitals.rss_bytes??0),0),u=Lt(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:gg({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:c,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:yg(a),known_projects:hg(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,m)=>f.localeCompare(m)),workers:a,github_balance:Ho({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:ld({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:ug(e.deaths,e.recentDeathLimit??lg)},engine:pg(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function ug(e,n){let t=[...e].sort((o,s)=>(Wn(s.ts)??0)-(Wn(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 pg(e){let n=e.upgrade,t=n?.running_version??e.daemon_version,r=n?.published_version??null,o=n?.newest_published_version??null,s=(n?.newer_published??0)>0,i=(n?.major_held??0)>0;return{running_version:t,published_version:r,newer_published:s,major_held:i,current:r==null&&o==null?null:!s&&!i}}function fg(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=Cn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=Wn(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms:n.nowMs==null||i==null?null:Math.max(0,n.nowMs-i),state:n.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:r,sampled_at:r==null?null:n.sampledAt,age_ms:r==null?null:n.ageMs,fresh:r!=null&&n.sampleFresh,rss_source:r==null?null:e.rss_source??null},budget:{name:o?.name??null,declared:o?.declared??s,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:mg(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function mg(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 hg(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 yg(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 gg(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 Wn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function Yo(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.daemon,r=n.staleness,o=n.host;return n.version===1&&typeof n.generated_at=="string"&&t!=null&&typeof t=="object"&&Number.isInteger(t.pid)&&typeof t.daemon_version=="string"&&typeof t.protocol_version=="number"&&r!=null&&typeof r=="object"&&typeof r.stale=="boolean"&&typeof r.threshold_ms=="number"&&Array.isArray(r.unmeasured_workers)&&o!=null&&typeof o=="object"&&Number.isInteger(o.worker_count)&&Number.isInteger(o.project_count)&&typeof o.observed_rss_bytes=="number"&&Array.isArray(n.projects)&&Array.isArray(n.workers)&&(n.known_projects===void 0||Array.isArray(n.known_projects)&&n.known_projects.every(s=>typeof s=="string"))&&(n.registered_projects===void 0||Array.isArray(n.registered_projects)&&n.registered_projects.every(s=>typeof s=="string"))&&(n.repository_activity===void 0||ad(n.repository_activity))&&(n.github_balance===void 0||Uo(n.github_balance))&&(n.deaths===void 0||kg(n.deaths))&&(n.engine===void 0||Rg(n.engine))&&(n.metrics===void 0||ed(n.metrics))}function kg(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return Number.isInteger(n.count)&&Array.isArray(n.recent)}function Rg(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")}var fd={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};function Ne(e){return[...e].length}function G(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 Xo(e,n){return e+" ".repeat(Math.max(0,n-Ne(e)))}function U(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}function Vt(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 Fn(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return Vt(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 qt(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 Zo(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}var es="!unregistered",Bn="\u21E1",Me="\u2020",ln="\u25D0",an="\u25EF",ns="\u21B3",ts="redskilled unreachable \u2014 Worker state unknown";function dn(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Jt(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function Hn(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 rs(e){let n=[];return e.workers.length>0&&e.workers.length<=e.maxWorkers&&n.push("workers"),e.mode==="global"&&e.projects.length>0&&e.projects.length<=e.maxProjects&&n.push("projects"),n.push("host"),n}var j={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Ce(e,n=j){let t=Hn(e,n.project),r=dn(e,n),o=Jt(e,n),s=_g(e,n,r,t),i=rs({mode:n.mode,maxWorkers:n.maxWorkers,maxProjects:n.maxProjects,workers:r,projects:o}),a={detail:"host",line:s};for(let u of i){let f=Og(s,bg(u,n,r,o),n.separator);if(a={detail:u,line:f},Ne(f)<=n.maxWidth)break}let l=G(a.line,n.maxWidth),d=n.verbose&&a.detail==="workers"?jg(r,n):[],c=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!==c||l!==a.line,stale:e.staleness.stale,generated_at:e.generated_at}}function ss(e){let n=e.options??j,t=G(ts,n.maxWidth);return{version:1,line:t,lines:[t],verbose:n.verbose,mode:n.mode,project:n.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}function bg(e,n,t,r){return e==="workers"?t.map(o=>Pg(o,n)):e==="projects"?r.map(Dg):[]}function _g(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(os(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(os(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(os(e,n)),o.push(es)):o.push(vg(n.project,r)),o.push(wg(e));let s=xg(e);s!=null&&o.push(s);let i=Sg(e);return i!=null&&o.push(i),e.staleness.stale&&o.push(Eg(e)),o.join(" ")}function wg(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${Bn}`}function xg(e){let n=e.github_balance;return n==null?null:n.posture==="spent"?`${an} quota spent`:n.posture==="reserved"?`${ln} quota band`:null}function Sg(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Me}${n.count} ${n.latest.sender_class}`}function vg(e,n){return n==="unregistered"?`project unknown \u2014 ${e} is not registered on this host`:"project unknown \u2014 this directory resolved to no project"}function os(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,s)=>o+s.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${U(t)}/${U(r)}`:U(t)}function Eg(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function Pg(e,n){let t=Qt(e,n.mode),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?U(r):`${U(r)}/${U(e.budget.bytes)}`;return`${t} ${o}`}function jg(e,n){let t=[];for(let r of e){let o=Zo(r.log.last_line);o!=null&&t.push(G(` ${ns} ${Qt(r,n.mode)}: ${o}`,n.maxWidth))}return t}function Qt(e,n){return n==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Dg(e){return`${e.project_label} ${e.worker_count}w ${U(e.observed_rss_bytes)}`}function Og(e,n,t){return[e,...n].join(t)}var Un=["wid","run","org","iss","bar","phase","elapsed","hb","loc","tks","tls","rsn","txt"],Se={mode:"local",project:null,maxWidth:200,maxRows:16},Ag=" ",md="\u2588",Lg="\u25B6",Tg="\u2717",$g="\u2591";function zt(e,n=Se){let t=Hn(e,n.project),r=dn(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(u=>Ig(u,n)),i=Hg(s),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:s[f],line:G(Ug(s[f],i),n.maxWidth)})),l=Ng(e,n,r,t),d=r.length-o.length,c=[l.line,...a.map(u=>u.line)];return d>0&&c.push(G(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),c.push(...Cg(e,n)),c.push(...Mg(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Un,header:l,rows:a,lines:c,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Ig(e,n){let t=e.display??fd,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:hd(t),phase:[t.phase,t.step].filter(o=>!!o).join("\xB7"),elapsed:qt(e.uptime_ms),hb:`hb=${t.heartbeat??"?"}`,loc:Bg(t.added,t.removed),tks:t.tokens==null?"":`tks=${Vt(t.tokens)}`,tls:t.tools==null?"":`tls=${t.tools}`,rsn:t.reasoning==null?"":`rsn=${t.reasoning}`,txt:t.text==null?"":`txt=${t.text}`}}function hd(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 md.repeat(Math.floor(n));let o=e.failed?Tg:Lg;return`${md.repeat(r)}${o}${$g.repeat(Math.floor(n)-r-1)}`}function Ng(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(w=>w.project_label===n.project),s={open_pull_requests:o?.counts?.open_pull_requests??null,recently_closed:o?.counts?.recently_closed??null,open_issues:o?.counts?.open_issues??null,stale:o?.stale===!0},i={memory_used_fraction:e.host.ceiling_used_fraction,memory_used_bytes:e.host.consumption.memory_bytes,memory_ceiling_bytes:e.host.ceiling.memory_bytes,worker_count:e.host.worker_count,worker_ceiling:e.host.ceiling.worker_count},a=Fg(t),l=o?.repository??n.project,d=e.engine??null,c=d?.running_version??e.daemon.daemon_version,u=e.deaths??null,f=e.metrics??null,m=[`\xBB ${l??"host"} v${c}${d!=null&&d.current===!1?Bn:""}`];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(i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`),m.push(Wg(i)),s.open_pull_requests!=null&&m.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&m.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&m.push(`iss=${s.open_issues}`),s.stale&&m.push("!counts stale");let h=f==null?null:yd(f.hour);if(h!=null&&m.push(h),u!=null&&u.count>0&&u.latest!=null&&m.push(`${Me}${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&&Ne(b)>n.maxWidth?m.filter(w=>w!==h).join(" \xB7 "):b;return{repo:l,project:n.project,project_match:r,version:c,engine:d,deaths:u,metrics:f,model:a,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:G(k,n.maxWidth)}}function yd(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${Fn(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${Fn(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${Fn(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 Mg(e,n){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let r=t.posture==="spent"?an:ln,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[G(`${r} github budget ${t.posture}${o} \u2014 ${t.reason}`,n.maxWidth)]}function Cg(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(s=>G(`${Me} ${s.kind} ${s.id} pid=${s.pid} ${s.sender_class}/${s.confidence} phase=${s.last_phase}`+(s.signal==null?"":` signal=${s.signal}`)+(s.evidence==null?"":` \u2014 ${s.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(G(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function Wg(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${U(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${U(e.memory_used_bytes)}/${U(e.memory_ceiling_bytes)}${n}`}function Fg(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 Bg(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 Hg(e){let n=Object.fromEntries(Un.map(t=>[t,0]));for(let t of e)for(let r of Un)n[r]=Math.max(n[r],Ne(t[r]));return n}function Ug(e,n){return Un.filter(r=>n[r]>0).map(r=>Xo(e[r],n[r])).join(Ag).replace(/\s+$/,"")}var Yt=1;async function Gn(e,n){return await vt(e,n,"redskilled daemon")}function kd(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:Yt,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:qg(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:na(n,{hostCeilingBytes:e.hostCeilingBytes??null}),upgrade:Jg(e)}}function qg(e){let n=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(n),r=e.queue??null,o=new Map(r==null?[]:r.projects.map(s=>[s.project_label,s]));return[...e.registrations??[]].map(s=>{let i=o.get(s.project_label);return{...s,...t?{renewal:Ta(s,n)}:{},...r==null||i==null?{}:{last_poll:{at:r.fetched_at,outcome:i.outcome,depth:i.depth,request_count:r.request_count,detail:i.detail}}}}).sort((s,i)=>s.project_label.localeCompare(i.project_label))}function Jg(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 Rd(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)&&ta(n.budget_accounting)&&(n.scope===void 0||ja(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every($o))&&(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||zg(n.major_hold))}function zg(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 er}from"node:child_process";import{existsSync as cs}from"node:fs";import{delimiter as sk,join as Dd}from"node:path";import{join as bd}from"node:path";import{existsSync as Yg}from"node:fs";import{createRequire as Xg}from"node:module";var _d="redskilled-job-object.node",We=100;function cn(e){return{available:!1,reason:e}}function Zg(e,n,t){return[bd(t,"prebuilds",`${e}-${n}`,_d),bd(t,"native","build","Release",_d)]}function wd(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return cn(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??nk(),o=e.exists??Yg,s=Zg(n,t,r),i=s.find(d=>o(d));if(i==null)return cn(`no Job Object addon was found for ${n}-${t} (looked in ${s.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let a=e.requireFn??Xg(import.meta.url),l;try{l=a(i)}catch(d){return cn(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return ek(l)?{available:!0,binding:l}:cn(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function ek(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function nk(){return new URL("..",import.meta.url).pathname}function xd(e){let n=e??{},t=[],r=tk(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<We?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 ${We}, 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 tk(e){return Cn({budget:e})}var Xt=5,Sd=19;function is(e){return{available:!1,reason:e}}var rk="an address-space rlimit is not a resident-memory ceiling: a runtime that reserves address space it never faults in would die under a limit it never used, so no memory rlimit is set and the daemon's RSS sampling floor is the ceiling that actually holds";function Ed(e,n){let t=e??{},r=[],o;if(!n.canRenice)r.push("nice is not on this host, so no priority control was applied and the Worker competes with interactive work");else if(t.cpu_weight==null)o=Xt;else if(t.cpu_weight<We){let a=Math.round(Sd*(We-t.cpu_weight)/We);o=Math.min(Sd,Math.max(Xt,a))}else o=Xt,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${We}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Xt}`);let s=vd(t.max_processes);s==null&&t.max_processes!=null&&r.push(`max_processes=${t.max_processes} is not a positive whole number, so no ulimit -u is set`);let i=vd(t.cpu_seconds);return i==null&&t.cpu_seconds!=null&&r.push(`cpu_seconds=${t.cpu_seconds} is not a positive whole number, so no ulimit -t is set`),{...o!=null?{nice:o}:{},...s!=null?{max_processes:s}:{},...i!=null?{cpu_seconds:i}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:rk,...r.length>0?{note:r.join("; ")}:{}}}function Pd(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 ${ok(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
71
- `),e.command,...e.args]}function jd(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 ls(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 vd(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function ok(e){return`'${e.replace(/'/g,"'\\''")}'`}var Od="REDSKILLED_PLACEMENT",Zt="red-worker",as="/bin/sh";function Ad(e=process.env,n=process.platform){let t=is(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:wd({platform:n}),posix:t};let r=cn(`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:ik(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&cs(Dd(o,"systemd","private"));return{platform:n,systemdRun:Id("systemd-run",e),userSession:s,jobObjects:r,posix:t}}function ik(e){return cs(as)?{available:!0,shell:as,nice:Id("nice",e)}:is(`no POSIX shell was found at ${as}, so there is nothing to apply rlimits or priority in`)}function Ld(e=process.env){let n=(e[Od]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function lk(e,n,t=Zt){return Td(e,n,t).replace(/\.service$/,"")}function Td(e,n,t=Zt){return`${ds(t,"red-worker",24)}-${ds(e,"project",32)}-${ds(n,"worker",32)}.service`}function $d(e){let n=[...e.args??[]],t={...e.budget??{},...e.budget?.memory_max==null&&e.memoryCeiling?.memory_max!=null?{memory_max:e.memoryCeiling.memory_max}:{}},r=t.memory_max??t.memory_high??null,o=t.memory_high!=null||t.memory_max!=null||t.cpu_weight!=null,s=e.target??{isolation:"transient-unit"},i=u=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:u,budget:t,...r!=null?{memoryCeiling:r}:{},environment:On({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(s.isolation==="inherit")return i("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return i(`worker isolation disabled by ${Od}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return dk(e,n,t,r,o,i);if(e.probes.platform==="darwin")return ak(e,n,t,r,i);if(e.probes.platform!=="linux")return i(`transient-unit placement is the Linux backend (platform=${e.probes.platform}): the Worker is charged to the daemon's own resource group`);if(!e.probes.systemdRun)return i("transient-unit placement unavailable: systemd-run is not on PATH; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");if(!e.probes.userSession)return i("transient-unit placement unavailable: no systemd --user session; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");let a=Td(e.projectLabel,e.workerId,s.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=On({scope:a,memory_ceiling:r,scope_degradation:null});for(let[u,f]of Object.entries({...e.env??{},...d}))l.push(`--setenv=${u}=${f}`);let c=ls(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,...c!=null?{budgetWarning:c}:{}}}function ak(e,n,t,r,o){let s=e.probes.posix;if(!s.available)return o(`POSIX limit placement unavailable: ${s.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let i=Ed(t,{canRenice:s.nice!=null}),a=t.memory_high!=null||t.memory_max!=null,l=jd(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:Pd({limits:i,nice:s.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:i,warning:l,budget:t,...r!=null?{memoryCeiling:r}:{},environment:On({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: "+i.memory_ceiling_reason}:{}}}function dk(e,n,t,r,o,s){let i=e.probes.jobObjects;if(!i.available)return s(`Job Object placement unavailable: ${i.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let a=xd(t),l=lk(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:On({scope:l,memory_ceiling:r,scope_degradation:null}),...ck(o&&a.note!=null?`${a.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,ls(e.budget))}}function ck(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function Id(e,n){for(let t of(n.PATH??"").split(sk)){if(!t)continue;let r=Dd(t,e);if(cs(r))return r}return null}function ds(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function us(e,n){let t=[],r=[];for(let o of e){let s=!1;try{s=await n(o)===!0}catch{s=!1}(s?t:r).push(o)}return{alive:t,dead:r}}var Nd=3e4;function Md(e){return e.unit!=null&&e.unit!==""?uk(e.unit):B(e.pid)}function uk(e){let n=er("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var pk="REDSKILLED_UNIT_DISCOVERY",Cd="(unowned)";function Wd(e){let n=er("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 fk(e=process.env){let n=(e[pk]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Fd(e,n,t=process.env){return fk(t)&&e===n}function Bd(e=Zt){let n=er("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return n.error!=null||n.status!==0?[]:(n.stdout??"").split(`
72
- `).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function Hd(e){let n=new Set(e.held.map(o=>o.unit).filter(o=>o!=null&&o!=="")),t=new Set,r=[];for(let o of e.units)o===""||n.has(o)||t.has(o)||(t.add(o),r.push({worker_id:o.replace(/\.service$/,""),project_label:Cd,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 Ud(e){return e.project_label.trim()!==""?e:{...e,project_label:Cd,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 Gd(e){if(e.unit!=null&&e.unit!==""){let n=er("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 mk(e,n=50){if(Jd(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 hk(e,n={}){let t=n.batchSize??50;if(Jd(e),e.length>t)throw new Error(`redskilled queue discovery spans at most ${t} selectors in one query, and this batch holds ${e.length}: split it with planQueueDiscoveryBatches rather than dropping the remainder`);let r=e.map((i,a)=>({alias:`q${a}`,project:i}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...r.map(({alias:i,project:a})=>` ${i}: search(query: ${JSON.stringify(a.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
73
- `),aliases:r}}function yk(e,n){let t=Kn(n),r=Kn(t.data),o=Array.isArray(t.errors)?t.errors.map(Kn):[],s=kk(r.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let d=bk(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 c=o.find(u=>Rk(u.path,a));return s.exhausted||Qd(c)?{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`+(s.reset_at==null?"":`; the quota resets at ${s.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: ${ps(c?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function gk(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 Vd(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 qd(e){if(e.projects.length===0)return gk(e.now);let n=e.batchSize??50,t=mk(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=hk(s,{batchSize:n});try{let a=await e.transport(i.query),l=yk(i,a);r.push(...l.projects),o=Kd(o,l.rate_limit)}catch(a){let l=a instanceof Error?a.message:String(a),d=/rate limit|secondary rate|429/i.test(l);o=Kd(o,{remaining:null,reset_at:null,exhausted:d});for(let c of s)r.push({project_label:c.project_label,outcome:d?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(c.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 Jd(e){if(e.length===0)throw new Error("redskilled queue discovery needs at least one registered project");let n=new Set;for(let t of e){if(typeof t.project_label!="string"||t.project_label==="")throw new Error("redskilled queue discovery needs a project label for every registered project");if(typeof t.selector!="string"||t.selector==="")throw new Error(`redskilled queue discovery needs a selector for project ${JSON.stringify(t.project_label)}: a project that names no work has no queue to discover`);if(n.has(t.project_label))throw new Error(`redskilled holds one selector per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function Kd(e,n){return{remaining:n.remaining==null?e.remaining:e.remaining==null?n.remaining:Math.min(e.remaining,n.remaining),reset_at:n.reset_at??e.reset_at,exhausted:e.exhausted||n.exhausted}}function kk(e,n){let t=Kn(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(Qd)||r===0}}function Qd(e){return e==null?!1:ps(e.type)==="RATE_LIMITED"||/rate limit/i.test(ps(e.message))}function Rk(e,n){return Array.isArray(e)&&e.includes(n)}function bk(e){let n=Kn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Kn(e){return _k(e)?e:{}}function _k(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ps(e){return typeof e=="string"?e:""}var wk={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},xk=["runner","model","effort","origin","issue","phase","step","heartbeat"],Sk=["phase_index","phase_total","added","removed","tokens","tools","reasoning","text"];function zd(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...wk};for(let r of xk){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of Sk){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}import{randomUUID as Zd}from"node:crypto";import{spawn as jk}from"node:child_process";import{closeSync as Dk,mkdirSync as Ok,openSync as Ak}from"node:fs";import{dirname as Lk}from"node:path";import{delimiter as Yd,dirname as vk}from"node:path";function Ek(e,n=Yd){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function Pk(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=vk(n);return t===""||t==="."?null:t}function Xd(e,n=process.execPath,t=Yd){let r=Ek(e,t),o=Pk(n);return o==null?r.join(t):[o,...r.filter(s=>s!==o)].join(t)}var Vn=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},nr=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function Tk(e){if(e==null||e.trim()==="")return null;try{return Ok(Lk(e),{recursive:!0}),Ak(e,"a")}catch{return null}}function $k(e){try{Dk(e)}catch{}}function Ik(e){let n=[["project_label",e.project_label],["workspace_path",e.workspace_path],["command",e.command]];for(let[t,r]of n)if(typeof r!="string"||r.trim()==="")throw new Vn(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new Vn("redskilled worker spec args must be an array")}function Nk(e){if(e==null)throw new nr("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new nr(e.reason,e)}function nc(e){let{spec:n,admission:t}=e;Nk(t),Ik(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(n.worker_id??e.workerId??Zd()).trim()||Zd(),i=e.probes??Ad(r),a=e.openLog===!1?null:Tk(n.log_path),l={...n.env??{},PATH:Xd(n.env?.PATH??r.PATH,e.execPath??process.execPath)},d=$d({workerId:s,projectLabel:n.project_label,workspacePath:n.workspace_path,command:n.command,args:n.args,budget:n.budget,...e.memoryCeiling!=null?{memoryCeiling:e.memoryCeiling}:{},target:n.placement,env:l,enabled:e.enabled??Ld(r),probes:i,pipeOutput:a!==null}),u=(e.spawnFn??jk)(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&&$k(a),u.pid==null)throw u.once("error",()=>{}),new Vn(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${s}`);let f=d.job!=null?Mk(d,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(k,w)=>{try{f?.job?.close()}catch{}e.onExit?.(s,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:s,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 Mk(e,n,t){let r=e.job;if(r==null)return{};let o="the Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling";if(!n.jobObjects.available)return{warning:`Job Object placement unavailable: ${n.jobObjects.reason}. ${o}`};let s;try{s=n.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(i){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${ec(i)}. ${o}`}}try{s.assign(t)}catch(i){try{s.close()}catch{}return{warning:`Worker pid ${t} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${ec(i)}. ${o}`}}return{job:s}}function ec(e){return e instanceof Error?e.message:String(e)}import{open as Ck,stat as Wk}from"node:fs/promises";var Fk=16*1024;async function tc(e,n=Fk){let t;try{t=(await Wk(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let s=await Ck(e,"r");try{let i=Buffer.alloc(r);await s.read(i,0,r,t-r),o=i.toString("utf8")}finally{await s.close()}}catch{return null}return Bk(o)}function Bk(e){let n=e.split(`
74
- `);for(let t=n.length-1;t>=0;t-=1){let r=n[t].replace(/\r$/,"");if(r.trim()!=="")return r}return null}import{spawn as tR}from"node:child_process";import{existsSync as rR,readdirSync as oR}from"node:fs";import{dirname as sR,join as ac,resolve as iR}from"node:path";var Hk="<version>";function ve(e,n=[],t){let r=t&&t.trim().length>0?t.trim():Hk;return[`npx -y -p ${$e}@${r}`,e,...n].join(" ")}function ee(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 fs(e,n){let t=ee(e),r=ee(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var _E=4*60*60*1e3;me();me();import{spawnSync as Uk}from"node:child_process";import{mkdir as Gk,rm as Kk,writeFile as Vk}from"node:fs/promises";import{existsSync as qk}from"node:fs";import{homedir as Jk}from"node:os";import{dirname as Qk,join as ms}from"node:path";var un="redskilled.service",hs="REDSKILLED_SUPERVISED",zk="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function Yk(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||ms(e.HOME?.trim()||Jk(),".config");return ms(n,"systemd","user")}function ys(e=process.env){return ms(Yk(e),un)}function rc(e,n={}){let t=n.env??process.env,r=Dt(n.override??{},n.entryLookup??{}),o=[...r.args,...Te(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:un,unitPath:ys(t),command:r.command,args:o,text:Xk(r.command,o,e)}}function Xk(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${zk}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(Zk).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${hs}=1"`,`Environment="REDSKILLED_SESSION=${oc(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
75
- `)}function Zk(e){return/[\s"'\\$%]/.test(e)?`"${oc(e)}"`:e}function oc(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function sc(e,n={}){let t=n.writeFile??eR,r=n.run??gs,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(tr("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(tr("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function ic(e={}){let n=e.removeFile??nR,t=e.run??gs,r=ys(e.env??process.env),o=[tr("disable",t,["systemctl","--user","disable","--now",un])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(tr("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function lc(e={}){let n=e.exists??qk,t=e.run??gs,r=ys(e.env??process.env),o=n(r);return{unitName:un,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",un]).status===0,active:o&&t(["systemctl","--user","is-active",un]).status===0,floor:"auto-spawn"}}function tr(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 eR(e,n){await Gk(Qk(e),{recursive:!0}),await Vk(e,n,{encoding:"utf8",mode:420})}async function nR(e){await Kk(e,{force:!0})}function gs(e){let n=Uk(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 dc=75,uc=9e5,cc="redskilled-replacement-entry-unresolved",lR="REDSKILLED_NO_REGISTRY_PROBE",pc="REDSKILLED_BORN_BY_REPLACEMENT";function fc(e=process.env){return e[pc]==="1"}function mc(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function hc(e){let n=e.running.trim();if(qn(n))return null;let t=e.newest?.trim()??"",r=ee(t),o=ee(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:aR(r.major,e.supervised)}}function aR(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: ${ve("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 yc(e){let n=e.running.trim();if(qn(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||ee(t)===null?{act:"hold",reason:"published-unknown"}:fs(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function qn(e){let n=e.trim();return ee(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function gc(e=process.env){return e[hs]==="1"}var ks=class extends Error{code=cc;searched;constructor(n,t){super(`${cc}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
65
+ `).filter(eg).map(ng)}function ga(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,Xh(t)):n.delete(t.worker_id));return[...n.values()]}function Xh(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 Zh(e){return{...e}}function eg(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 ng(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:ye(e.project_label)??"",pid:Number(e.pid??0),workspace_path:ye(e.workspace_path)??"",log_path:ye(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:ye(e.unit),memory_high:ye(e.memory_high),memory_max:ye(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:ye(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:ye(e.signal),reason:ye(e.reason)}}function ye(e){return e==null||e===""?null:String(e)}function ya(e){let n=[...e.projects].sort((i,l)=>i.project_label.localeCompare(l.project_label)),t=e.backoffUntilMs??null,r=t!=null&&e.nowMs<t,o=[],s=[];for(let i of n){let l=Math.max(0,e.live[i.project_label]??0),a=Object.prototype.hasOwnProperty.call(e.queue,i.project_label),d=a?e.queue[i.project_label]??null:null,c={project_label:i.project_label,queue_depth:d,target:i.target,live:l};if(r){o.push({...c,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?.[i.project_label];if(u!=null&&e.nowMs<u){o.push({...c,outcome:"birth-halted",wanted:0,detail:`project ${JSON.stringify(i.project_label)} lost 3 Workers in a row inside 60000ms of birth, so it is not asked for another before ${new Date(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({...c,outcome:"queue-unknown",wanted:0,detail:a?`the last poll produced no depth for project ${JSON.stringify(i.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(i.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...c,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(i.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,i.target),d)-l);if(f===0){o.push({...c,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for none`});continue}o.push({...c,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for ${f} more`});for(let m=0;m<f;m+=1)(s[m]??(s[m]=[])).push({project_label:i.project_label,index:l+m,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function ka(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}var Nt={shortLifeStreak:0,haltUntilMs:null};function Ra(e,n,t){if(n>=6e4)return Nt;let r=e.shortLifeStreak+1;return r<3?{shortLifeStreak:r,haltUntilMs:null}:{shortLifeStreak:r,haltUntilMs:t+6e5}}function ba(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 wa(e){let n=e.workers.map(tg),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:og({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function xa(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 tg(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 rg(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 og(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${rg(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${_a(e.held,"Worker")} across ${_a(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 _a(e,n){return`${e} ${n}${e===1?"":"s"}`}function Eo(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 sg,mkdir as ig,readFile as lg,rm as ag,writeFile as dg}from"node:fs/promises";import{dirname as Sa,join as ja}from"node:path";import{tmpdir as va}from"node:os";var cg="redskilled.machine.claim.toon",ug="REDSKILLED_MACHINE_DIR",pg=8,Se=class extends Error{constructor(t,r,o){super(mg(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},Ea;function Da(){return Ea??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},Ea}function fg(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[ug]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||va():va();return ja(o,`redskilled-${e.machineIdHash}`)}function Mt(e){return ja(fg(e),cg)}function Ct(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??B;async function s(){let a;try{a=await lg(e,"utf8")}catch(c){if(c.code==="ENOENT"||Po(c))return;throw c}let d=gg(a);return yg(d)?d:void 0}function i(a,d){return{version:1,scope:"machine",pid:a.pid,start_time:a.startTime,uid:a.uid,machine_id_hash:n.machineIdHash,session_key_hash:n.sessionKeyHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}async function l(){try{return await ag(e,{force:!0}),!0}catch(a){if(Po(a))return!1;throw a}}return{claimPath:e,read:s,async claim(a){await ig(Sa(e),{recursive:!0,mode:1023})!=null&&await sg(Sa(e),1023).catch(()=>{});let c=!1;for(let u=0;u<pg;u+=1){let f=i(a,r());try{return await dg(e,hg(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:c,claim:f}}catch(h){if(h.code!=="EEXIST"){if(Po(h))return{claimed:!1,reason:"stale-claim-not-reapable"};throw h}}let m=await s();if(!m){if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable"};c=!0;continue}if(Pa(m,a,n.socketPath))return{claimed:!0,reaped:c,claim:m};if(await o(m.pid))return{claimed:!1,reason:"held",claim:m};if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable",claim:m};c=!0}return{claimed:!1,reason:"contended"}},async release(a){let d=await s();return!d||!Pa(d,a,n.socketPath)?!1:await l()}}}function Oa(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 Aa(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 mg(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 Po(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function Pa(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function hg(e){return`${C(e,{keyedMapCollapse:!0})}
66
+ `}function gg(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return q(n)}catch{return null}}}function yg(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 kg=["worker_id","slot","workspace_path","log_path"],jo=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${kg.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},Rg=/\{\{([a-z_]+)\}\}/g;function bg(e,n){let t=(i,l)=>i.replace(Rg,(a,d)=>{switch(d){case"worker_id":return n.worker_id;case"slot":return String(n.slot);case"workspace_path":return n.workspace_path;case"log_path":return n.log_path??"";default:throw new jo(d,l)}}),r=e.argv.map((i,l)=>t(i,`argv word ${l}`)),o={};for(let[i,l]of Object.entries(e.env??{}))o[i]=t(l,`env entry ${JSON.stringify(i)}`);let s=e.log_path==null?void 0:t(e.log_path,"the log path");return{argv:r,env:o,...s==null||s===""?{}:{log_path:s}}}function La(e,n,t){let r=bg(e,n),o=r.log_path??n.log_path,[s,...i]=r.argv;if(s===void 0||s==="")throw new Error(`redskilled cannot start a Worker for project ${JSON.stringify(t.project_label)}: its launch expanded to an argv with no command`);return{worker_id:n.worker_id,project_label:t.project_label,workspace_path:n.workspace_path,...o==null||o===""?{}:{log_path:o},command:s,args:i,env:r.env}}function Do(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 Oo(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 Ao(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 _g=3e5,wg=.5,To=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 Ta(e,n){if(n.held!=null)throw new To(n.held);let t=Lo(e.project_label,"a project label"),r=Lo(e.selector,"a selector"),o=Do(e.argv,t),s=Ao(e.env,t),i=Oo(e.log_path,t),l=Lo(e.workspace_path,`a workspace path for project ${JSON.stringify(t)}`);if(!Number.isInteger(e.target)||e.target<0)throw new Error(`redskilled needs a whole, non-negative target to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.target)}`);let a=e.renew_within_ms??_g;if(!Number.isFinite(a)||a<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let d=Date.parse(n.now);if(!Number.isFinite(d))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(n.now)}`);return{version:1,project_label:t,selector:r,argv:o,workspace_path:l,env:s,...i==null?{}:{log_path:i},target:e.target,registered_at:new Date(d).toISOString(),renew_within_ms:a,renew_by:new Date(d+a).toISOString(),renewed_at:new Date(d).toISOString(),renewals:0,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 $a(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:Do(n.launch.argv,e.project_label),env:Ao(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=n.launch==null?e.log_path:Oo(n.launch.log_path,e.project_label),{log_path:i,...l}=e;return{...l,...s==null?{}:{log_path:s},...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1}}function Ia(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(n.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,n.liveWorkers??0),s=n.queue,i=s!=null&&s.outcome==="counted"?s.depth:null,l=i!=null&&i>0?"open-work":o>0?"live-worker":null;if(l==null){let a=i===0?"drained":"uncounted";return{registration:e,verdict:a,detail:a==="drained"?`project ${r} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${r}, and an uncounted queue never sustains a registration \u2014 it stands on its own deadline of ${e.renew_by}`}}return{registration:{...e,renew_by:new Date(t+e.renew_within_ms).toISOString(),sustained_at:new Date(t).toISOString(),sustains:(e.sustains??0)+1,sustained_by:l},verdict:l,detail:l==="open-work"?`project ${r} has ${i} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function xg(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function Na(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*wg;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 Ma(e,n){let t=[],r=[];for(let o of e)(xg(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function $o(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||Sg(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 Sg(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function Lo(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var vg={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 Ca(e){return`worker-${e}`}function Wa(e){let n=vg[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 Fa(e){return e==="single-object"?"rest":"graphql"}function T(e,n,t,r,o){return{key:e,kind:"read",cardinality:n,surface:o??Fa(n),budget:t,...o?{only:o}:{},why:r}}function H(e,n,t,r){return{key:e,kind:"write",cardinality:"single-object",surface:n,budget:t,why:r}}var Ba=[T("issue view","single-object","rest","one issue by number; REST answers it in one request against the idle pool"),T("pr view","single-object","rest","one pull request by number, polled per Worker per iteration"),T("repo view","single-object","rest","one repository's own metadata"),T("run view","single-object","rest","one Actions run; the Actions API has no GraphQL surface either way"),T("release view","single-object","rest","one release by tag"),T("pr diff","single-object","rest","one pull request's diff, served by a REST media type"),T("issue list","multi-node","graphql","a connection of issues; one GraphQL query beats N REST pages"),T("pr list","multi-node","graphql","a connection of pull requests; one GraphQL query beats N REST pages"),T("pr checks","multi-node","graphql","every check context on one commit, which is a connection, not an object"),T("release list","multi-node","rest","Releases have no GraphQL connection gh reads; REST pages them","rest"),T("run list","multi-node","rest","the Actions API has no GraphQL surface, so a listing draws the request pool","rest"),T("label list","multi-node","graphql","a connection of labels inside one repository"),T("issue list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),T("pr list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),T("search issues","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("search prs","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("search repos","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),T("api graphql","multi-node","graphql","the caller wrote the query; `gh api graphql` is GraphQL by construction"),T("api rest","single-object","rest","any `gh api <path>` that is not `graphql` is a REST request"),H("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),H("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),H("issue close","graphql","graphql","gh closes with the closeIssue mutation"),H("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),H("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),H("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),H("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),H("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),H("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),H("pr close","graphql","graphql","gh closes with a GraphQL mutation"),H("pr edit","graphql","graphql","gh edits with GraphQL mutations"),H("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),H("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),H("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],Eg=new Map(Ba.map(e=>[e.key,e]));function Ha(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 Io(e){let n=Ha(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 Ft=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(n){let t=Io(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 Ua(e){return Eg.get(Io(e))??null}function Ga(e){let n=Ua(e);if(!n)throw new Ft(e);return n}function No(e){return Ga(e).surface}var Va="rate_limit",qa={rest:"core",graphql:"graphql",search:"search"},ke=["rest","graphql","search"];function Gt(e,n){return{version:1,origin:"asked",outcome:"unanswered",source:"GET /rate_limit",asked_at:e,request_count:0,pools:{rest:null,graphql:null,search:null},unreported_pools:[...ke],detail:n??"no balance has been asked for yet, so none is known"}}var Co=15e3,on=.15,Ht=[{at_or_below_fraction:0,every_ms:Co,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:on,every_ms:3e4,why:"inside the reserved band: the posture can change between two calls"},{at_or_below_fraction:.5,every_ms:12e4,why:"below half: tightening, because the band is now reachable inside one window"},{at_or_below_fraction:1,every_ms:6e5,why:"above half: rare, because nothing this balance decides is anywhere close"}],Mo=2;function Ja(e,n){let t=Ka(e),r=Ka(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let l of ke){let a=qa[l],d=r[a],c=Dg(l,a,d);o[l]=c,c==null&&s.push(l)}let i=ke.length-s.length;return{version:1,origin:"asked",outcome:i>0?"asked":"unanswered",source:"GET /rate_limit",asked_at:n.askedAt,request_count:1,pools:o,unreported_pools:s,detail:i>0?`the token's own answer for ${i} of ${ke.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function Wo(e){try{let n=await e.transport();return Ja(n,{askedAt:e.now})}catch(n){let t=n instanceof Error?n.message:String(n);return{...Gt(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function Fo(e){let n=null;for(let t of ke){let r=e.pools[t];r!=null&&(n==null||r.fraction<n.fraction)&&(n=r)}return n}function Kt(e,n){let t=Fo(e);if(t==null)return Ut(on).every_ms;let r=Ut(t.fraction);if(t.remaining>0)return r.every_ms;let o=za(n.now,t.reset_at);return o==null?r.every_ms:Math.max(Co,Math.min(r.every_ms,o))}function Bo(e,n=on){return Math.ceil(e.limit*n)}function Qa(e,n,t=on){let r=e.pools[n];return r==null?"unknown":r.remaining<=0?"spent":r.remaining<Bo(r,t)?"reserved":"open"}function Ho(e){let n=e.reservedFraction??on,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:Ut(n).every_ms*Mo,stale:!1,posture:"unknown",reserved_fraction:n,next_poll_ms:Ut(n).every_ms,pools:[],unreported_pools:[...ke],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let r=Kt(t,{now:e.now}),o=e.stalenessMs??r*Mo,s=za(t.asked_at,e.now),i=t.outcome==="asked"&&(s==null||s>o),l=ke.map(c=>t.pools[c]).filter(c=>c!=null),a=jg(t,n),d=Fo(t);return{version:1,origin:"asked",outcome:t.outcome,asked_at:t.asked_at,age_ms:s,threshold_ms:o,stale:i,posture:a,reserved_fraction:n,next_poll_ms:r,pools:l,unreported_pools:t.unreported_pools,reason:i?`this balance is stale: asked ${s==null?"at an unreadable instant":`${s}ms ago`}, past the ${o}ms window, so the posture below is the last one the token confirmed and not the current one`:Pg(a,d,t,n)}}function Uo(e){if(!Ko(e))return!1;let n=e;return n.version===1&&n.origin==="asked"&&(n.outcome==="asked"||n.outcome==="unanswered")&&(n.asked_at===null||typeof n.asked_at=="string")&&(n.age_ms===null||typeof n.age_ms=="number")&&typeof n.threshold_ms=="number"&&typeof n.stale=="boolean"&&typeof n.posture=="string"&&typeof n.reserved_fraction=="number"&&typeof n.next_poll_ms=="number"&&Array.isArray(n.pools)&&Array.isArray(n.unreported_pools)&&typeof n.reason=="string"}function Pg(e,n,t,r){if(n==null)return t.detail;let o=Bo(n,r);switch(e){case"spent":return`the ${n.pool} pool is spent and resets at ${n.reset_at}: work is not queued, it is refused`;case"reserved":return`the ${n.pool} pool has ${n.remaining} of ${n.limit} left, inside the reserved band of ${o}: convenience reads are refused and the claim, a landing and a closing comment still pass`;default:return`the ${n.pool} pool is the tightest at ${n.remaining} of ${n.limit}, above the reserved band of ${o}`}}function jg(e,n){let t="unknown";for(let r of ke){if(e.pools[r]==null)continue;let o=Qa(e,r,n);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function Ut(e){for(let n of Ht)if(e<=n.at_or_below_fraction)return n;return Ht[Ht.length-1]}function Dg(e,n,t){if(!Ko(t))return null;let r=Bt(t.limit),o=Bt(t.remaining),s=Bt(t.used),i=Bt(t.reset);return r==null||r<=0||o==null?null:{pool:e,resource:n,limit:r,remaining:o,used:s??0,reset_at:i==null?"":new Date(i*1e3).toISOString(),fraction:o/r}}function Go(e){let n=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let r=await t(`${n}/${Va}`,{method:"GET",headers:{authorization:`bearer ${e.token}`,accept:"application/vnd.github+json"}});if(!r.ok)throw new Error(`the balance ask was refused with HTTP ${r.status}`);return await r.json()}}function za(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 Bt(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function Ka(e){return Ko(e)?e:{}}function Ko(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function td(e){return{generated_at:e.now,hour:Ya("hour",36e5,e),day:Ya("day",864e5,e)}}function Vt(e,n,t){let r=Cn(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(l=>{let a=Cn(n(l));return a==null?!1:r==null||r-a<=o});return i.length<=s?i:i.slice(i.length-s)}function Ya(e,n,t){let r=Cn(t.now),o=r==null?null:r-n,s=e==="hour"?"1h":"24h",i=t.observations.map(u=>({observation:u,at:Cn(u.observed_at)})).filter(u=>u.at!=null&&ed(u.at,o,r)).sort((u,f)=>u.at-f.at),l=t.outcomes.map(u=>Cn(u.ts)).filter(u=>u!=null&&ed(u,o,r)),a=Xa(i,u=>u.tokens,"tokens",s),d=Xa(i,u=>u.tools,"tools",s),c=[];return i.length===0?c.push("worker-vitals"):(a.samples===0&&c.push("worker-vitals.tokens"),d.samples===0&&c.push("worker-vitals.tools")),l.length===0&&c.push("worker-outcomes"),{window:e,window_ms:n,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:a,tools_per_min:d,issues_per_hour:Og(l.length,n,s),runner_share:Za("runner",i,u=>u.runner,s),model_share:Za("model",i,u=>u.model,s),unavailable:c}}function Xa(e,n,t,r){let o=new Map,s=0;for(let d of e){let c=n(d.observation);if(c==null||!Number.isFinite(c))continue;s+=1;let u=o.get(d.observation.worker_id)??[];u.push({at:d.at,count:c}),o.set(d.observation.worker_id,u)}if(s===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${r}`,samples:0};let i=0,l=null,a=null;for(let d of o.values()){if(d.length<2)continue;for(let f=1;f<d.length;f++){let m=d[f-1],h=d[f];m==null||h==null||(i+=Math.max(0,h.count-m.count))}let c=d[0],u=d[d.length-1];c!=null&&(l=l==null?c.at:Math.min(l,c.at)),u!=null&&(a=a==null?u.at:Math.max(a,u.at))}return l==null||a==null||a<=l?{value:null,absent_reason:`the last ${r} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:s}:{value:i/((a-l)/6e4),absent_reason:null,samples:s}}function Og(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 Za(e,n,t,r){let o=new Map;for(let d of n){let c=t(d.observation);c!=null?o.set(d.observation.worker_id,c):o.has(d.observation.worker_id)||o.set(d.observation.worker_id,null)}let s=new Map,i=0,l=0;for(let d of o.values()){if(d==null){l+=1;continue}i+=1,s.set(d,(s.get(d)??0)+1)}let a=[...s.entries()].map(([d,c])=>({key:d,worker_count:c,share:c/i})).sort((d,c)=>c.worker_count-d.worker_count||d.key.localeCompare(c.key));return{dimension:e,attributed_workers:i,unattributed_workers:l,shares:a,absent_reason:a.length>0?null:o.size===0?`no Worker was observed in the last ${r}`:`no Worker published a ${e} in the last ${r}`}}function ed(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function Cn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function rd(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.generated_at=="string"&&nd(n.hour)&&nd(n.day)}function nd(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.window=="string"&&typeof n.window_ms=="number"&&Vo(n.tokens_per_min)&&Vo(n.tools_per_min)&&Vo(n.issues_per_hour)&&Array.isArray(n.unavailable)}function Vo(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return(n.value===null||typeof n.value=="number")&&(n.absent_reason===null||typeof n.absent_reason=="string")&&Number.isInteger(n.samples)}import{execFileSync as Ag}from"node:child_process";import{existsSync as Lg,readFileSync as qt,readdirSync as Tg}from"node:fs";import{dirname as $g,join as Ie}from"node:path";function Wn(e){let n=Mn(e),t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let s=rn(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function od(e){let n=[],t=[];for(let r of e.workers){let o=Wn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(Mn(r).memory_max??Mn(r).memory_high)==null?"this Worker declared no memory budget and the host derived no ceiling for it, so the sampler has none to enforce":"this Worker's declared memory budget cannot be reduced to bytes, so the sampler has no ceiling to enforce"});continue}let s=e.rss[r.worker_id];if(typeof s!="number"||!Number.isFinite(s)){t.push({worker_id:r.worker_id,reason:"the host produced no RSS reading for this Worker on this tick, and an unmeasured Worker is never killed on suspicion"});continue}if(!(s<=o.bytes)){if(e.sources?.[r.worker_id]==="cgroup"&&o.name==="MemoryMax"){t.push({worker_id:r.worker_id,reason:`this Worker's ${o.name} of ${o.declared} is held by the kernel on its own cgroup, and the reading is memory.current \u2014 which counts reclaimable page cache the kernel drops before it kills anything, so the daemon does not duplicate an enforcement that can tell cache from anonymous memory`});continue}n.push(Ig(r,o,s))}}return{terminations:n,unenforceable:t}}function Ig(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 Ng=4096;function sd(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return r;let o={},s={},i={},l=Cg(e,t,n);for(let[u,f]of l){let m=Bg(f);m!=null&&(o[u]=m.memoryBytes,m.cpuSeconds!=null&&(s[u]=m.cpuSeconds),i[u]="cgroup")}let a=e.filter(u=>i[u.worker_id]==null);if(a.length===0)return{rss:o,cpu_seconds:s,sources:i};let d=Gg(t,n);if(d.size===0)return{rss:o,cpu_seconds:s,sources:i};let c=new Map;for(let u of d.values()){let f=c.get(u.ppid);f?f.push(u.pid):c.set(u.ppid,[u.pid])}for(let u of a){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 D of c.get(k)??[])h.push(D)}}o[u.worker_id]=f,s[u.worker_id]=m,i[u.worker_id]="process-tree"}return{rss:o,cpu_seconds:s,sources:i}}var Mg="/sys/fs/cgroup";function Cg(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let s=t.cgroupRoot??Mg,i=e.filter(a=>a.unit!=null&&a.unit!=="");if(i.length===0)return r;let l=Wg(s,t);for(let a of i)for(let d of l){let c=Ie(d,a.unit);if(Lg(Ie(c,"memory.current"))){r.set(a.worker_id,c);break}}return r}function Wg(e,n){let t=n.selfCgroupPath??Fg(),r=[],o=l=>{r.includes(l)||r.push(l)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(Ie(e,s));let l=$g(s);if(l===s)break;s=l}o(e);let i=n.uid??process.getuid?.();return i!=null&&o(Ie(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),r}function Fg(){try{for(let e of qt("/proc/self/cgroup","utf8").split(`
67
+ `))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function Bg(e){let n;try{n=qt(Ie(e,"memory.current"),"utf8")}catch{return null}let t=Number(n.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:Hg(e)}}function Hg(e){let n;try{n=qt(Ie(e,"cpu.stat"),"utf8")}catch{return null}return Ug(n)}function Ug(e){for(let n of e.split(`
68
+ `)){let[t,r]=n.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(r);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function Gg(e,n){return n.procRoot!=null||e==="linux"?zg(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?Jg(Kg(n.psTable)):new Map}function Kg(e){try{return(e??Vg)()}catch{return""}}function Vg(){return Ag("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var qg=1024;function Jg(e){let n=new Map;for(let t of e.split(`
69
+ `)){let r=t.trim().split(/\s+/);if(r.length!==4)continue;let[o,s,i]=r.slice(0,3).map(Number);if(![o,s,i].every(a=>a!=null&&Number.isSafeInteger(a)&&a>=0))continue;let l=Qg(r[3]);l!=null&&n.set(o,{pid:o,ppid:s,rssBytes:i*qg,cpuSeconds:l})}return n}function Qg(e){let n=e.indexOf("-"),t=n<0?0:Number(e.slice(0,n));if(!Number.isFinite(t)||t<0)return null;let r=e.slice(n+1).split(":"),o=t*86400,s=1;for(let i=r.length-1;i>=0;i--){let l=Number(r[i]);if(!Number.isFinite(l)||l<0||r[i]==="")return null;o+=l*s,s*=60}return o}function zg(e){let n=new Map,t;try{t=Tg(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=qt(Ie(e,r,"stat"),"utf8")}catch{continue}let s=Xg(o);s&&n.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*Ng,cpuSeconds:s.cpuTicks/Yg})}return n}var Yg=100;function Xg(e){let n=e.lastIndexOf(")");if(n<0)return null;let t=Number(e.slice(0,e.indexOf(" "))),r=e.slice(n+1).trim().split(/\s+/),o=Number(r[1]),s=Number(r[11]),i=Number(r[12]),l=Number(r[21]);return!Number.isSafeInteger(t)||!Number.isSafeInteger(o)||!Number.isFinite(l)||!Number.isFinite(s)||!Number.isFinite(i)?null:{pid:t,ppid:o,rssPages:Math.max(0,l),cpuTicks:Math.max(0,s)+Math.max(0,i)}}var Zg=["api","graphql"],ey=No(Zg);function ny(e,n="https://api.github.com"){return e==="graphql"?`${n}/graphql`:n}var id=100,Qo=6e4,ty=2*Qo,ry=7*24*60*60*1e3,qo=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 zo(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new qo(t.project_label,t.token_ref,n)}function oy(e,n={now:new Date(0).toISOString()}){ly(e);let t=n.closedWindowMs??ry,r=Date.parse(n.now);if(!Number.isFinite(r))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(n.now)}`);let o=new Date(r-Math.max(0,t)).toISOString(),s=e.map((a,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:a}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { cost remaining resetAt }",...s.flatMap(({alias:a,search_alias:d,project:c})=>{let u=JSON.stringify(c.owner),f=JSON.stringify(c.name),m=JSON.stringify(`repo:${c.owner}/${c.name} is:closed closed:>=${o}`);return[` ${a}: 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(`
70
+ `),aliases:s,closed_since:o}}function sy(e,n,t){let r=sn(n),o=sn(r.data),s=Array.isArray(r.errors)?r.errors.map(sn):[],i=ay(o.rateLimit,s),l=e.aliases.map(({alias:a,search_alias:d,project:c})=>{let u=c.owner+"/"+c.name,f=o[a],m=s.find(h=>ld(h.path,a)||ld(h.path,d));if(Jt(f)){let h=ad(f.open_pull_requests),b=ad(f.open_issues),k=dy(o[d]);if(h!=null&&b!=null&&k!=null)return{project_label:c.project_label,repository:u,outcome:"counted",counts:{open_pull_requests:h,open_issues:b,recently_closed:k},detail:`counted ${u} for project ${JSON.stringify(c.project_label)}`}}return i.exhausted||fd(m)?{project_label:c.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${i.reset_at==null?"":`; the quota resets at ${i.reset_at}`}`}:{project_label:c.project_label,repository:u,outcome:"unreachable",counts:null,detail:`${u} is not reachable with the host token: ${Jo(m?.message)||"the query returned no such repository"}`}});return{version:1,fetched_at:t.fetchedAt,request_count:1,project_count:l.length,rate_limit:i,projects:l}}function iy(e){return{version:1,fetched_at:e,request_count:0,project_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1,point_cost:null},projects:[]}}async function dd(e){if(e.projects.length===0)return iy(e.now);zo(e.projects,e.hostTokenRef);let n=oy(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return sy(n,t,{fetchedAt:e.now})}catch(t){let r=t instanceof Error?t.message:String(t),o=/rate limit|secondary rate|429/i.test(r);return{version:1,fetched_at:e.now,request_count:1,project_count:e.projects.length,rate_limit:{remaining:null,reset_at:null,exhausted:o,point_cost:null},projects:e.projects.map(s=>({project_label:s.project_label,repository:`${s.owner}/${s.name}`,outcome:o?"rate-limited":"unreachable",counts:null,detail:`the activity fetch failed before ${s.owner}/${s.name} answered: ${r}`}))}}}function cd(e){let n=e.stalenessMs??ty,t=e.activity;if(t==null)return{version:1,fetched_at:null,age_ms:null,threshold_ms:n,stale:!1,request_count:0,rate_limit:{remaining:null,reset_at:null,exhausted:!1,point_cost:null},projects:[],reason:"the daemon polls no repository, so there are no counts to age"};let r=Date.parse(e.now),o=Date.parse(t.fetched_at),s=Number.isFinite(r)&&Number.isFinite(o)?Math.max(0,r-o):null,i=s==null||s>n;return{version:1,fetched_at:t.fetched_at,age_ms:s,threshold_ms:n,stale:t.projects.length>0&&i,request_count:t.request_count,rate_limit:t.rate_limit,projects:t.projects.map(l=>({...l,fetched_at:t.fetched_at,age_ms:s,stale:i})),reason:t.projects.length===0?"the daemon polls no repository, so there are no counts to age":s==null?"these counts carry no readable instant, so they cannot be presented as current":i?`these counts are ${s}ms old, past the ${n}ms window`:`fetched ${s}ms ago, within the ${n}ms window`}}function ud(e){if(!Jt(e))return!1;let n=e;return n.version===1&&(n.fetched_at===null||typeof n.fetched_at=="string")&&(n.age_ms===null||typeof n.age_ms=="number")&&typeof n.threshold_ms=="number"&&typeof n.stale=="boolean"&&Number.isInteger(n.request_count)&&Jt(n.rate_limit)&&Array.isArray(n.projects)&&typeof n.reason=="string"}function pd(e){let n=e.endpoint??ny(ey),t=e.fetchImpl??fetch;return async r=>{let o=await t(n,{method:"POST",headers:{authorization:`bearer ${e.token}`,"content-type":"application/json",accept:"application/vnd.github+json"},body:JSON.stringify({query:r})});if(!o.ok){let s=o.headers.get("x-ratelimit-remaining"),i=o.status===429||s==="0";throw new Error(`the activity query was refused with HTTP ${o.status}`+(i?": the host token's rate limit is spent":""))}return await o.json()}}function ly(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>id)throw new Error(`redskilled activity fetch spans at most ${id} repositories in one query`);let n=new Set;for(let t of e){if(t.project_label===""||t.owner===""||t.name==="")throw new Error("redskilled activity fetch needs a project label and an owner/name for every registered project");if(n.has(t.project_label))throw new Error(`redskilled holds one repository per project, and ${JSON.stringify(t.project_label)} is registered twice`);n.add(t.project_label)}}function ay(e,n){let t=sn(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(fd),i=typeof t.cost=="number"&&Number.isFinite(t.cost)?t.cost:null;return{remaining:r,reset_at:o,exhausted:s||r===0,point_cost:i}}function fd(e){if(e==null)return!1;let n=Jo(e.type),t=Jo(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function ld(e,n){return Array.isArray(e)&&e.includes(n)}function ad(e){let n=sn(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function dy(e){let n=sn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function sn(e){return Jt(e)?e:{}}function Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jo(e){return typeof e=="string"?e:""}var cy=3e4,uy=4,py=["logs","vitals","display"];function md(e,n){if(n===void 0)return e;let t=py.filter(o=>n[o]!==!0);if(t.length===0)return e;let r=o=>n[o]===!0;return{...e,workers:e.workers.map(o=>({...o,...r("vitals")?{}:{vitals:fy,budget:{...o.budget,used_bytes:null,used_fraction:null}},...r("logs")?{}:{log:my},...r("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var fy={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},my={last_line:null,published_at:null,source:null};function hd(e){let n=e.stalenessMs??cy,t=Fn(e.now),r=e.sampledAt==null?null:Fn(e.sampledAt),o=t==null||r==null?null:Math.max(0,t-r),s=o!=null&&o<=n,i=new Set(e.reattachedWorkerIds??[]),l=e.hostState.workers.map(f=>yy(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:i.has(f.worker_id)?"reattached":"running"})),a=l.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=l.length-a.length,c=l.reduce((f,m)=>f+(m.vitals.rss_bytes??0),0),u=It(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:_y({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:l.length,measuredCount:d,unmeasured:a}),host:{worker_count:l.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:u,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:c,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:by(l),known_projects:Ry(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,m)=>f.localeCompare(m)),workers:l,github_balance:Ho({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:cd({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:hy(e.deaths,e.recentDeathLimit??uy)},engine:gy(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function hy(e,n){let t=[...e].sort((o,s)=>(Fn(s.ts)??0)-(Fn(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 gy(e){let n=e.upgrade,t=n?.running_version??e.daemon_version,r=n?.published_version??null,o=n?.newest_published_version??null,s=(n?.newer_published??0)>0,i=(n?.major_held??0)>0;return{running_version:t,published_version:r,newer_published:s,major_held:i,current:r==null&&o==null?null:!s&&!i}}function yy(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=Wn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=Fn(e.started_at);return{worker_id:e.worker_id,project_label:e.project_label,workspace_path:e.workspace_path,pid:e.pid,started_at:e.started_at,uptime_ms:n.nowMs==null||i==null?null:Math.max(0,n.nowMs-i),state:n.state,isolated:e.isolated,unit:e.unit??null,warnings:[...e.warnings],vitals:{rss_bytes:r,sampled_at:r==null?null:n.sampledAt,age_ms:r==null?null:n.ageMs,fresh:r!=null&&n.sampleFresh,rss_source:r==null?null:e.rss_source??null},budget:{name:o?.name??null,declared:o?.declared??s,bytes:o?.bytes??null,used_bytes:r,used_fraction:o==null||o.bytes<=0||r==null?null:r/o.bytes,enforceable:o!=null},log:ky(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function ky(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 Ry(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 by(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 _y(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 Fn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function Yo(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.daemon,r=n.staleness,o=n.host;return n.version===1&&typeof n.generated_at=="string"&&t!=null&&typeof t=="object"&&Number.isInteger(t.pid)&&typeof t.daemon_version=="string"&&typeof t.protocol_version=="number"&&r!=null&&typeof r=="object"&&typeof r.stale=="boolean"&&typeof r.threshold_ms=="number"&&Array.isArray(r.unmeasured_workers)&&o!=null&&typeof o=="object"&&Number.isInteger(o.worker_count)&&Number.isInteger(o.project_count)&&typeof o.observed_rss_bytes=="number"&&Array.isArray(n.projects)&&Array.isArray(n.workers)&&(n.known_projects===void 0||Array.isArray(n.known_projects)&&n.known_projects.every(s=>typeof s=="string"))&&(n.registered_projects===void 0||Array.isArray(n.registered_projects)&&n.registered_projects.every(s=>typeof s=="string"))&&(n.repository_activity===void 0||ud(n.repository_activity))&&(n.github_balance===void 0||Uo(n.github_balance))&&(n.deaths===void 0||wy(n.deaths))&&(n.engine===void 0||xy(n.engine))&&(n.metrics===void 0||rd(n.metrics))}function wy(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return Number.isInteger(n.count)&&Array.isArray(n.recent)}function xy(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")}var gd={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,started_at:null,context:null,eta:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null};function Xo(e,n){let t=e.display?.started_at;if(t!=null&&t!==""){let r=Date.parse(t),o=Date.parse(n);if(Number.isFinite(r)&&Number.isFinite(o))return Math.max(0,o-r)}return e.uptime_ms}function Ne(e){return[...e].length}function G(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 Zo(e,n){return e+" ".repeat(Math.max(0,n-Ne(e)))}function U(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}function Bn(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 Hn(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return Bn(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 Un(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 es(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}var ns="!unregistered",Gn="\u21E1",Me="\u2020",ln="\u25D0",an="\u25EF",ts="\u21B3",rs="redskilled unreachable \u2014 Worker state unknown";function dn(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Qt(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function Kn(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 os(e){let n=[];return e.workers.length>0&&e.workers.length<=e.maxWorkers&&n.push("workers"),e.mode==="global"&&e.projects.length>0&&e.projects.length<=e.maxProjects&&n.push("projects"),n.push("host"),n}var j={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Ce(e,n=j){let t=Kn(e,n.project),r=dn(e,n),o=Qt(e,n),s=vy(e,n,r,t),i=os({mode:n.mode,maxWorkers:n.maxWorkers,maxProjects:n.maxProjects,workers:r,projects:o}),l={detail:"host",line:s};for(let u of i){let f=$y(s,Sy(u,n,r,o),n.separator);if(l={detail:u,line:f},Ne(f)<=n.maxWidth)break}let a=G(l.line,n.maxWidth),d=n.verbose&&l.detail==="workers"?Ly(r,n):[],c=r.length>0?"workers":"host";return{version:1,line:a,lines:[a,...d],verbose:n.verbose,mode:n.mode,project:n.project,project_match:t,detail:l.detail,degraded:l.detail!==c||a!==l.line,stale:e.staleness.stale,generated_at:e.generated_at}}function is(e){let n=e.options??j,t=G(rs,n.maxWidth);return{version:1,line:t,lines:[t],verbose:n.verbose,mode:n.mode,project:n.project,project_match:"unanswered",detail:"host",degraded:!0,stale:!0,generated_at:e.generated_at}}function Sy(e,n,t,r){return e==="workers"?t.map(o=>Ay(o,n)):e==="projects"?r.map(Ty):[]}function vy(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(ss(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(ss(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(ss(e,n)),o.push(ns)):o.push(Dy(n.project,r)),o.push(Ey(e));let s=Py(e);s!=null&&o.push(s);let i=jy(e);return i!=null&&o.push(i),e.staleness.stale&&o.push(Oy(e)),o.join(" ")}function Ey(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${Gn}`}function Py(e){let n=e.github_balance;return n==null?null:n.posture==="spent"?`${an} quota spent`:n.posture==="reserved"?`${ln} quota band`:null}function jy(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${Me}${n.count} ${n.latest.sender_class}`}function Dy(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 ss(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,s)=>o+s.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${U(t)}/${U(r)}`:U(t)}function Oy(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function Ay(e,n){let t=zt(e,n.mode),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?U(r):`${U(r)}/${U(e.budget.bytes)}`;return`${t} ${o}`}function Ly(e,n){let t=[];for(let r of e){let o=es(r.log.last_line);o!=null&&t.push(G(` ${ts} ${zt(r,n.mode)}: ${o}`,n.maxWidth))}return t}function zt(e,n){return n==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Ty(e){return`${e.project_label} ${e.worker_count}w ${U(e.observed_rss_bytes)}`}function $y(e,n,t){return[e,...n].join(t)}var Vn=["wid","run","org","iss","bar","phase","elapsed","eta","hb","loc","tks","ctx","tls","rsn","txt"],de={mode:"local",project:null,maxWidth:200,maxRows:16},Iy=" ",yd="\u2588",Ny="\u25B6",My="\u2717",Cy="\u2591";function cn(e,n=de){let t=Kn(e,n.project),r=dn(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(u=>Wy(u,n,e.generated_at)),i=Vy(s),l=o.map((u,f)=>({worker_id:u.worker_id,project_label:u.project_label,mine:n.project!=null&&u.project_label===n.project,cells:s[f],line:G(qy(s[f],i),n.maxWidth)})),a=Fy(e,n,r,t),d=r.length-o.length,c=[a.line,...l.map(u=>u.line)];return d>0&&c.push(G(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),c.push(...Hy(e,n)),c.push(...By(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Vn,header:a,rows:l,lines:c,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Wy(e,n,t){let r=e.display??gd,o=[r.runner,r.model,r.effort].filter(s=>!!s).join(" ");return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:o===""?"":`run=${o}`,org:r.origin==null?"":`org=${r.origin}`,iss:r.issue==null?"":`iss=${r.issue}`,bar:kd(r),phase:[r.phase,r.step].filter(s=>!!s).join("\xB7"),elapsed:Un(Xo(e,t)),eta:r.eta==null?"":`eta=${Un(r.eta*1e3)}`,hb:`hb=${r.heartbeat??"?"}`,loc:Ky(r.added,r.removed),tks:r.tokens==null?"":`tks=${Bn(r.tokens)}`,ctx:r.context==null?"":`ctx=${Bn(r.context)}`,tls:r.tools==null?"":`tls=${r.tools}`,rsn:r.reasoning==null?"":`rsn=${r.reasoning}`,txt:r.text==null?"":`txt=${r.text}`}}function kd(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 yd.repeat(Math.floor(n));let o=e.failed?My:Ny;return`${yd.repeat(r)}${o}${Cy.repeat(Math.floor(n)-r-1)}`}function Fy(e,n,t,r){let o=(e.repository_activity?.projects??[]).find(w=>w.project_label===n.project),s={open_pull_requests:o?.counts?.open_pull_requests??null,recently_closed:o?.counts?.recently_closed??null,open_issues:o?.counts?.open_issues??null,stale:o?.stale===!0},i={memory_used_fraction:e.host.ceiling_used_fraction,memory_used_bytes:e.host.consumption.memory_bytes,memory_ceiling_bytes:e.host.ceiling.memory_bytes,worker_count:e.host.worker_count,worker_ceiling:e.host.ceiling.worker_count},l=Gy(t),a=o?.repository??n.project,d=e.engine??null,c=d?.running_version??e.daemon.daemon_version,u=e.deaths??null,f=e.metrics??null,m=[`\xBB ${a??"host"} v${c}${d!=null&&d.current===!1?Gn:""}`];r==="unregistered"&&m.push("!unregistered"),r==="name-only"&&m.push("!lapsed"),l!=null&&m.push(l),m.push(`wrk=${t.length}/${e.host.worker_count}`),m.push(i.worker_ceiling==null?"slots=\u221E":`slots=${i.worker_count}/${i.worker_ceiling}`),m.push(Uy(i)),s.open_pull_requests!=null&&m.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&m.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&m.push(`iss=${s.open_issues}`),s.stale&&m.push("!counts stale");let h=f==null?null:Rd(f.hour);if(h!=null&&m.push(h),u!=null&&u.count>0&&u.latest!=null&&m.push(`${Me}${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&&Ne(b)>n.maxWidth?m.filter(w=>w!==h).join(" \xB7 "):b;return{repo:a,project:n.project,project_match:r,version:c,engine:d,deaths:u,metrics:f,model:l,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:G(k,n.maxWidth)}}function Rd(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${Hn(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${Hn(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${Hn(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 By(e,n){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let r=t.posture==="spent"?an:ln,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[G(`${r} github budget ${t.posture}${o} \u2014 ${t.reason}`,n.maxWidth)]}function Hy(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(s=>G(`${Me} ${s.kind} ${s.id} pid=${s.pid} ${s.sender_class}/${s.confidence} phase=${s.last_phase}`+(s.signal==null?"":` signal=${s.signal}`)+(s.evidence==null?"":` \u2014 ${s.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(G(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function Uy(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${U(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${U(e.memory_used_bytes)}/${U(e.memory_ceiling_bytes)}${n}`}function Gy(e){for(let n of e){let t=n.display;if(t==null)continue;let r=[t.runner,t.model,t.effort].filter(o=>!!o);if(r.length>0)return r.join("\xB7")}return null}function Ky(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 Vy(e){let n=Object.fromEntries(Vn.map(t=>[t,0]));for(let t of e)for(let r of Vn)n[r]=Math.max(n[r],Ne(t[r]));return n}function qy(e,n){return Vn.filter(r=>n[r]>0).map(r=>Zo(e[r],n[r])).join(Iy).replace(/\s+$/,"")}var Yt=1;async function qn(e,n){return await jt(e,n,"redskilled daemon")}function _d(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:Yt,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:Yy(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:oa(n,{hostCeilingBytes:e.hostCeilingBytes??null}),upgrade:Xy(e)}}function Yy(e){let n=e.now==null?Number.NaN:Date.parse(e.now),t=Number.isFinite(n),r=e.queue??null,o=new Map(r==null?[]:r.projects.map(s=>[s.project_label,s]));return[...e.registrations??[]].map(s=>{let i=o.get(s.project_label);return{...s,...t?{renewal:Na(s,n)}:{},...r==null||i==null?{}:{last_poll:{at:r.fetched_at,outcome:i.outcome,depth:i.depth,request_count:r.request_count,detail:i.detail}}}}).sort((s,i)=>s.project_label.localeCompare(i.project_label))}function Xy(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 wd(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)&&sa(n.budget_accounting)&&(n.scope===void 0||Aa(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every($o))&&(n.upgrade===void 0||Zy(n.upgrade))}function Zy(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||ek(n.major_hold))}function ek(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 er}from"node:child_process";import{existsSync as us}from"node:fs";import{delimiter as dk,join as Ld}from"node:path";import{join as xd}from"node:path";import{existsSync as nk}from"node:fs";import{createRequire as tk}from"node:module";var Sd="redskilled-job-object.node",We=100;function un(e){return{available:!1,reason:e}}function rk(e,n,t){return[xd(t,"prebuilds",`${e}-${n}`,Sd),xd(t,"native","build","Release",Sd)]}function vd(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return un(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??sk(),o=e.exists??nk,s=rk(n,t,r),i=s.find(d=>o(d));if(i==null)return un(`no Job Object addon was found for ${n}-${t} (looked in ${s.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let l=e.requireFn??tk(import.meta.url),a;try{a=l(i)}catch(d){return un(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return ok(a)?{available:!0,binding:a}:un(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function ok(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function sk(){return new URL("..",import.meta.url).pathname}function Ed(e){let n=e??{},t=[],r=ik(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<We?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 ${We}, 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 ik(e){return Wn({budget:e})}var Xt=5,Pd=19;function ls(e){return{available:!1,reason:e}}var lk="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 Dd(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=Xt;else if(t.cpu_weight<We){let l=Math.round(Pd*(We-t.cpu_weight)/We);o=Math.min(Pd,Math.max(Xt,l))}else o=Xt,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${We}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${Xt}`);let s=jd(t.max_processes);s==null&&t.max_processes!=null&&r.push(`max_processes=${t.max_processes} is not a positive whole number, so no ulimit -u is set`);let i=jd(t.cpu_seconds);return i==null&&t.cpu_seconds!=null&&r.push(`cpu_seconds=${t.cpu_seconds} is not a positive whole number, so no ulimit -t is set`),{...o!=null?{nice:o}:{},...s!=null?{max_processes:s}:{},...i!=null?{cpu_seconds:i}:{},memory_ceiling:"sampling-floor",memory_ceiling_reason:lk,...r.length>0?{note:r.join("; ")}:{}}}function Od(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 ${ak(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
71
+ `),e.command,...e.args]}function Ad(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 as(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 jd(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function ak(e){return`'${e.replace(/'/g,"'\\''")}'`}var Td="REDSKILLED_PLACEMENT",Zt="red-worker",ds="/bin/sh";function $d(e=process.env,n=process.platform){let t=ls(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:vd({platform:n}),posix:t};let r=un(`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:ck(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&us(Ld(o,"systemd","private"));return{platform:n,systemdRun:Cd("systemd-run",e),userSession:s,jobObjects:r,posix:t}}function ck(e){return us(ds)?{available:!0,shell:ds,nice:Cd("nice",e)}:ls(`no POSIX shell was found at ${ds}, so there is nothing to apply rlimits or priority in`)}function Id(e=process.env){let n=(e[Td]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function uk(e,n,t=Zt){return Nd(e,n,t).replace(/\.service$/,"")}function Nd(e,n,t=Zt){return`${cs(t,"red-worker",24)}-${cs(e,"project",32)}-${cs(n,"worker",32)}.service`}function Md(e){let n=[...e.args??[]],t={...e.budget??{},...e.budget?.memory_max==null&&e.memoryCeiling?.memory_max!=null?{memory_max:e.memoryCeiling.memory_max}:{}},r=t.memory_max??t.memory_high??null,o=t.memory_high!=null||t.memory_max!=null||t.cpu_weight!=null,s=e.target??{isolation:"transient-unit"},i=u=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:u,budget:t,...r!=null?{memoryCeiling:r}:{},environment:An({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(s.isolation==="inherit")return i("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return i(`worker isolation disabled by ${Td}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return fk(e,n,t,r,o,i);if(e.probes.platform==="darwin")return pk(e,n,t,r,i);if(e.probes.platform!=="linux")return i(`transient-unit placement is the Linux backend (platform=${e.probes.platform}): the Worker is charged to the daemon's own resource group`);if(!e.probes.systemdRun)return i("transient-unit placement unavailable: systemd-run is not on PATH; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");if(!e.probes.userSession)return i("transient-unit placement unavailable: no systemd --user session; the Worker is charged to the daemon's own resource group and a memory-pressure kill will hit the whole session");let l=Nd(e.projectLabel,e.workerId,s.unit_prefix),a=["--user","--collect","--quiet","--wait",`--unit=${l}`,`--working-directory=${e.workspacePath}`];e.pipeOutput===!0&&a.push("--pipe"),t.memory_high!=null&&a.push(`--property=MemoryHigh=${t.memory_high}`),t.memory_max!=null&&a.push(`--property=MemoryMax=${t.memory_max}`),t.cpu_weight!=null&&a.push(`--property=CPUWeight=${t.cpu_weight}`);let d=An({scope:l,memory_ceiling:r,scope_degradation:null});for(let[u,f]of Object.entries({...e.env??{},...d}))a.push(`--setenv=${u}=${f}`);let c=as(e.budget);return{isolated:!0,backend:"transient-unit",unit:l,command:e.probes.systemdRun,args:[...a,"--",e.command,...n],budget:t,...r!=null?{memoryCeiling:r}:{},environment:d,...c!=null?{budgetWarning:c}:{}}}function pk(e,n,t,r,o){let s=e.probes.posix;if(!s.available)return o(`POSIX limit placement unavailable: ${s.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let i=Dd(t,{canRenice:s.nice!=null}),l=t.memory_high!=null||t.memory_max!=null,a=Ad(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:Od({limits:i,nice:s.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:i,warning:a,budget:t,...r!=null?{memoryCeiling:r}:{},environment:An({scope:null,memory_ceiling:r,scope_degradation:a}),...l?{budgetWarning:"the declared memory budget is enforced by the daemon's RSS sampling floor rather than by the kernel: "+i.memory_ceiling_reason}:{}}}function fk(e,n,t,r,o,s){let i=e.probes.jobObjects;if(!i.available)return s(`Job Object placement unavailable: ${i.reason}. The Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling`);let l=Ed(t),a=uk(e.projectLabel,e.workerId,e.target?.unit_prefix);return{isolated:!0,backend:"job-object",command:e.command,args:[...n],cwd:e.workspacePath,job:{name:a,limits:l},budget:t,...r!=null?{memoryCeiling:r}:{},environment:An({scope:a,memory_ceiling:r,scope_degradation:null}),...mk(o&&l.note!=null?`${l.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,as(e.budget))}}function mk(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function Cd(e,n){for(let t of(n.PATH??"").split(dk)){if(!t)continue;let r=Ld(t,e);if(us(r))return r}return null}function cs(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function ps(e,n){let t=[],r=[];for(let o of e){let s=!1;try{s=await n(o)===!0}catch{s=!1}(s?t:r).push(o)}return{alive:t,dead:r}}var Wd=3e4;function Fd(e){return e.unit!=null&&e.unit!==""?hk(e.unit):B(e.pid)}function hk(e){let n=er("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var gk="REDSKILLED_UNIT_DISCOVERY",Bd="(unowned)";function Hd(e){let n=er("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 yk(e=process.env){let n=(e[gk]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Ud(e,n,t=process.env){return yk(t)&&e===n}function Gd(e=Zt){let n=er("systemctl",["--user","list-units","--type=service","--state=active","--plain","--no-legend","--no-pager",`${e}-*.service`],{encoding:"utf8"});return n.error!=null||n.status!==0?[]:(n.stdout??"").split(`
72
+ `).map(t=>t.trim().split(/\s+/)[0]??"").filter(t=>t.startsWith(`${e}-`)&&t.endsWith(".service"))}function Kd(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:Bd,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 Vd(e){return e.project_label.trim()!==""?e:{...e,project_label:Bd,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 qd(e){if(e.unit!=null&&e.unit!==""){let n=er("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 kk(e,n=50){if(Yd(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 Rk(e,n={}){let t=n.batchSize??50;if(Yd(e),e.length>t)throw new Error(`redskilled queue discovery spans at most ${t} selectors in one query, and this batch holds ${e.length}: split it with planQueueDiscoveryBatches rather than dropping the remainder`);let r=e.map((i,l)=>({alias:`q${l}`,project:i}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...r.map(({alias:i,project:l})=>` ${i}: search(query: ${JSON.stringify(l.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
73
+ `),aliases:r}}function bk(e,n){let t=Jn(n),r=Jn(t.data),o=Array.isArray(t.errors)?t.errors.map(Jn):[],s=wk(r.rateLimit,o);return{projects:e.aliases.map(({alias:l,project:a})=>{let d=Sk(r[l]);if(d!=null)return{project_label:a.project_label,outcome:"counted",depth:d,detail:`project ${JSON.stringify(a.project_label)} has ${d} item(s) matching its selector`};let c=o.find(u=>xk(u.path,l));return s.exhausted||Xd(c)?{project_label:a.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(a.project_label)} answered, so this queue has no depth rather than a depth of zero`+(s.reset_at==null?"":`; the quota resets at ${s.reset_at}`)}:{project_label:a.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(a.project_label)} could not be counted with the host token: ${fs(c?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function _k(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 Qd(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 zd(e){if(e.projects.length===0)return _k(e.now);let n=e.batchSize??50,t=kk(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=Rk(s,{batchSize:n});try{let l=await e.transport(i.query),a=bk(i,l);r.push(...a.projects),o=Jd(o,a.rate_limit)}catch(l){let a=l instanceof Error?l.message:String(l),d=/rate limit|secondary rate|429/i.test(a);o=Jd(o,{remaining:null,reset_at:null,exhausted:d});for(let c of s)r.push({project_label:c.project_label,outcome:d?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(c.project_label)} answered: ${a}`})}}return{version:1,fetched_at:e.now,request_count:t.length,project_count:r.length,batch_size:n,rate_limit:o,projects:r}}function Yd(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 Jd(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 wk(e,n){let t=Jn(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(Xd)||r===0}}function Xd(e){return e==null?!1:fs(e.type)==="RATE_LIMITED"||/rate limit/i.test(fs(e.message))}function xk(e,n){return Array.isArray(e)&&e.includes(n)}function Sk(e){let n=Jn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function Jn(e){return vk(e)?e:{}}function vk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fs(e){return typeof e=="string"?e:""}var Ek={runner:null,model:null,effort:null,origin:null,issue:null,phase:null,step:null,phase_index:null,phase_total:null,failed:!1,heartbeat:null,started_at:null,context:null,eta:null,added:null,removed:null,tokens:null,tools:null,reasoning:null,text:null},Pk=["runner","model","effort","origin","issue","phase","step","heartbeat","started_at"],jk=["phase_index","phase_total","context","eta","added","removed","tokens","tools","reasoning","text"];function Zd(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...Ek};for(let r of Pk){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of jk){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}import{randomUUID as tc}from"node:crypto";import{spawn as Lk}from"node:child_process";import{closeSync as Tk,mkdirSync as $k,openSync as Ik}from"node:fs";import{dirname as Nk}from"node:path";import{delimiter as ec,dirname as Dk}from"node:path";function Ok(e,n=ec){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function Ak(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=Dk(n);return t===""||t==="."?null:t}function nc(e,n=process.execPath,t=ec){let r=Ok(e,t),o=Ak(n);return o==null?r.join(t):[o,...r.filter(s=>s!==o)].join(t)}var Qn=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},nr=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function Mk(e){if(e==null||e.trim()==="")return null;try{return $k(Nk(e),{recursive:!0}),Ik(e,"a")}catch{return null}}function Ck(e){try{Tk(e)}catch{}}function Wk(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 Qn(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new Qn("redskilled worker spec args must be an array")}function Fk(e){if(e==null)throw new nr("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new nr(e.reason,e)}function oc(e){let{spec:n,admission:t}=e;Fk(t),Wk(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(n.worker_id??e.workerId??tc()).trim()||tc(),i=e.probes??$d(r),l=e.openLog===!1?null:Mk(n.log_path),a={...n.env??{},PATH:nc(n.env?.PATH??r.PATH,e.execPath??process.execPath)},d=Md({workerId:s,projectLabel:n.project_label,workspacePath:n.workspace_path,command:n.command,args:n.args,budget:n.budget,...e.memoryCeiling!=null?{memoryCeiling:e.memoryCeiling}:{},target:n.placement,env:a,enabled:e.enabled??Id(r),probes:i,pipeOutput:l!==null}),u=(e.spawnFn??Lk)(d.command,d.args,{...d.cwd!=null?{cwd:d.cwd}:{},detached:!0,stdio:l===null?"ignore":["ignore",l,l],env:d.backend==="transient-unit"?{...r}:{...r,...a,...d.environment}});if(l!==null&&Ck(l),u.pid==null)throw u.once("error",()=>{}),new Qn(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${s}`);let f=d.job!=null?Bk(d,i,u.pid):null;u.once("error",()=>{}),u.once("exit",(k,w)=>{try{f?.job?.close()}catch{}e.onExit?.(s,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:s,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 Bk(e,n,t){let r=e.job;if(r==null)return{};let o="the Worker is charged to the daemon's own resource group and the daemon's RSS sampling floor is the only remaining ceiling";if(!n.jobObjects.available)return{warning:`Job Object placement unavailable: ${n.jobObjects.reason}. ${o}`};let s;try{s=n.jobObjects.binding.createJobObject({name:r.name,limits:r.limits})}catch(i){return{warning:`Job Object ${JSON.stringify(r.name)} could not be created: ${rc(i)}. ${o}`}}try{s.assign(t)}catch(i){try{s.close()}catch{}return{warning:`Worker pid ${t} could not be assigned to Job Object ${JSON.stringify(r.name)}: ${rc(i)}. ${o}`}}return{job:s}}function rc(e){return e instanceof Error?e.message:String(e)}import{open as Hk,stat as Uk}from"node:fs/promises";var Gk=16*1024;async function sc(e,n=Gk){let t;try{t=(await Uk(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let s=await Hk(e,"r");try{let i=Buffer.alloc(r);await s.read(i,0,r,t-r),o=i.toString("utf8")}finally{await s.close()}}catch{return null}return Kk(o)}function Kk(e){let n=e.split(`
74
+ `);for(let t=n.length-1;t>=0;t-=1){let r=n[t].replace(/\r$/,"");if(r.trim()!=="")return r}return null}import{spawn as iR}from"node:child_process";import{existsSync as lR,readdirSync as aR}from"node:fs";import{dirname as dR,join as uc,resolve as cR}from"node:path";var Vk="<version>";function ve(e,n=[],t){let r=t&&t.trim().length>0?t.trim():Vk;return[`npx -y -p ${$e}@${r}`,e,...n].join(" ")}function ee(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 ms(e,n){let t=ee(e),r=ee(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var vE=4*60*60*1e3;ge();ge();import{spawnSync as qk}from"node:child_process";import{mkdir as Jk,rm as Qk,writeFile as zk}from"node:fs/promises";import{existsSync as Yk}from"node:fs";import{homedir as Xk}from"node:os";import{dirname as Zk,join as hs}from"node:path";var pn="redskilled.service",gs="REDSKILLED_SUPERVISED",eR="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function nR(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||hs(e.HOME?.trim()||Xk(),".config");return hs(n,"systemd","user")}function ys(e=process.env){return hs(nR(e),pn)}function ic(e,n={}){let t=n.env??process.env,r=Lt(n.override??{},n.entryLookup??{}),o=[...r.args,...Te(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:pn,unitPath:ys(t),command:r.command,args:o,text:tR(r.command,o,e)}}function tR(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${eR}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(rR).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${gs}=1"`,`Environment="REDSKILLED_SESSION=${lc(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
75
+ `)}function rR(e){return/[\s"'\\$%]/.test(e)?`"${lc(e)}"`:e}function lc(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function ac(e,n={}){let t=n.writeFile??oR,r=n.run??ks,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(tr("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(tr("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function dc(e={}){let n=e.removeFile??sR,t=e.run??ks,r=ys(e.env??process.env),o=[tr("disable",t,["systemctl","--user","disable","--now",pn])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(tr("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function cc(e={}){let n=e.exists??Yk,t=e.run??ks,r=ys(e.env??process.env),o=n(r);return{unitName:pn,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",pn]).status===0,active:o&&t(["systemctl","--user","is-active",pn]).status===0,floor:"auto-spawn"}}function tr(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 oR(e,n){await Jk(Zk(e),{recursive:!0}),await zk(e,n,{encoding:"utf8",mode:420})}async function sR(e){await Qk(e,{force:!0})}function ks(e){let n=qk(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 pc=75,mc=9e5,fc="redskilled-replacement-entry-unresolved",uR="REDSKILLED_NO_REGISTRY_PROBE",hc="REDSKILLED_BORN_BY_REPLACEMENT";function gc(e=process.env){return e[hc]==="1"}function yc(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function kc(e){let n=e.running.trim();if(zn(n))return null;let t=e.newest?.trim()??"",r=ee(t),o=ee(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:pR(r.major,e.supervised)}}function pR(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: ${ve("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 Rc(e){let n=e.running.trim();if(zn(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||ee(t)===null?{act:"hold",reason:"published-unknown"}:ms(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function zn(e){let n=e.trim();return ee(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function bc(e=process.env){return e[gs]==="1"}var Rs=class extends Error{code=fc;searched;constructor(n,t){super(`${fc}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
76
76
  searched:
77
77
  ${t.map(r=>` ${r}`).join(`
78
- `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function dR(e,n={}){let t=n.env??process.env,r=n.exists??rR,o=n.execPath??process.execPath,s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,a=[],l=[[ac(jt(t),i),"bundle-cache"]];s&&l.push([ac(sR(iR(s)),i),"caller-sibling-bundle"]);for(let[d,c]of l)if(a.push(d),r(d))return{command:o,args:[d],version:e,source:c,searched:a};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new ks(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 kc(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>dR(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function Rc(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??uR)(dc),{...e,exitCode:dc};let o=[...e.entry.args,...Te(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??cR(r.env))(e.entry,o),e}function cR(e){return(n,t)=>{let r=tR(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[pc]:"1"}});r.on("error",()=>{}),r.unref()}}function uR(e){process.exitCode=e,process.exit(e)}async function bc(e,n=process.env,t=pR){let r=wc(n),o=xc(e,n);if(n[lR]==="1")return{version:o,newest:r};let s=ee(e)===null?"0.0.0":e;try{let i=await zl({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function _c(e,n=process.env,t){let r=t??Rs;return{version:xc(e,n,r),newest:wc(n,r)}}function wc(e=process.env,n=Rs){return vc(Sc(e,n))}function xc(e,n=process.env,t=Rs){let r=ee(e.trim())?.major;return r===void 0?null:vc(Sc(n,t).filter(o=>ee(o)?.major===r))}function Sc(e,n){let t=[];for(let r of n(jt(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||ee(o)===null||t.push(o)}return t}function vc(e){let n=null;for(let t of e)(n===null||fs(t,n)>0)&&(n=t);return n}function Rs(e){try{return oR(e)}catch{return[]}}async function pR(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 fR,readFile as mR,rename as hR,rm as bs,writeFile as Ec}from"node:fs/promises";import{randomUUID as yR}from"node:crypto";import{dirname as gR}from"node:path";var rr=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function Jn(e){let n;try{n=await mR(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=kR(n);return RR(t)?t:void 0}var Pc;function Dc(){return Pc??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Pc}function Oc(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??B;async function s(){return await Jn(e)}async function i(l){let d=`${e}.${l.pid}.${yR()}.tmp`;await Ec(d,jc(l),{encoding:"utf8",mode:384}),await hR(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:s,async acquire(l){await fR(gR(e),{recursive:!0,mode:448});let d=!1;for(;;){let c=r(),u=a(l,c);try{return await Ec(e,jc(u),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:u}}catch(m){if(m.code!=="EEXIST")throw m}let f=await s();if(!f){await bs(e,{force:!0}),d=!0;continue}if(_s(f,l))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await bs(e,{force:!0}),d=!0}},async renew(l){let d=await s();if(!d||!_s(d,l))throw new rr(e);let c={...d,renewed_at:r()};return await i(c),c},async release(l){let d=await s();if(!d)return!1;if(!_s(d,l))throw new rr(e);return await bs(e,{force:!0}),!0}}}function _s(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function jc(e){return`${C(e,{keyedMapCollapse:!0})}
79
- `}function kR(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return q(n)}catch{return null}}}function RR(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 ws=3e5,PR=1e4,jR=6e4,DR=15e3,OR=3e4,Ac=16,pn=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},AR="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Tc(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??ws,o=e.clock??(()=>new Date().toISOString()),s=e.launch??nc,i=e.ceiling??da();e.repositoryActivity!=null&&zo(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let a=e.owner??Dc(),l=e.leaseStore??Oc(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??Ea(),c={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},u=e.machineClaimStore??It(n.machineClaimPath,c,{clock:o});await SR(ER(n.socketPath),{recursive:!0,mode:448});let f=await u.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new pn(n.socketPath):new xe(u.claimPath,f.reason,f.claim);let m=await l.acquire(a);if(!m.acquired)throw await u.release(d).catch(()=>{}),new pn(n.socketPath,m.lease);let h;try{h=await LR(n.socketPath)}catch(p){throw await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),p}let b=o(),k=e.eventLane??pa(n.eventLanePath),w=e.liveness??Md,D=e.livenessGraceMs??Nd,z=e.stopWorker??Gd,de=e.unitInventory??(()=>Fd(n.machineClaimPath,$t({machineIdHash:n.machineIdHash}))?Bd():[]),ce=e.unitMainPid??Wd,Be=e.treeSampler??td,lr=e.readLogTail??tc,Is=e.sampleMs??DR,Ns=e.leaseRenewMs??OR,Ms=e.publishedVersion??(p=>bc(p)),Cs=e.replaceCheckMs??uc,Ws=e.publishedProbeTimeoutMs??PR,hu=e.localPublishedEvidence??(p=>_c(p,e.replacementIO?.env??process.env)),yu=e.bornByReplacement??fc(),Fs=e.replaceBootCheckMs??jR,Bs=e.supervised??gc(),Hs=e.replacementIO??{},te=e.repositoryActivity,Us=te?.intervalMs??Qo,Yn=e.githubBalance,Ee=e.queueDiscovery,Xn=Ee?.transport??te?.transport,ar=Ee?.unconfiguredReason??AR,Gs=Ee?.intervalMs??15e3,Ks=e.demandMs??15e3,gu=e.demandBackoffMs??3e4,v=new Map,ke=new Set,He=new Map,Zn=new Map,dr=[],et=[],$=new Map,cr=new Set,Vs={},ur=null,qs=null,pr=null,Js=!1,fr=0,mr=null,mn="none",hr=null,Qs=null,yr=null,hn=null,Re=null,nt=null,yn=[],gn=null,tt={},gr=!1,Ue,kn,Rn,bn,_n,rt,wn,Ge,xn,K=!1,kr=!1,ot=null,zs,Rr=new Promise(p=>{zs=p});function Sn(p){Ys(p);let y=Date.parse(p),g=$a($.values(),y);for(let _ of g.lapsed)$.delete(_.project_label),ku(_,y);return g.lapsed}function ku(p,y){let g=Number.isFinite(y)?new Date(y).toISOString():p.renew_by;yn.push({project_label:p.project_label,at:g,renew_by:p.renew_by,renewals:p.renewals,sustains:p.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(p.project_label)}: it stood until ${p.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`}),yn.length>Ac&&yn.splice(0,yn.length-Ac)}function Ys(p){if($.size===0)return;let y=Date.parse(p);if(!Number.isFinite(y))return;let g={};for(let x of v.values())g[x.project_label]=(g[x.project_label]??0)+1;let _=new Map((Re?.projects??[]).map(x=>[x.project_label,x]));for(let x of[...$.values()]){let P=_.get(x.project_label),pe=La(x,{now:p,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:g[x.project_label]??0});pe.registration!==x&&$.set(x.project_label,pe.registration)}}function st(){let p=o();return Sn(p),kd({now:p,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:a.pid,startedAt:b,scope:Pa(u.claimPath,c,d),workers:[...v.values()],registrations:[...$.values()],lapses:yn,queue:Re,published:{version:qs,checkedAt:pr,newer:Js,replacement:mn,newest:hr,majorHold:Qs,checks:fr,holdReason:mr}})}function it(){return pd({hostState:st(),ceiling:i,rss:Vs,sampledAt:ur,logLines:Object.fromEntries(He),displays:Object.fromEntries(Zn),now:o(),reattachedWorkerIds:[...ke],repositoryActivity:yr,githubBalance:hn,...e.deaths===void 0?{}:{deaths:e.deaths},metrics:Za({observations:dr,outcomes:et,now:o()})})}function Ru(p,y){dr=Ut([...dr,{worker_id:y,observed_at:p.published_at,tokens:p.display.tokens,tools:p.display.tools,runner:p.display.runner,model:p.display.model}],g=>g.observed_at,{now:o()})}function bu(p){et=Ut([...et,p],y=>y.ts,{now:o()})}async function br(){return te==null||te.projects.length===0?null:(yr=await id({projects:te.projects,hostTokenRef:te.hostTokenRef,transport:te.transport,closedWindowMs:te.closedWindowMs,now:o()}),yr)}async function Xs(){return Yn==null?null:(hn=await Wo({transport:Yn.transport,now:o()}),hn)}function _u(){if(K||Ge!=null||Yn==null)return;let p=()=>{Ge=void 0,Xs().catch(()=>{}).then(()=>{if(K)return;let y=Yn.intervalMsOverride??Ht(hn??wu(),{now:o()});Ge=setTimeout(p,y),Ge.unref()})};p()}function wu(){return Bt(o())}function xu(){if(!(Xn!=null||Ee?.armTransport==null))try{let p=Ee.armTransport();if(p.transport!=null){Xn=p.transport;return}p.unconfiguredReason!=null&&(ar=p.unconfiguredReason)}catch(p){ar=`this host could not resolve a tracker credential: ${p instanceof Error?p.message:String(p)}`}}async function Zs(){let p=o();Sn(p);let y=[...$.values()].map(g=>({project_label:g.project_label,selector:g.selector})).sort((g,_)=>g.project_label.localeCompare(_.project_label));return y.length===0?null:(xu(),Xn==null?(Re=Vd(y,p,ar),Re):(Re=await qd({projects:y,transport:Xn,now:p,...Ee?.batchSize==null?{}:{batchSize:Ee.batchSize}}),Ys(o()),Re))}async function ei(){let p=o();if(gr)return nt??ha(p);gr=!0;try{await wr().catch(()=>{});let y={};for(let A of v.values())y[A.project_label]=(y[A.project_label]??0)+1;let g={};for(let A of Re?.projects??[])g[A.project_label]=A.depth;let _=Date.parse(p),x=ma({projects:[...$.values()].map(A=>({project_label:A.project_label,selector:A.selector,argv:A.argv,workspace_path:A.workspace_path,target:A.target})),queue:g,live:y,nowMs:Number.isFinite(_)?_:0,backoffUntilMs:gn,birthHaltUntilMs:ga(tt,Number.isFinite(_)?_:0)}),P=[],pe=null;for(let A of x.births){let Ve,Gu=Qn(),ut=$.get(A.project_label),fi=Da({argv:A.argv,...ut?.env==null?{}:{env:ut.env},...ut?.log_path==null?{}:{log_path:ut.log_path}},{worker_id:Gu,slot:A.index,workspace_path:A.workspace_path},{project_label:A.project_label});try{Ve=_r(fi)}catch(vr){pe=vr instanceof Error?vr.message:String(vr),gn=(Number.isFinite(_)?_:Date.now())+gu;break}P.push({project_label:A.project_label,worker_id:Ve.worker.worker_id,pid:Ve.worker.pid,warnings:fi.log_path==null?[...Ve.warnings,`project ${JSON.stringify(A.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(Ve.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:Ve.warnings})}return pe==null&&x.births.length>0&&(gn=null),nt={version:1,at:p,requested:x.births.length,granted:P,shortfall:x.births.length-P.length,refusal:pe,retry_after:gn==null?null:new Date(gn).toISOString(),projects:x.intents},nt}finally{gr=!1}}function Su(p){return Ce(it(),{...j,mode:p?.mode??j.mode,project:p?.project??j.project,maxWorkers:p?.max_workers??j.maxWorkers,maxProjects:p?.max_projects??j.maxProjects,maxWidth:p?.max_width??j.maxWidth,verbose:p?.verbose??j.verbose})}function vu(p){return zt(it(),{mode:p?.mode??Se.mode,project:p?.project??Se.project,maxWidth:p?.max_width??Se.maxWidth,maxRows:p?.max_rows??Se.maxRows})}function Ke(p,y,g){return Na({op:p,sessionProject:y??null,targetProject:g})}async function Eu(p){let y=v.get(p.worker_id),g=Ke(Ia(p.command),p.session_project,y?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(p.command!=="stop")throw new Error(`redskilled does not implement ${p.command}: it owns birth, death and limits, and ${p.command} is a work decision the project's own bundle makes on top of them`);let _=y!=null&&await Au(y,p.detail??"stopped by its own project");return{version:1,command:p.command,worker_id:p.worker_id,applied:_,reach:g,detail:_?`redskilled stopped Worker ${JSON.stringify(p.worker_id)} of project ${JSON.stringify(y.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(p.worker_id)} to stop`}}function lt(p){v.delete(p),ke.delete(p),He.delete(p),Zn.delete(p)}function ni(p){let y=v.get(p.worker_id),g=Ke("worker-heartbeat",p.session_project,y?.project_label??null);if(!g.permitted)throw new Error(g.reason);if(typeof p.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(y==null)return{version:1,worker_id:p.worker_id,accepted:!1,reach:g,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(p.worker_id)} to publish a line for`};let _=o();He.set(p.worker_id,{line:p.last_log_line,published_at:_,source:"heartbeat"});let x=p.display===void 0?null:zd(p.display);if(x!=null){let P={display:x,published_at:_};Zn.set(p.worker_id,P),Ru(P,p.worker_id)}return{version:1,worker_id:p.worker_id,accepted:!0,reach:g,published_at:_,detail:`redskilled stored a line for Worker ${JSON.stringify(p.worker_id)} without reading it`}}async function Pu(p,y,g){let _=`exit code=${y??"null"} signal=${g??"null"}`;if(p.unit!=null&&p.unit!==""&&await Du(p)){Ou(p,`its launch client ended (${_}) while unit ${JSON.stringify(p.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}lt(p.worker_id),ue("worker-death",p,_,{exitCode:y,signal:g}),I()}function ju(p,y){if(!Number.isFinite(y)||y<0){tt[p]=Tt;return}let g=tt[p]??Tt,_=ya(g,y,Date.parse(o()));tt[p]=_,_.haltUntilMs!=null&&g.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(p)} lost ${_.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(_.haltUntilMs).toISOString()}
80
- `)}async function Du(p){try{return await w(p)===!0}catch{return!1}}function Ou(p,y){let g=p.unit==null?null:ce(p.unit);v.set(p.worker_id,{...p,...g!=null&&g>0?{pid:g}:{},warnings:[...p.warnings,y]}),ke.add(p.worker_id),I()}function ti(p,y){let g=Ke("project-register",y,p.project_label);if(!g.permitted)throw new Error(g.reason);let _=o();Sn(_);let x=Oa(p,{now:_,held:$.get(p.project_label)});return $.set(x.project_label,x),I(),{version:1,registration:x,reach:g,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 ri(p,y={}){let g=Ke("project-renew",y.sessionProject,p);if(!g.permitted)throw new Error(g.reason);let _=o();Sn(_);let x=$.get(p);if(x==null)throw new Nt(p);let P=Aa(x,{now:_,...y.renewWithinMs==null?{}:{renew_within_ms:y.renewWithinMs},...y.launch==null?{}:{launch:y.launch}});return $.set(P.project_label,P),I(),{version:1,registration:P,reach:g,detail:`redskilled renewed the registration for project ${JSON.stringify(P.project_label)}, which now stands until ${P.renew_by} after renewal ${P.renewals}`+(y.launch==null?"":`, carrying launch revision ${P.launch_revision} for its next Worker`)}}function oi(p,y){let g=Ke("project-deregister",y,p);if(!g.permitted)throw new Error(g.reason);let _=$.delete(p);return{version:1,project_label:p,released:_,reach:g,detail:_?`redskilled released the registration for project ${JSON.stringify(p)}`:`redskilled held no registration for project ${JSON.stringify(p)}, so there was nothing to release`}}async function Au(p,y){try{await z(p)}catch{}return lt(p.worker_id),ue("worker-death",p,y),I(),!0}function si(p){return la({ceiling:i,workers:[...v.values()],budget:p.budget,projectLabel:p.project_label})}function _r(p){let y=aa({ceiling:i,workers:[...v.values()],budget:p.budget}),g=s({spec:p,admission:si(p),memoryCeiling:y,clock:o,onExit:(_,x,P)=>{let pe=v.get(_);if(pe==null){I();return}Pu(pe,x,P).catch(()=>{})}});return v.set(g.worker.worker_id,g.worker),ue("worker-birth",g.worker,null),I(),g}function ue(p,y,g,_={}){if(K)return;let x=o();(p==="worker-death"||p==="worker-budget-kill")&&(bu({worker_id:y.worker_id,ts:x,outcome:p}),ju(y.project_label,Date.parse(x)-Date.parse(y.started_at))),k.record({event:p,worker:y,ts:x,detail:g,..._.exitCode!==void 0?{exitCode:_.exitCode}:{},..._.signal!==void 0?{signal:_.signal}:{}}).catch(()=>{})}async function wr(){let p=Date.parse(o()),y=[...v.values()].filter(_=>{if(ke.has(_.worker_id))return!0;let x=Date.parse(_.started_at);return!Number.isFinite(x)||p-x>=D});if(y.length===0)return[];let{dead:g}=await us(y,w);for(let _ of g)lt(_.worker_id),ue("worker-death",_,"the host no longer confirms this Worker");return g.length>0&&I(),g}async function ii(p,y){let g=v.get(p);if(!g)return!1;try{await z(g)}catch{}return lt(p),ue("worker-budget-kill",g,y),I(),!0}async function li(){let p=[...v.values()];if(p.length===0)return[];let y;try{y=await Be(p)}catch{return[]}let g=y.rss;Vs=g,ur=o(),Lu(y.cpu_seconds,ur);let{terminations:_}=nd({workers:p,rss:g}),x=[];for(let P of _)await ii(P.worker_id,P.reason)&&x.push(P);return x}function Lu(p,y){for(let[g,_]of Object.entries(p)){if(typeof _!="number"||!Number.isFinite(_))continue;let x=v.get(g);x&&v.set(g,{...x,cpu:{cpu_seconds:_,sampled_at:y}})}}async function Tu(){try{return Ws<=0?await Ms(t):await new Promise(p=>{let y=setTimeout(()=>p(xr()),Ws);y.unref(),Ms(t).then(g=>{clearTimeout(y),p(g)},()=>{clearTimeout(y),p(xr())})})}catch{return xr()}}function xr(){try{return hu(t)}catch{return null}}async function ai(){if(qn(t))return fr+=1,pr=o(),mr="local-build",{act:"hold",reason:"local-build"};let p=mc(await Tu()),y=p.version;qs=y,hr=p.newest??null,pr=o(),Qs=hc({running:t,newest:hr,supervised:Bs});let g=yc({running:t,published:y,supervised:Bs});return Js=g.act==="replace",fr+=1,mr=g.act==="hold"?g.reason:null,mn!=="in-progress"&&(mn=g.act==="replace"?"pending":"none"),g}async function at(){let p=await ai();if(p.act!=="replace"||mn==="in-progress")return p;let y=kc(p,Hs);return mn="in-progress",await k.flush().catch(()=>{}),await ct({reason:"replaced"}),Rc(y,n,{...r==null?{}:{idleMs:r},io:Hs}),p}function $u(){K||_n!=null||Cs<=0||(!yu&&Fs>0&&(rt=setTimeout(()=>{at().catch(()=>{})},Fs),rt.unref()),_n=setInterval(()=>{at().catch(()=>{})},Cs),_n.unref())}async function di(){return await l.renew(a).catch(()=>null)}function Iu(){K||Rn!=null||Ns<=0||(Rn=setInterval(()=>{di()},Ns),Rn.unref())}function Nu(){K||kn!=null||Is<=0||(kn=setInterval(()=>{li().catch(()=>{})},Is),kn.unref())}function Mu(){K||wn!=null||te==null||te.projects.length===0||Us<=0||(br().catch(()=>{}),wn=setInterval(()=>{br().catch(()=>{})},Us),wn.unref())}function Cu(){K||xn!=null||Gs<=0||(xn=setInterval(()=>{Zs().catch(()=>{})},Gs),xn.unref())}function Wu(){K||bn!=null||Ks<=0||(bn=setInterval(()=>{ei().catch(()=>{})},Ks),bn.unref())}function I(){K||(Ue&&clearTimeout(Ue),Ue=setTimeout(()=>{wr().catch(()=>{}).then(()=>ci())},r),Ue.unref())}function ci(){return v.size>0?(I(),"held-by-workers"):(Sn(o()),$.size>0?(I(),"held-by-registrations"):(Fu(),"exited"))}async function Fu(){if(!qn(t)){if((await at().catch(()=>null))?.act==="replace"||kr||K)return;if(v.size>0||$.size>0){I();return}}await ct({reason:"idle"})}function dt(p){return Ra({reason:p,socketPath:n.socketPath,daemonVersion:t,pid:a.pid,workers:[...v.values()],projects:[...$.keys()]})}function ui(p){if(ot!=null)return ot;let y=p.reason??"requested",g=p.note?.trim();return ot=k.recordDaemonStop({ts:o(),pid:a.pid,socketPath:n.socketPath,reason:y,detail:g==null||g===""?dt(y).detail:`${dt(y).detail} \u2014 ${g}`,...p.signal==null?{}:{signal:p.signal}}).catch(()=>{}),ot}async function ct(p={}){if(kr)return await Rr;kr=!0,await ui(p),K=!0,Ue&&clearTimeout(Ue),kn&&clearInterval(kn),Rn&&clearInterval(Rn),_n&&clearInterval(_n),rt&&clearTimeout(rt),wn&&clearInterval(wn),Ge&&clearTimeout(Ge),xn&&clearInterval(xn),bn&&clearInterval(bn),await k.flush().catch(()=>{}),h.close();for(let y of cr)y.destroy();return await new Promise(y=>h.once("close",()=>y())),await Lc(n.socketPath,{force:!0}),await l.release(a).catch(()=>{}),await u.release(d).catch(()=>{}),zs(),await Rr}let pi=await k.read().catch(()=>[]);et=Ut(pi.filter(p=>p.event==="worker-death"||p.event==="worker-budget-kill").map(p=>({worker_id:p.worker_id,ts:p.ts,outcome:p.event})),p=>p.ts,{now:o()});let Bu=fa(pi),Sr=await us(Bu,w);for(let p of Sr.alive){let y=Ud(p),g=y.unit==null||B(y.pid)?null:ce(y.unit);v.set(y.worker_id,g!=null&&g>0?{...y,pid:g}:y),ke.add(y.worker_id)}for(let p of Sr.dead)ue("worker-death",p,"the Worker ended while no daemon was watching");let Hu=Hd({units:await Promise.resolve(de()).catch(()=>[]),held:[...v.values()],mainPid:ce,now:b});for(let p of Hu)v.set(p.worker_id,p),ke.add(p.worker_id),ue("worker-birth",p,"adopted from an active unit with no birth on this lane");for(let p of Sr.alive){if(p.log_path==null||He.has(p.worker_id))continue;let y=await lr(p.log_path).catch(()=>null);y==null||y.trim()===""||He.set(p.worker_id,{line:y,published_at:o(),source:"rehydrated"})}h.on("connection",p=>{cr.add(p),p.once("close",()=>cr.delete(p)),I(),TR(p,async(y,g)=>{I();let _=await Uu(y);g(_),y.op==="shutdown"&&setImmediate(()=>void ct({reason:"requested"}))})});async function Uu(p){try{if(p.op==="ping")return{id:p.id,ok:!0,value:{pong:!0,protocol_version:Yt,daemon_version:t,pid:a.pid}};if(p.op==="host-state")return{id:p.id,ok:!0,value:st()};if(p.op==="statusline-payload")return{id:p.id,ok:!0,value:ud(it(),p.extras)};if(p.op==="statusline-string")return{id:p.id,ok:!0,value:Su(p.render)};if(p.op==="statusline-dashboard")return{id:p.id,ok:!0,value:vu(p.dashboard)};if(p.op==="worker-heartbeat")return{id:p.id,ok:!0,value:ni(p.heartbeat)};if(p.op==="project-register")return{id:p.id,ok:!0,value:ti(p.registration,p.session_project)};if(p.op==="project-renew")return{id:p.id,ok:!0,value:ri(p.project_label,{...p.session_project==null?{}:{sessionProject:p.session_project},...p.renew_within_ms==null?{}:{renewWithinMs:p.renew_within_ms},...p.launch==null?{}:{launch:p.launch}})};if(p.op==="project-deregister")return{id:p.id,ok:!0,value:oi(p.project_label,p.session_project)};if(p.op==="worker-command")return{id:p.id,ok:!0,value:await Eu(p.command)};if(p.op==="worker-start"){let g=Ke("worker-start",p.session_project,p.spec.project_label);if(!g.permitted)return{id:p.id,ok:!1,error:g.reason};let _=_r(p.spec);return await k.flush().catch(()=>{}),{id:p.id,ok:!0,value:{worker:_.worker,admission:_.admission,warnings:_.warnings}}}if(p.op==="shutdown"){let g=dt("requested");return await ui({reason:"requested",...p.detail==null?{}:{note:p.detail}}),{id:p.id,ok:!0,value:g}}let y=p;return{id:y.id??Qn(),ok:!1,error:`unsupported redskilled op: ${y.op??"unknown"}`}}catch(y){return{id:p.id??Qn(),ok:!1,error:y instanceof Error?y.message:String(y)}}}return I(),Nu(),Iu(),$u(),Mu(),_u(),Cu(),Wu(),{socketPath:n.socketPath,lease:m.lease,startedAt:b,closed:Rr,startWorker:_r,admit:si,ceiling:()=>i,killWorkerOverBudget:ii,sampleMemoryBudgets:li,renewLease:di,pollRepositoryActivity:br,pollGithubBalance:Xs,githubBalance:()=>hn,pollQueueDiscovery:Zs,queueDiscovery:()=>Re,driveDemand:ei,demand:()=>nt,sweepWorkerLiveness:wr,publishWorkerHeartbeat:ni,reattached:()=>[...ke].map(p=>v.get(p)).filter(p=>p!=null),flushEvents:()=>k.flush(),trackWorker(p){v.set(p.worker_id,p),ue("worker-birth",p,null),I()},releaseWorker(p){let y=v.get(p),g=v.delete(p);return ke.delete(p),He.delete(p),Zn.delete(p),y&&ue("worker-death",y,"released by the daemon"),I(),g},workerCount:()=>v.size,registerProject:ti,renewProject:ri,deregisterProject:oi,registrations:()=>st().registrations??[],hostState:st,statuslinePayload:it,evaluateIdle:ci,observePublishedVersion:ai,checkForReplacement:at,stopReport:dt,stop:ct}}async function LR(e){for(let n=0;n<2;n++){let t=vR();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 ne(e))throw new pn(e);await Lc(e,{force:!0})}}throw new pn(e)}async function ne(e,n=250){try{return(await vt({socketPath:e,timeoutMs:n},{id:Qn(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function TR(e,n){Hl(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??Qn(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function xs(e){let n=e.socketPath,t=$R(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 ${$c(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 \`${ve("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 \`${ve("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function Ss(e){return`${e.reason} ${e.repair}`}function $R(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:IR(n.acquired_at,e.now??new Date().toISOString())}}function IR(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 $c(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`}me();var Mc=1e4,Fe=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"?`. ${Ss(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},vs=class extends Fe{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}};async function or(e,n={}){let t=n.answers??await ne(e.socketPath),r=await Jn(e.leasePath).catch(()=>{});return xs({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&B(r.pid)})}async function Es(e,n={}){try{return await WR(e,n)}catch(t){if(t instanceof xe||t instanceof Fe)throw t;let r=await or(e).catch(()=>{});throw new Fe(e.socketPath,t,r)}}async function WR(e,n){if(await MR(CR(e.socketPath),{recursive:!0,mode:448}),await ne(e.socketPath))return"already-running";await HR(e);let t=await BR(e,n);if(t!=null)return t;let r=await Gl(e.lockPath,{...n.spawnLockMaxAgeMs==null?{}:{maxAgeMs:n.spawnLockMaxAgeMs},onReap:n.onSpawnLockReaped??FR});if(!r.acquired)return await Ic(e,n,void 0,r),"joined";try{if(await ne(e.socketPath))return"already-running";let o=await KR(e,n);return await Ic(e,n,o),"spawned"}finally{await Kl(r)}}function FR(e){process.stderr.write(`redskilled: reaped the spawn lock ${JSON.stringify(e.lockPath)} (${e.reason}, ${Math.round(e.ageMs/1e3)}s old, holder ${e.holder==null?"unnamed":`pid ${e.holder.pid}`}) and went on to spawn
81
- `)}async function BR(e,n){let t=await or(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??Mc,o=Date.now()+r;for(;;){if(await ne(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(i=>setTimeout(i,25))}let s=await or(e).catch(()=>{});if(s==null||s.kind!=="held-unresponsive")return null;throw new vs(e.socketPath,s,new Error(`it did not answer a ping within ${r}ms, and no second daemon was spawned because pid ${s.holder?.pid??"unknown"} still holds this socket`))}async function HR(e){let t=await It(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&B(t.pid))throw new xe(e.machineClaimPath,"held",t)}async function Cc(e,n,t={}){await Es(e,t);let r;try{r=await Gn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:Nc()})}catch(o){throw new Fe(e.socketPath,o,await or(e).catch(()=>{}))}if(!r.ok)throw new Error(r.error);return r.value}async function Wc(e,n={},t={}){if(!await ne(e.socketPath))return ba(e.socketPath);let r;try{r=await Gn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Nc(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new Fe(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!Eo(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await UR(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 UR(e,n){let t=Date.now()+n;for(;;){if(!await ne(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function Fc(e,n={}){let t=await Cc(e,{op:"host-state"},n);if(!Rd(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function GR(e,n={},t){let r=await Cc(e,{op:"statusline-payload",...n.sessionProject!=null?{session_project:n.sessionProject}:{},...t==null?{}:{extras:t}},n);if(!Yo(r))throw new Error("redskilled daemon returned a malformed statusline payload");return r}async function Bc(e,n=j,t={}){let r=await GR(e,t,{vitals:!0,logs:n.verbose});return Ce(r,n)}async function Ic(e,n,t,r){let o=Date.now()+(n.readyTimeoutMs??Mc);for(;;){if(await ne(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=o){if(r!=null)throw new Error(`no redskilled daemon answered on ${JSON.stringify(e.socketPath)} within the ready window, and ${Vl(r)}`);let s=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${s}`)}await new Promise(s=>setTimeout(s,25))}}async function KR(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await ea({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,...Te(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=NR(r.command,s,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return i.on("error",a=>{o.failure=a}),i.on("exit",(a,l)=>{o.exit=l?`died on ${l}`:`exited with code ${a??-1}`}),i.unref(),o}me();import{chmod as Jc,mkdir as zc,readFile as Yc,stat as tb,writeFile as rb}from"node:fs/promises";import{homedir as Ds}from"node:os";import{dirname as ob,join as Os}from"node:path";import{join as VR}from"node:path";var Hc=["local","tmp","host"],qR="local",zn="plugins.dev.workspace.target";var Ps=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function Gc(e){let n=nn(e,zn),t=zR(n??"").trim();return t===""?void 0:t}function Kc(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:qR};let t=Hc.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 Ps(`${zn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${Hc.join(", ")}) or an absolute parent directory for Workers.`)}function Vc(e,n){return e.kind==="preset"?e.preset==="host":QR(JR(e.parentDir,n),Le(n))}function JR(e,n){return e==="~"?Uc(n):e.startsWith("~/")?VR(n,e.slice(2)):Uc(e)}function QR(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Uc(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function zR(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}me();import{createHash as YR}from"node:crypto";import{hostname as XR}from"node:os";import{join as sr}from"node:path";var fn="redskilled.sock",ZR="REDSKILLED_SESSION";function eb(e={}){let n=e.env??process.env,t=n[ZR]?.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 nb(e={}){return qc(e.host??XR())}function ge(e={}){let n=eb(e),t=e.runtimeDir??Et({key:`redskilled:${n}`,socketFileName:fn,env:e.env,uid:e.uid}),r=nb(e);return{sessionKey:n,sessionKeyHash:qc(n),machineIdHash:r,runtimeDir:t,socketPath:sr(t,fn),lockPath:sr(t,"redskilled.spawn.lock"),leasePath:sr(t,"redskilled.lease.toon"),eventLanePath:sr(t,ua),machineClaimPath:e.machineClaimPath??$t({env:e.env,machineIdHash:r,platform:e.platform})}}function qc(e){return YR("sha256").update(e).digest("hex").slice(0,12)}var js=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${ve("red-skills-redskilled",["provision"])}\` directly`;async function Xc(e=Ds()){let n=Le(e),t=await Ls(n);return t===void 0?(await zc(n,{recursive:!0,mode:ie}),await Jc(n,ie),{path:n,created:!0,tightened:!1,mode:ie}):t===ie?{path:n,created:!1,tightened:!1,mode:t}:(await Jc(n,ie),{path:n,created:!1,tightened:!0,mode:ie})}var Zc={needed:!1,declaredBy:`no ${zn} in view`};async function As(e={}){let n=e.homeDir??Ds(),t=e.declaredTarget?.trim();if(t)return Qc(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return Zc;let o=Os(r,".red","config.yaml"),s=await Yc(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=Gc(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Qc(i,n,o)}function Qc(e,n,t){let r=`${zn}: ${e} (${t})`;try{return{needed:Vc(Kc(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function eu(e){let n=[sb(e),ib(e),lb(e),ab(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 sb(e){let n=e.homeNeed??Zc;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:js}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??ie;return t!==ie?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${ie.toString(8)}`,fix:`${js} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function ib(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 \`${ve("red-skills-redskilled",["provision"])}\``}}function lb(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:`${js} \u2014 it starts the daemon and waits for the socket`}}function ab(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 nu(e={}){let n=e.env??process.env,t=e.homeDir??Ds(),r=e.paths??ge({env:n}),o=Le(t),[s,i,a]=await Promise.all([Ls(o),ne(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):As({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:a,entry:we(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await cb(ub(e,n,t),n)}}var db="redskilled.service";function tu(e){return Os(e,"systemd","user",db)}function ru(e){let n=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${n}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
82
- `)}async function ou(e){let n=tu(e.configHome);return await Ls(n)!==void 0?{path:n,status:"already-present"}:(await zc(ob(n),{recursive:!0}),await rb(n,e.unit,"utf8"),{path:n,status:"installed"})}async function cb(e,n){if(process.platform!=="linux")return"unsupported";try{return await Yc(tu(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function ub(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??Os(t,".config")}async function Ls(e){try{return(await tb(e)).mode&511}catch{return}}import{readdir as iu,rm as pb,stat as fb}from"node:fs/promises";import{dirname as mb,join as Ts}from"node:path";var hb=5*6e4,yb="redskilled.";function gb(e={}){let n=e.env??process.env,t=i=>mb(Et({key:"redskilled:reclaim-probe",socketFileName:fn,env:i,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=n,s=[t(n),t(o)];return[...new Set(s)]}async function lu(e={}){let n=e.roots??gb(e),t=e.graceMs??hb,r=e.now??Date.now,o=e.isPidAlive??B,s=e.answers??_b,i=e.dryRun===!0,a=[];for(let l of n){let d;try{d=(await iu(l,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name)}catch{continue}for(let c of d.sort())a.push(await kb(Ts(l,c),{graceMs:t,now:r,pidAlive:o,answers:s,dryRun:i}))}return{roots:n,scanned:a.length,reclaimed:a.filter(l=>l.verdict==="reclaimed").length,dryRun:i,entries:a}}async function kb(e,n){let t;try{t=(await iu(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:au(i),removed:[]}}let r=t.filter(i=>i.startsWith(yb));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await Rb(Ts(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 su(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(fn)&&await n.answers(Ts(e,fn)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await bb(e,n.now);return s!==void 0&&s<n.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(s/1e3)}s ago`,removed:[]}:await su(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function su(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await pb(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:au(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function Rb(e){try{return await Jn(e)}catch{return}}async function bb(e,n){try{return Math.max(0,n()-(await fb(e)).mtimeMs)}catch{return}}async function _b(e){try{return(await Gn({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function au(e){return e instanceof Error?e.message:String(e)}var wb="plugins.dev.statusline",xb="dev.statusline";function Sb(e){let n=[],t=a=>{for(let l of[wb,xb]){let d=`${l}.${a}`,c=nn(e,d)?.trim();if(c!=null&&c!=="")return{key:d,value:c}}},r=t("mode"),o={};r!=null&&(r.value==="local"||r.value==="global"?o.mode=r.value:n.push({...r,reason:"expected `local` or `global`"}));let s=[{leaf:"max_workers",assign:a=>{o.maxWorkers=a}},{leaf:"max_projects",assign:a=>{o.maxProjects=a}},{leaf:"max_width",assign:a=>{o.maxWidth=a}}];for(let a of s){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 i=t("verbose");return i!=null&&(i.value==="true"||i.value==="false"?o.verbose=i.value==="true":n.push({...i,reason:"expected `true` or `false`"})),{config:o,warnings:n}}var vb={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 du(e){let{values:n,positionals:t}=Oe(e,vb),r=[],o={},s=n.mode??t.find(a=>a==="global"||a==="local");s!=null&&(s==="local"||s==="global"?o.mode=s:r.push({key:"--mode",value:s,reason:"expected `local` or `global`"})),n.project!=null&&(o.project=n.project),n.verbose!==void 0&&(o.verbose=n.verbose===!0);let i=[{flag:"max-workers",assign:a=>{o.maxWorkers=a}},{flag:"max-projects",assign:a=>{o.maxProjects=a}},{flag:"max-width",assign:a=>{o.maxWidth=a}}];for(let a of i){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 cu(e={}){let n=e.configText==null?{config:{},warnings:[]}:Sb(e.configText),t=e.flags??{};return{options:{...j,mode:t.mode??n.config.mode??j.mode,project:t.project!==void 0?t.project:e.project??j.project,maxWorkers:t.maxWorkers??n.config.maxWorkers??j.maxWorkers,maxProjects:t.maxProjects??n.config.maxProjects??j.maxProjects,maxWidth:t.maxWidth??n.config.maxWidth??j.maxWidth,verbose:t.verbose??n.config.verbose??j.verbose},warnings:n.warnings}}var Pb=`Usage: redskilled <command> [options]
78
+ `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function fR(e,n={}){let t=n.env??process.env,r=n.exists??lR,o=n.execPath??process.execPath,s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,l=[],a=[[uc(At(t),i),"bundle-cache"]];s&&a.push([uc(dR(cR(s)),i),"caller-sibling-bundle"]);for(let[d,c]of a)if(l.push(d),r(d))return{command:o,args:[d],version:e,source:c,searched:l};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new Rs(e,l);return{command:t.RED_SKILLS_NPX||"npx",args:["-y","-p",`@reddb-io/red-skills@${e}`,"red-skills-redskilled"],version:e,source:"pinned-dispatch",searched:l}}function _c(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>fR(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function wc(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??hR)(pc),{...e,exitCode:pc};let o=[...e.entry.args,...Te(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??mR(r.env))(e.entry,o),e}function mR(e){return(n,t)=>{let r=iR(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[hc]:"1"}});r.on("error",()=>{}),r.unref()}}function hR(e){process.exitCode=e,process.exit(e)}async function xc(e,n=process.env,t=gR){let r=vc(n),o=Ec(e,n);if(n[uR]==="1")return{version:o,newest:r};let s=ee(e)===null?"0.0.0":e;try{let i=await Zl({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function Sc(e,n=process.env,t){let r=t??bs;return{version:Ec(e,n,r),newest:vc(n,r)}}function vc(e=process.env,n=bs){return jc(Pc(e,n))}function Ec(e,n=process.env,t=bs){let r=ee(e.trim())?.major;return r===void 0?null:jc(Pc(n,t).filter(o=>ee(o)?.major===r))}function Pc(e,n){let t=[];for(let r of n(At(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||ee(o)===null||t.push(o)}return t}function jc(e){let n=null;for(let t of e)(n===null||ms(t,n)>0)&&(n=t);return n}function bs(e){try{return aR(e)}catch{return[]}}async function gR(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 yR,readFile as kR,rename as RR,rm as _s,writeFile as Dc}from"node:fs/promises";import{randomUUID as bR}from"node:crypto";import{dirname as _R}from"node:path";var rr=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function Yn(e){let n;try{n=await kR(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=wR(n);return xR(t)?t:void 0}var Oc;function Lc(){return Oc??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Oc}function Tc(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??B;async function s(){return await Yn(e)}async function i(a){let d=`${e}.${a.pid}.${bR()}.tmp`;await Dc(d,Ac(a),{encoding:"utf8",mode:384}),await RR(d,e)}function l(a,d){return{version:1,pid:a.pid,start_time:a.startTime,session_key_hash:n.sessionKeyHash,machine_id_hash:n.machineIdHash,socket_path:n.socketPath,acquired_at:d,renewed_at:d}}return{read:s,async acquire(a){await yR(_R(e),{recursive:!0,mode:448});let d=!1;for(;;){let c=r(),u=l(a,c);try{return await Dc(e,Ac(u),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:u}}catch(m){if(m.code!=="EEXIST")throw m}let f=await s();if(!f){await _s(e,{force:!0}),d=!0;continue}if(ws(f,a))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await _s(e,{force:!0}),d=!0}},async renew(a){let d=await s();if(!d||!ws(d,a))throw new rr(e);let c={...d,renewed_at:r()};return await i(c),c},async release(a){let d=await s();if(!d)return!1;if(!ws(d,a))throw new rr(e);return await _s(e,{force:!0}),!0}}}function ws(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function Ac(e){return`${C(e,{keyedMapCollapse:!0})}
79
+ `}function wR(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return q(n)}catch{return null}}}function xR(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 xs=3e5,AR=1e4,LR=6e4,TR=15e3,$R=3e4,$c=16,fn=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},IR="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Nc(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??xs,o=e.clock??(()=>new Date().toISOString()),s=e.launch??oc,i=e.ceiling??pa();e.repositoryActivity!=null&&zo(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??Lc(),a=e.leaseStore??Tc(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??Da(),c={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},u=e.machineClaimStore??Ct(n.machineClaimPath,c,{clock:o});await jR(OR(n.socketPath),{recursive:!0,mode:448});let f=await u.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new fn(n.socketPath):new Se(u.claimPath,f.reason,f.claim);let m=await a.acquire(l);if(!m.acquired)throw await u.release(d).catch(()=>{}),new fn(n.socketPath,m.lease);let h;try{h=await NR(n.socketPath)}catch(p){throw await a.release(l).catch(()=>{}),await u.release(d).catch(()=>{}),p}let b=o(),k=e.eventLane??ha(n.eventLanePath),w=e.liveness??Fd,D=e.livenessGraceMs??Wd,z=e.stopWorker??qd,ue=e.unitInventory??(()=>Ud(n.machineClaimPath,Mt({machineIdHash:n.machineIdHash}))?Gd():[]),pe=e.unitMainPid??Hd,Be=e.treeSampler??sd,lr=e.readLogTail??sc,Cs=e.sampleMs??TR,Ws=e.leaseRenewMs??$R,Fs=e.publishedVersion??(p=>xc(p)),Bs=e.replaceCheckMs??mc,Hs=e.publishedProbeTimeoutMs??AR,Ru=e.localPublishedEvidence??(p=>Sc(p,e.replacementIO?.env??process.env)),bu=e.bornByReplacement??gc(),Us=e.replaceBootCheckMs??LR,Gs=e.supervised??bc(),Ks=e.replacementIO??{},te=e.repositoryActivity,Vs=te?.intervalMs??Qo,et=e.githubBalance,Ee=e.queueDiscovery,nt=Ee?.transport??te?.transport,ar=Ee?.unconfiguredReason??IR,qs=Ee?.intervalMs??15e3,Js=e.demandMs??15e3,_u=e.demandBackoffMs??3e4,v=new Map,Re=new Set,He=new Map,tt=new Map,dr=[],rt=[],$=new Map,cr=new Set,Qs={},ur=null,zs=null,pr=null,Ys=!1,fr=0,mr=null,hn="none",hr=null,Xs=null,gr=null,gn=null,be=null,ot=null,yn=[],kn=null,st={},yr=!1,Ue,Rn,bn,_n,wn,it,xn,Ge,Sn,K=!1,kr=!1,lt=null,Zs,Rr=new Promise(p=>{Zs=p});function vn(p){ei(p);let g=Date.parse(p),y=Ma($.values(),g);for(let _ of y.lapsed)$.delete(_.project_label),wu(_,g);return y.lapsed}function wu(p,g){let y=Number.isFinite(g)?new Date(g).toISOString():p.renew_by;yn.push({project_label:p.project_label,at:y,renew_by:p.renew_by,renewals:p.renewals,sustains:p.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(p.project_label)}: it stood until ${p.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`}),yn.length>$c&&yn.splice(0,yn.length-$c)}function ei(p){if($.size===0)return;let g=Date.parse(p);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((be?.projects??[]).map(x=>[x.project_label,x]));for(let x of[...$.values()]){let P=_.get(x.project_label),me=Ia(x,{now:p,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:y[x.project_label]??0});me.registration!==x&&$.set(x.project_label,me.registration)}}function at(){let p=o();return vn(p),_d({now:p,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:l.pid,startedAt:b,scope:Oa(u.claimPath,c,d),workers:[...v.values()],registrations:[...$.values()],lapses:yn,queue:be,published:{version:zs,checkedAt:pr,newer:Ys,replacement:hn,newest:hr,majorHold:Xs,checks:fr,holdReason:mr}})}function dt(){return hd({hostState:at(),ceiling:i,rss:Qs,sampledAt:ur,logLines:Object.fromEntries(He),displays:Object.fromEntries(tt),now:o(),reattachedWorkerIds:[...Re],repositoryActivity:gr,githubBalance:gn,...e.deaths===void 0?{}:{deaths:e.deaths},metrics:td({observations:dr,outcomes:rt,now:o()})})}function xu(p,g){dr=Vt([...dr,{worker_id:g,observed_at:p.published_at,tokens:p.display.tokens,tools:p.display.tools,runner:p.display.runner,model:p.display.model}],y=>y.observed_at,{now:o()})}function Su(p){rt=Vt([...rt,p],g=>g.ts,{now:o()})}async function br(){return te==null||te.projects.length===0?null:(gr=await dd({projects:te.projects,hostTokenRef:te.hostTokenRef,transport:te.transport,closedWindowMs:te.closedWindowMs,now:o()}),gr)}async function ni(){return et==null?null:(gn=await Wo({transport:et.transport,now:o()}),gn)}function vu(){if(K||Ge!=null||et==null)return;let p=()=>{Ge=void 0,ni().catch(()=>{}).then(()=>{if(K)return;let g=et.intervalMsOverride??Kt(gn??Eu(),{now:o()});Ge=setTimeout(p,g),Ge.unref()})};p()}function Eu(){return Gt(o())}function Pu(){if(!(nt!=null||Ee?.armTransport==null))try{let p=Ee.armTransport();if(p.transport!=null){nt=p.transport;return}p.unconfiguredReason!=null&&(ar=p.unconfiguredReason)}catch(p){ar=`this host could not resolve a tracker credential: ${p instanceof Error?p.message:String(p)}`}}async function ti(){let p=o();vn(p);let g=[...$.values()].map(y=>({project_label:y.project_label,selector:y.selector})).sort((y,_)=>y.project_label.localeCompare(_.project_label));return g.length===0?null:(Pu(),nt==null?(be=Qd(g,p,ar),be):(be=await zd({projects:g,transport:nt,now:p,...Ee?.batchSize==null?{}:{batchSize:Ee.batchSize}}),ei(o()),be))}async function ri(){let p=o();if(yr)return ot??ka(p);yr=!0;try{await wr().catch(()=>{});let g={};for(let A of v.values())g[A.project_label]=(g[A.project_label]??0)+1;let y={};for(let A of be?.projects??[])y[A.project_label]=A.depth;let _=Date.parse(p),x=ya({projects:[...$.values()].map(A=>({project_label:A.project_label,selector:A.selector,argv:A.argv,workspace_path:A.workspace_path,target:A.target})),queue:y,live:g,nowMs:Number.isFinite(_)?_:0,backoffUntilMs:kn,birthHaltUntilMs:ba(st,Number.isFinite(_)?_:0)}),P=[],me=null;for(let A of x.births){let Ve,Ju=Xn(),mt=$.get(A.project_label),gi=La({argv:A.argv,...mt?.env==null?{}:{env:mt.env},...mt?.log_path==null?{}:{log_path:mt.log_path}},{worker_id:Ju,slot:A.index,workspace_path:A.workspace_path},{project_label:A.project_label});try{Ve=_r(gi)}catch(vr){me=vr instanceof Error?vr.message:String(vr),kn=(Number.isFinite(_)?_:Date.now())+_u;break}P.push({project_label:A.project_label,worker_id:Ve.worker.worker_id,pid:Ve.worker.pid,warnings:gi.log_path==null?[...Ve.warnings,`project ${JSON.stringify(A.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(Ve.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:Ve.warnings})}return me==null&&x.births.length>0&&(kn=null),ot={version:1,at:p,requested:x.births.length,granted:P,shortfall:x.births.length-P.length,refusal:me,retry_after:kn==null?null:new Date(kn).toISOString(),projects:x.intents},ot}finally{yr=!1}}function ju(p){return Ce(dt(),{...j,mode:p?.mode??j.mode,project:p?.project??j.project,maxWorkers:p?.max_workers??j.maxWorkers,maxProjects:p?.max_projects??j.maxProjects,maxWidth:p?.max_width??j.maxWidth,verbose:p?.verbose??j.verbose})}function Du(p){return cn(dt(),{mode:p?.mode??de.mode,project:p?.project??de.project,maxWidth:p?.max_width??de.maxWidth,maxRows:p?.max_rows??de.maxRows})}function Ke(p,g,y){return Wa({op:p,sessionProject:g??null,targetProject:y})}async function Ou(p){let g=v.get(p.worker_id),y=Ke(Ca(p.command),p.session_project,g?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(p.command!=="stop")throw new Error(`redskilled does not implement ${p.command}: it owns birth, death and limits, and ${p.command} is a work decision the project's own bundle makes on top of them`);let _=g!=null&&await Iu(g,p.detail??"stopped by its own project");return{version:1,command:p.command,worker_id:p.worker_id,applied:_,reach:y,detail:_?`redskilled stopped Worker ${JSON.stringify(p.worker_id)} of project ${JSON.stringify(g.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(p.worker_id)} to stop`}}function ct(p){v.delete(p),Re.delete(p),He.delete(p),tt.delete(p)}function oi(p){let g=v.get(p.worker_id),y=Ke("worker-heartbeat",p.session_project,g?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(typeof p.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:p.worker_id,accepted:!1,reach:y,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(p.worker_id)} to publish a line for`};let _=o();He.set(p.worker_id,{line:p.last_log_line,published_at:_,source:"heartbeat"});let x=p.display===void 0?null:Zd(p.display);if(x!=null){let P={display:x,published_at:_};tt.set(p.worker_id,P),xu(P,p.worker_id)}return{version:1,worker_id:p.worker_id,accepted:!0,reach:y,published_at:_,detail:`redskilled stored a line for Worker ${JSON.stringify(p.worker_id)} without reading it`}}async function Au(p,g,y){let _=`exit code=${g??"null"} signal=${y??"null"}`;if(p.unit!=null&&p.unit!==""&&await Tu(p)){$u(p,`its launch client ended (${_}) while unit ${JSON.stringify(p.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}ct(p.worker_id),fe("worker-death",p,_,{exitCode:g,signal:y}),I()}function Lu(p,g){if(!Number.isFinite(g)||g<0){st[p]=Nt;return}let y=st[p]??Nt,_=Ra(y,g,Date.parse(o()));st[p]=_,_.haltUntilMs!=null&&y.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(p)} lost ${_.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(_.haltUntilMs).toISOString()}
80
+ `)}async function Tu(p){try{return await w(p)===!0}catch{return!1}}function $u(p,g){let y=p.unit==null?null:pe(p.unit);v.set(p.worker_id,{...p,...y!=null&&y>0?{pid:y}:{},warnings:[...p.warnings,g]}),Re.add(p.worker_id),I()}function si(p,g){let y=Ke("project-register",g,p.project_label);if(!y.permitted)throw new Error(y.reason);let _=o();vn(_);let x=Ta(p,{now:_,held:$.get(p.project_label)});return $.set(x.project_label,x),I(),{version:1,registration:x,reach:y,detail:`redskilled holds a registration for project ${JSON.stringify(x.project_label)} at a target of ${x.target} until ${x.renew_by}, and has read neither its selector nor its argv`}}function ii(p,g={}){let y=Ke("project-renew",g.sessionProject,p);if(!y.permitted)throw new Error(y.reason);let _=o();vn(_);let x=$.get(p);if(x==null)throw new Wt(p);let P=$a(x,{now:_,...g.renewWithinMs==null?{}:{renew_within_ms:g.renewWithinMs},...g.launch==null?{}:{launch:g.launch}});return $.set(P.project_label,P),I(),{version:1,registration:P,reach:y,detail:`redskilled renewed the registration for project ${JSON.stringify(P.project_label)}, which now stands until ${P.renew_by} after renewal ${P.renewals}`+(g.launch==null?"":`, carrying launch revision ${P.launch_revision} for its next Worker`)}}function li(p,g){let y=Ke("project-deregister",g,p);if(!y.permitted)throw new Error(y.reason);let _=$.delete(p);return{version:1,project_label:p,released:_,reach:y,detail:_?`redskilled released the registration for project ${JSON.stringify(p)}`:`redskilled held no registration for project ${JSON.stringify(p)}, so there was nothing to release`}}async function Iu(p,g){try{await z(p)}catch{}return ct(p.worker_id),fe("worker-death",p,g),I(),!0}function ai(p){return ca({ceiling:i,workers:[...v.values()],budget:p.budget,projectLabel:p.project_label})}function _r(p){let g=ua({ceiling:i,workers:[...v.values()],budget:p.budget}),y=s({spec:p,admission:ai(p),memoryCeiling:g,clock:o,onExit:(_,x,P)=>{let me=v.get(_);if(me==null){I();return}Au(me,x,P).catch(()=>{})}});return v.set(y.worker.worker_id,y.worker),fe("worker-birth",y.worker,null),I(),y}function fe(p,g,y,_={}){if(K)return;let x=o();(p==="worker-death"||p==="worker-budget-kill")&&(Su({worker_id:g.worker_id,ts:x,outcome:p}),Lu(g.project_label,Date.parse(x)-Date.parse(g.started_at))),k.record({event:p,worker:g,ts:x,detail:y,..._.exitCode!==void 0?{exitCode:_.exitCode}:{},..._.signal!==void 0?{signal:_.signal}:{}}).catch(()=>{})}async function wr(){let p=Date.parse(o()),g=[...v.values()].filter(_=>{if(Re.has(_.worker_id))return!0;let x=Date.parse(_.started_at);return!Number.isFinite(x)||p-x>=D});if(g.length===0)return[];let{dead:y}=await ps(g,w);for(let _ of y)ct(_.worker_id),fe("worker-death",_,"the host no longer confirms this Worker");return y.length>0&&I(),y}async function di(p,g){let y=v.get(p);if(!y)return!1;try{await z(y)}catch{}return ct(p),fe("worker-budget-kill",y,g),I(),!0}async function ci(){let p=[...v.values()];if(p.length===0)return[];let g;try{g=await Be(p)}catch{return[]}let y=g.rss;Qs=y,ur=o(),Nu(g.cpu_seconds,ur);let{terminations:_}=od({workers:p,rss:y}),x=[];for(let P of _)await di(P.worker_id,P.reason)&&x.push(P);return x}function Nu(p,g){for(let[y,_]of Object.entries(p)){if(typeof _!="number"||!Number.isFinite(_))continue;let x=v.get(y);x&&v.set(y,{...x,cpu:{cpu_seconds:_,sampled_at:g}})}}async function Mu(){try{return Hs<=0?await Fs(t):await new Promise(p=>{let g=setTimeout(()=>p(xr()),Hs);g.unref(),Fs(t).then(y=>{clearTimeout(g),p(y)},()=>{clearTimeout(g),p(xr())})})}catch{return xr()}}function xr(){try{return Ru(t)}catch{return null}}async function ui(){if(zn(t))return fr+=1,pr=o(),mr="local-build",{act:"hold",reason:"local-build"};let p=yc(await Mu()),g=p.version;zs=g,hr=p.newest??null,pr=o(),Xs=kc({running:t,newest:hr,supervised:Gs});let y=Rc({running:t,published:g,supervised:Gs});return Ys=y.act==="replace",fr+=1,mr=y.act==="hold"?y.reason:null,hn!=="in-progress"&&(hn=y.act==="replace"?"pending":"none"),y}async function ut(){let p=await ui();if(p.act!=="replace"||hn==="in-progress")return p;let g=_c(p,Ks);return hn="in-progress",await k.flush().catch(()=>{}),await ft({reason:"replaced"}),wc(g,n,{...r==null?{}:{idleMs:r},io:Ks}),p}function Cu(){K||wn!=null||Bs<=0||(!bu&&Us>0&&(it=setTimeout(()=>{ut().catch(()=>{})},Us),it.unref()),wn=setInterval(()=>{ut().catch(()=>{})},Bs),wn.unref())}async function pi(){return await a.renew(l).catch(()=>null)}function Wu(){K||bn!=null||Ws<=0||(bn=setInterval(()=>{pi()},Ws),bn.unref())}function Fu(){K||Rn!=null||Cs<=0||(Rn=setInterval(()=>{ci().catch(()=>{})},Cs),Rn.unref())}function Bu(){K||xn!=null||te==null||te.projects.length===0||Vs<=0||(br().catch(()=>{}),xn=setInterval(()=>{br().catch(()=>{})},Vs),xn.unref())}function Hu(){K||Sn!=null||qs<=0||(Sn=setInterval(()=>{ti().catch(()=>{})},qs),Sn.unref())}function Uu(){K||_n!=null||Js<=0||(_n=setInterval(()=>{ri().catch(()=>{})},Js),_n.unref())}function I(){K||(Ue&&clearTimeout(Ue),Ue=setTimeout(()=>{wr().catch(()=>{}).then(()=>fi())},r),Ue.unref())}function fi(){return v.size>0?(I(),"held-by-workers"):(vn(o()),$.size>0?(I(),"held-by-registrations"):(Gu(),"exited"))}async function Gu(){if(!zn(t)){if((await ut().catch(()=>null))?.act==="replace"||kr||K)return;if(v.size>0||$.size>0){I();return}}await ft({reason:"idle"})}function pt(p){return wa({reason:p,socketPath:n.socketPath,daemonVersion:t,pid:l.pid,workers:[...v.values()],projects:[...$.keys()]})}function mi(p){if(lt!=null)return lt;let g=p.reason??"requested",y=p.note?.trim();return lt=k.recordDaemonStop({ts:o(),pid:l.pid,socketPath:n.socketPath,reason:g,detail:y==null||y===""?pt(g).detail:`${pt(g).detail} \u2014 ${y}`,...p.signal==null?{}:{signal:p.signal}}).catch(()=>{}),lt}async function ft(p={}){if(kr)return await Rr;kr=!0,await mi(p),K=!0,Ue&&clearTimeout(Ue),Rn&&clearInterval(Rn),bn&&clearInterval(bn),wn&&clearInterval(wn),it&&clearTimeout(it),xn&&clearInterval(xn),Ge&&clearTimeout(Ge),Sn&&clearInterval(Sn),_n&&clearInterval(_n),await k.flush().catch(()=>{}),h.close();for(let g of cr)g.destroy();return await new Promise(g=>h.once("close",()=>g())),await Ic(n.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await u.release(d).catch(()=>{}),Zs(),await Rr}let hi=await k.read().catch(()=>[]);rt=Vt(hi.filter(p=>p.event==="worker-death"||p.event==="worker-budget-kill").map(p=>({worker_id:p.worker_id,ts:p.ts,outcome:p.event})),p=>p.ts,{now:o()});let Ku=ga(hi),Sr=await ps(Ku,w);for(let p of Sr.alive){let g=Vd(p),y=g.unit==null||B(g.pid)?null:pe(g.unit);v.set(g.worker_id,y!=null&&y>0?{...g,pid:y}:g),Re.add(g.worker_id)}for(let p of Sr.dead)fe("worker-death",p,"the Worker ended while no daemon was watching");let Vu=Kd({units:await Promise.resolve(ue()).catch(()=>[]),held:[...v.values()],mainPid:pe,now:b});for(let p of Vu)v.set(p.worker_id,p),Re.add(p.worker_id),fe("worker-birth",p,"adopted from an active unit with no birth on this lane");for(let p of Sr.alive){if(p.log_path==null||He.has(p.worker_id))continue;let g=await lr(p.log_path).catch(()=>null);g==null||g.trim()===""||He.set(p.worker_id,{line:g,published_at:o(),source:"rehydrated"})}h.on("connection",p=>{cr.add(p),p.once("close",()=>cr.delete(p)),I(),MR(p,async(g,y)=>{I();let _=await qu(g);y(_),g.op==="shutdown"&&setImmediate(()=>void ft({reason:"requested"}))})});async function qu(p){try{if(p.op==="ping")return{id:p.id,ok:!0,value:{pong:!0,protocol_version:Yt,daemon_version:t,pid:l.pid}};if(p.op==="host-state")return{id:p.id,ok:!0,value:at()};if(p.op==="statusline-payload")return{id:p.id,ok:!0,value:md(dt(),p.extras)};if(p.op==="statusline-string")return{id:p.id,ok:!0,value:ju(p.render)};if(p.op==="statusline-dashboard")return{id:p.id,ok:!0,value:Du(p.dashboard)};if(p.op==="worker-heartbeat")return{id:p.id,ok:!0,value:oi(p.heartbeat)};if(p.op==="project-register")return{id:p.id,ok:!0,value:si(p.registration,p.session_project)};if(p.op==="project-renew")return{id:p.id,ok:!0,value:ii(p.project_label,{...p.session_project==null?{}:{sessionProject:p.session_project},...p.renew_within_ms==null?{}:{renewWithinMs:p.renew_within_ms},...p.launch==null?{}:{launch:p.launch}})};if(p.op==="project-deregister")return{id:p.id,ok:!0,value:li(p.project_label,p.session_project)};if(p.op==="worker-command")return{id:p.id,ok:!0,value:await Ou(p.command)};if(p.op==="worker-start"){let y=Ke("worker-start",p.session_project,p.spec.project_label);if(!y.permitted)return{id:p.id,ok:!1,error:y.reason};let _=_r(p.spec);return await k.flush().catch(()=>{}),{id:p.id,ok:!0,value:{worker:_.worker,admission:_.admission,warnings:_.warnings}}}if(p.op==="shutdown"){let y=pt("requested");return await mi({reason:"requested",...p.detail==null?{}:{note:p.detail}}),{id:p.id,ok:!0,value:y}}let g=p;return{id:g.id??Xn(),ok:!1,error:`unsupported redskilled op: ${g.op??"unknown"}`}}catch(g){return{id:p.id??Xn(),ok:!1,error:g instanceof Error?g.message:String(g)}}}return I(),Fu(),Wu(),Cu(),Bu(),vu(),Hu(),Uu(),{socketPath:n.socketPath,lease:m.lease,startedAt:b,closed:Rr,startWorker:_r,admit:ai,ceiling:()=>i,killWorkerOverBudget:di,sampleMemoryBudgets:ci,renewLease:pi,pollRepositoryActivity:br,pollGithubBalance:ni,githubBalance:()=>gn,pollQueueDiscovery:ti,queueDiscovery:()=>be,driveDemand:ri,demand:()=>ot,sweepWorkerLiveness:wr,publishWorkerHeartbeat:oi,reattached:()=>[...Re].map(p=>v.get(p)).filter(p=>p!=null),flushEvents:()=>k.flush(),trackWorker(p){v.set(p.worker_id,p),fe("worker-birth",p,null),I()},releaseWorker(p){let g=v.get(p),y=v.delete(p);return Re.delete(p),He.delete(p),tt.delete(p),g&&fe("worker-death",g,"released by the daemon"),I(),y},workerCount:()=>v.size,registerProject:si,renewProject:ii,deregisterProject:li,registrations:()=>at().registrations??[],hostState:at,statuslinePayload:dt,evaluateIdle:fi,observePublishedVersion:ui,checkForReplacement:ut,stopReport:pt,stop:ft}}async function NR(e){for(let n=0;n<2;n++){let t=DR();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 ne(e))throw new fn(e);await Ic(e,{force:!0})}}throw new fn(e)}async function ne(e,n=250){try{return(await jt({socketPath:e,timeoutMs:n},{id:Xn(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function MR(e,n){Kl(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??Xn(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function Ss(e){let n=e.socketPath,t=CR(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 ${Mc(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 \`${ve("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 \`${ve("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function vs(e){return`${e.reason} ${e.repair}`}function CR(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:WR(n.acquired_at,e.now??new Date().toISOString())}}function WR(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 Mc(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`}ge();var Fc=1e4,Fe=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"?`. ${vs(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},Es=class extends Fe{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}};async function or(e,n={}){let t=n.answers??await ne(e.socketPath),r=await Yn(e.leasePath).catch(()=>{});return Ss({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&B(r.pid)})}async function Ps(e,n={}){try{return await UR(e,n)}catch(t){if(t instanceof Se||t instanceof Fe)throw t;let r=await or(e).catch(()=>{});throw new Fe(e.socketPath,t,r)}}async function UR(e,n){if(await BR(HR(e.socketPath),{recursive:!0,mode:448}),await ne(e.socketPath))return"already-running";await VR(e);let t=await KR(e,n);if(t!=null)return t;let r=await ql(e.lockPath,{...n.spawnLockMaxAgeMs==null?{}:{maxAgeMs:n.spawnLockMaxAgeMs},onReap:n.onSpawnLockReaped??GR});if(!r.acquired)return await Cc(e,n,void 0,r),"joined";try{if(await ne(e.socketPath))return"already-running";let o=await JR(e,n);return await Cc(e,n,o),"spawned"}finally{await Jl(r)}}function GR(e){process.stderr.write(`redskilled: reaped the spawn lock ${JSON.stringify(e.lockPath)} (${e.reason}, ${Math.round(e.ageMs/1e3)}s old, holder ${e.holder==null?"unnamed":`pid ${e.holder.pid}`}) and went on to spawn
81
+ `)}async function KR(e,n){let t=await or(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??Fc,o=Date.now()+r;for(;;){if(await ne(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(i=>setTimeout(i,25))}let s=await or(e).catch(()=>{});if(s==null||s.kind!=="held-unresponsive")return null;throw new Es(e.socketPath,s,new Error(`it did not answer a ping within ${r}ms, and no second daemon was spawned because pid ${s.holder?.pid??"unknown"} still holds this socket`))}async function VR(e){let t=await Ct(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&B(t.pid))throw new Se(e.machineClaimPath,"held",t)}async function Bc(e,n,t={}){await Ps(e,t);let r;try{r=await qn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:Wc()})}catch(o){throw new Fe(e.socketPath,o,await or(e).catch(()=>{}))}if(!r.ok)throw new Error(r.error);return r.value}async function Hc(e,n={},t={}){if(!await ne(e.socketPath))return xa(e.socketPath);let r;try{r=await qn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Wc(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new Fe(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!Eo(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await qR(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 qR(e,n){let t=Date.now()+n;for(;;){if(!await ne(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function Uc(e,n={}){let t=await Bc(e,{op:"host-state"},n);if(!wd(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Gc(e,n={},t){let r=await Bc(e,{op:"statusline-payload",...n.sessionProject!=null?{session_project:n.sessionProject}:{},...t==null?{}:{extras:t}},n);if(!Yo(r))throw new Error("redskilled daemon returned a malformed statusline payload");return r}async function Kc(e,n=j,t={}){let r=await Gc(e,t,{vitals:!0,logs:n.verbose,display:!0});return Ce(r,n)}async function Vc(e,n={},t={}){let r=await Gc(e,t,{vitals:!0,logs:!0,display:!0});return cn(r,{...de,...n})}async function Cc(e,n,t,r){let o=Date.now()+(n.readyTimeoutMs??Fc);for(;;){if(await ne(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=o){if(r!=null)throw new Error(`no redskilled daemon answered on ${JSON.stringify(e.socketPath)} within the ready window, and ${Ql(r)}`);let s=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${s}`)}await new Promise(s=>setTimeout(s,25))}}async function JR(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await ra({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,...Te(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=FR(r.command,s,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return i.on("error",l=>{o.failure=l}),i.on("exit",(l,a)=>{o.exit=a?`died on ${a}`:`exited with code ${l??-1}`}),i.unref(),o}ge();import{chmod as Zc,mkdir as nu,readFile as tu,stat as sb,writeFile as ib}from"node:fs/promises";import{homedir as Os}from"node:os";import{dirname as lb,join as As}from"node:path";import{join as QR}from"node:path";var qc=["local","tmp","host"],zR="local",Zn="plugins.dev.workspace.target";var js=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function Qc(e){let n=nn(e,Zn),t=ZR(n??"").trim();return t===""?void 0:t}function zc(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:zR};let t=qc.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 js(`${Zn}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${qc.join(", ")}) or an absolute parent directory for Workers.`)}function Yc(e,n){return e.kind==="preset"?e.preset==="host":XR(YR(e.parentDir,n),Le(n))}function YR(e,n){return e==="~"?Jc(n):e.startsWith("~/")?QR(n,e.slice(2)):Jc(e)}function XR(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Jc(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function ZR(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}ge();import{createHash as eb}from"node:crypto";import{hostname as nb}from"node:os";import{join as sr}from"node:path";var mn="redskilled.sock",tb="REDSKILLED_SESSION";function rb(e={}){let n=e.env??process.env,t=n[tb]?.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 ob(e={}){return Xc(e.host??nb())}function ce(e={}){let n=rb(e),t=e.runtimeDir??Dt({key:`redskilled:${n}`,socketFileName:mn,env:e.env,uid:e.uid}),r=ob(e);return{sessionKey:n,sessionKeyHash:Xc(n),machineIdHash:r,runtimeDir:t,socketPath:sr(t,mn),lockPath:sr(t,"redskilled.spawn.lock"),leasePath:sr(t,"redskilled.lease.toon"),eventLanePath:sr(t,ma),machineClaimPath:e.machineClaimPath??Mt({env:e.env,machineIdHash:r,platform:e.platform})}}function Xc(e){return eb("sha256").update(e).digest("hex").slice(0,12)}var Ds=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${ve("red-skills-redskilled",["provision"])}\` directly`;async function ru(e=Os()){let n=Le(e),t=await Ts(n);return t===void 0?(await nu(n,{recursive:!0,mode:ie}),await Zc(n,ie),{path:n,created:!0,tightened:!1,mode:ie}):t===ie?{path:n,created:!1,tightened:!1,mode:t}:(await Zc(n,ie),{path:n,created:!1,tightened:!0,mode:ie})}var ou={needed:!1,declaredBy:`no ${Zn} in view`};async function Ls(e={}){let n=e.homeDir??Os(),t=e.declaredTarget?.trim();if(t)return eu(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return ou;let o=As(r,".red","config.yaml"),s=await tu(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=Qc(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:eu(i,n,o)}function eu(e,n,t){let r=`${Zn}: ${e} (${t})`;try{return{needed:Yc(zc(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function su(e){let n=[ab(e),db(e),cb(e),ub(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 ab(e){let n=e.homeNeed??ou;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:Ds}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??ie;return t!==ie?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${ie.toString(8)}`,fix:`${Ds} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function db(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 \`${ve("red-skills-redskilled",["provision"])}\``}}function cb(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:`${Ds} \u2014 it starts the daemon and waits for the socket`}}function ub(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 iu(e={}){let n=e.env??process.env,t=e.homeDir??Os(),r=e.paths??ce({env:n}),o=Le(t),[s,i,l]=await Promise.all([Ts(o),ne(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Ls({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:xe(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await fb(mb(e,n,t),n)}}var pb="redskilled.service";function lu(e){return As(e,"systemd","user",pb)}function au(e){let n=e.socketPath?` --socket ${e.socketPath}`:"";return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)","","[Service]","Type=simple",`ExecStart=${e.command} serve${n}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
82
+ `)}async function du(e){let n=lu(e.configHome);return await Ts(n)!==void 0?{path:n,status:"already-present"}:(await nu(lb(n),{recursive:!0}),await ib(n,e.unit,"utf8"),{path:n,status:"installed"})}async function fb(e,n){if(process.platform!=="linux")return"unsupported";try{return await tu(lu(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function mb(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??As(t,".config")}async function Ts(e){try{return(await sb(e)).mode&511}catch{return}}import{readdir as uu,rm as hb,stat as gb}from"node:fs/promises";import{dirname as yb,join as $s}from"node:path";var kb=5*6e4,Rb="redskilled.";function bb(e={}){let n=e.env??process.env,t=i=>yb(Dt({key:"redskilled:reclaim-probe",socketFileName:mn,env:i,...e.uid===void 0?{}:{uid:e.uid}})),{XDG_RUNTIME_DIR:r,...o}=n,s=[t(n),t(o)];return[...new Set(s)]}async function pu(e={}){let n=e.roots??bb(e),t=e.graceMs??kb,r=e.now??Date.now,o=e.isPidAlive??B,s=e.answers??Sb,i=e.dryRun===!0,l=[];for(let a of n){let d;try{d=(await uu(a,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name)}catch{continue}for(let c of d.sort())l.push(await _b($s(a,c),{graceMs:t,now:r,pidAlive:o,answers:s,dryRun:i}))}return{roots:n,scanned:l.length,reclaimed:l.filter(a=>a.verdict==="reclaimed").length,dryRun:i,entries:l}}async function _b(e,n){let t;try{t=(await uu(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:fu(i),removed:[]}}let r=t.filter(i=>i.startsWith(Rb));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await wb($s(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 cu(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(mn)&&await n.answers($s(e,mn)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await xb(e,n.now);return s!==void 0&&s<n.graceMs?{dir:e,verdict:"young",reason:`no lease, modified ${Math.round(s/1e3)}s ago`,removed:[]}:await cu(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function cu(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await hb(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:fu(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function wb(e){try{return await Yn(e)}catch{return}}async function xb(e,n){try{return Math.max(0,n()-(await gb(e)).mtimeMs)}catch{return}}async function Sb(e){try{return(await qn({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function fu(e){return e instanceof Error?e.message:String(e)}var vb="plugins.dev.statusline",Eb="dev.statusline";function Pb(e){let n=[],t=l=>{for(let a of[vb,Eb]){let d=`${a}.${l}`,c=nn(e,d)?.trim();if(c!=null&&c!=="")return{key:d,value:c}}},r=t("mode"),o={};r!=null&&(r.value==="local"||r.value==="global"?o.mode=r.value:n.push({...r,reason:"expected `local` or `global`"}));let s=[{leaf:"max_workers",assign:l=>{o.maxWorkers=l}},{leaf:"max_projects",assign:l=>{o.maxProjects=l}},{leaf:"max_width",assign:l=>{o.maxWidth=l}}];for(let l of s){let a=t(l.leaf);if(a==null)continue;let d=Number(a.value);Number.isInteger(d)&&d>=0?l.assign(d):n.push({...a,reason:"expected a whole number of zero or more"})}let i=t("verbose");return i!=null&&(i.value==="true"||i.value==="false"?o.verbose=i.value==="true":n.push({...i,reason:"expected `true` or `false`"})),{config:o,warnings:n}}var jb={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 Is(e){let{values:n,positionals:t}=Oe(e,jb),r=[],o={},s=n.mode??t.find(l=>l==="global"||l==="local");s!=null&&(s==="local"||s==="global"?o.mode=s:r.push({key:"--mode",value:s,reason:"expected `local` or `global`"})),n.project!=null&&(o.project=n.project),n.verbose!==void 0&&(o.verbose=n.verbose===!0);let i=[{flag:"max-workers",assign:l=>{o.maxWorkers=l}},{flag:"max-projects",assign:l=>{o.maxProjects=l}},{flag:"max-width",assign:l=>{o.maxWidth=l}}];for(let l of i){let a=n[l.flag];if(a==null)continue;let d=Number(a);Number.isInteger(d)&&d>=0?l.assign(d):r.push({key:`--${l.flag}`,value:a,reason:"expected a whole number of zero or more"})}return{flags:o,warnings:r}}function Ns(e={}){let n=e.configText==null?{config:{},warnings:[]}:Pb(e.configText),t=e.flags??{};return{options:{...j,mode:t.mode??n.config.mode??j.mode,project:t.project!==void 0?t.project:e.project??j.project,maxWorkers:t.maxWorkers??n.config.maxWorkers??j.maxWorkers,maxProjects:t.maxProjects??n.config.maxProjects??j.maxProjects,maxWidth:t.maxWidth??n.config.maxWidth??j.maxWidth,verbose:t.verbose??n.config.verbose??j.verbose},warnings:n.warnings}}var Ob=`Usage: redskilled <command> [options]
83
83
 
84
84
  Commands:
85
85
  host-state (default) print the host's state as JSON
86
86
  serve run the daemon in this process
87
87
  statusline [global] render one agent-host status line
88
+ dashboard [global] render the host view a terminal can read
88
89
  unit install | uninstall | status \u2014 the optional supervisor
89
90
  provision make this machine ready; --check is the read-only half
90
91
  reclaim clear runtime dirs left by dead sessions
91
92
 
92
93
  Run \`redskilled <command> --help\` for a command's own usage.
93
94
  \`--version\` (\`-v\`) prints the build stamp; both answer offline.
94
- `,jb={serve:`Usage: redskilled serve [options]
95
+ `,Ab={serve:`Usage: redskilled serve [options]
95
96
 
96
97
  Runs the daemon in this process. Every path is a flag and none is derived
97
98
  (ADR 0130 rule 3); what is absent falls back to the session derivation.
@@ -115,7 +116,17 @@ no queue \u2014 an honest unknown, never a drained one.
115
116
 
116
117
  Prints the host's state as JSON. Contacts the running daemon; the default
117
118
  command when none is named.
118
- `,statusline:`Usage: redskilled statusline [global] [--verbose] [flags]
119
+ `,dashboard:`Usage: redskilled dashboard [global] [flags]
120
+
121
+ The host view the herdr plugin and the VS Code extension draw, at the density a
122
+ terminal can read. Same payload and same render as the statusline (ADR 0132
123
+ decision 1) \u2014 a density argument, never a second renderer.
124
+
125
+ global every project's Workers, each naming its owner
126
+ --max-width N hard ceiling in characters
127
+
128
+ It always writes something and always exits 0: a dashboard that printed nothing
129
+ is indistinguishable from a host with no Workers.`,statusline:`Usage: redskilled statusline [global] [--verbose] [flags]
119
130
 
120
131
  Renders the status line the agent host prints verbatim. Config is read on this
121
132
  side and only decided values cross the socket (ADR 0130 rule 10).
@@ -155,19 +166,24 @@ Reports every session runtime dir it looked at and why it kept or removed it.
155
166
 
156
167
  --dry-run the same report with nothing removed
157
168
  --grace-ms <n> how long a dir must be idle before it is reclaimed
158
- `};function Db(e){return e==="--help"||e==="-h"||e==="help"}var Ob={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)}},fu="REDSKILLED_HOST_TOKEN";function ir(){try{let n=Eb("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function mu(e=process.env,n=ir){let t=(e[fu]??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 Ab(e,n=process.env,t=ir){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...uu(e,n,t),armTransport:()=>uu(e,n,t)}}function Lb(e,n=process.env,t=ir){let r=mu(n,t);if(r==null)return null;let o=n.GITHUB_API_URL;return{transport:Go({token:r.token,...o?{origin:o}:{}})}}function uu(e,n=process.env,t=ir){let r=mu(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${fu}, 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:dd({token:r.token,...o?{endpoint:o}:{}})}}async function Tb(e){if(e[0]==="--version"||e[0]==="-v"){let o=Kr("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
159
- `:`${Yi(o)}
160
- `),0}if(Db(e[0]))return process.stdout.write(Pb),0;let{command:n,args:t}=nl(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(jb[n]),0;if(n==="serve"){let{values:o}=Oe(t,Ob),s=Ab(o),i=Lb(o),a=pu(Le($s()),"state"),l=_l({stateRoot:a});process.stderr.write(`${wl(l)}
161
- `);let d=yl({lanePath:An(a),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),c=await Tc({paths:Gb(o),idleMs:o["idle-ms"]??ws,daemonVersion:o["daemon-version"]??Kr("redskilled").version,deaths:l.attributions,queueDiscovery:s,...i==null?{}:{githubBalance:i},...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let u of["SIGTERM","SIGINT"])process.once(u,()=>void c.stop({reason:"signal",signal:u}).catch(()=>{}));return await c.closed,d.phase("closed"),0}if(n==="stop")return await Ib(t);if(n==="statusline")return await Mb(t);if(n==="unit")return await Nb(t);if(n==="provision")return await Wb(t);if(n==="reclaim")return await Bb(t);let r=await Fc(ge());return process.stdout.write(`${JSON.stringify(r,null,2)}
162
- `),0}var $b={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function Ib(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=Oe(e,$b),o=await Wc(n.paths??ge(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${C({running:o.running,stopped:o.stopped,reason:o.reason,socket:o.socket_path,daemon_version:o.daemon_version,pid:o.pid,holding:{workers:o.holding.workers.length,projects:[...o.holding.projects]},surviving:[...o.surviving],workers:o.holding.workers.map(s=>({worker_id:s.worker_id,project_label:s.project_label,pid:s.pid,unit:s.unit,isolated:s.isolated,survives:s.survives})),detail:o.detail})}
163
- `),o.running&&!o.stopped?1:0}async function Nb(e,n={}){let t=n.write??(s=>process.stdout.write(s)),r=n.paths??ge(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(lc(n.unitIO??{}),null,2)}
164
- `),0;if(o==="install"){let s=await sc(rc(r),n.unitIO??{});return t(`${JSON.stringify(s,null,2)}
165
- `),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await ic(n.unitIO??{}),null,2)}
166
- `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function Mb(e,n={}){let t=n.write??(l=>process.stdout.write(l)),r=n.warn??(l=>process.stderr.write(l)),o=du(e),s=Ub(n.cwd??process.cwd()),i=cu({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let l of[...i.warnings,...o.warnings])r(`redskilled statusline: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
167
- `);let a;try{a=await Bc(n.paths??ge(),i.options,{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(l){r(`redskilled statusline: ${l instanceof Error?l.message:String(l)}
168
- `),a=ss({options:i.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${a.lines.join(`
169
+ `};function Lb(e){return e==="--help"||e==="-h"||e==="help"}var Tb={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)}},gu="REDSKILLED_HOST_TOKEN";function ir(){try{let n=Db("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function yu(e=process.env,n=ir){let t=(e[gu]??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 $b(e,n=process.env,t=ir){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...mu(e,n,t),armTransport:()=>mu(e,n,t)}}function Ib(e,n=process.env,t=ir){let r=yu(n,t);if(r==null)return null;let o=n.GITHUB_API_URL;return{transport:Go({token:r.token,...o?{origin:o}:{}})}}function mu(e,n=process.env,t=ir){let r=yu(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${gu}, 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:pd({token:r.token,...o?{endpoint:o}:{}})}}async function Nb(e){if(e[0]==="--version"||e[0]==="-v"){let o=Kr("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
170
+ `:`${el(o)}
171
+ `),0}if(Lb(e[0]))return process.stdout.write(Ob),0;let{command:n,args:t}=ol(e,{commands:{serve:{},stop:{},"host-state":{},statusline:{},dashboard:{},unit:{},provision:{},reclaim:{}},default:"host-state"});if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(Ab[n]),0;if(n==="serve"){let{values:o}=Oe(t,Tb),s=$b(o),i=Ib(o),l=hu(Le(Ms()),"state"),a=Sl({stateRoot:l});process.stderr.write(`${vl(a)}
172
+ `);let d=Rl({lanePath:Ln(l),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),c=await Nc({paths:Vb(o),idleMs:o["idle-ms"]??xs,daemonVersion:o["daemon-version"]??Kr("redskilled").version,deaths:a.attributions,queueDiscovery:s,...i==null?{}:{githubBalance:i},...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let u of["SIGTERM","SIGINT"])process.once(u,()=>void c.stop({reason:"signal",signal:u}).catch(()=>{}));return await c.closed,d.phase("closed"),0}if(n==="stop")return await Cb(t);if(n==="statusline")return await Fb(t);if(n==="dashboard")return await Jb(t);if(n==="unit")return await Wb(t);if(n==="provision")return await Hb(t);if(n==="reclaim")return await Gb(t);let r=await Uc(ce());return process.stdout.write(`${JSON.stringify(r,null,2)}
173
+ `),0}var Mb={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function Cb(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=Oe(e,Mb),o=await Hc(n.paths??ce(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${C({running:o.running,stopped:o.stopped,reason:o.reason,socket:o.socket_path,daemon_version:o.daemon_version,pid:o.pid,holding:{workers:o.holding.workers.length,projects:[...o.holding.projects]},surviving:[...o.surviving],workers:o.holding.workers.map(s=>({worker_id:s.worker_id,project_label:s.project_label,pid:s.pid,unit:s.unit,isolated:s.isolated,survives:s.survives})),detail:o.detail})}
174
+ `),o.running&&!o.stopped?1:0}async function Wb(e,n={}){let t=n.write??(s=>process.stdout.write(s)),r=n.paths??ce(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(cc(n.unitIO??{}),null,2)}
175
+ `),0;if(o==="install"){let s=await ac(ic(r),n.unitIO??{});return t(`${JSON.stringify(s,null,2)}
176
+ `),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await dc(n.unitIO??{}),null,2)}
177
+ `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function Fb(e,n={}){let t=n.write??(a=>process.stdout.write(a)),r=n.warn??(a=>process.stderr.write(a)),o=Is(e),s=ku(n.cwd??process.cwd()),i=Ns({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let a of[...i.warnings,...o.warnings])r(`redskilled statusline: ignoring ${a.key}=${a.value} \u2014 ${a.reason}
178
+ `);let l;try{l=await Kc(n.paths??ce(),i.options,{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(a){r(`redskilled statusline: ${a instanceof Error?a.message:String(a)}
179
+ `),l=is({options:i.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${l.lines.join(`
180
+ `)}
181
+ `),0}var Bb={"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 Hb(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=Oe(e,Bb),o=n.paths??ce(),s=n.homeDir??Ms(),i=await Ls({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),l=r.check||!i.needed?void 0:await ru(s),a;if(!r.check&&!r["no-start"])try{await Ps(o,n.client??{})}catch(f){a=f instanceof Error?f.message:String(f)}let d=await iu({paths:o,homeNeed:i,...n.homeDir==null?{}:{homeDir:n.homeDir},...n.configHome==null?{}:{configHome:n.configHome},...n.client?.serverCommand==null?{}:{entryOverride:{serverCommand:n.client.serverCommand,serverArgs:n.client.serverArgs}}}),c=r["install-unit"]&&ae(d.entry)?await du({configHome:n.configHome??Kb(),unit:au({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=su(d);return t(`${C({verdict:u.verdict,home:{path:l?.path??d.homePath,created:l?.created??!1,tightened:l?.tightened??!1,needed:i.needed,needed_by:i.declaredBy},socket:d.socketPath,...a==null?{}:{start_error:a},...c==null?{}:{unit:{path:c.path,status:c.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}))})}
182
+ `),u.verdict==="ok"?0:1}var Ub={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function Gb(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=Oe(e,Ub),o=await pu({...n.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return t(`${C({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(s=>({dir:s.dir,verdict:s.verdict,reason:s.reason,removed:[...s.removed]}))})}
183
+ `),o.entries.some(s=>s.verdict==="failed")?1:0}function Kb(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:hu(Ms(),".config")}function ku(e){let n=uo(e);return n.configText==null?{label:null}:{configText:n.configText,label:Tl(e)}}function Vb(e){let n=ce();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 qb=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;qb&&Nb(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
184
+ `),process.exitCode=1});async function Jb(e,n={}){let t=n.write??(l=>process.stdout.write(l)),r=n.warn??(l=>process.stderr.write(l)),o=Is(e),s=ku(n.cwd??process.cwd()),i=Ns({...s.configText==null?{}:{configText:s.configText},project:s.label,flags:o.flags});for(let l of[...i.warnings,...o.warnings])r(`redskilled dashboard: ignoring ${l.key}=${l.value} \u2014 ${l.reason}
185
+ `);try{let l=await Vc(n.paths??ce(),{...i.options.project==null?{}:{project:i.options.project},mode:i.options.mode,...i.options.maxWidth==null?{}:{maxWidth:i.options.maxWidth}},{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}});t(`${l.lines.join(`
169
186
  `)}
170
- `),0}var Cb={"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 Wb(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=Oe(e,Cb),o=n.paths??ge(),s=n.homeDir??$s(),i=await As({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),a=r.check||!i.needed?void 0:await Xc(s),l;if(!r.check&&!r["no-start"])try{await Es(o,n.client??{})}catch(f){l=f instanceof Error?f.message:String(f)}let d=await nu({paths:o,homeNeed:i,...n.homeDir==null?{}:{homeDir:n.homeDir},...n.configHome==null?{}:{configHome:n.configHome},...n.client?.serverCommand==null?{}:{entryOverride:{serverCommand:n.client.serverCommand,serverArgs:n.client.serverArgs}}}),c=r["install-unit"]&&ae(d.entry)?await ou({configHome:n.configHome??Hb(),unit:ru({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=eu(d);return t(`${C({verdict:u.verdict,home:{path:a?.path??d.homePath,created:a?.created??!1,tightened:a?.tightened??!1,needed:i.needed,needed_by:i.declaredBy},socket:d.socketPath,...l==null?{}:{start_error:l},...c==null?{}:{unit:{path:c.path,status:c.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}))})}
171
- `),u.verdict==="ok"?0:1}var Fb={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function Bb(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=Oe(e,Fb),o=await lu({...n.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return t(`${C({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(s=>({dir:s.dir,verdict:s.verdict,reason:s.reason,removed:[...s.removed]}))})}
172
- `),o.entries.some(s=>s.verdict==="failed")?1:0}function Hb(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:pu($s(),".config")}function Ub(e){let n=uo(e);return n.configText==null?{label:null}:{configText:n.configText,label:Ol(e)}}function Gb(e){let n=ge();return{...n,socketPath:e.socket??n.socketPath,leasePath:e.lease??n.leasePath,eventLanePath:e.events??n.eventLanePath,sessionKeyHash:e["session-key-hash"]??n.sessionKeyHash,machineIdHash:e["machine-id-hash"]??n.machineIdHash,machineClaimPath:e["machine-claim"]??n.machineClaimPath}}var Kb=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;Kb&&Tb(process.argv.slice(2)).then(e=>{process.exitCode=e},e=>{process.stderr.write(`redskilled: ${e instanceof Error?e.message:String(e)}
173
- `),process.exitCode=1});export{fu as REDSKILLED_HOST_TOKEN_ENV,Pb as REDSKILLED_USAGE,uu as armRedskilledQueueTransport,mu as resolveRedskilledHostToken,Lb as resolveServeGithubBalance,Ab as resolveServeQueueDiscovery,Wb as runProvision,Bb as runReclaim,Tb as runRedskilledCli,Mb as runStatusline,Ib as runStop,Nb as runUnit};
187
+ `)}catch(l){r(`redskilled dashboard: ${l instanceof Error?l.message:String(l)}
188
+ `),t(`redskilled unreachable \u2014 the host was not asked, so its Workers are unknown
189
+ `)}return 0}export{gu as REDSKILLED_HOST_TOKEN_ENV,Ob as REDSKILLED_USAGE,mu as armRedskilledQueueTransport,yu as resolveRedskilledHostToken,Ib as resolveServeGithubBalance,$b as resolveServeQueueDiscovery,Jb as runDashboard,Hb as runProvision,Gb as runReclaim,Nb as runRedskilledCli,Fb as runStatusline,Cb as runStop,Wb as runUnit};