@reddb-io/red-skills 3.3.21 → 3.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,85 +1,85 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var op=Object.defineProperty;var sp=(e,n)=>()=>(e&&(n=e(e=0)),n);var ip=(e,n)=>{for(var t in n)op(e,t,{get:n[t],enumerable:!0})};var oa={};ip(oa,{REDSKILLED_BIN_ENV:()=>_o,REDSKILLED_BUNDLE_ASSET:()=>ae,REDSKILLED_ENTRY_UNRESOLVED:()=>Nn,RedskilledDaemonEntryError:()=>Mn,isRedskilledEntryPath:()=>xo,isResolvedRedskilledEntry:()=>de,redskilledBundleCacheRoot:()=>Tt,redskilledServeArgv:()=>Ie,requireRedskilledEntry:()=>$t,resolveRedskilledEntry:()=>Se});import{existsSync as uh,readdirSync as ph}from"node:fs";import{homedir as fh}from"node:os";import{basename as bo,dirname as Ro,join as z,resolve as Lt}from"node:path";function de(e){return"command"in e}function Ie(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 Tt(e=process.env){return ra(e)}function Se(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??uh,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[_o];if(a)return{command:a,args:[],source:"env-redskilled-bin",entry:a};if(i&&xo(i))return l(Lt(i),"caller-entry");let d=[];for(let[c,u]of yh(i,n.rootDir,t,n.listDir??bh))if(d.push(c),r(c))return l(c,u);return{diagnostic:Nn,searched:d,...i?{callerEntry:Lt(i)}:{}}}function $t(e={},n={}){let t=Se(e,n);if(de(t))return t;throw new Mn(t)}function xo(e){let n=bo(e);return n===ae||wo.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:gh(Lt(e))}function gh(e){let n=Ro(e);for(let t=0;t<4;t++){if(bo(n)==="redskilled")return!0;let r=Ro(n);if(r===n)return!1;n=r}return!1}function*yh(e,n,t,r){if(e){let s=Ro(Lt(e));yield[z(s,ae),"caller-sibling-bundle"];let i=mh.exec(bo(e));i&&(yield[z(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[z(s,"..","dist",ae),"caller-sibling-bundle"]}for(let s of hh){let i=t[s];i&&(yield[z(i,"dist",ae),"plugin-root-bundle"],yield[z(i,"..","..","dist",ae),"plugin-root-bundle"])}n&&(yield[z(n,"dist",ae),"repo-bundle"],yield[z(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[z(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=ra(t);yield[z(o,ae),"bundle-cache"];for(let s of kh(o,r))yield[z(o,s),"bundle-cache"]}function ra(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||z(e.HOME||fh(),".cache");return z(n,"red-skills","bundles")}function kh(e,n){return n(e).filter(t=>wo.test(t)).sort((t,r)=>Rh(ta(r),ta(t)))}function ta(e){return wo.exec(e)?.[1]??""}function Rh(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 bh(e){try{return ph(e)}catch{return[]}}var ae,Nn,_o,Mn,mh,wo,hh,ye=sp(()=>{"use strict";ae="redskilled.bundle.min.mjs",Nn="redskilled-daemon-entry-unresolved",_o="REDSKILLED_BIN";Mn=class extends Error{code=Nn;searched;callerEntry;constructor(n){super(`${Nn}: no published ${ae} found to spawn the redskilled daemon from${n.callerEntry?` (caller entry: ${n.callerEntry}, which is NOT used as a fallback)`:""}
3
+ var Pp=Object.defineProperty;var Dp=(e,n)=>()=>(e&&(n=e(e=0)),n);var jp=(e,n)=>{for(var t in n)Pp(e,t,{get:n[t],enumerable:!0})};var xa={};jp(xa,{REDSKILLED_BIN_ENV:()=>jo,REDSKILLED_BUNDLE_ASSET:()=>de,REDSKILLED_ENTRY_UNRESOLVED:()=>Bn,RedskilledDaemonEntryError:()=>Fn,isRedskilledEntryPath:()=>Ao,isResolvedRedskilledEntry:()=>ce,redskilledBundleCacheRoot:()=>Ht,redskilledServeArgv:()=>Ce,requireRedskilledEntry:()=>Ut,resolveRedskilledEntry:()=>Pe});import{existsSync as $h,readdirSync as Ih}from"node:fs";import{homedir as Nh}from"node:os";import{basename as Do,dirname as Po,join as Y,resolve as Ft}from"node:path";function ce(e){return"command"in e}function Ce(e,n={}){let t=["serve","--socket",e.socketPath,"--lease",e.leasePath,"--events",e.eventLanePath,"--session-key-hash",e.sessionKeyHash,"--machine-id-hash",e.machineIdHash,"--machine-claim",e.machineClaimPath];return n.idleMs!=null&&t.push("--idle-ms",String(n.idleMs)),n.daemonVersion!=null&&t.push("--daemon-version",n.daemonVersion),t}function Ht(e=process.env){return wa(e)}function Pe(e={},n={}){if(e.serverCommand)return{command:e.serverCommand,args:e.serverArgs??[],source:"server-command"};let t=n.env??process.env,r=n.exists??$h,o=n.execPath??process.execPath,s=n.execArgv??[],i=n.callerEntry===void 0?process.argv[1]:n.callerEntry,l=(u,p)=>({command:o,args:[...s,u],source:p,entry:u}),a=t[jo];if(a)return{command:a,args:[],source:"env-redskilled-bin",entry:a};if(i&&Ao(i))return l(Ft(i),"caller-entry");let d=[];for(let[u,p]of Bh(i,n.rootDir,t,n.listDir??Uh))if(d.push(u),r(u))return l(u,p);return{diagnostic:Bn,searched:d,...i?{callerEntry:Ft(i)}:{}}}function Ut(e={},n={}){let t=Pe(e,n);if(ce(t))return t;throw new Fn(t)}function Ao(e){let n=Do(e);return n===de||Oo.test(n)||n==="red-skills-redskilled"||n==="red-skills-redskilled.mjs"?!0:n!=="cli.js"&&n!=="cli.mjs"&&n!=="cli.ts"?!1:Wh(Ft(e))}function Wh(e){let n=Po(e);for(let t=0;t<4;t++){if(Do(n)==="redskilled")return!0;let r=Po(n);if(r===n)return!1;n=r}return!1}function*Bh(e,n,t,r){if(e){let s=Po(Ft(e));yield[Y(s,de),"caller-sibling-bundle"];let i=Mh.exec(Do(e));i&&(yield[Y(s,`redskilled-${i[2]}.bundle.min.mjs`),"caller-sibling-bundle"]),yield[Y(s,"..","dist",de),"caller-sibling-bundle"]}for(let s of Ch){let i=t[s];i&&(yield[Y(i,"dist",de),"plugin-root-bundle"],yield[Y(i,"..","..","dist",de),"plugin-root-bundle"])}n&&(yield[Y(n,"dist",de),"repo-bundle"],yield[Y(n,"apps","redskilled","dist","cli.js"),"workspace-entry"],yield[Y(n,"node_modules","@reddb-io","redskilled","dist","cli.js"),"node-modules-entry"]);let o=wa(t);yield[Y(o,de),"bundle-cache"];for(let s of Fh(o,r))yield[Y(o,s),"bundle-cache"]}function wa(e){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Y(e.HOME||Nh(),".cache");return Y(n,"red-skills","bundles")}function Fh(e,n){return n(e).filter(t=>Oo.test(t)).sort((t,r)=>Hh(_a(r),_a(t)))}function _a(e){return Oo.exec(e)?.[1]??""}function Hh(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 Ih(e)}catch{return[]}}var de,Bn,jo,Fn,Mh,Oo,Ch,_e=Dp(()=>{"use strict";de="redskilled.bundle.min.mjs",Bn="redskilled-daemon-entry-unresolved",jo="REDSKILLED_BIN";Fn=class extends Error{code=Bn;searched;callerEntry;constructor(n){super(`${Bn}: no published ${de} 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)}};mh=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,wo=/^redskilled-(.+)\.bundle\.min\.mjs$/,hh=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as a_}from"node:child_process";import{homedir as Us}from"node:os";import{join as Su}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}},je=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 je(e,n)}function ze(e){return e instanceof je?e:e instanceof Qe?new je(e.line,e.reason):new je(0,String(e&&e.message?e.message:e))}var xi=["type","kind","event"],Oe="|",Si=new Set(["order","discriminator","rows","common"]);var O=",";function yt(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 oe(e){return R(e,"invalid quoted string")}function q(e,n){if(e==="")return"";if(e.startsWith('"'))return Pi(e,n);if(e.includes('"'))throw oe(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:lp(e)?Number(e):e}function X(e,n){let t=e.trim();if(t.startsWith('"'))return[Pi(t,n),!0];if(t.includes('"')||/\s/.test(t))throw R(n,"expected non-empty field name");return[t,!1]}var vi=/["\\\u0000-\u0008\u000a-\u001f]/g;function Pi(e,n){if(e.charCodeAt(0)!==34)throw oe(n);let t="",r=1;for(;r<e.length;){vi.lastIndex=r;let o=vi.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(r,o.index);throw oe(n)}if(o[0]!=="\\")throw oe(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 oe(n);let l=Number.parseInt(i,16);if(l>=55296&&l<=57343)throw oe(n);t+=String.fromCharCode(l),r+=4;break}default:throw oe(n)}}throw oe(n)}function Di(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 oe(t);n=o+2;continue}if(r===-1)throw oe(t);return r+1}}function Z(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=Di(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=Di(e,o+1,t)}return-1}function lp(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function ap(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function dp(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 se(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function B(e,n){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return dp(e);if(typeof e=="string")return up(e,n);throw R(0,"not a primitive")}function cp(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function N(e){return cp(e)?e:kt(e)}function up(e,n){return Dr(e,n)?kt(e):e}function Dr(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||ap(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}var Ei=/["\\\u0000-\u001f]/g;function kt(e){let n='"',t=0;Ei.lastIndex=0;let r;for(;(r=Ei.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 ee(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 ji(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 Oi(e,n){let t=[],r=!1;return yt(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);ie(a,i,n),t.push({number:i,depth:a,content:o.slice(l),blankBefore:r}),r=!1}),t}function ie(e,n,t){if(t.maxDepth!==0&&e>t.maxDepth)throw R(n,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function 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,ie(r,n,t)):i==="}"&&(r=Math.max(0,r-1)))}}function Ti(e){if(!L(e)||Object.keys(e).length===0)return e;let n={};for(let[t,r]of Object.entries(e)){let o=pp(r,1);if(o===void 0)return e;ee(n,t,o)}return n}function pp(e,n){if(!L(e)||!fp(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=mp(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 $i(n);let a=new Map;for(let[u,f]of Object.entries(e))if(!Si.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 jr(n);let h=d.get(u)??0,b=m[h];if(b===void 0)throw jr(n);return d.set(u,h+1),hp(r,u,l[f],b,n)});for(let[u,f]of a)if((d.get(u)??0)!==f.length)throw jr(n);return c}function fp(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function mp(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=>Rp(c,t));if(l.some(c=>c===""))throw M(t);let a=kp(i,t),d=l.length*a;if(!Number.isSafeInteger(d))throw M(t);if(d!==n)throw $i(t);return Array.from({length:d},(c,u)=>l[u%l.length])}function hp(e,n,t,r,o){let s={};ee(s,e,n);for(let[i,l]of Object.entries(t??{})){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw M(o);ee(s,i,l)}for(let[i,l]of Object.entries(gp(r,o))){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw M(o);ee(s,i,l)}return s}function gp(e,n){let t={};for(let[r,o]of Object.entries(e))yp(t,r.split("."),o,n);return Rt(t,n)}function yp(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 Rt(e,n){return Array.isArray(e)?e.map(t=>Rt(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 Rt(e[String(r)],n)}):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Rt(r,n)])):e}function kp(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 Rp(e,n){try{return decodeURIComponent(e)}catch{throw M(n)}}function Ai(e){return encodeURIComponent(e)}function M(e){return R(e,"invalid cyclic array wire")}function $i(e){return R(e,"cyclic array length mismatch")}function jr(e){return R(e,"cyclic array group length mismatch")}function Ii(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=bp(s);if(i===void 0)return;t.push([o,i])}let r=[];for(let[o,s]of t)Sp(r,o,s);return r.join("")}function bp(e){if(!Array.isArray(e)||e.length===0||!e.every(L))return;let n=_p(e);if(n===void 0)return;let t=e.map(l=>l[n]),r=wp(t);if(r===void 0)return;let o=xp(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)&&!Or(u,c,d))return;s.get(a).push(d)}let i=[];for(let l of r.cycle){let a=s.get(l),d=Ep(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 _p(e){return xi.find(n=>e.every(t=>typeof t[n]=="string"))}function wp(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(Ai).join(","),s=`cycle(${t.map(Ai).join(",")})*${r}`;if(s.length<=o.length*.4)return{cycle:t,encoded:s,repeats:r}}}function xp(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(!vp(s)||!e.every(i=>Object.prototype.hasOwnProperty.call(i,s))||!e.every(i=>se(i[s])))break;t.push(s)}return t}function Sp(e,n,t){e.push(N(n),`:
9
- `),e.push(" order: ",B(t.order.encoded,Oe),`
10
- `),e.push(" discriminator: ",B(t.discriminator,Oe),`
6
+ `)}`),this.name="RedskilledDaemonEntryError",this.searched=n.searched,n.callerEntry!=null&&(this.callerEntry=n.callerEntry)}};Mh=/^([a-z0-9-]+)-(.+)\.bundle\.min\.mjs$/,Oo=/^redskilled-(.+)\.bundle\.min\.mjs$/,Ch=["RED_SKILLS_DEV_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT","CODEX_PLUGIN_ROOT","OPENCODE_PLUGIN_ROOT"]});import{execFileSync as L_}from"node:child_process";import{homedir as ai}from"node:os";import{join as Ku}from"node:path";var en=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonError",this.line=n,this.reason=t}},Le=class extends Error{constructor(n,t){super(n===0?t:`line ${n}: ${t}`),this.name="ToonlError",this.line=n,this.reason=t}};function b(e,n){return new en(e,n)}function v(e,n){return new Le(e,n)}function nn(e){return e instanceof Le?e:e instanceof en?new Le(e.line,e.reason):new Le(0,String(e&&e.message?e.message:e))}var Hi=["type","kind","event"],Te="|",Ui=new Set(["order","discriminator","rows","common"]);var L=",";function Et(e){let n=e.split(`
7
+ `);return n.length>0&&n[n.length-1]===""&&n.pop(),n.map(t=>t.endsWith("\r")?t.slice(0,-1):t)}function se(e){return b(e,"invalid quoted string")}function J(e,n){if(e==="")return"";if(e.startsWith('"'))return Vi(e,n);if(e.includes('"'))throw se(n);return e==="true"?!0:e==="false"?!1:e==="null"?null:Op(e)?Number(e):e}function Z(e,n){let t=e.trim();if(t.startsWith('"'))return[Vi(t,n),!0];if(t.includes('"')||/\s/.test(t))throw b(n,"expected non-empty field name");return[t,!1]}var Gi=/["\\\u0000-\u0008\u000a-\u001f]/g;function Vi(e,n){if(e.charCodeAt(0)!==34)throw se(n);let t="",r=1;for(;r<e.length;){Gi.lastIndex=r;let o=Gi.exec(e);if(o===null)break;if(o[0]==='"'){if(e.slice(o.index+1).trim()==="")return t+e.slice(r,o.index);throw se(n)}if(o[0]!=="\\")throw se(n);t+=e.slice(r,o.index);let s=e[o.index+1];switch(r=o.index+2,s){case'"':t+='"';break;case"\\":t+="\\";break;case"n":t+=`
8
+ `;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":{let i=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(i))throw se(n);let l=Number.parseInt(i,16);if(l>=55296&&l<=57343)throw se(n);t+=String.fromCharCode(l),r+=4;break}default:throw se(n)}}throw se(n)}function qi(e,n,t){for(;;){let r=e.indexOf('"',n),o=e.indexOf("\\",n);if(o!==-1&&(r===-1||o<r)){if(o===e.length-1)throw se(t);n=o+2;continue}if(r===-1)throw se(t);return r+1}}function ee(e,n,t){if(e==="")return[];let r=[],o=0,s=0;for(;s<e.length;){let i=e.indexOf('"',s),l=e.indexOf(n,s);if(l!==-1&&(i===-1||l<i))r.push(e.slice(o,l).trim()),o=l+1,s=l+1;else if(i!==-1)s=qi(e,i+1,t);else break}return r.push(e.slice(o).trim()),r}function F(e,n,t){let r=0;for(;r<e.length;){let o=e.indexOf('"',r),s=e.indexOf(n,r);if(s!==-1&&(o===-1||s<o))return s;if(o===-1)return-1;r=qi(e,o+1,t)}return-1}function Op(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Ap(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function Lp(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw b(0,"number is not representable in TOON");return String(e)}function ie(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function H(e,n){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Lp(e);if(typeof e=="string")return $p(e,n);throw b(0,"not a primitive")}function Tp(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function M(e){return Tp(e)?e:Pt(e)}function $p(e,n){return Nr(e,n)?Pt(e):e}function Nr(e,n){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||Ap(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(n)||e.startsWith("-")}var Ki=/["\\\u0000-\u001f]/g;function Pt(e){let n='"',t=0;Ki.lastIndex=0;let r;for(;(r=Ki.exec(e))!==null;){let o=e.charCodeAt(r.index),s;o===34?s='\\"':o===92?s="\\\\":o===10?s="\\n":o===13?s="\\r":o===9?s="\\t":s=`\\u${o.toString(16).padStart(4,"0")}`,n+=e.slice(t,r.index)+s,t=r.index+1}return`${n}${e.slice(t)}"`}function ne(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function T(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ji(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 Qi(e,n){let t=[],r=!1;return Et(e).forEach((o,s)=>{let i=s+1;if(o.trim()===""){r=!0;return}let l=o.length-o.replace(/^ +/,"").length;if(o[l]===" ")throw b(i,"invalid indentation");if(n.strict&&l%n.indent!==0)throw b(i,"invalid indentation");let a=Math.floor(l/n.indent);le(a,i,n),t.push({number:i,depth:a,content:o.slice(l),blankBefore:r}),r=!1}),t}function le(e,n,t){if(t.maxDepth!==0&&e>t.maxDepth)throw b(n,`maximum nesting depth exceeded (maxDepth ${t.maxDepth})`)}function Tn(e,n,t){if(t.maxDepth===0)return;let r=0,o=!1,s=!1;for(let i of e){if(s){s=!1;continue}if(o&&i==="\\"){s=!0;continue}if(i==='"'){o=!o;continue}o||(i==="{"?(r+=1,le(r,n,t)):i==="}"&&(r=Math.max(0,r-1)))}}function Xi(e){if(!T(e)||Object.keys(e).length===0)return e;let n={};for(let[t,r]of Object.entries(e)){let o=Ip(r,1);if(o===void 0)return e;ne(n,t,o)}return n}function Ip(e,n){if(!T(e)||!Np(e))return;let{order:t,discriminator:r,rows:o}=e;if(typeof t!="string"||typeof r!="string"||!Number.isSafeInteger(o)||o<0)throw C(n);let s=Mp(t,o,n),i=e.common,l=i===void 0?Array.from({length:o},()=>({})):i;if(!Array.isArray(l)||l.length!==o||!l.every(T))throw Zi(n);let a=new Map;for(let[p,f]of Object.entries(e))if(!Ui.has(p)){if(!Array.isArray(f)||!f.every(T))throw C(n);a.set(p,f)}if(a.size===0)throw C(n);let d=new Map,u=s.map((p,f)=>{let m=a.get(p);if(m===void 0)throw Mr(n);let g=d.get(p)??0,_=m[g];if(_===void 0)throw Mr(n);return d.set(p,g+1),Cp(r,p,l[f],_,n)});for(let[p,f]of a)if((d.get(p)??0)!==f.length)throw Mr(n);return u}function Np(e){return Object.prototype.hasOwnProperty.call(e,"order")||Object.prototype.hasOwnProperty.call(e,"discriminator")||Object.prototype.hasOwnProperty.call(e,"rows")}function Mp(e,n,t){if(!e.startsWith("cycle("))throw C(t);let r=e.slice(6),o=r.indexOf(")*");if(o===-1)throw C(t);let s=r.slice(0,o),i=r.slice(o+2);if(s===""||i.includes("+tail("))throw C(t);let l=s.split(",").map(u=>Hp(u,t));if(l.some(u=>u===""))throw C(t);let a=Fp(i,t),d=l.length*a;if(!Number.isSafeInteger(d))throw C(t);if(d!==n)throw Zi(t);return Array.from({length:d},(u,p)=>l[p%l.length])}function Cp(e,n,t,r,o){let s={};ne(s,e,n);for(let[i,l]of Object.entries(t??{})){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw C(o);ne(s,i,l)}for(let[i,l]of Object.entries(Wp(r,o))){if(i===e||Object.prototype.hasOwnProperty.call(s,i))throw C(o);ne(s,i,l)}return s}function Wp(e,n){let t={};for(let[r,o]of Object.entries(e))Bp(t,r.split("."),o,n);return Dt(t,n)}function Bp(e,n,t,r){if(n.some(s=>s===""))throw C(r);let o=e;for(let s=0;s<n.length;s+=1){let i=n[s];if(s===n.length-1){o[i]=t;return}if(o[i]??={},o=o[i],!T(o))throw C(r)}}function Dt(e,n){return Array.isArray(e)?e.map(t=>Dt(t,n)):T(e)?Number.isSafeInteger(e.length)&&e.length>=0?Array.from({length:e.length},(t,r)=>{if(!Object.prototype.hasOwnProperty.call(e,String(r)))throw C(n);return Dt(e[String(r)],n)}):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Dt(r,n)])):e}function Fp(e,n){if(e===""||e.length>1&&e.startsWith("0")||!/^[0-9]+$/.test(e))throw C(n);let t=Number(e);if(!Number.isSafeInteger(t))throw C(n);return t}function Hp(e,n){try{return decodeURIComponent(e)}catch{throw C(n)}}function zi(e){return encodeURIComponent(e)}function C(e){return b(e,"invalid cyclic array wire")}function Zi(e){return b(e,"cyclic array length mismatch")}function Mr(e){return b(e,"cyclic array group length mismatch")}function el(e){if(!T(e))return;let n=Object.entries(e);if(n.length===0)return;let t=[];for(let[o,s]of n){let i=Up(s);if(i===void 0)return;t.push([o,i])}let r=[];for(let[o,s]of t)qp(r,o,s);return r.join("")}function Up(e){if(!Array.isArray(e)||e.length===0||!e.every(T))return;let n=Gp(e);if(n===void 0)return;let t=e.map(l=>l[n]),r=Kp(t);if(r===void 0)return;let o=Vp(e,n),s=new Map;for(let l of e){let a=l[n];s.has(a)||s.set(a,[]);let d={};for(let[u,p]of Object.entries(l))if(u!==n&&!o.includes(u)&&!Cr(p,u,d))return;s.get(a).push(d)}let i=[];for(let l of r.cycle){let a=s.get(l),d=Qp(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 Gp(e){return Hi.find(n=>e.every(t=>typeof t[n]=="string"))}function Kp(e){if(!(e.length<12))for(let n=2;n<=Math.min(8,Math.floor(e.length/3));n+=1){if(e.length%n!==0)continue;let t=e.slice(0,n);if(new Set(t).size<2||!e.every((i,l)=>i===t[l%n]))continue;let r=e.length/n;if(r<3)continue;let o=e.map(zi).join(","),s=`cycle(${t.map(zi).join(",")})*${r}`;if(s.length<=o.length*.4)return{cycle:t,encoded:s,repeats:r}}}function Vp(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(!Jp(s)||!e.every(i=>Object.prototype.hasOwnProperty.call(i,s))||!e.every(i=>ie(i[s])))break;t.push(s)}return t}function qp(e,n,t){e.push(M(n),`:
9
+ `),e.push(" order: ",H(t.order.encoded,Te),`
10
+ `),e.push(" discriminator: ",H(t.discriminator,Te),`
11
11
  `),e.push(" rows: ",String(t.rows.length),`
12
- `),t.common.length>0&&Li(e,"common",t.common,t.commonRows);for(let r of t.groups)Li(e,r.label,r.fields,r.rows)}function Li(e,n,t,r){e.push(" ",N(n),"[",String(r.length),Oe,"]{",t.map(N).join(Oe),`}:
13
- `);for(let o of r)e.push(" ",t.map(s=>B(o[s],Oe)).join(Oe),`
14
- `)}function vp(e){return e!==""&&Ar(e)}function Or(e,n,t,r=new Set){if(!Ar(n))return!1;if(se(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)=>Or(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(".")&&Or(i,`${n}.${s}`,t,r));return r.delete(e),o}return!1}function Ep(e){let n=Object.keys(e[0]??{});if(e.every(t=>Pp(Object.keys(t),n)))return n.every(Ar)?n:void 0}function Pp(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function Ar(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function Ye(e,n){let t=e[n]??e[e.length-1];return R(t===void 0?1:t.number,"array length mismatch")}function bt(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]=X(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=jp(f.slice(1,-1),u),m=Tr(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 Ni(e){let n=W(e,"{",0);if(n===-1||!e.endsWith("}"))throw R(0,"invalid keyed map header");let t,r;try{[t,r]=X(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=Dp(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 Dp(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]=X(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(!Mi(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(Ci(r[a].path,r[d].path)||On(r[a].path,r[d].path)||On(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 jp(e,n){if(n!==O&&e.includes(O)&&(e.includes("[")||e.includes("{")))return Lr(e,O,n);try{return Lr(e,n,n)}catch(t){if(n!==O&&t.reason!=="duplicate key")return Lr(e,O,n);throw t}}function Lr(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]=X(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=Op(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(Mi(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=Tr(i);for(let a=0;a<l.length;a+=1)for(let d=a+1;d<l.length;d+=1)if(Ci(l[a].path,l[d].path)||On(l[a].path,l[d].path)||On(l[d].path,l[a].path))throw R(0,"duplicate key");return i}function Op(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 Tr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?Tr(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function _t(e,n,t){return e.listDelimiter===void 0?q(n,t):Z(n,e.listDelimiter,t).map(r=>q(r,t))}function Mi(e,n){return e.length===1&&e!==n&&!/[ \t\r\n"[\]{}:]/.test(e)}function Ci(e,n){return e.length===n.length&&On(e,n)}function On(e,n){return n.every((t,r)=>e[r]===t)}function wt(e,n){return R(n,e.reason??String(e.message))}function J(e,n){let t=ji(n),r=Oi(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=bt(o.content,W(o.content,":",o.number))}catch(c){if(t.strict)throw wt(c,o.number);d=void 0}if(d!==void 0)return Tp(d,r,t)}if(s&&W(o.content,":",o.number)===-1)return q(o.content.trim(),o.number);let i={index:0},l=Ir(r,i,0,t),a=r[i.index];if(a!==void 0)throw R(a.number,"expected end of document");return t.cyclicDiscriminatedArrays?Ti(l):l}function Ir(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}=Ap(e,n,t,r);Ki(o,i,l,a,r,s.number)}return o}function Ap(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=Ni(l)}catch(k){if(r.strict)throw wt(k,o.number);n.index+=1;let w=$r(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=Lp(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=bt(l,i)}catch(k){if(r.strict)throw wt(k,o.number);n.index+=1;let w=$r(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=Nr(h,a,e,n,t,r);return{key:h.key,quoted:h.keyQuoted,value:b}}let[u,f]=X(l,o.number);if(u===""&&!f)throw R(o.number,"expected non-empty field name");n.index+=1;let m=$r(e,n,t,a,o.number,r);return{key:u,quoted:f,value:m}}function $r(e,n,t,r,o,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return q(i,o);let l=e[n.index];return l!==void 0&&l.depth>t?Ir(e,n,t+1,s):{}}function Lp(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]=X(i.content.slice(0,l),i.number);if(a===""&&!d)throw R(i.number,"expected non-empty field name");let c=Z(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)=>{Ze(u,f.path,_t(f,c[m],i.number),o,i.number)}),Ki(s,a,d,u,o,i.number),t.index+=1}return s}function Tp(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=Nr(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 Nr(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 $p(e,e.fields,t,r,o+1,s)}if(l!==""){let a=Z(l,e.delimiter,i).map(d=>q(d,i));if(a.length!==e.len)throw R(i,"array length mismatch");return a}return Fp(e,t,r,o+1,s)}function $p(e,n,t,r,o,s){if(e.fieldTree!==void 0&&Wp(e.fieldTree))return Ip(e,t,r,o,s);let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0)throw Ye(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(!Xe(a.content,e.delimiter,a.number))break;let d=Z(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)=>{Ze(c,u.path,_t(u,d[f],a.number),s,a.number)}),i.push(c),r.index+=1}if(i.length!==e.len)throw Ye(t,r.index);let l=t[r.index];if(l!==void 0&&l.depth>=o&&Xe(l.content,e.delimiter,l.number))throw R(l.number,"array length mismatch");return i}function Ip(e,n,t,r,o){return Wi(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function Wi(e,n,t,r,o,s,i,l){let a=[],d=Fi(e,n,t,r,o.index,s,i);for(;a.length<e;){let u=r[o.index];if(u===void 0)throw Ye(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(!Xe(u.content,t,u.number))break;let f=Z(u.content,t,u.number),m={cellIndex:0,nextIndex:o.index+1,flatWidth:xt(n),childTableFields:d},h=Bi(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(Cp(n,h,l)),o.index=m.nextIndex}if(a.length!==e)throw Ye(r,o.index);let c=r[o.index];if(c!==void 0&&c.depth>=s&&Xe(c.content,t,c.number))throw R(c.number,"array length mismatch");return a}function Bi(e,n,t,r,o,s,i,l){let a={};return e.forEach((d,c)=>{let u=e.slice(c+1),f=Np(d,u,n,t,r,o,s,i,l);Ze(a,[d.key],f,l,t)}),a}function Np(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=>q(u,r));return s.cellIndex+=e.fixedLength,c}if(e.children!==void 0){let c=xt(e.children),u=t[s.cellIndex],f=Ui(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+Bp(n)):k){if(f===void 0)throw R(r,"array row length mismatch");return s.cellIndex+=1,Wi(f,e.children,l,o,{get index(){return s.nextIndex},set index(j){s.nextIndex=j}},i,a,!1)}return Bi(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,_t(e,d,r)}function Fi(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=Hi(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 Hi(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||!Xe(f.content,r,f.number))return;let m=Z(f.content,r,f.number),h=Mp(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&&Xe(c.content,r,c.number))return}catch{return}return{nextIndex:a,consumedChildRows:d}}function Mp(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=Ui(t[a]);if(f===void 0)return;a+=1;let m=Fi(f,u.children,r,o,d,i,l);if(m===void 0)return;let h=Hi(f,u.children,m,r,o,d,i,l);if(h===void 0)return;d=h.nextIndex,c+=f+h.consumedChildRows}else a+=xt(u.children);else a+=1;if(a>t.length)return}if(a===t.length)return{nextIndex:d,consumedChildRows:c}}function Cp(e,n,t){return t&&e.length===1&&e[0].fixedLength!==void 0?n[e[0].key]:n}function Ui(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function Wp(e){return e.some(n=>n.fixedLength!==void 0||n.children!==void 0)}function xt(e){return e.reduce((n,t)=>n+Gi(t),0)}function Gi(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?xt(e.children):1}function Bp(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+Gi(t),0)}function Xe(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 Fp(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 Ye(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(Hp(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 Hp(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=bt(s,i)}catch{l=void 0}if(l!==void 0){let a=s.slice(i+1);return Nr(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 Ir(i,{index:0},t+1,r)}return n.index+=1,q(s,o.number)}function Ki(e,n,t,r,o,s){if(o.expandPaths&&!t&&n.includes(".")){let i=n.split(".");if(i.every(Up)){Ze(e,i,r,o,s);return}}Ze(e,[n],r,o,s)}function Ze(e,n,t,r,o){ie(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");ee(e,s,t);return}if(i&&!L(e[s])){if(r.strict)throw R(o,"path expansion conflict");ee(e,s,{})}else i||ee(e,s,{});Ze(e[s],n.slice(1),t,r,o)}function Up(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=Ii(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?Br(s,void 0,e,0,!1,o):L(e)?Vi(s,e,0,o):s.push(B(e,r)),s.join("")}function en(e,n){e.push(" ".repeat(n*2))}function Vi(e,n,t,r){ie(t,0,r);for(let[o,s]of Object.entries(n))en(e,t),Cr(e,o,s,t,r)}function Cr(e,n,t,r,o){if(ie(r,0,o),Array.isArray(t)){Br(e,n,t,r,!1,o);return}if(L(t)){let s=o.keyedMapCollapse?Kp(t,o,r+1):void 0;if(s!==void 0){e.push(N(n),"{",Fr(o.delimiter),s.fields.map(i=>Gr(i,o.delimiter)).join(o.delimiter),`}:
15
- `);for(let[i,l]of Object.entries(t)){en(e,r+1);let a=[];e.push(N(i),": ",s.paths.map(d=>Kr(Ur(l,d.path),d,o.delimiter,o,a,r+2)).join(o.delimiter),`
16
- `),e.push(...a)}return}e.push(N(n),`:
17
- `),Vi(e,t,r+1,o);return}e.push(N(n),": ",B(t,o.delimiter),`
18
- `)}function Br(e,n,t,r,o,s){if(ie(r,0,s),t.length===0){n!==void 0?e.push(N(n),`: []
12
+ `),t.common.length>0&&Yi(e,"common",t.common,t.commonRows);for(let r of t.groups)Yi(e,r.label,r.fields,r.rows)}function Yi(e,n,t,r){e.push(" ",M(n),"[",String(r.length),Te,"]{",t.map(M).join(Te),`}:
13
+ `);for(let o of r)e.push(" ",t.map(s=>H(o[s],Te)).join(Te),`
14
+ `)}function Jp(e){return e!==""&&Wr(e)}function Cr(e,n,t,r=new Set){if(!Wr(n))return!1;if(ie(e))return t[n]=e,!0;if(Array.isArray(e)){if(r.has(e))return!1;r.add(e),t[`${n}.length`]=e.length;let o=e.every((s,i)=>Cr(s,`${n}.${i}`,t,r));return r.delete(e),o}if(T(e)){if(r.has(e))return!1;r.add(e);let o=Object.entries(e).every(([s,i])=>!s.includes(".")&&Cr(i,`${n}.${s}`,t,r));return r.delete(e),o}return!1}function Qp(e){let n=Object.keys(e[0]??{});if(e.every(t=>zp(Object.keys(t),n)))return n.every(Wr)?n:void 0}function zp(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function Wr(e){return e.split(".").every(n=>/^[A-Za-z_][A-Za-z0-9_]*$|^(?:0|[1-9][0-9]*)$/.test(n))}function tn(e,n){let t=e[n]??e[e.length-1];return b(t===void 0?1:t.number,"array length mismatch")}function jt(e,n){if(n===-1)throw b(0,"array header missing colon");let t=e.slice(0,n),r=F(t,"[",0);if(r===-1)throw b(0,"invalid array header");let o,s;try{[o,s]=Z(t.slice(0,r),0)}catch{throw b(0,"invalid array header")}let i=t.slice(r+1),l=i.indexOf("]");if(l===-1)throw b(0,"invalid array header");let a=i.slice(0,l),d=/^[0-9]*/.exec(a)[0];if(d===""||d.length>1&&d.startsWith("0"))throw b(0,"invalid array header");let u=Number.parseInt(d,10),p;switch(a.slice(d.length)){case"":p=",";break;case" ":p=" ";break;case"|":p="|";break;default:throw b(0,"invalid array header")}let f=i.slice(l+1),m,g;if(f==="")m=void 0,g=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{g=Xp(f.slice(1,-1),p),m=Fr(g)}catch(_){throw b(0,_.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw b(0,"invalid array header");return{key:o,keyQuoted:s,len:u,delimiter:p,fields:m,fieldTree:g}}function nl(e){let n=F(e,"{",0);if(n===-1||!e.endsWith("}"))throw b(0,"invalid keyed map header");let t,r;try{[t,r]=Z(e.slice(0,n),0)}catch{throw b(0,"invalid keyed map header")}if(t===""&&!r)throw b(0,"expected non-empty field name");let o=e.slice(n+1,-1),s=L;(o.startsWith("|")||o.startsWith(" "))&&(s=o[0],o=o.slice(1));let i;try{i=Yp(o,s,s)}catch(l){throw b(0,l.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:t,keyQuoted:r,delimiter:s,fields:i}}function Yp(e,n,t){let r=[],o=0;function s(a,d){let u=0;for(;o<e.length&&!(d&&e[o]==="}");){if(e[o]===n||e[o]==="}")throw b(0,"invalid array header");let p=o;for(;o<e.length;){let g=e[o];if(g==='"'){i();continue}if(g===n||g==="{"||g==="}"||g==="[")break;o+=1}let[f,m]=Z(e.slice(p,o),0);if(f===""&&!m)throw b(0,"invalid array header");if(u+=1,e[o]==="["){o+=1;let g=o;for(;o<e.length&&e[o]!=="]";)o+=1;if(o>=e.length)throw b(0,"invalid array header");let _=e.slice(g,o);if(!tl(_,t))throw b(0,"invalid array header");o+=1,r.push({path:[...a,f],listDelimiter:_})}else if(e[o]==="{"){o+=1;let g=r.length;if(s([...a,f],!0),e[o]!=="}"||r.length===g)throw b(0,"invalid array header");o+=1}else r.push({path:[...a,f],listDelimiter:void 0});if(e[o]===n){if(o+=1,o>=e.length||e[o]==="}")throw b(0,"invalid array header");continue}if(d?e[o]==="}":o===e.length)break;throw b(0,"invalid array header")}if(u===0)throw b(0,"invalid array header")}function i(){for(o+=1;o<e.length;){let a=e[o];if(o+=1,a==="\\")o+=1;else if(a==='"')return}}if(s([],!1),o!==e.length)throw b(0,"invalid array header");let l=new Set;for(let a=0;a<r.length;a+=1)for(let d=a+1;d<r.length;d+=1)if(rl(r[a].path,r[d].path)||$n(r[a].path,r[d].path)||$n(r[d].path,r[a].path))throw b(0,"duplicate key");for(let a of r){let u=a.path.join("\0");if(l.has(u))throw b(0,"duplicate key");l.add(u)}return r}function Xp(e,n){if(n!==L&&e.includes(L)&&(e.includes("[")||e.includes("{")))return Br(e,L,n);try{return Br(e,n,n)}catch(t){if(n!==L&&t.reason!=="duplicate key")return Br(e,L,n);throw t}}function Br(e,n,t){let r=0;function o(a){let d=[];for(;r<e.length&&!(a&&e[r]==="}");){if(e[r]===n||e[r]==="}")throw b(0,"invalid array header");let u=r;for(;r<e.length;){let g=e[r];if(g==='"'){s();continue}if(g===n||g==="{"||g==="}"||g==="[")break;r+=1}let[p,f]=Z(e.slice(u,r),0);if(p===""&&!f)throw b(0,"invalid array header");let m={key:p};if(e[r]==="["){r+=1;let g=r;for(;r<e.length&&e[r]!=="]";)r+=1;if(r>=e.length)throw b(0,"invalid array header");let _=e.slice(g,r);r+=1;let k=Zp(_);if(k!==void 0){if(k.delimiter!==t)throw b(0,"invalid array header");m.fixedLength=k.len,m.fixedDelimiter=k.delimiter}else if(tl(_,t))m.listDelimiter=_;else throw b(0,"invalid array header")}else if(e[r]==="{"){if(r+=1,m.children=o(!0),e[r]!=="}"||m.children.length===0)throw b(0,"invalid array header");r+=1}if(d.push(m),e[r]===n){if(r+=1,r>=e.length||e[r]==="}")throw b(0,"invalid array header");continue}if(a?e[r]==="}":r===e.length)break;throw b(0,"invalid array header")}if(d.length===0)throw b(0,"invalid array header");return d}function s(){for(r+=1;r<e.length;){let a=e[r];if(r+=1,a==="\\")r+=1;else if(a==='"')return}}let i=o(!1);if(r!==e.length)throw b(0,"invalid array header");let l=Fr(i);for(let a=0;a<l.length;a+=1)for(let d=a+1;d<l.length;d+=1)if(rl(l[a].path,l[d].path)||$n(l[a].path,l[d].path)||$n(l[d].path,l[a].path))throw b(0,"duplicate key");return i}function Zp(e){let n=/^[0-9]+/.exec(e)?.[0];if(n===void 0||n.length>1&&n.startsWith("0"))return;let t=e.slice(n.length),r;switch(t){case"":r=L;break;case" ":r=" ";break;case"|":r="|";break;default:return}return{len:Number.parseInt(n,10),delimiter:r}}function Fr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.children!==void 0?Fr(t.children,r):[{path:r,listDelimiter:t.listDelimiter}]})}function Ot(e,n,t){return e.listDelimiter===void 0?J(n,t):ee(n,e.listDelimiter,t).map(r=>J(r,t))}function tl(e,n){return e.length===1&&e!==n&&!/[ \t\r\n"[\]{}:]/.test(e)}function rl(e,n){return e.length===n.length&&$n(e,n)}function $n(e,n){return n.every((t,r)=>e[r]===t)}function At(e,n){return b(n,e.reason??String(e.message))}function Q(e,n){let t=Ji(n),r=Qi(e,t),o=r[0];if(o===void 0)return{};if(o.depth!==0)throw b(o.number,"invalid indentation");let s=r.length===1;if(s&&o.content.trim()==="[]")return[];if(o.content.startsWith("[")){Tn(o.content,o.number,t);let d;try{d=jt(o.content,F(o.content,":",o.number))}catch(u){if(t.strict)throw At(u,o.number);d=void 0}if(d!==void 0)return tf(d,r,t)}if(s&&F(o.content,":",o.number)===-1)return J(o.content.trim(),o.number);let i={index:0},l=Ur(r,i,0,t),a=r[i.index];if(a!==void 0)throw b(a.number,"expected end of document");return t.cyclicDiscriminatedArrays?Xi(l):l}function Ur(e,n,t,r){let o={};for(;n.index<e.length;){let s=e[n.index];if(s.depth<t)break;if(s.depth>t)throw b(s.number,"invalid indentation");let{key:i,quoted:l,value:a}=ef(e,n,t,r);cl(o,i,l,a,r,s.number)}return o}function ef(e,n,t,r){let o=e[n.index],s=o.content,i=F(s,":",o.number);if(i===-1)throw b(o.number,"expected `key: value`");let l=s.slice(0,i),a=s.slice(i+1),d=F(l,"[",o.number),u=F(l,"{",o.number);if(u!==-1&&(d===-1||u<d)){Tn(l,o.number,r);let g;try{g=nl(l)}catch(k){if(r.strict)throw At(k,o.number);n.index+=1;let w=Hr(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:w}}if(a.trim()!=="")throw b(o.number,"expected keyed map rows");let _=nf(g,e,n,t+1,r);return{key:g.key,quoted:g.keyQuoted,value:_}}if(d!==-1){Tn(l,o.number,r);let g;try{g=jt(l,i)}catch(k){if(r.strict)throw At(k,o.number);n.index+=1;let w=Hr(e,n,t,a,o.number,r);return{key:l.trim(),quoted:!1,value:w}}if(g.key===""&&!g.keyQuoted)throw b(o.number,"expected non-empty field name");let _=Gr(g,a,e,n,t,r);return{key:g.key,quoted:g.keyQuoted,value:_}}let[p,f]=Z(l,o.number);if(p===""&&!f)throw b(o.number,"expected non-empty field name");n.index+=1;let m=Hr(e,n,t,a,o.number,r);return{key:p,quoted:f,value:m}}function Hr(e,n,t,r,o,s){let i=r.trim();if(i==="[]")return[];if(i!=="")return J(i,o);let l=e[n.index];return l!==void 0&&l.depth>t?Ur(e,n,t+1,s):{}}function nf(e,n,t,r,o){let s={};for(t.index+=1;t.index<n.length;){let i=n[t.index];if(i.depth<r)break;if(i.depth>r)throw b(i.number,"invalid indentation");if(i.blankBefore&&o.strict)throw b(i.number,"blank line inside keyed map");let l=F(i.content,":",i.number);if(l===-1)throw b(i.number,"expected `key: value`");let[a,d]=Z(i.content.slice(0,l),i.number);if(a===""&&!d)throw b(i.number,"expected non-empty field name");let u=ee(i.content.slice(l+1).trim(),e.delimiter,i.number);if(u.length!==e.fields.length)throw b(i.number,"keyed map row length mismatch");let p={};e.fields.forEach((f,m)=>{on(p,f.path,Ot(f,u[m],i.number),o,i.number)}),cl(s,a,d,p,o,i.number),t.index+=1}return s}function tf(e,n,t){let r=n[0],o=F(r.content,":",r.number);if(o===-1)throw b(r.number,"expected `key: value`");let s=r.content.slice(o+1),i={index:0},l=Gr(e,s,n,i,0,t),a=n[i.index];if(a!==void 0)throw b(a.number,"expected end of document");return l}function Gr(e,n,t,r,o,s){let i=t[r.index].number,l=n.trim();if(r.index+=1,e.fields!==void 0){if(l!=="")throw b(i,"expected tabular rows");return rf(e,e.fields,t,r,o+1,s)}if(l!==""){let a=ee(l,e.delimiter,i).map(d=>J(d,i));if(a.length!==e.len)throw b(i,"array length mismatch");return a}return uf(e,t,r,o+1,s)}function rf(e,n,t,r,o,s){if(e.fieldTree!==void 0&&df(e.fieldTree))return of(e,t,r,o,s);let i=[];for(;i.length<e.len;){let a=t[r.index];if(a===void 0)throw tn(t,r.index);if(a.depth<o)break;if(a.depth>o)throw b(a.number,"invalid indentation");if(a.blankBefore&&s.strict)throw b(a.number,"blank line inside array");if(!rn(a.content,e.delimiter,a.number))break;let d=ee(a.content,e.delimiter,a.number);if(d.length!==n.length)throw b(a.number,"array row length mismatch");let u={};n.forEach((p,f)=>{on(u,p.path,Ot(p,d[f],a.number),s,a.number)}),i.push(u),r.index+=1}if(i.length!==e.len)throw tn(t,r.index);let l=t[r.index];if(l!==void 0&&l.depth>=o&&rn(l.content,e.delimiter,l.number))throw b(l.number,"array length mismatch");return i}function of(e,n,t,r,o){return ol(e.len,e.fieldTree,e.delimiter,n,t,r,o,!0)}function ol(e,n,t,r,o,s,i,l){let a=[],d=il(e,n,t,r,o.index,s,i);for(;a.length<e;){let p=r[o.index];if(p===void 0)throw tn(r,o.index);if(p.depth<s)break;if(p.depth>s)throw b(p.number,"invalid indentation");if(p.blankBefore&&i.strict)throw b(p.number,"blank line inside array");if(!rn(p.content,t,p.number))break;let f=ee(p.content,t,p.number),m={cellIndex:0,nextIndex:o.index+1,flatWidth:Lt(n),childTableFields:d},g=sl(n,f,p.number,r,m,s+1,t,i);if(m.cellIndex!==f.length)throw b(p.number,"array row length mismatch");a.push(af(n,g,l)),o.index=m.nextIndex}if(a.length!==e)throw tn(r,o.index);let u=r[o.index];if(u!==void 0&&u.depth>=s&&rn(u.content,t,u.number))throw b(u.number,"array length mismatch");return a}function sl(e,n,t,r,o,s,i,l){let a={};return e.forEach((d,u)=>{let p=e.slice(u+1),f=sf(d,p,n,t,r,o,s,i,l);on(a,[d.key],f,l,t)}),a}function sf(e,n,t,r,o,s,i,l,a){if(e.fixedLength!==void 0){if(s.cellIndex+e.fixedLength>t.length)throw b(r,"array row length mismatch");let u=t.slice(s.cellIndex,s.cellIndex+e.fixedLength).map(p=>J(p,r));return s.cellIndex+=e.fixedLength,u}if(e.children!==void 0){let u=Lt(e.children),p=t[s.cellIndex],f=al(p),m=t.length-s.cellIndex-1,g=o[s.nextIndex],_=g!==void 0&&g.depth===i,k=s.childTableFields===void 0?void 0:s.childTableFields.has(e);if(k===void 0?f!==void 0&&(_||t.length!==s.flatWidth&&m<u+cf(n)):k){if(f===void 0)throw b(r,"array row length mismatch");return s.cellIndex+=1,ol(f,e.children,l,o,{get index(){return s.nextIndex},set index(O){s.nextIndex=O}},i,a,!1)}return sl(e.children,t,r,o,s,i,l,a)}let d=t[s.cellIndex];if(d===void 0)throw b(r,"array row length mismatch");return s.cellIndex+=1,Ot(e,d,r)}function il(e,n,t,r,o,s,i){let l=n.filter(u=>u.children!==void 0);if(l.length===0)return new Set;if(l.length>12)return;let a,d=1<<l.length;for(let u=0;u<d;u+=1){let p=new Set;l.forEach((m,g)=>{u&1<<g&&p.add(m)});let f=ll(e,n,p,t,r,o,s,i);f!==void 0&&(a===void 0||f.consumedChildRows>a.consumedChildRows||f.consumedChildRows===a.consumedChildRows&&p.size<a.childTableFields.size)&&(a={childTableFields:p,consumedChildRows:f.consumedChildRows})}return a?.childTableFields}function ll(e,n,t,r,o,s,i,l){let a=s,d=0;try{for(let p=0;p<e;p+=1){let f=o[a];if(f===void 0||f.depth!==i||f.blankBefore&&l.strict||!rn(f.content,r,f.number))return;let m=ee(f.content,r,f.number),g=lf(n,t,m,r,o,a+1,i+1,l);if(g===void 0||o[g.nextIndex]?.depth>i)return;d+=g.consumedChildRows,a=g.nextIndex}let u=o[a];if(u!==void 0&&u.depth>=i&&rn(u.content,r,u.number))return}catch{return}return{nextIndex:a,consumedChildRows:d}}function lf(e,n,t,r,o,s,i,l){let a=0,d=s,u=0;for(let p of e){if(p.fixedLength!==void 0)a+=p.fixedLength;else if(p.children!==void 0)if(n.has(p)){let f=al(t[a]);if(f===void 0)return;a+=1;let m=il(f,p.children,r,o,d,i,l);if(m===void 0)return;let g=ll(f,p.children,m,r,o,d,i,l);if(g===void 0)return;d=g.nextIndex,u+=f+g.consumedChildRows}else a+=Lt(p.children);else a+=1;if(a>t.length)return}if(a===t.length)return{nextIndex:d,consumedChildRows:u}}function af(e,n,t){return t&&e.length===1&&e[0].fixedLength!==void 0?n[e[0].key]:n}function al(e){if(!(e===void 0||!/^(0|[1-9][0-9]*)$/.test(e)))return Number.parseInt(e,10)}function df(e){return e.some(n=>n.fixedLength!==void 0||n.children!==void 0)}function Lt(e){return e.reduce((n,t)=>n+dl(t),0)}function dl(e){return e.fixedLength!==void 0?e.fixedLength:e.children!==void 0?Lt(e.children):1}function cf(e){return e.reduce((n,t)=>t.children!==void 0?n+1:n+dl(t),0)}function rn(e,n,t){let r=F(e,":",t);if(r===-1)return!0;let o=F(e,n,t);return o===-1?!1:o<r}function uf(e,n,t,r,o){let s=[];for(;s.length<e.len;){let l=n[t.index];if(l===void 0||l.depth<r)throw tn(n,t.index);if(l.depth>r)throw b(l.number,"invalid indentation");if(l.blankBefore&&o.strict)throw b(l.number,"blank line inside array");s.push(pf(n,t,r,o))}let i=n[t.index];if(i!==void 0&&i.depth>=r)throw b(i.number,"array length mismatch");return s}function pf(e,n,t,r){let o=e[n.index];if(!o.content.startsWith("-"))throw b(o.number,"expected array item");let s=o.content.slice(1).replace(/^\s+/,"");if(s==="")return n.index+=1,{};if(s.startsWith("[")){let i=F(s,":",o.number);Tn(s,o.number,r);let l;try{l=jt(s,i)}catch{l=void 0}if(l!==void 0){let a=s.slice(i+1);return Gr(l,a,e,n,t,r)}}if(F(s,":",o.number)!==-1){let i=[{number:o.number,depth:t+1,content:s,blankBefore:!1}];for(n.index+=1;n.index<e.length;){let l=e[n.index];if(l.depth<=t)break;i.push(l),n.index+=1}return Ur(i,{index:0},t+1,r)}return n.index+=1,J(s,o.number)}function cl(e,n,t,r,o,s){if(o.expandPaths&&!t&&n.includes(".")){let i=n.split(".");if(i.every(ff)){on(e,i,r,o,s);return}}on(e,[n],r,o,s)}function on(e,n,t,r,o){le(n.length-1,o,r);let s=n[0],i=Object.prototype.hasOwnProperty.call(e,s);if(n.length===1){if(i&&r.strict)throw b(o,"duplicate key");ne(e,s,t);return}if(i&&!T(e[s])){if(r.strict)throw b(o,"path expansion conflict");ne(e,s,{})}else i||ne(e,s,{});on(e[s],n.slice(1),t,r,o)}function ff(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function W(e,n={}){let t=n.maxDepth??1e3,r=n.delimiter??L;if(![L,"|"," "].includes(r))throw b(0,"invalid array header");let o={nestedTabularHeaders:n.nestedTabularHeaders===!0,keyedMapCollapse:n.keyedMapCollapse===!0,primitiveArrayColumns:n.primitiveArrayColumns===!0,objectArrayColumns:n.objectArrayColumns===!0,cyclicDiscriminatedArrays:n.cyclicDiscriminatedArrays===!0,delimiter:r,maxDepth:t===Number.POSITIVE_INFINITY?0:Math.max(0,Math.floor(t))};if(o.cyclicDiscriminatedArrays){let i=el(e);if(i!==void 0)return i}let s=[];return Array.isArray(e)?Jr(s,void 0,e,0,!1,o):T(e)?ul(s,e,0,o):s.push(H(e,r)),s.join("")}function sn(e,n){e.push(" ".repeat(n*2))}function ul(e,n,t,r){le(t,0,r);for(let[o,s]of Object.entries(n))sn(e,t),Vr(e,o,s,t,r)}function Vr(e,n,t,r,o){if(le(r,0,o),Array.isArray(t)){Jr(e,n,t,r,!1,o);return}if(T(t)){let s=o.keyedMapCollapse?hf(t,o,r+1):void 0;if(s!==void 0){e.push(M(n),"{",Qr(o.delimiter),s.fields.map(i=>Xr(i,o.delimiter)).join(o.delimiter),`}:
15
+ `);for(let[i,l]of Object.entries(t)){sn(e,r+1);let a=[];e.push(M(i),": ",s.paths.map(d=>Zr(Yr(l,d.path),d,o.delimiter,o,a,r+2)).join(o.delimiter),`
16
+ `),e.push(...a)}return}e.push(M(n),`:
17
+ `),ul(e,t,r+1,o);return}e.push(M(n),": ",H(t,o.delimiter),`
18
+ `)}function Jr(e,n,t,r,o,s){if(le(r,0,s),t.length===0){n!==void 0?e.push(M(n),`: []
19
19
  `):o?e.push(`[0]:
20
20
  `):e.push(`[]
21
- `);return}if(t.every(se)){Mr(e,n,t.length,void 0,s.delimiter),e.push(" "),e.push(t.map(l=>B(l,s.delimiter)).join(s.delimiter)),e.push(`
22
- `);return}let i=o?void 0:qi(t,s,r+1);if(i!==void 0){Mr(e,n,t.length,i.fields,s.delimiter),e.push(`
23
- `);for(let l of t){en(e,r+1);let a=[];e.push(i.paths.map(d=>Kr(Ur(l,d.path),d,s.delimiter,s,a,r+2)).join(s.delimiter)),e.push(`
24
- `),e.push(...a)}return}Mr(e,n,t.length,void 0,s.delimiter),e.push(`
25
- `);for(let l of t)en(e,r+1),Gp(e,l,r+1,s)}function Gp(e,n,t,r){if(ie(t,0,r),Array.isArray(n)){e.push("- "),Br(e,void 0,n,t,!0,r);return}if(L(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
26
- `);return}e.push("- "),Cr(e,o[0][0],o[0][1],t+1,r);for(let[s,i]of o.slice(1))en(e,t+1),Cr(e,s,i,t+1,r);return}e.push("- ",B(n,r.delimiter),`
27
- `)}function Mr(e,n,t,r,o){n!==void 0&&e.push(N(n)),e.push("[",String(t),Fr(o),"]"),r!==void 0&&e.push("{",r.map(s=>Gr(s,o)).join(o),"}"),e.push(":")}function Fr(e){return e===O?"":e}function qi(e,n,t){let r=Vp(e,n);if(r!==void 0)return r;let o=Wr(e.map(s=>({value:s})),n,t);return o===void 0?void 0:{fields:o,paths:Hr(o)}}function Kp(e,n,t){let r=Object.values(e);if(!(r.length<2))return qi(r,n,t)}function Wr(e,n,t){ie(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})=>se(a)))continue;if(n.primitiveArrayColumns&&i.every(({value:a})=>Array.isArray(a)&&a.every(se))){s.listDelimiter=";";continue}if(n.objectArrayColumns&&i.every(({value:a})=>Array.isArray(a))){let a=Ji(i.map(({value:c})=>c));if(a!==void 0){s.fixedLength=a.fixedLength,s.fixedDelimiter=n.delimiter;continue}let d=Wr(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=Wr(i,n,t+1);if(l===void 0)return;s.children=l}return o}}function Vp(e,n){if(!n.objectArrayColumns)return;let t=Ji(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:n.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function Ji(e){let n=e[0]?.length;if(!(!Number.isInteger(n)||n===0)&&e.every(t=>Array.isArray(t)&&t.length===n&&t.every(se)))return{fixedLength:n}}function Hr(e,n=[]){return e.flatMap(t=>{let r=[...n,t.key];return t.childTable===!0?[{path:r,childFields:t.children}]:t.fixedLength!==void 0?[{path:r,fixedLength:t.fixedLength}]:t.children===void 0?[{path:r,listDelimiter:t.listDelimiter}]:Hr(t.children,r)})}function Ur(e,n){let t=e;for(let r of n)t=t[r];return t}function Gr(e,n){return e.listDelimiter!==void 0?`${N(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${N(e.key)}[${e.fixedLength}${Fr(n)}]`:e.children===void 0?N(e.key):`${N(e.key)}{${e.children.map(t=>Gr(t,n)).join(n)}}`}function Kr(e,n,t,r,o,s){return n.childFields!==void 0?(qp(o,e,n.childFields,r,s),String(e.length)):n.fixedLength!==void 0?e.map(i=>B(i,t)).join(t):n.listDelimiter===void 0?B(e,t):e.map(i=>Jp(i,t,n.listDelimiter)).join(n.listDelimiter)}function qp(e,n,t,r,o){for(let s of n){en(e,o);let i=[];e.push(Hr(t).map(l=>Kr(Ur(s,l.path),l,r.delimiter,r,i,o+1)).join(r.delimiter)),e.push(`
28
- `),e.push(...i)}}function Jp(e,n,t){return typeof e!="string"?B(e,n):Dr(e,n)||e.includes(t)?kt(e):e}var tl=[O,"|"," "];var rl=8,ol=/^[A-Za-z0-9_-]+$/,vw=new TextEncoder,Ew=new TextDecoder;function Xp(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 sl(e,n){if(!ol.test(e))throw S(n,"invalid tag")}function Zp(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!ol.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 ef(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(!tl.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),sl(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=Z(c,l,n).map(f=>X(f,n)[0])}catch(f){throw ze(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 nf(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 Qi(e,n,t,r){let o;try{o=Z(e,n,r)}catch(s){throw ze(s)}if(o.length!==t)throw S(r,"row arity mismatch");for(let s of o)try{q(s,r)}catch(i){throw ze(i)}return o}function tf(e,n,t){let r={};return e.forEach((o,s)=>{try{ee(r,o,q(n[s],t))}catch(i){throw ze(i)}}),r}function rf(e,n,t){if(e.startsWith("- "))throw S(n,"reserved line prefix");let r=Xp(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=ef(e,n);if(o!==null)return o.continuation?(nf(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=Zp(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:Qi(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:Qi(e,t.delimiter,t.fields.length,n)}}function of(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>=rl)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(yt(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=rf(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 j=r.get(w.tag).current;j.rows.push(w.cells),d(j,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 we(e){return of(e).flatMap(n=>n.rows.map(t=>tf(n.fields,t,0)))}function sf(e){if(!tl.includes(e))throw S(0,"invalid header delimiter")}function zi(e,n,t=!1){return`[${`${t?"~":""}${e===O?"":e}`}]{${n}}:
29
- `}function Yi(e,n){return`[]<${e}>{${n}}:
30
- `}function Vr(e,n){return n.map(N).join(e)}function lf(e){if(!Array.isArray(e)||e.length===0)throw S(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=X(String(n),0)}catch(r){throw ze(r)}if(t==="")throw S(0,"TOONL header requires fields");return t})}function Xi(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function Zi(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw S(0,"TOONL continuation cadence must be positive")}function af(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function el(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=>!se(e[t])))throw S(0,"TOONL rows must be flat objects");return n}function df(e){return JSON.stringify([...e].sort())}function nl(e,n){let t=df(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function ge({delimiter:e=O,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){sf(e),Zi(t),Zi(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=()=>af(f,a,d)?(a=0,d=0,zi(e,s,!0)):"",b=k=>{sl(k,0);let w=c.get(k);if(w===void 0){if(c.size>=rl)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=nl(el(k),i),j="";(o===null||o.length!==w.length||o.some((fe,Ue)=>fe!==w[Ue]))&&(j+=m(),o=w,s=Vr(e,o),l=0,a=0,d=0,j+=zi(e,s));let Y=o.map(fe=>B(k[fe],e));j+=h();let pe=`${Y.join(e)}
32
- `;return j+=pe,l+=1,a+=1,d+=pe.length,j},declareLane(k,w){if(u)throw S(0,"TOONL encoder is closed");let j=lf(w),Y=Vr(O,j),pe=b(k);return Xi(pe.fields,j)?"":(pe.fields=j,Yi(k,Y))},pushTagged(k,w){if(u)throw S(0,"TOONL encoder is closed");let j=b(k),Y=nl(el(w),j.fieldsByShape),pe=Vr(O,Y),fe=Y.map(dr=>B(w[dr],O)),Ue="";return Xi(j.fields,Y)||(j.fields=Y,Ue+=Yi(k,pe)),`${Ue}${k}:${fe.join(O)}
33
- `},end(){return u?"":(u=!0,m())}}}function qr(e){let n={app:e,version:cf(nn("__RED_BUILD_VERSION__",()=>"3.3.21")??"0.0.0-dev"),gitSha:nn("__RED_BUILD_GIT_SHA__",()=>"bae98be31c9aa17a4bd850e053045c2ffb276781")??"unknown",buildTime:nn("__RED_BUILD_TIME__",()=>"2026-08-03T15:53:12Z")??"unknown",bundleAsset:nn("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=nn("__REDDB_SDK_VERSION__",()=>""),r=nn("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function cf(e){return e.startsWith("v")?e.slice(1):e}function il(e){return`${e.app} ${e.version} ${e.gitSha}`}function nn(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var ll={"=":"data",":=":{to:"data",typed:!0},":":"meta"},uf=/^[a-z][a-z0-9+.-]*:\/\//i;function pf(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 ff(e=ll){return Object.entries(e).map(([n,t])=>pf(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function mf(e){return/^-\d+(\.\d+)?$/.test(e)}function An(e){return!(!e||e.startsWith("-")&&!mf(e))}function St(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 al(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=>al(t.trim())):e}function Ae(e,n){switch(n){case"boolean":return hf(e);case"number":return gf(e);case"array":return e.split(",").map(t=>St(t.trim()));case"string":default:return e}}function hf(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function gf(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 xe(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function yf(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 kf(e){let n=[],t=bf(e);if(n.push(E("section-header","Usage:"),E("text"," "),E("usage-text",t),E("newline",`
34
- `),E("newline",`
35
- `)),e.positional&&e.positional.length>0){n.push(E("section-header","Arguments:"),E("newline",`
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
- `),E("indent"," "),E("option-description",r.description),E("newline",`
38
- `))}n.push(E("newline",`
39
- `))}if(e.options&&Object.keys(e.options).length>0){n.push(E("section-header","Options:"),E("newline",`
40
- `));let r=_f(e.options);n.push(...r)}return n}function Rf(e,n){let t=kf(e);return yf(t,n)}function bf(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 _f(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 dl(e){let n=Df(e.options??{},e.autoShort??!1),t=ff(e.separators??ll);return{schema:e,parse(r){return wf(r,e,n,t)},help(){return Rf(e,e.formatter)}}}function wf(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?Ae(h,f.type):h),a++}o.positional[f.name]=m,i++}else{let m=f.type?Ae(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=Ef(c,a,e,o,t,n);continue}if(c.startsWith("-")&&c.length>1&&!Tf(c)){a=Pf(c,a,e,o,t,n);continue}let u=xf(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?al(m):xe(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?Ae(b,f.type):b),a++}o.positional[f.name]=h,i++;continue}let m=f.type?Ae(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 Of(o,n,t),Af(o,n,l),Lf(o,n,t),o}function xf(e,n){if(uf.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(Sf(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(vf(o,s,t))return{key:o,value:s,config:t}}}return null}function Sf(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function vf(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 Ef(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 vt(d,c,n+1,r,o,s)}let l=o.get(i);if(l){if(l.type!=="boolean"){let a=t[n+1];return An(a)?vt(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 Pf(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=Jr(a,o);return c?vt(c.name,d,n+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=St(xe(d))),n+1)}if(i.length===1){let l=Jr(i,o);if(l){if(l.type!=="boolean"){let a=t[n+1];return An(a)?vt(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(An(a))return r.options[i]=St(xe(a)),n+2;r.options[i]=!0}return n+1}for(let l of i){let a=Jr(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 vt(e,n,t,r,o,s){let i=o.get(e);if(i){if(i.choices){let a=i.type?Ae(xe(n),i.type):xe(n);if(!i.choices.includes(a))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${i.choices.join(", ")}`),t}let l=i.type?Ae(xe(n),i.type):xe(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]=St(xe(n)));return t}function Df(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=jf(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 jf(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 Jr(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function Of(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?Ae(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 Af(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 Lf(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 Tf(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 If(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&&An(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 Le(e,n,t={}){let o=dl({options:$f(n),separators:{},allowUnknown:!0}).parse([...e]),s={},i=If(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 zr=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 cl(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 zr(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as Vf,mkdirSync as qf,readFileSync as bl,statSync as Jf}from"node:fs";import{dirname as wl,join as Qf}from"node:path";var ul="RED_WORKER_SCOPE",pl="RED_WORKER_MEMORY_CEILING",fl="RED_WORKER_SCOPE_DEGRADATION",Xr={scope:null,memory_ceiling:null,scope_degradation:null};function Zr(e){return{scope:Yr(e[ul]),memory_ceiling:Yr(e[pl]),scope_degradation:Yr(e[fl])}}function Ln(e){let n={};return e.scope!=null&&e.scope!==""&&(n[ul]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[pl]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[fl]=e.scope_degradation),n}function Yr(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as Cf,readdirSync as Wf,readFileSync as yl,rmSync as Bf,writeFileSync as Ff}from"node:fs";import{basename as Hf,join as tn}from"node:path";import{isAbsolute as sx,join as Et,resolve as ix}from"node:path";function Nf(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var ml="deaths",hl="deaths.toonl";function Pt(e){return Et(Nf(e),ml)}function Tn(e){return Et(Pt(e),hl)}var $n="live",gl="attributions.toonl";function Dt(e){return Et(Pt(e),$n)}function eo(e){return Et(Pt(e),gl)}var to=tn("sys","kernel","random","boot_id"),kl=1;function ro(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:kl,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:Rl(tn(t,to)),cgroup:Uf(t,r),last_phase:e.last_phase}}function Rl(e){try{let n=yl(e,"utf8").trim();return n===""?null:n}catch{return null}}function Uf(e,n){let t=Rl(tn(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 oo(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function so(e,n){let t=tn(e,oo(n));try{return Cf(e,{recursive:!0,mode:448}),Ff(t,ge({trailer:!1}).push(Kf(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function Te(e,n){try{Bf(tn(e,oo(n)),{force:!0})}catch{}}function io(e,n){let t;try{t=Wf(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=tn(e,o);try{let l=we(yl(s,"utf8"))[0];if(l===void 0)throw new Error("anchor holds no record");r.push(Gf(l))}catch(i){n?.(Hf(s),i instanceof Error?i.message:String(i))}}return r}function Gf(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:no(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:no(e.pid),ppid:no(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 no(e){return typeof e=="number"?e:Number(e)}function Kf(e){return{...e}}var zf=1,Yf=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function Xf(e){return typeof e=="string"&&Yf.has(e)}var Zf="startup";function em(e,n){return{...e.scope??Xr,version:zf,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 nm(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 ao={mkdir(e){qf(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=Jf(e).size}catch{return!0}if(n===0)return!0;try{return bl(e,"utf8").endsWith(`
43
- `)}catch{return!0}},append(e,n){Vf(e,n,{encoding:"utf8",mode:384})},read(e){return bl(e,"utf8")}};function tm(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function rm(e,n,t=ao){let r=ge({trailer:!1}).push(tm(n));return t.mkdir(wl(e)),t.endsClean(e)||t.append(e,`
44
- `),t.append(e,r),n}function xl(e){let n=e.endsWith(`
21
+ `);return}if(t.every(ie)){Kr(e,n,t.length,void 0,s.delimiter),e.push(" "),e.push(t.map(l=>H(l,s.delimiter)).join(s.delimiter)),e.push(`
22
+ `);return}let i=o?void 0:pl(t,s,r+1);if(i!==void 0){Kr(e,n,t.length,i.fields,s.delimiter),e.push(`
23
+ `);for(let l of t){sn(e,r+1);let a=[];e.push(i.paths.map(d=>Zr(Yr(l,d.path),d,s.delimiter,s,a,r+2)).join(s.delimiter)),e.push(`
24
+ `),e.push(...a)}return}Kr(e,n,t.length,void 0,s.delimiter),e.push(`
25
+ `);for(let l of t)sn(e,r+1),mf(e,l,r+1,s)}function mf(e,n,t,r){if(le(t,0,r),Array.isArray(n)){e.push("- "),Jr(e,void 0,n,t,!0,r);return}if(T(n)){let o=Object.entries(n);if(o.length===0){e.push(`-
26
+ `);return}e.push("- "),Vr(e,o[0][0],o[0][1],t+1,r);for(let[s,i]of o.slice(1))sn(e,t+1),Vr(e,s,i,t+1,r);return}e.push("- ",H(n,r.delimiter),`
27
+ `)}function Kr(e,n,t,r,o){n!==void 0&&e.push(M(n)),e.push("[",String(t),Qr(o),"]"),r!==void 0&&e.push("{",r.map(s=>Xr(s,o)).join(o),"}"),e.push(":")}function Qr(e){return e===L?"":e}function pl(e,n,t){let r=gf(e,n);if(r!==void 0)return r;let o=qr(e.map(s=>({value:s})),n,t);return o===void 0?void 0:{fields:o,paths:zr(o)}}function hf(e,n,t){let r=Object.values(e);if(!(r.length<2))return pl(r,n,t)}function qr(e,n,t){le(t,0,n);let r=e[0]?.value;if(!T(r))return;let o=Object.keys(r).map(s=>({key:s}));if(o.length!==0){for(let{value:s}of e)if(!T(s)||Object.keys(s).length!==o.length||o.some(l=>!Object.prototype.hasOwnProperty.call(s,l.key)))return;for(let s of o){let i=e.map(({value:a})=>({value:a[s.key]}));if(i.every(({value:a})=>ie(a)))continue;if(n.primitiveArrayColumns&&i.every(({value:a})=>Array.isArray(a)&&a.every(ie))){s.listDelimiter=";";continue}if(n.objectArrayColumns&&i.every(({value:a})=>Array.isArray(a))){let a=fl(i.map(({value:u})=>u));if(a!==void 0){s.fixedLength=a.fixedLength,s.fixedDelimiter=n.delimiter;continue}let d=qr(i.flatMap(({value:u})=>u.map(p=>({value:p}))),n,t+1);if(d!==void 0){s.children=d,s.childTable=!0;continue}}if(!n.nestedTabularHeaders)return;let l=qr(i,n,t+1);if(l===void 0)return;s.children=l}return o}}function gf(e,n){if(!n.objectArrayColumns)return;let t=fl(e);return t===void 0?void 0:{fields:[{key:"values",fixedLength:t.fixedLength,fixedDelimiter:n.delimiter}],paths:[{path:[],fixedLength:t.fixedLength}]}}function fl(e){let n=e[0]?.length;if(!(!Number.isInteger(n)||n===0)&&e.every(t=>Array.isArray(t)&&t.length===n&&t.every(ie)))return{fixedLength:n}}function zr(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}]:zr(t.children,r)})}function Yr(e,n){let t=e;for(let r of n)t=t[r];return t}function Xr(e,n){return e.listDelimiter!==void 0?`${M(e.key)}[${e.listDelimiter}]`:e.fixedLength!==void 0?`${M(e.key)}[${e.fixedLength}${Qr(n)}]`:e.children===void 0?M(e.key):`${M(e.key)}{${e.children.map(t=>Xr(t,n)).join(n)}}`}function Zr(e,n,t,r,o,s){return n.childFields!==void 0?(yf(o,e,n.childFields,r,s),String(e.length)):n.fixedLength!==void 0?e.map(i=>H(i,t)).join(t):n.listDelimiter===void 0?H(e,t):e.map(i=>kf(i,t,n.listDelimiter)).join(n.listDelimiter)}function yf(e,n,t,r,o){for(let s of n){sn(e,o);let i=[];e.push(zr(t).map(l=>Zr(Yr(s,l.path),l,r.delimiter,r,i,o+1)).join(r.delimiter)),e.push(`
28
+ `),e.push(...i)}}function kf(e,n,t){return typeof e!="string"?H(e,n):Nr(e,n)||e.includes(t)?Pt(e):e}var _l=[L,"|"," "];var wl=8,xl=/^[A-Za-z0-9_-]+$/,Qw=new TextEncoder,zw=new TextDecoder;function wf(e,n){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let t=e.slice(2,-1);if(!/^[0-9]+$/.test(t))throw v(n,"invalid trailer count");return Number.parseInt(t,10)}function Sl(e,n){if(!xl.test(e))throw v(n,"invalid tag")}function xf(e,n){let t=e.indexOf(":");if(t<=0)return null;let r=e.slice(0,t);if(!xl.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw v(n,"invalid tag");return null}return{tag:r,cellsText:e.slice(t+1)}}function Sf(e,n){if(!e.startsWith("["))return null;let t=e.slice(1),r=t.indexOf("]");if(r===-1)throw v(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(!_l.includes(i)&&i!=="")throw v(n,"invalid header delimiter");let l=i===""?L:i,a=t.slice(r+1),d=null;if(!s&&a.startsWith("<")){let f=a.indexOf(">");if(f===-1)throw v(n,"invalid tag");if(d=a.slice(1,f),Sl(d,n),i!=="")throw v(n,"invalid header delimiter");a=a.slice(f+1)}if(!a.startsWith("{")||!a.endsWith("}:"))throw v(n,"invalid header");let u=a.slice(1,-2),p;try{p=ee(u,l,n).map(f=>Z(f,n)[0])}catch(f){throw nn(f)}if(p.length===0||p.some(f=>f===""))throw v(n,"invalid header fields");return{delimiter:l,fields:p,fieldText:u,continuation:s,tag:d}}function vf(e,n,t){if(e===null||e.delimiter===void 0)throw v(t,"continuation header before header");if(e.delimiter!==n.delimiter||e.fieldText!==n.fieldText)throw v(t,"continuation header mismatch")}function ml(e,n,t,r){let o;try{o=ee(e,n,r)}catch(s){throw nn(s)}if(o.length!==t)throw v(r,"row arity mismatch");for(let s of o)try{J(s,r)}catch(i){throw nn(i)}return o}function Ef(e,n,t){let r={};return e.forEach((o,s)=>{try{ne(r,o,J(n[s],t))}catch(i){throw nn(i)}}),r}function Pf(e,n,t){if(e.startsWith("- "))throw v(n,"reserved line prefix");let r=wf(e,n);if(r!==null){if(t===null||t.delimiter===void 0)throw v(n,"trailer without header");if(t.rowCount!==r)throw v(n,"trailer count mismatch");return{kind:"trailer"}}let o=Sf(e,n);if(o!==null)return o.continuation?(vf(t,o,n),{kind:"continuation"}):o.tag!==null?{kind:"tag-header",header:o}:{kind:"header",header:o};let s=xf(e,n);if(s!==null){let i=t?.taggedLanes?.get(s.tag);if(i===void 0)throw v(n,"unknown tag");return{kind:"tagged-row",tag:s.tag,cells:ml(s.cellsText,i.delimiter,i.fields.length,n)}}if(t===null||t.delimiter===void 0)throw v(n,"row before header");return{kind:"row",cells:ml(e,t.delimiter,t.fields.length,n)}}function Df(e,n={}){let t=[],r=new Map,o=[],s=[],i=null,l=!1,a=!1;function d(m,g){let _=s.at(-1);if(_!==void 0&&_.lane===m.lane&&_.delimiter===m.delimiter&&_.fieldText===m.fieldText){_.rows.push(g);return}s.push({lane:m.lane,delimiter:m.delimiter,fields:m.fields,fieldText:m.fieldText,rows:[g]})}function u(){i!==null&&o.push({delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,lane:i.lane,rows:i.rows})}function p(m,g,_){let k=r.get(m);if(k===void 0){if(r.size>=wl)throw v(_,"too many tagged lanes");k={segments:[],current:null},r.set(m,k),t.push(m)}else k.current!==null&&k.segments.push(k.current);k.current={lane:m,delimiter:g.delimiter,fields:g.fields,fieldText:g.fieldText,rows:[]},k.delimiter=g.delimiter,k.fields=g.fields,k.fieldText=g.fieldText}if(Et(e).forEach((m,g)=>{let _=g+1;if(m==="")return;let k=i===null?{taggedLanes:r}:{delimiter:i.delimiter,fields:i.fields,fieldText:i.fieldText,rowCount:i.rows.length,taggedLanes:r},w=Pf(m,_,k);if(w.kind==="trailer"){u(),i=null;return}if(w.kind!=="continuation"){if(w.kind==="tag-header"){a=!0,p(w.header.tag,w.header,_);return}if(w.kind==="header"){u(),l||(t.push(null),l=!0),i={lane:null,delimiter:w.header.delimiter,fields:w.header.fields,fieldText:w.header.fieldText,rows:[]};return}if(w.kind==="tagged-row"){a=!0;let O=r.get(w.tag).current;O.rows.push(w.cells),d(O,w.cells);return}if(i===null)throw v(_,"row before header");i.rows.push(w.cells),d(i,w.cells)}}),!a)return u(),n.preserveInterleaving===!0,o;let f=[];u();for(let m of t){if(m===null){f.push(...o);continue}let g=r.get(m);f.push(...g.segments),g.current!==null&&f.push(g.current)}return n.preserveInterleaving===!0?s:f}function ve(e){return Df(e).flatMap(n=>n.rows.map(t=>Ef(n.fields,t,0)))}function jf(e){if(!_l.includes(e))throw v(0,"invalid header delimiter")}function hl(e,n,t=!1){return`[${`${t?"~":""}${e===L?"":e}`}]{${n}}:
29
+ `}function gl(e,n){return`[]<${e}>{${n}}:
30
+ `}function eo(e,n){return n.map(M).join(e)}function Of(e){if(!Array.isArray(e)||e.length===0)throw v(0,"TOONL header requires fields");return e.map(n=>{let t;try{[t]=Z(String(n),0)}catch(r){throw nn(r)}if(t==="")throw v(0,"TOONL header requires fields");return t})}function yl(e,n){return e!==null&&e.length===n.length&&e.every((t,r)=>t===n[r])}function kl(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw v(0,"TOONL continuation cadence must be positive")}function Af(e,n,t){return e.continuationEveryRows!==void 0&&n>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&t>=e.continuationEveryBytes}function Rl(e){if(e===null||typeof e!="object"||Array.isArray(e))throw v(0,"TOONL output requires object rows");let n=Object.keys(e);if(n.length===0)throw v(0,"TOONL output requires object rows");if(n.some(t=>!ie(e[t])))throw v(0,"TOONL rows must be flat objects");return n}function Lf(e){return JSON.stringify([...e].sort())}function bl(e,n){let t=Lf(e),r=n.get(t);return r!==void 0?r:(n.set(t,e),e)}function be({delimiter:e=L,trailer:n=!0,continuationEveryRows:t,continuationEveryBytes:r}={}){jf(e),kl(t),kl(r);let o=null,s="",i=new Map,l=0,a=0,d=0,u=new Map,p=!1,f={continuationEveryRows:t,continuationEveryBytes:r},m=()=>o===null||!n?"":`[=${l}]
31
+ `,g=()=>Af(f,a,d)?(a=0,d=0,hl(e,s,!0)):"",_=k=>{Sl(k,0);let w=u.get(k);if(w===void 0){if(u.size>=wl)throw v(0,"too many tagged lanes");w={fields:null,fieldsByShape:new Map},u.set(k,w)}return w};return{push(k){if(p)throw v(0,"TOONL encoder is closed");let w=bl(Rl(k),i),O="";(o===null||o.length!==w.length||o.some((ge,qe)=>ge!==w[qe]))&&(O+=m(),o=w,s=eo(e,o),l=0,a=0,d=0,O+=hl(e,s));let X=o.map(ge=>H(k[ge],e));O+=g();let he=`${X.join(e)}
32
+ `;return O+=he,l+=1,a+=1,d+=he.length,O},declareLane(k,w){if(p)throw v(0,"TOONL encoder is closed");let O=Of(w),X=eo(L,O),he=_(k);return yl(he.fields,O)?"":(he.fields=O,gl(k,X))},pushTagged(k,w){if(p)throw v(0,"TOONL encoder is closed");let O=_(k),X=bl(Rl(w),O.fieldsByShape),he=eo(L,X),ge=X.map(hr=>H(w[hr],L)),qe="";return yl(O.fields,X)||(O.fields=X,qe+=gl(k,he)),`${qe}${k}:${ge.join(L)}
33
+ `},end(){return p?"":(p=!0,m())}}}function no(e){let n={app:e,version:Tf(ln("__RED_BUILD_VERSION__",()=>"3.3.22")??"0.0.0-dev"),gitSha:ln("__RED_BUILD_GIT_SHA__",()=>"61db0dc2964c9e3d76234252dee063c9b129f53d")??"unknown",buildTime:ln("__RED_BUILD_TIME__",()=>"2026-08-03T19:10:50Z")??"unknown",bundleAsset:ln("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},t=ln("__REDDB_SDK_VERSION__",()=>""),r=ln("__REDDB_BINARY_TAG__",()=>"");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function Tf(e){return e.startsWith("v")?e.slice(1):e}function vl(e){return`${e.app} ${e.version} ${e.gitSha}`}function ln(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var El={"=":"data",":=":{to:"data",typed:!0},":":"meta"},$f=/^[a-z][a-z0-9+.-]*:\/\//i;function If(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 Nf(e=El){return Object.entries(e).map(([n,t])=>If(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function Mf(e){return/^-\d+(\.\d+)?$/.test(e)}function In(e){return!(!e||e.startsWith("-")&&!Mf(e))}function Tt(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 Pl(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=>Pl(t.trim())):e}function $e(e,n){switch(n){case"boolean":return Cf(e);case"number":return Wf(e);case"array":return e.split(",").map(t=>Tt(t.trim()));case"string":default:return e}}function Cf(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function Wf(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let n=Number(e);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${e}" to number`);return n}function Ee(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Bf(e,n={}){return e.map(t=>{let r=n[t.type];return r?r(t.value):t.value}).join("")}function P(e,n){return{type:e,value:n}}function Ff(e){let n=[],t=Uf(e);if(n.push(P("section-header","Usage:"),P("text"," "),P("usage-text",t),P("newline",`
34
+ `),P("newline",`
35
+ `)),e.positional&&e.positional.length>0){n.push(P("section-header","Arguments:"),P("newline",`
36
+ `));for(let r of e.positional)if(r.description){let o=r.variadic?`${r.name}...`:r.name;n.push(P("indent"," "),P("positional-name",`<${o}>`)),r.required||n.push(P("positional-optional"," (optional)")),n.push(P("newline",`
37
+ `),P("indent"," "),P("option-description",r.description),P("newline",`
38
+ `))}n.push(P("newline",`
39
+ `))}if(e.options&&Object.keys(e.options).length>0){n.push(P("section-header","Options:"),P("newline",`
40
+ `));let r=Gf(e.options);n.push(...r)}return n}function Hf(e,n){let t=Ff(e);return Bf(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 Gf(e,n=!1){let t=[],r=[],o=n?"global-option-flag":"option-flag",s=n?"global-option-type":"option-type",i=n?"global-option-default":"option-default",l=n?"global-option-description":"option-description";for(let[d,u]of Object.entries(e)){if(u.hidden)continue;let p=[],f=_=>{p.includes(_)||p.push(_)};u.short&&f(`-${u.short}`),f(`--${d}`);for(let _ of u.aliases??[])_.length===1?f(`-${_}`):f(`--${_}`);let m=p.join(", "),g=u.type&&u.type!=="boolean"?`<${u.type}>`:void 0;r.push({flags:m,type:g,desc:u.description??"",default:u.default!==void 0?String(u.default):void 0})}let a=Math.max(...r.map(d=>d.flags.length+(d.type?d.type.length+1:0)),20);for(let d of r){let u=d.flags.length+(d.type?d.type.length+1:0),p=" ".repeat(a-u+2);t.push(P("indent"," ")),t.push(P(o,d.flags)),d.type&&(t.push(P("text"," ")),t.push(P(s,d.type))),t.push(P("text",p)),t.push(P(l,d.desc)),d.default!==void 0&&(t.push(P("text"," ")),t.push(P(i,`(default: ${d.default})`))),t.push(P("newline",`
41
+ `))}return t}function Dl(e){let n=Yf(e.options??{},e.autoShort??!1),t=Nf(e.separators??El);return{schema:e,parse(r){return Kf(r,e,n,t)},help(){return Hf(e,e.formatter)}}}function Kf(e,n,t,r){let o={positional:{},options:{},errors:[],rest:[]},s=new Set(r.map(u=>u.to));for(let u of s)o[u]={};let i=0,l=n.positional??[],a=0,d=!1;for(;a<e.length;){let u=e[a];if(n.stopEarly&&i>0){o.rest=e.slice(a);break}if(u==="--"&&!d){d=!0,a++;continue}if(d){if(i<l.length){let f=l[i];if(f.variadic){let m=[];for(;a<e.length;){let g=e[a];m.push(f.type?$e(g,f.type):g),a++}o.positional[f.name]=m,i++}else{let m=f.type?$e(u,f.type):u;o.positional[f.name]=m,i++,a++}}else n.allowUnknown!==!1&&(o.rest=o.rest??[],o.rest.push(u)),a++;continue}if(u.startsWith("--")){a=Qf(u,a,e,o,t,n);continue}if(u.startsWith("-")&&u.length>1&&!tm(u)){a=zf(u,a,e,o,t,n);continue}let p=Vf(u,r);if(p){let{key:f,value:m,config:g}=p,_=o,k=_[g.to]??(_[g.to]={});k[f]=g.typed?Pl(m):Ee(m),a++;continue}if(i<l.length){let f=l[i];if(f.variadic){let g=[];for(;a<e.length&&!e[a].startsWith("-");){let _=e[a];g.push(f.type?$e(_,f.type):_),a++}o.positional[f.name]=g,i++;continue}let m=f.type?$e(u,f.type):u;o.positional[f.name]=m,i++}else n.allowUnknown!==!1?o.rest.push(u):o.errors.push(`Unexpected positional argument: ${u}`);a++}return Zf(o,n,t),em(o,n,l),nm(o,n,t),o}function Vf(e,n){if($f.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(qf(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(Jf(o,s,t))return{key:o,value:s,config:t}}}return null}function qf(e){return e?/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e):!1}function Jf(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 Qf(e,n,t,r,o,s){let i=e.slice(2);if(i.startsWith("no-")){let a=i.slice(3),d=o.get(a);if(d?.negatable!==!1&&d?.type==="boolean")return r.options[d.name]=!1,n+1}if(i.includes("=")){let a=i.indexOf("="),d=i.slice(0,a),u=i.slice(a+1);return $t(d,u,n+1,r,o,s)}let l=o.get(i);if(l){if(l.type!=="boolean"){let a=t[n+1];return In(a)?$t(l.name,a,n+2,r,o,s):(r.errors.push(`Option --${i} requires a value`),n+1)}return r.options[l.name]=!0,n+1}return s.strict?r.errors.push(`Unknown option: --${i}`):s.allowUnknown!==!1&&(r.options[i]=!0),n+1}function zf(e,n,t,r,o,s){let i=e.slice(1);if(i.includes("=")){let l=i.indexOf("="),a=i.slice(0,l),d=i.slice(l+1),u=to(a,o);return u?$t(u.name,d,n+1,r,o,s):(s.strict?r.errors.push(`Unknown option: -${a}`):s.allowUnknown!==!1&&(r.options[a]=Tt(Ee(d))),n+1)}if(i.length===1){let l=to(i,o);if(l){if(l.type!=="boolean"){let a=t[n+1];return In(a)?$t(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(In(a))return r.options[i]=Tt(Ee(a)),n+2;r.options[i]=!0}return n+1}for(let l of i){let a=to(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 $t(e,n,t,r,o,s){let i=o.get(e);if(i){if(i.choices){let a=i.type?$e(Ee(n),i.type):Ee(n);if(!i.choices.includes(a))return r.errors.push(`Invalid value for '${e}': '${n}'. Allowed: ${i.choices.join(", ")}`),t}let l=i.type?$e(Ee(n),i.type):Ee(n);if(i.type==="array"){let a=r.options[e];Array.isArray(a)?a.push(...l):r.options[e]=l}else r.options[e]=l}else s.strict?r.errors.push(`Unknown option: --${e}`):s.allowUnknown!==!1&&(r.options[e]=Tt(Ee(n)));return t}function Yf(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=Xf(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 Xf(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 to(e,n){for(let t of n.values())if(t.short===e||t.aliases.includes(e))return t}function Zf(e,n,t){for(let r of t.values())if(e.options[r.name]===void 0)if(r.env&&process.env[r.env]!==void 0){let o=process.env[r.env];e.options[r.name]=r.type?$e(o,r.type):o}else r.default!==void 0&&(e.options[r.name]=r.default);for(let r of n.positional??[])e.positional[r.name]===void 0&&r.default!==void 0&&(e.positional[r.name]=r.default)}function em(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 nm(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 tm(e){return/^-\d+(\.\d+)?$/.test(e)}var ro=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 rm(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 om(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&&In(e[o+1])&&(a=e[o+1],o+=1),a===void 0)continue;let d=r.get(l)??[];d.push(a),r.set(l,d)}return r}function Ie(e,n,t={}){let o=Dl({options:rm(n),separators:{},allowUnknown:!0}).parse([...e]),s={},i=om(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 ro(d.length===1?`-${d}`:`--${d}`,Object.keys(n).map(u=>u.length===1?`-${u}`:`--${u}`))}for(let[a,d]of Object.entries(n)){let u=o.options[a];u!==void 0&&(d.kind==="boolean"?s[a]=u:d.type==="array"?s[a]=(i.get(a)??[]).map(p=>d.coerce(p)):s[a]=d.coerce(String(u)))}return{values:s,positionals:o.rest}}var oo=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 jl(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 oo(t,Object.keys(n.commands))}let o=n.keepArgvOnDefault??!0;return{command:n.default,args:o?[...e]:r}}import{appendFileSync as hm,mkdirSync as gm,readFileSync as Wl,statSync as ym}from"node:fs";import{dirname as Fl,join as km}from"node:path";var Ol="RED_WORKER_SCOPE",Al="RED_WORKER_MEMORY_CEILING",Ll="RED_WORKER_SCOPE_DEGRADATION",io={scope:null,memory_ceiling:null,scope_degradation:null};function lo(e){return{scope:so(e[Ol]),memory_ceiling:so(e[Al]),scope_degradation:so(e[Ll])}}function Nn(e){let n={};return e.scope!=null&&e.scope!==""&&(n[Ol]=e.scope),e.memory_ceiling!=null&&e.memory_ceiling!==""&&(n[Al]=e.memory_ceiling),e.scope_degradation!=null&&e.scope_degradation!==""&&(n[Ll]=e.scope_degradation),n}function so(e){let n=(e??"").trim();return n===""?null:n}import{mkdirSync as lm,readdirSync as am,readFileSync as Nl,rmSync as dm,writeFileSync as cm}from"node:fs";import{basename as um,join as an}from"node:path";import{isAbsolute as jx,join as It,resolve as Ox}from"node:path";function sm(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}var Tl="deaths",$l="deaths.toonl";function Nt(e){return It(sm(e),Tl)}function Mn(e){return It(Nt(e),$l)}var Cn="live",Il="attributions.toonl";function Mt(e){return It(Nt(e),Cn)}function ao(e){return It(Nt(e),Il)}var uo=an("sys","kernel","random","boot_id"),Ml=1;function po(e,n={}){let t=n.procRoot??"/proc",r=e.pid??process.pid;return{version:Ml,ts:(n.now??(()=>new Date().toISOString()))(),kind:e.kind,id:e.id,pid:r,ppid:e.ppid??process.ppid,boot_id:Cl(an(t,uo)),cgroup:pm(t,r),last_phase:e.last_phase}}function Cl(e){try{let n=Nl(e,"utf8").trim();return n===""?null:n}catch{return null}}function pm(e,n){let t=Cl(an(e,String(n),"cgroup"));if(t===null)return null;let r=t.split(`
42
+ `),o=r.find(i=>i.startsWith("0::"));if(o)return o.slice(3)||null;let s=r[0]?.split(":").slice(2).join(":");return s===void 0||s===""?null:s}function fo(e){let n=e.id.replace(/[^A-Za-z0-9._-]/g,"_");return`${e.kind}-${n}-${e.pid}.toon`}function mo(e,n){let t=an(e,fo(n));try{return lm(e,{recursive:!0,mode:448}),cm(t,be({trailer:!1}).push(mm(n)),{encoding:"utf8",mode:384}),t}catch{return null}}function Ne(e,n){try{dm(an(e,fo(n)),{force:!0})}catch{}}function ho(e,n){let t;try{t=am(e)}catch{return[]}let r=[];for(let o of t.sort()){if(!o.endsWith(".toon"))continue;let s=an(e,o);try{let l=ve(Nl(s,"utf8"))[0];if(l===void 0)throw new Error("anchor holds no record");r.push(fm(l))}catch(i){n?.(um(s),i instanceof Error?i.message:String(i))}}return r}function fm(e){let n=e.kind;if(n!=="launcher"&&n!=="worker"&&n!=="daemon")throw new Error(`presence anchor has unknown kind ${String(n)}`);return{version:co(e.version),ts:String(e.ts),kind:n,id:String(e.id),pid:co(e.pid),ppid:co(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 co(e){return typeof e=="number"?e:Number(e)}function mm(e){return{...e}}var Rm=1,bm=new Set(["exit","signal","uncaught-exception","unhandled-rejection"]);function _m(e){return typeof e=="string"&&bm.has(e)}var wm="startup";function xm(e,n){return{...e.scope??io,version:Rm,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 Sm(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 yo={mkdir(e){gm(e,{recursive:!0,mode:448})},endsClean(e){let n;try{n=ym(e).size}catch{return!0}if(n===0)return!0;try{return Wl(e,"utf8").endsWith(`
43
+ `)}catch{return!0}},append(e,n){hm(e,n,{encoding:"utf8",mode:384})},read(e){return Wl(e,"utf8")}};function vm(e){let n={};for(let[t,r]of Object.entries(e))n[t]=r;return n}function Em(e,n,t=yo){let r=be({trailer:!1}).push(vm(n));return t.mkdir(Fl(e)),t.endsClean(e)||t.append(e,`
44
+ `),t.append(e,r),n}function Hl(e){let n=e.endsWith(`
45
45
  `)?e:e.slice(0,e.lastIndexOf(`
46
- `)+1);return n===""?[]:we(n).map(om)}function om(e){let n=e.exit_path;if(!Xf(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:Q(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:Q(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:Q(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:Q(e.uptime_s),rss_kb:Q(e.rss_kb),max_rss_kb:Q(e.max_rss_kb),user_cpu_us:Q(e.user_cpu_us),system_cpu_us:Q(e.system_cpu_us),minor_page_faults:Q(e.minor_page_faults),major_page_faults:Q(e.major_page_faults),voluntary_ctx_switches:Q(e.voluntary_ctx_switches),involuntary_ctx_switches:Q(e.involuntary_ctx_switches)}}function Q(e){return typeof e=="number"?e:Number(e)}function Sl(e,n=ao){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return xl(t)}var sm=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],lo=null;function vl(e){let n=e.host??process,t=e.io??ao,r=e.clock??(()=>new Date().toISOString()),o=n.pid,s=e.scope??Zr(process.env),i=e.phase??Zf,l=null,a=e.presenceDir===void 0?Qf(wl(e.lanePath),$n):e.presenceDir,d=null,c=()=>{a!==null&&(d=ro({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),so(a,d))},u=k=>{if(!l){try{l=rm(e.lanePath,em({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...k},nm(n)),t)}catch{}a!==null&&d!==null&&Te(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:_l(k)})},unhandledRejection(k){u({exit_path:"unhandled-rejection",detail:_l(k)})}},h=[...(e.signals??sm).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&&Te(a,d),lo===b&&(lo=null)},handlers:f};return e.setActive!==!1&&(lo=b),c(),b}function _l(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as im,readdirSync as lm,readFileSync as jt,statSync as am,writeFileSync as dm}from"node:fs";import{join as jl}from"node:path";var cm=1,um=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],pm=512*1024;function fm(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??um,r=[],o=jl(n,to),s=null;try{let a=jt(o,"utf8").trim();s=a===""?null:a,r.push({source:o,result:s?"read":"empty",detail:s})}catch(a){r.push({source:o,result:co(a),detail:null})}let i=new Set;try{for(let a of lm(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:co(a),detail:null})}let l=[];for(let a of t)try{let c=mm(a,e.tailBytes??pm).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:co(d),detail:null})}return{boot_id:s,live_pids:i,journal:l,probes:r}}function co(e){return e.code==="ENOENT"?"absent":"unreadable"}function mm(e,n){let t=am(e).size,r=jt(e,"utf8");return t<=n?r:r.slice(r.length-n)}var hm=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,gm=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,ym=/Killed (\/\S*) due to memory pressure/,km=/\bopid=(\d+)\b/,El=/\bsig=(\d+)\b/,Rm=/\buid=(\d+)\b/,bm=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,_m={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function wm(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:cm,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=>Pl(u,e.pid,hm)||Pl(u,e.pid,gm));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=ym.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(km.exec(u)?.[1])===e.pid&&El.test(u));if(d!==void 0){let u=Number(El.exec(d)?.[1]),f=Rm.exec(d)?.[1];return i("user-signal",o?"medium":"high",_m[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=>bm.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 Pl(e,n,t){return Number(t.exec(e)?.[1])===n}var xm=" | ";function Dl(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(xm)}function Sm(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:Dl(e.evidence),checked:Dl(e.checked)}}function vm(e){let n=ge({trailer:!1});return e.map(t=>n.push(Sm(t))).join("")}function Ol(e){let n=Dt(e.stateRoot),t=eo(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??fm({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=io(n,u=>s.push(u)),l=Sl(Tn(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),Te(n,u);continue}a.push(wm(u,o,l,r())),Te(n,u)}return a.length>0&&Em(t,a),{attributions:a,alive:d,self_recorded:c,skipped:s,laneText:()=>{try{return jt(t,"utf8")}catch{return""}}}}function Al(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 Em(e,n){try{im(jl(e,".."),{recursive:!0,mode:448});let t=Pm(e),r=t===""||t.endsWith(`
46
+ `)+1);return n===""?[]:ve(n).map(Pm)}function Pm(e){let n=e.exit_path;if(!_m(n))throw new Error(`death record has unknown exit_path ${JSON.stringify(n)}`);let t=e.kind;if(t!=="launcher"&&t!=="worker"&&t!=="daemon")throw new Error(`death record has unknown kind ${JSON.stringify(t)}`);return{version:z(e.version),ts:String(e.ts),kind:t,id:String(e.id),pid:z(e.pid),exit_path:n,signal:e.signal==null?null:String(e.signal),exit_code:e.exit_code==null?null:z(e.exit_code),last_phase:String(e.last_phase),detail:e.detail==null?null:String(e.detail),scope:e.scope==null?null:String(e.scope),memory_ceiling:e.memory_ceiling==null?null:String(e.memory_ceiling),scope_degradation:e.scope_degradation==null?null:String(e.scope_degradation),uptime_s:z(e.uptime_s),rss_kb:z(e.rss_kb),max_rss_kb:z(e.max_rss_kb),user_cpu_us:z(e.user_cpu_us),system_cpu_us:z(e.system_cpu_us),minor_page_faults:z(e.minor_page_faults),major_page_faults:z(e.major_page_faults),voluntary_ctx_switches:z(e.voluntary_ctx_switches),involuntary_ctx_switches:z(e.involuntary_ctx_switches)}}function z(e){return typeof e=="number"?e:Number(e)}function Ul(e,n=yo){let t;try{t=n.read(e)}catch(r){if(r.code==="ENOENT")return[];throw r}return Hl(t)}var Dm=["SIGTERM","SIGINT","SIGHUP","SIGQUIT"],go=null;function Gl(e){let n=e.host??process,t=e.io??yo,r=e.clock??(()=>new Date().toISOString()),o=n.pid,s=e.scope??lo(process.env),i=e.phase??wm,l=null,a=e.presenceDir===void 0?km(Fl(e.lanePath),Cn):e.presenceDir,d=null,u=()=>{a!==null&&(d=po({kind:e.kind,id:e.id,last_phase:i,pid:o},{procRoot:e.procRoot}),mo(a,d))},p=k=>{if(!l){try{l=Em(e.lanePath,xm({ts:r(),kind:e.kind,id:e.id,pid:o,last_phase:i,scope:s,...k},Sm(n)),t)}catch{}a!==null&&d!==null&&Ne(a,d)}},f={signal(k){p({exit_path:"signal",signal:k})},exit(k){p({exit_path:"exit",exit_code:k})},uncaughtException(k){p({exit_path:"uncaught-exception",detail:Bl(k)})},unhandledRejection(k){p({exit_path:"unhandled-rejection",detail:Bl(k)})}},g=[...(e.signals??Dm).map(k=>{let w=()=>{if(f.signal(k),!(n.listenerCount?.(k)!==1||!n.kill)){n.off(k,w);try{n.kill(o,k)}catch{}}};return[k,w]}),["uncaughtException",(...k)=>f.uncaughtException(k[0])],["unhandledRejection",(...k)=>f.unhandledRejection(k[0])],["exit",(...k)=>f.exit(typeof k[0]=="number"?k[0]:null)]];for(let[k,w]of g)n.on(k,w);let _={lanePath:e.lanePath,phase(k){i=k,l||u()},currentPhase:()=>i,written:()=>l,uninstall(){for(let[k,w]of g)n.off(k,w);a!==null&&d!==null&&Ne(a,d),go===_&&(go=null)},handlers:f};return e.setActive!==!1&&(go=_),u(),_}function Bl(e){if(e instanceof Error)return`${e.name}: ${e.message}`;try{return String(e)}catch{return"(undescribable)"}}import{mkdirSync as jm,readdirSync as Om,readFileSync as Ct,statSync as Am,writeFileSync as Lm}from"node:fs";import{join as Jl}from"node:path";var Tm=1,$m=["/var/log/kern.log","/var/log/syslog","/var/log/messages"],Im=512*1024;function Nm(e={}){let n=e.procRoot??"/proc",t=e.journalPaths??$m,r=[],o=Jl(n,uo),s=null;try{let a=Ct(o,"utf8").trim();s=a===""?null:a,r.push({source:o,result:s?"read":"empty",detail:s})}catch(a){r.push({source:o,result:ko(a),detail:null})}let i=new Set;try{for(let a of Om(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:ko(a),detail:null})}let l=[];for(let a of t)try{let u=Mm(a,e.tailBytes??Im).split(`
47
+ `).filter(p=>p.trim()!=="");l.push(...u),r.push({source:a,result:u.length===0?"empty":"read",detail:`${u.length} lines`})}catch(d){r.push({source:a,result:ko(d),detail:null})}return{boot_id:s,live_pids:i,journal:l,probes:r}}function ko(e){return e.code==="ENOENT"?"absent":"unreadable"}function Mm(e,n){let t=Am(e).size,r=Ct(e,"utf8");return t<=n?r:r.slice(r.length-n)}var Cm=/(?:Out of memory|Memory cgroup out of memory)[^\n]*?Killed process (\d+)/,Wm=/oom[-_]kill:[^\n]*?\bpid=(\d+)/,Bm=/Killed (\/\S*) due to memory pressure/,Fm=/\bopid=(\d+)\b/,Kl=/\bsig=(\d+)\b/,Hm=/\buid=(\d+)\b/,Um=/systemd-shutdown|Powering off|System is powering down|Reboot: |Unmounting file systems/,Gm={2:"SIGINT",9:"SIGKILL",15:"SIGTERM"};function Km(e,n,t,r){let o=e.boot_id!==null&&n.boot_id!==null&&e.boot_id!==n.boot_id,s=[...n.probes.map(p=>`${p.source}: ${p.result}${p.detail?` (${p.detail})`:""}`),`boot id: anchored under ${e.boot_id??"unknown"}, host now ${n.boot_id??"unknown"} (${o?"changed":"same"})`,`parent account: ppid ${e.ppid}`,`cgroup: ${e.cgroup??"unknown"}`],i=(p,f,m,g)=>({version:Tm,ts:r,kind:e.kind,id:e.id,pid:e.pid,last_seen:e.ts,last_phase:e.last_phase,sender_class:p,confidence:f,signal:m,host_boot_changed:o,evidence:g,checked:s}),l=o?["the host rebooted since the anchor, so this line may name a reused pid"]:[],a=n.journal.find(p=>Vl(p,e.pid,Cm)||Vl(p,e.pid,Wm));if(a!==void 0)return i("oomd",o?"medium":"high","SIGKILL",[a,...l]);if(e.cgroup!==null)for(let p of n.journal){let f=Bm.exec(p)?.[1];if(f!==void 0){if(f===e.cgroup)return i("oomd",o?"medium":"high","SIGKILL",[p,...l]);if(e.cgroup.startsWith(`${f}/`))return i("oomd","medium","SIGKILL",[p,`the killed scope ${f} is an ancestor of this process's ${e.cgroup}`,...l])}}let d=n.journal.find(p=>Number(Fm.exec(p)?.[1])===e.pid&&Kl.test(p));if(d!==void 0){let p=Number(Kl.exec(d)?.[1]),f=Hm.exec(d)?.[1];return i("user-signal",o?"medium":"high",Gm[p]??null,[d,...f===void 0?[]:[`sent by uid ${f}`],...l])}let u=t.find(p=>p.pid===e.ppid);if(u!==void 0&&!n.live_pids.has(e.ppid))return i("parent-death","medium",null,[`parent pid ${e.ppid} (${u.kind} ${u.id}) recorded its own death at ${u.ts} via ${u.exit_path}${u.signal?` ${u.signal}`:""}`]);if(o){let p=n.journal.find(f=>Um.test(f));return p!==void 0?i("teardown","high",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,p]):i("teardown","medium",null,[`host boot id changed from ${e.boot_id} to ${n.boot_id}`,"no shutdown record on any journal read: the host stopped without announcing it (a freeze or a power loss, not an orderly teardown)"])}return i("unknown","none",null,[])}function Vl(e,n,t){return Number(t.exec(e)?.[1])===n}var Vm=" | ";function ql(e){return e.map(n=>n.replace(/[|\n\r]+/g," ").trim()).join(Vm)}function qm(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:ql(e.evidence),checked:ql(e.checked)}}function Jm(e){let n=be({trailer:!1});return e.map(t=>n.push(qm(t))).join("")}function Ql(e){let n=Mt(e.stateRoot),t=ao(e.stateRoot),r=e.now??(()=>new Date().toISOString()),o=e.evidence??Nm({procRoot:e.procRoot,journalPaths:e.journalPaths}),s=[],i=ho(n,p=>s.push(p)),l=Ul(Mn(e.stateRoot)),a=[],d=[],u=[];for(let p of i){if(o.live_pids.has(p.pid)){d.push(p);continue}if(l.find(m=>m.pid===p.pid&&m.id===p.id)!==void 0){u.push(p),Ne(n,p);continue}a.push(Km(p,o,l,r())),Ne(n,p)}return a.length>0&&Qm(t,a),{attributions:a,alive:d,self_recorded:u,skipped:s,laneText:()=>{try{return Ct(t,"utf8")}catch{return""}}}}function zl(e){let n=e.skipped.length===0?"":` | unreadable anchors=${e.skipped.join(",")}`;if(e.attributions.length===0)return`death reaper: no un-recorded deaths (live=${e.alive.length} self-recorded=${e.self_recorded.length})${n}`;let t=e.attributions.map(r=>` | ${r.kind} ${r.id} pid=${r.pid} ${r.sender_class}/${r.confidence} phase=${r.last_phase}`+(r.evidence[0]?` evidence="${r.evidence[0]}"`:"")).join("");return`death reaper: attributed ${e.attributions.length}${t}${n}`}function Qm(e,n){try{jm(Jl(e,".."),{recursive:!0,mode:448});let t=zm(e),r=t===""||t.endsWith(`
48
48
  `)?"":`
49
- `;dm(e,`${t}${r}${vm(n)}`,{encoding:"utf8",mode:384})}catch{}}function Pm(e){try{return jt(e,"utf8")}catch{return""}}import{join as Dm}from"node:path";var jm=[".red","redskilled"],le=448;function $e(e){return Dm(e,...jm)}import{execFileSync as Um}from"node:child_process";import{readFileSync as Gm}from"node:fs";import{dirname as Cl,join as Km}from"node:path";import{existsSync as Om,readFileSync as Mx}from"node:fs";import{dirname as Am,join as Lm}from"node:path";function Ll(e,n){let t=e;for(let r=0;r<16;r++){let o=Lm(t,n);if(Om(o))return o;let s=Am(t);if(s===t)break;t=s}return null}function Tm(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function rn(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 Tm(d)}}import{createHash as $m}from"node:crypto";var Im="project.name";function $l(e){let n=rn(e,Im)?.trim();return n===void 0||n===""?void 0:n}var Nm=8,Il="project";function Nl(e){let n=Fm(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:Mm(e.remoteUrl)??{name:Cm(e.checkoutPath,n),source:"basename"},o=Bm(n??uo(e.checkoutPath));return{name:r.name,slug:`${Wm(r.name)}-${o}`,hash:o,source:r.source}}function Ml(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 Mm(e){let n=Ml(e);return n===void 0?void 0:{name:n,source:"remote"}}function Cm(e,n){let t=n===void 0?"":Tl(Hm(n));if(t!=="")return t;let r=Tl(uo(e));return r===""?Il:r}function Wm(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?Il:t}function Bm(e){return $m("sha256").update(e).digest("hex").slice(0,Nm)}function Fm(e){let n=uo(e??"");return n===""?void 0:n}function uo(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function Tl(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function Hm(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var Vm=2e3;function Wl(e){return qm(e).name}function qm(e){let n=fo(e),t=po(e,["rev-parse","--absolute-git-dir"])??po(e,["rev-parse","--git-common-dir"]),r=po(e,["remote","get-url","origin"]);return Nl({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function fo(e){let n=Ll(e,Km(".red","config.yaml"));if(n==null)return{};let t;try{t=Gm(n,"utf8")}catch{return{}}let r=$l(t),o=Cl(Cl(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function po(e,n){try{let t=Um("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Vm}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as Jc}from"node:crypto";import{spawn as Rb}from"node:child_process";import{mkdir as bb}from"node:fs/promises";import{dirname as _b}from"node:path";import{createHash as zm}from"node:crypto";import{constants as ko}from"node:fs";import{mkdir as Jl,open as Ym,readFile as Xm,rm as Ql,stat as Zm}from"node:fs/promises";import{createConnection as eh}from"node:net";import{tmpdir as nh}from"node:os";import{dirname as zl,join as In}from"node:path";var Jm="toon";function Hl(e){return e.trimStart().startsWith("{")?"json":"toon"}function ho(e){let n=0;for(;e[n]===`
51
- `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=Hl(t);if(r==="json"){let s=t.indexOf(`
49
+ `;Lm(e,`${t}${r}${Jm(n)}`,{encoding:"utf8",mode:384})}catch{}}function zm(e){try{return Ct(e,"utf8")}catch{return""}}import{join as Ym}from"node:path";var Xm=[".red","redskilled"],ae=448;function Me(e){return Ym(e,...Xm)}import{execFileSync as ph}from"node:child_process";import{readFileSync as fh}from"node:fs";import{dirname as ra,join as mh}from"node:path";import{existsSync as Zm,readFileSync as lS}from"node:fs";import{dirname as eh,join as nh}from"node:path";function Yl(e,n){let t=e;for(let r=0;r<16;r++){let o=nh(t,n);if(Zm(o))return o;let s=eh(t);if(s===t)break;t=s}return null}function th(e){let n=e.indexOf(" #");return(n>=0?e.slice(0,n):e).trim()}function dn(e,n){let t=[];for(let r of e.split(`
50
+ `)){let o=r.replace(/\r$/,""),s=o.trim();if(!s||s.startsWith("#"))continue;let i=o.indexOf(":");if(i<0)continue;let l=o.length-o.trimStart().length,a=o.slice(0,i).trim();if(!a)continue;let d=o.slice(i+1).trim();for(;t.length&&t[t.length-1].indent>=l;)t.pop();if(t.push({indent:l,key:a}),d&&t.map(p=>p.key).join(".")===n)return th(d)}}import{createHash as rh}from"node:crypto";var oh="project.name";function Zl(e){let n=dn(e,oh)?.trim();return n===void 0||n===""?void 0:n}var sh=8,ea="project";function na(e){let n=ch(e.gitCommonDir),t=(e.declaredName??"").trim(),r=t!==""?{name:t,source:"declared"}:ih(e.remoteUrl)??{name:lh(e.checkoutPath,n),source:"basename"},o=dh(n??Ro(e.checkoutPath));return{name:r.name,slug:`${ah(r.name)}-${o}`,hash:o,source:r.source}}function ta(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 ih(e){let n=ta(e);return n===void 0?void 0:{name:n,source:"remote"}}function lh(e,n){let t=n===void 0?"":Xl(uh(n));if(t!=="")return t;let r=Xl(Ro(e));return r===""?ea:r}function ah(e){let t=e.split("/").map(r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")).filter(r=>r!=="").join("--");return t===""?ea:t}function dh(e){return rh("sha256").update(e).digest("hex").slice(0,sh)}function ch(e){let n=Ro(e??"");return n===""?void 0:n}function Ro(e){let n=e.trim().replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function Xl(e){let n=e.split("/").filter(t=>t!=="");return n[n.length-1]??""}function uh(e){return e.split("/").filter(t=>t!=="").slice(0,-1).join("/")}var hh=2e3;function oa(e){return gh(e).name}function gh(e){let n=_o(e),t=bo(e,["rev-parse","--absolute-git-dir"])??bo(e,["rev-parse","--git-common-dir"]),r=bo(e,["remote","get-url","origin"]);return na({checkoutPath:n.root??e,...t!==void 0?{gitCommonDir:t}:{},...r!==void 0?{remoteUrl:r}:{},...n.name!==void 0?{declaredName:n.name}:{}})}function _o(e){let n=Yl(e,mh(".red","config.yaml"));if(n==null)return{};let t;try{t=fh(n,"utf8")}catch{return{}}let r=Zl(t),o=ra(ra(n));return{...r===void 0?{}:{name:r},configText:t,root:o}}function bo(e,n){try{let t=ph("git",[...n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:hh}).trim();return t===""?void 0:t}catch{return}}import{randomUUID as hu}from"node:crypto";import{spawn as Ub}from"node:child_process";import{mkdir as Gb}from"node:fs/promises";import{dirname as Kb}from"node:path";import{createHash as Rh}from"node:crypto";import{constants as Eo}from"node:fs";import{mkdir as fa,open as bh,readFile as _h,rm as ma,stat as wh}from"node:fs/promises";import{createConnection as xh}from"node:net";import{tmpdir as Sh}from"node:os";import{dirname as ha,join as Wn}from"node:path";var yh="toon";function la(e){return e.trimStart().startsWith("{")?"json":"toon"}function xo(e){let n=0;for(;e[n]===`
51
+ `||e[n]==="\r";)n+=1;let t=e.slice(n);if(t==="")return null;let r=la(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 go(e){let n=Hl(e)==="json"?mo:Bl,t=n===mo?Bl:mo;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function mo(e){return JSON.parse(e)}function Bl(e){return J(e)}function yo(e,n){if(n==="toon"){let t=Qm(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 So(e){let n=la(e)==="json"?wo:sa,t=n===wo?sa:wo;try{return n(e)}catch(r){try{return t(e)}catch{throw r}}}function wo(e){return JSON.parse(e)}function sa(e){return Q(e)}function vo(e,n){if(n==="toon"){let t=kh(e);if(t!==null)return t.endsWith(`
55
55
  `)?`${t}
56
56
  `:`${t}
57
57
 
58
58
  `}return`${JSON.stringify(e)}
59
- `}function Qm(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 Ul(e,n){return!Fl(e)||!Fl(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function Fl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Gl=new Set;function Kl(e){return Gl.has(e)?"json":Jm}function Vl(e){Gl.add(e)}var th=108;async function Ot(e,n,t="resident server"){let r=e.wire,o=r??Kl(e.socketPath),s=await ql(e,n,t,o);return r||o==="json"||!Ul(n,s)?s:(Vl(e.socketPath),await ql(e,n,t,"json"))}async function ql(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=eh(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(yo(n,r))}),l.on("data",f=>{d+=f.toString("utf8");let m=ho(d);m&&(d=m.rest,u(()=>{try{s(go(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 Yl(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=ho(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(yo(l,s.dialect))}catch{}};(async()=>{let l;try{l=go(s.frame),await n(l,i)}catch(a){t(a,l,i)}finally{e.end()}})()})}async function rh(e){await Jl(zl(e),{recursive:!0,mode:448});try{return await Ym(e,ko.O_CREAT|ko.O_EXCL|ko.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}var oh=6e4,Xl="resident-spawn-lock v1",sh=3;async function Zl(e,n={}){let t=n.maxAgeMs??oh,r=n.now??Date.now,o=n.pid??process.pid,s=n.isPidAlive??H;await Jl(zl(e),{recursive:!0,mode:448});let i=[];for(let l=0;;l+=1){let a=await rh(e);if(a)return await a.writeFile(`${Xl} pid=${o} taken=${new Date(r()).toISOString()}
60
- `).catch(()=>{}),{acquired:!0,lockPath:e,handle:a,reaped:i};let d=await lh(e),c=await dh(e,d,r());if(l>=sh||c==null)return{acquired:!1,lockPath:e,holder:d,ageMs:c};let u=ih(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 Ql(e,{force:!0}),i.push(f),n.onReap?.(f)}}async function ea(e){await e.handle.close().catch(()=>{}),await Ql(e.lockPath,{force:!0})}function ih(e,n,t,r){return e==null?n>t?"unattributed":null:r(e.pid)?n>t?"aged-out":null:"holder-dead"}function na(e){let n=e.ageMs==null?"of unknown age":`taken ${Math.round(e.ageMs/1e3)}s ago`,t=e.holder==null?"an owner it does not name":`pid ${e.holder.pid} (at ${e.holder.takenAt})`;return`no spawn was attempted: the spawn lock ${JSON.stringify(e.lockPath)} is held by ${t}, ${n}. If that process is gone, remove the file to clear it`}async function lh(e){try{return ah(await Xm(e,"utf8"))}catch{return null}}function ah(e){let n=e.split(`
61
- `,1)[0]?.trim()??"";if(!n.startsWith(Xl))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 dh(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 Zm(e)).mtimeMs)}catch{return null}}function H(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}var ch="/tmp";function At(e){let n=e.env??process.env,t=zm("sha256").update(e.key).digest("hex").slice(0,20),r=a=>In(a,e.socketFileName).length<th,o=n.XDG_RUNTIME_DIR;if(o){let a=In(o,"red-skills",t);if(r(a))return a}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=In(`red-skills-${s}`,t),l=In(nh(),i);return r(l)||process.platform==="win32"?l:In(ch,i)}ye();import{homedir as Th}from"node:os";import{join as Oo}from"node:path";import{spawnSync as $h}from"node:child_process";import{createHash as Ih}from"node:crypto";import{existsSync as Nh,readdirSync as Mh}from"node:fs";import{mkdir as da,readFile as Ch,rename as Wh,writeFile as Bh}from"node:fs/promises";import{dirname as Fh}from"node:path";var Me="@reddb-io/red-skills",_h="https://registry.npmjs.org",wh="canary",Ne=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}},xh=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;function vo(e){return typeof e=="string"&&xh.test(e.trim())}function sa(e){return`${e}-.bundle.min.mjs`}var Sh=".unversioned";function vh(e,n,t="stable"){if(t==="canary")return`${e}-canary.bundle.min.mjs`;if(!vo(n))throw new Ne("invalid-version",`refusing to key the ${e} bundle cache on ${JSON.stringify(n??"")}: it would mint ${sa(e)}, a name no resolver prefers and one whose mere existence satisfies the cache-first test forever (#3153)`);return`${e}-${n.trim()}.bundle.min.mjs`}function It(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return Cn(r,vh(n,t,o))}function Eh(e){return e==="dev"?["rsp","redskilled"]:[]}function Ph(e){return`${e}.bundle.min.mjs`}function Dh(e){return Cn("dist",Ph(e))}function jh(e,n="stable"){return`${Me}@${n==="canary"?wh:e}`}function Eo(e=Me){return`${_h}/${e.replace("/","%2F")}`}async function Po(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=It({plugin:t,version:r,cacheDir:o,channel:s}),l=Eh(t),a=l.map(f=>It({plugin:f,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await Ah(e,a))return i;let d=jh(r,s),c=Cn(o,`.staging-${t}-${s==="canary"?"canary":r}`),u;try{u=await e.materialize(d,c)}catch(f){throw aa(f,d)}for(let f of[t,...l]){let m=Dh(f),h=Cn(u,m);if(!await e.exists(h))throw new Ne("bundle-missing",`npm package ${d} has no ${m}`);let b=f===t?i:It({plugin:f,version:r,cacheDir:o,channel:s});await e.writeFile(b,await e.readFile(h))}return await Oh(e,o,[t,...l]),i}async function Oh(e,n,t){if(e.rename)for(let r of t){let o=Cn(n,sa(r));try{if(!await e.exists(o))continue;await e.rename(o,`${o}${Sh}`)}catch{}}}async function Ah(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function ia(e,n,t=Me){let r;try{r=await e.fetchText(Eo(t))}catch(s){throw aa(s,t)}let o=Do(r);return{sameMajor:Lh(o,n),newest:jo(o)}}function Do(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 Lh(e,n){let t=So(n);if(t===null)return null;let r=null;for(let o of e)So(o)===t&&(r===null||la(o,r)>0)&&(r=o);return r}function jo(e){let n=null;for(let t of e){let r=String(t).trim();So(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||la(r,n)>0)&&(n=r)}return n}function So(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?Number(n[1]):null}function la(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 aa(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new Ne("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new Ne("package-missing",`npm could not resolve ${n}: ${t}`,e):new Ne("network",`failed to resolve ${n}: ${t}`,e)}function Cn(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}ye();var ca={async materialize(e,n){await da(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 Oo(n,"node_modules",...Me.split("/"))},async readFile(e){return new Uint8Array(await Ch(e))},async writeFile(e,n){await da(Fh(e),{recursive:!0}),await Bh(e,n)},async exists(e){return Nh(e)},sha256(e){return Ih("sha256").update(e).digest("hex")},async fetchText(e){let n=await fetch(e,{redirect:"follow"});if(!n.ok)throw new Error(`GET ${e} -> ${n.status}`);return await n.text()},async rename(e,n){await Wh(e,n)}},Hh="redskilled";function Uh(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Oo(e.HOME||Th(),".cache");return Oo(n,"red-skills","bundles")}var Gh=/^([a-z0-9-]+)-(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?)\.bundle\.min\.mjs$/;async function Kh(e,n){if(vo(e.version))return e.version.trim();let t=e.listCacheDir??Jh,r=Vh(t(n),"dev");if(r)return r;try{let s=await(e.bundleIO??ca).fetchText(Eo());return jo(Do(s))}catch{return null}}function Vh(e,n){let t=null;for(let r of e){let o=Gh.exec(r);if(!o||o[1]!==n)continue;let s=o[2];(t===null||qh(s,t)>0)&&(t=s)}return t}function qh(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n);return Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function Jh(e){try{return Mh(e)}catch{return[]}}async function Qh(e={},n={},t={}){let r=Se(e,n);if(de(r))return r;let o=t.env??n.env??process.env,s=Uh(o),i=await Kh(t,s);if(i===null)return r;try{await Po(t.bundleIO??ca,{plugin:Hh,version:i,cacheDir:s})}catch{return r}return Se(e,n)}async function ua(e={},n={},t={}){let r=await Qh(e,n,t);if(de(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(ye(),oa));throw new o(r)}import{randomUUID as et}from"node:crypto";import{mkdir as lb,rm as Gc}from"node:fs/promises";import{createServer as ab}from"node:net";import{dirname as db}from"node:path";import{totalmem as Yh}from"node:os";function Wn(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 pa(e,n={}){let t=0,r=0,o=0,s=[],i=[];for(let d of e){let c=Wn(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=on(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:zh(e.length,r,l,a)}}function zh(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 on(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 fa(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 ma="REDSKILLED_MEMORY_CEILING",Ao="REDSKILLED_WORKER_CEILING",ha=.7;function ya(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return on(n)}function Nt(e){let n=0,t=[];for(let r of e){let o=ya(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 ka(e){let{ceiling:n}=e,t=Nt(e.workers),r=ya(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 Ra(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=Nt(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 (${Ao} 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 ba(e=process.env,n=Yh()){let t=(e[ma]??"").trim(),r=(e[Ao]??"").trim(),o=eg(r);if(t!==""){let s=Zh(t,n);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"};ga(`redskilled: ${ma}=${JSON.stringify(t)} is not a memory ceiling this host can read; using ${ha*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return r!==""&&o===null&&!Xh(r)&&ga(`redskilled: ${Ao}=${JSON.stringify(r)} is not a positive integer; this host admits an unbounded number of Workers instead.`),{memory_bytes:Math.floor(n*ha),worker_count:o,source:"host-fraction"}}function Xh(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var ga=e=>process.stderr.write(`${e}
62
- `);function Zh(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)):on(e)??void 0}function eg(e){if(e===""||["infinity","none","off","unbounded"].includes(e.toLowerCase()))return null;let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:null}import{appendFile as ng,mkdir as tg,open as rg,readFile as og,stat as sg,truncate as _a}from"node:fs/promises";import{dirname as ig}from"node:path";var wa="redskilled.events.toonl";function lg(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 ag="daemon:";function dg(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${ag}${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 xa(e){let n=ge({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await tg(ig(e),{recursive:!0,mode:448}),await cg(e),await ng(e,n.push(mg(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(lg(o)),recordDaemonStop:o=>r(dg(o)),read:()=>ug(e),flush:async()=>{await t}}}async function cg(e){let n;try{n=(await sg(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await rg(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 _a(e,s-i+a+1);return}}await _a(e,0)}finally{await r.close()}}async function ug(e){let n;try{n=await og(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return pg(n)}function pg(e){let n=e.split(`
63
- `);return n.pop(),n.length===0?[]:we(`${n.join(`
59
+ `}function kh(e){try{let n=JSON.stringify(e);if(n===void 0)return null;let t=W(JSON.parse(n));return t.trim()===""?null:t}catch{return null}}function aa(e,n){return!ia(e)||!ia(n)||n.ok!==!1?!1:typeof e.id=="string"&&typeof n.id=="string"&&n.id!==e.id}function ia(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var da=new Set;function ca(e){return da.has(e)?"json":yh}function ua(e){da.add(e)}var vh=108;async function Wt(e,n,t="resident server"){let r=e.wire,o=r??ca(e.socketPath),s=await pa(e,n,t,o);return r||o==="json"||!aa(n,s)?s:(ua(e.socketPath),await pa(e,n,t,"json"))}async function pa(e,n,t,r){let o=e.timeoutMs??1e3;return await new Promise((s,i)=>{let l=xh(e.socketPath),a=!1,d="",u=setTimeout(()=>{p(()=>i(new Error(`${t} timed out`))),l.destroy()},o);function p(f){a||(a=!0,clearTimeout(u),f())}l.on("connect",()=>{l.write(vo(n,r))}),l.on("data",f=>{d+=f.toString("utf8");let m=xo(d);m&&(d=m.rest,p(()=>{try{s(So(m.frame))}catch(g){i(g)}}),l.end())}),l.on("error",f=>p(()=>i(f))),l.on("close",()=>{a||p(()=>i(new Error(`${t} closed without response`)))})})}function ga(e,n,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",o=>{r+=o;let s=xo(r);if(!s)return;r=s.rest,e.pause();let i=l=>{if(!(e.destroyed||!e.writable))try{e.write(vo(l,s.dialect))}catch{}};(async()=>{let l;try{l=So(s.frame),await n(l,i)}catch(a){t(a,l,i)}finally{e.end()}})()})}async function Eh(e){await fa(ha(e),{recursive:!0,mode:448});try{return await bh(e,Eo.O_CREAT|Eo.O_EXCL|Eo.O_RDWR)}catch(n){if(n.code!=="EEXIST")throw n;return null}}var Ph=6e4,ya="resident-spawn-lock v1",Dh=3;async function ka(e,n={}){let t=n.maxAgeMs??Ph,r=n.now??Date.now,o=n.pid??process.pid,s=n.isPidAlive??B;await fa(ha(e),{recursive:!0,mode:448});let i=[];for(let l=0;;l+=1){let a=await Eh(e);if(a)return await a.writeFile(`${ya} pid=${o} taken=${new Date(r()).toISOString()}
60
+ `).catch(()=>{}),{acquired:!0,lockPath:e,handle:a,reaped:i};let d=await Oh(e),u=await Lh(e,d,r());if(l>=Dh||u==null)return{acquired:!1,lockPath:e,holder:d,ageMs:u};let p=jh(d,u,t,s);if(p==null)return{acquired:!1,lockPath:e,holder:d,ageMs:u};let f={lockPath:e,reason:p,holder:d,ageMs:u};await ma(e,{force:!0}),i.push(f),n.onReap?.(f)}}async function Ra(e){await e.handle.close().catch(()=>{}),await ma(e.lockPath,{force:!0})}function jh(e,n,t,r){return e==null?n>t?"unattributed":null:r(e.pid)?n>t?"aged-out":null:"holder-dead"}function ba(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 Oh(e){try{return Ah(await _h(e,"utf8"))}catch{return null}}function Ah(e){let n=e.split(`
61
+ `,1)[0]?.trim()??"";if(!n.startsWith(ya))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 Lh(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 wh(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 Th="/tmp";function Bt(e){let n=e.env??process.env,t=Rh("sha256").update(e.key).digest("hex").slice(0,20),r=a=>Wn(a,e.socketFileName).length<vh,o=n.XDG_RUNTIME_DIR;if(o){let a=Wn(o,"red-skills",t);if(r(a))return a}let s=e.uid??(typeof process.getuid=="function"?process.getuid():"nouid"),i=Wn(`red-skills-${s}`,t),l=Wn(Sh(),i);return r(l)||process.platform==="win32"?l:Wn(Th,i)}_e();import{homedir as tg}from"node:os";import{join as Co}from"node:path";import{spawnSync as rg}from"node:child_process";import{createHash as og}from"node:crypto";import{existsSync as sg,readdirSync as ig}from"node:fs";import{mkdir as Da,readFile as lg,rename as ag,writeFile as dg}from"node:fs/promises";import{dirname as cg}from"node:path";var Be="@reddb-io/red-skills",Gh="https://registry.npmjs.org",Kh="canary",We=class extends Error{kind;cause;constructor(n,t,r){super(t),this.name="BundleFetchError",this.kind=n,this.cause=r}},Vh=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;function To(e){return typeof e=="string"&&Vh.test(e.trim())}function Sa(e){return`${e}-.bundle.min.mjs`}var qh=".unversioned";function Jh(e,n,t="stable"){if(t==="canary")return`${e}-canary.bundle.min.mjs`;if(!To(n))throw new We("invalid-version",`refusing to key the ${e} bundle cache on ${JSON.stringify(n??"")}: it would mint ${Sa(e)}, a name no resolver prefers and one whose mere existence satisfies the cache-first test forever (#3153)`);return`${e}-${n.trim()}.bundle.min.mjs`}function Gt(e){let{plugin:n,version:t,cacheDir:r,channel:o}=e;return Hn(r,Jh(n,t,o))}function Qh(e){return e==="dev"?["rsp","redskilled"]:[]}function zh(e){return`${e}.bundle.min.mjs`}function Yh(e){return Hn("dist",zh(e))}function Xh(e,n="stable"){return`${Be}@${n==="canary"?Kh:e}`}function $o(e=Be){return`${Gh}/${e.replace("/","%2F")}`}async function Io(e,n){let{plugin:t,version:r,cacheDir:o,channel:s="stable"}=n,i=Gt({plugin:t,version:r,cacheDir:o,channel:s}),l=Qh(t),a=l.map(f=>Gt({plugin:f,version:r,cacheDir:o,channel:s}));if(s!=="canary"&&await e.exists(i)&&await eg(e,a))return i;let d=Xh(r,s),u=Hn(o,`.staging-${t}-${s==="canary"?"canary":r}`),p;try{p=await e.materialize(d,u)}catch(f){throw Pa(f,d)}for(let f of[t,...l]){let m=Yh(f),g=Hn(p,m);if(!await e.exists(g))throw new We("bundle-missing",`npm package ${d} has no ${m}`);let _=f===t?i:Gt({plugin:f,version:r,cacheDir:o,channel:s});await e.writeFile(_,await e.readFile(g))}return await Zh(e,o,[t,...l]),i}async function Zh(e,n,t){if(e.rename)for(let r of t){let o=Hn(n,Sa(r));try{if(!await e.exists(o))continue;await e.rename(o,`${o}${qh}`)}catch{}}}async function eg(e,n){for(let t of n)if(!await e.exists(t))return!1;return!0}async function va(e,n,t=Be){let r;try{r=await e.fetchText($o(t))}catch(s){throw Pa(s,t)}let o=No(r);return{sameMajor:ng(o,n),newest:Mo(o)}}function No(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 ng(e,n){let t=Lo(n);if(t===null)return null;let r=null;for(let o of e)Lo(o)===t&&(r===null||Ea(o,r)>0)&&(r=o);return r}function Mo(e){let n=null;for(let t of e){let r=String(t).trim();Lo(r)===null||/^\d+\.\d+\.\d+[-+]/.test(r)||(n===null||Ea(r,n)>0)&&(n=r)}return n}function Lo(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 Pa(e,n){let t=e instanceof Error?e.message:String(e);return/ENOENT|command not found|spawn npm/i.test(t)?new We("npm-unavailable",`npm is unavailable while resolving ${n}: ${t}`,e):/\b404\b|E404|not found|no matching version|notarget/i.test(t)?new We("package-missing",`npm could not resolve ${n}: ${t}`,e):new We("network",`failed to resolve ${n}: ${t}`,e)}function Hn(e,n){return e.endsWith("/")?`${e}${n}`:`${e}/${n}`}_e();var ja={async materialize(e,n){await Da(n,{recursive:!0});let t=rg("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 Co(n,"node_modules",...Be.split("/"))},async readFile(e){return new Uint8Array(await lg(e))},async writeFile(e,n){await Da(cg(e),{recursive:!0}),await dg(e,n)},async exists(e){return sg(e)},sha256(e){return og("sha256").update(e).digest("hex")},async fetchText(e){let n=await fetch(e,{redirect:"follow"});if(!n.ok)throw new Error(`GET ${e} -> ${n.status}`);return await n.text()},async rename(e,n){await ag(e,n)}},ug="redskilled";function pg(e=process.env){if(e.RED_SKILLS_CACHE_DIR)return e.RED_SKILLS_CACHE_DIR;let n=e.XDG_CACHE_HOME||Co(e.HOME||tg(),".cache");return Co(n,"red-skills","bundles")}var fg=/^([a-z0-9-]+)-(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?)\.bundle\.min\.mjs$/;async function mg(e,n){if(To(e.version))return e.version.trim();let t=e.listCacheDir??yg,r=hg(t(n),"dev");if(r)return r;try{let s=await(e.bundleIO??ja).fetchText($o());return Mo(No(s))}catch{return null}}function hg(e,n){let t=null;for(let r of e){let o=fg.exec(r);if(!o||o[1]!==n)continue;let s=o[2];(t===null||gg(s,t)>0)&&(t=s)}return t}function gg(e,n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e),r=/^(\d+)\.(\d+)\.(\d+)/.exec(n);return Number(t[1])-Number(r[1])||Number(t[2])-Number(r[2])||Number(t[3])-Number(r[3])}function yg(e){try{return ig(e)}catch{return[]}}async function kg(e={},n={},t={}){let r=Pe(e,n);if(ce(r))return r;let o=t.env??n.env??process.env,s=pg(o),i=await mg(t,s);if(i===null)return r;try{await Io(t.bundleIO??ja,{plugin:ug,version:i,cacheDir:s})}catch{return r}return Pe(e,n)}async function Oa(e={},n={},t={}){let r=await kg(e,n,t);if(ce(r))return r;let{RedskilledDaemonEntryError:o}=await Promise.resolve().then(()=>(_e(),xa));throw new o(r)}import{randomUUID as at}from"node:crypto";import{mkdir as Pb,rm as uu}from"node:fs/promises";import{connect as Db,createServer as jb}from"node:net";import{dirname as Ob}from"node:path";import{totalmem as bg}from"node:os";function Un(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 Aa(e,n={}){let t=0,r=0,o=0,s=[],i=[];for(let d of e){let u=Un(d),p=!1;for(let[f,m]of[[u.memory_high,g=>t+=g],[u.memory_max,g=>r+=g]]){if(f==null)continue;let g=cn(f);g==null?p=!0:m(g)}u.cpu_weight!=null&&(o+=u.cpu_weight),p&&s.push(d.worker_id),d.isolated||i.push(d.worker_id)}let l=n.hostCeilingBytes??null,a=l==null?0:Math.max(0,r-l);return{version:1,worker_count:e.length,memory_high_bytes:t,memory_max_bytes:r,cpu_weight_total:o,unaccounted_workers:s.sort(),unisolated_workers:i.sort(),memory_ceiling_bytes:l,over_committed_bytes:a,over_commitment_reason:a===0?null:Rg(e.length,r,l,a)}}function Rg(e,n,t,r){return`this host's ${e} Worker(s) carry ${n} bytes of applied MemoryMax against a host ceiling of ${t} bytes \u2014 ${r} bytes over. A per-Worker MemoryMax is a wall rather than a reservation, so the host stays safe only while the Workers do not all peak together; the ceiling is not enforced host-wide.`}function cn(e){let n=/^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)(?:B)?\s*$/i.exec(e);if(!n)return null;let t={"":1,k:1024,m:1024**2,g:1024**3,t:1024**4}[n[2].toLowerCase()];return Math.round(Number(n[1])*t)}function La(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 Ta="REDSKILLED_MEMORY_CEILING",Wo="REDSKILLED_WORKER_CEILING",$a=.7;function Na(e){let n=e?.memory_max??e?.memory_high;if(n!=null)return cn(n)}function Kt(e){let n=0,t=[];for(let r of e){let o=Na(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 Ma(e){let{ceiling:n}=e,t=Kt(e.workers),r=Na(e.budget),o=r===void 0?null:r,s=t.memory_bytes+(r??0),i=t.worker_count+1,l=e.projectLabel!=null&&e.projectLabel!==""?` for project ${JSON.stringify(e.projectLabel)}`:"",a=`the host is already holding ${t.memory_bytes} bytes across ${t.worker_count} Worker(s)`,d=(u,p)=>({version:1,admitted:!1,verdict:u,reason:p,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s});return n.worker_count!=null&&i>n.worker_count?d("refused-over-worker-ceiling",`redskilled refused this Worker${l}: it would be Worker ${i} past a host ceiling of ${n.worker_count} Worker(s), and ${a}`):n.memory_bytes!=null&&r===null?d("refused-unaccountable-budget",`redskilled refused this Worker${l}: its declared memory budget cannot be reduced to bytes, so it cannot be proven to fit under the host ceiling of ${n.memory_bytes} bytes, and ${a}`):n.memory_bytes!=null&&s>n.memory_bytes?d("refused-over-memory-ceiling",`redskilled refused this Worker${l}: it would take the host to ${s} bytes of declared Worker memory, past the host ceiling of ${n.memory_bytes} bytes, and ${a}`):{version:1,admitted:!0,verdict:"admitted",reason:`redskilled admitted this Worker${l}: ${s} bytes of declared Worker memory against a host ceiling of ${n.memory_bytes??"unbounded"} bytes, and ${a}`,ceiling:n,consumption:t,requested_memory_bytes:o,projected_worker_count:i,projected_memory_bytes:s}}function Ca(e){let n=e.budget?.memory_max??e.budget?.memory_high;if(n!=null)return{memory_max:n,reason:`the client declared this Worker's memory ceiling (${n}), so the host derived none`};if(e.ceiling.memory_bytes==null)return{memory_max:null,reason:"this host admits Workers against no memory ceiling, so there is no accounting to derive a per-Worker ceiling from; the daemon's RSS sampling floor is the only remaining ceiling"};let t=Kt(e.workers),r=e.ceiling.memory_bytes-t.memory_bytes,o=e.ceiling.worker_count,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 (${Wo} 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 Wa(e=process.env,n=bg()){let t=(e[Ta]??"").trim(),r=(e[Wo]??"").trim(),o=xg(r);if(t!==""){let s=wg(t,n);if(s!==void 0)return{memory_bytes:s,worker_count:o,source:"declared"};Ia(`redskilled: ${Ta}=${JSON.stringify(t)} is not a memory ceiling this host can read; using ${$a*100}% of host memory instead. Accepted forms: systemd bytes (\`8G\`), a percentage (\`50%\`), or \`infinity\`.`)}return r!==""&&o===null&&!_g(r)&&Ia(`redskilled: ${Wo}=${JSON.stringify(r)} is not a positive integer; this host admits an unbounded number of Workers instead.`),{memory_bytes:Math.floor(n*$a),worker_count:o,source:"host-fraction"}}function _g(e){return["infinity","none","off","unbounded"].includes(e.trim().toLowerCase())}var Ia=e=>process.stderr.write(`${e}
62
+ `);function wg(e,n){let t=e.toLowerCase();if(["infinity","none","off","unbounded"].includes(t))return null;let r=/^(\d+(?:\.\d+)?)\s*%$/.exec(e);return r?Math.floor(n*(Number(r[1])/100)):cn(e)??void 0}function xg(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 Sg,mkdir as vg,open as Eg,readFile as Pg,stat as Dg,truncate as Ba}from"node:fs/promises";import{dirname as jg}from"node:path";var Fa="redskilled.events.toonl";function Og(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 Ag="daemon:";function Lg(e){return{version:1,ts:e.ts,event:"daemon-stop",worker_id:`${Ag}${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=be({trailer:!1}),t=Promise.resolve();async function r(o){let s=t.then(async()=>{await vg(jg(e),{recursive:!0,mode:448}),await Tg(e),await Sg(e,n.push(Mg(o)),{encoding:"utf8",mode:384})});return t=s.catch(()=>{}),await s,o}return{path:e,record:o=>r(Og(o)),recordDaemonStop:o=>r(Lg(o)),read:()=>$g(e),flush:async()=>{await t}}}async function Tg(e){let n;try{n=(await Dg(e)).size}catch(o){if(o.code==="ENOENT")return;throw o}if(n===0)return;let t=64*1024,r=await Eg(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 Ba(e,s-i+a+1);return}}await Ba(e,0)}finally{await r.close()}}async function $g(e){let n;try{n=await Pg(e,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return Ig(n)}function Ig(e){let n=e.split(`
63
+ `);return n.pop(),n.length===0?[]:ve(`${n.join(`
64
64
  `)}
65
- `).filter(hg).map(gg)}function Sa(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,fg(t)):n.delete(t.worker_id));return[...n.values()]}function fg(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 mg(e){return{...e}}function hg(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 gg(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:ke(e.project_label)??"",pid:Number(e.pid??0),workspace_path:ke(e.workspace_path)??"",log_path:ke(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:ke(e.unit),memory_high:ke(e.memory_high),memory_max:ke(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:ke(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:ke(e.signal),reason:ke(e.reason)}}function ke(e){return e==null||e===""?null:String(e)}function va(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 Ea(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}var Mt={shortLifeStreak:0,haltUntilMs:null};function Pa(e,n,t){if(n>=6e4)return Mt;let r=e.shortLifeStreak+1;return r<3?{shortLifeStreak:r,haltUntilMs:null}:{shortLifeStreak:r,haltUntilMs:t+6e5}}function Da(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 Oa(e){let n=e.workers.map(yg),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:Rg({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function Aa(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 yg(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 kg(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 Rg(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${kg(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${ja(e.held,"Worker")} across ${ja(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 ja(e,n){return`${e} ${n}${e===1?"":"s"}`}function Lo(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 bg,mkdir as _g,readFile as wg,rm as xg,writeFile as Sg}from"node:fs/promises";import{dirname as La,join as Na}from"node:path";import{tmpdir as Ta}from"node:os";var vg="redskilled.machine.claim.toon",Eg="REDSKILLED_MACHINE_DIR",Pg=8,ve=class extends Error{constructor(t,r,o){super(jg(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},$a;function Ma(){return $a??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},$a}function Dg(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[Eg]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||Ta():Ta();return Na(o,`redskilled-${e.machineIdHash}`)}function Ct(e){return Na(Dg(e),vg)}function Wt(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??H;async function s(){let a;try{a=await wg(e,"utf8")}catch(c){if(c.code==="ENOENT"||To(c))return;throw c}let d=Ag(a);return Lg(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 xg(e,{force:!0}),!0}catch(a){if(To(a))return!1;throw a}}return{claimPath:e,read:s,async claim(a){await _g(La(e),{recursive:!0,mode:1023})!=null&&await bg(La(e),1023).catch(()=>{});let c=!1;for(let u=0;u<Pg;u+=1){let f=i(a,r());try{return await Sg(e,Og(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:c,claim:f}}catch(h){if(h.code!=="EEXIST"){if(To(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(Ia(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||!Ia(d,a,n.socketPath)?!1:await l()}}}function Ca(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 Wa(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 jg(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 To(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function Ia(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function Og(e){return`${C(e,{keyedMapCollapse:!0})}
66
- `}function Ag(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return J(n)}catch{return null}}}function Lg(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 Tg=["worker_id","slot","workspace_path","log_path"],$o=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${Tg.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},$g=/\{\{([a-z_]+)\}\}/g;function Ig(e,n){let t=(i,l)=>i.replace($g,(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 $o(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 Ba(e,n,t){let r=Ig(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 Io(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 No(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 Mo(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 Ng=3e5,Mg=.5,Wo=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 Fa(e,n){if(n.held!=null)throw new Wo(n.held);let t=Co(e.project_label,"a project label"),r=Co(e.selector,"a selector"),o=Io(e.argv,t),s=Mo(e.env,t),i=No(e.log_path,t),l=Co(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??Ng;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 Bt=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 Ha(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:Io(n.launch.argv,e.project_label),env:Mo(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=n.launch==null?e.log_path:No(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 Ua(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 Cg(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function Ga(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*Mg;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 Ka(e,n){let t=[],r=[];for(let o of e)(Cg(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function Bo(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||Wg(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 Wg(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function Co(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var Bg={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 Va(e){return`worker-${e}`}function qa(e){let n=Bg[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 Ja(e){return e==="single-object"?"rest":"graphql"}function T(e,n,t,r,o){return{key:e,kind:"read",cardinality:n,surface:o??Ja(n),budget:t,...o?{only:o}:{},why:r}}function U(e,n,t,r){return{key:e,kind:"write",cardinality:"single-object",surface:n,budget:t,why:r}}var Qa=[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"),U("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),U("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),U("issue close","graphql","graphql","gh closes with the closeIssue mutation"),U("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),U("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),U("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),U("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),U("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),U("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),U("pr close","graphql","graphql","gh closes with a GraphQL mutation"),U("pr edit","graphql","graphql","gh edits with GraphQL mutations"),U("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),U("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),U("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],Fg=new Map(Qa.map(e=>[e.key,e]));function za(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 Fo(e){let n=za(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=Fo(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 Ya(e){return Fg.get(Fo(e))??null}function Xa(e){let n=Ya(e);if(!n)throw new Ft(e);return n}function Ho(e){return Xa(e).surface}var ed="rate_limit",nd={rest:"core",graphql:"graphql",search:"search"},Re=["rest","graphql","search"];function Kt(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:[...Re],detail:n??"no balance has been asked for yet, so none is known"}}var Go=15e3,sn=.15,Ut=[{at_or_below_fraction:0,every_ms:Go,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:sn,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"}],Uo=2;function td(e,n){let t=Za(e),r=Za(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let l of Re){let a=nd[l],d=r[a],c=Gg(l,a,d);o[l]=c,c==null&&s.push(l)}let i=Re.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 ${Re.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function Ko(e){try{let n=await e.transport();return td(n,{askedAt:e.now})}catch(n){let t=n instanceof Error?n.message:String(n);return{...Kt(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function Vo(e){let n=null;for(let t of Re){let r=e.pools[t];r!=null&&(n==null||r.fraction<n.fraction)&&(n=r)}return n}function Vt(e,n){let t=Vo(e);if(t==null)return Gt(sn).every_ms;let r=Gt(t.fraction);if(t.remaining>0)return r.every_ms;let o=od(n.now,t.reset_at);return o==null?r.every_ms:Math.max(Go,Math.min(r.every_ms,o))}function qo(e,n=sn){return Math.ceil(e.limit*n)}function rd(e,n,t=sn){let r=e.pools[n];return r==null?"unknown":r.remaining<=0?"spent":r.remaining<qo(r,t)?"reserved":"open"}function Jo(e){let n=e.reservedFraction??sn,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:Gt(n).every_ms*Uo,stale:!1,posture:"unknown",reserved_fraction:n,next_poll_ms:Gt(n).every_ms,pools:[],unreported_pools:[...Re],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let r=Vt(t,{now:e.now}),o=e.stalenessMs??r*Uo,s=od(t.asked_at,e.now),i=t.outcome==="asked"&&(s==null||s>o),l=Re.map(c=>t.pools[c]).filter(c=>c!=null),a=Ug(t,n),d=Vo(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`:Hg(a,d,t,n)}}function Qo(e){if(!Yo(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 Hg(e,n,t,r){if(n==null)return t.detail;let o=qo(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 Ug(e,n){let t="unknown";for(let r of Re){if(e.pools[r]==null)continue;let o=rd(e,r,n);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function Gt(e){for(let n of Ut)if(e<=n.at_or_below_fraction)return n;return Ut[Ut.length-1]}function Gg(e,n,t){if(!Yo(t))return null;let r=Ht(t.limit),o=Ht(t.remaining),s=Ht(t.used),i=Ht(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 zo(e){let n=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let r=await t(`${n}/${ed}`,{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 od(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 Ht(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function Za(e){return Yo(e)?e:{}}function Yo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cd(e){return{generated_at:e.now,hour:sd("hour",36e5,e),day:sd("day",864e5,e)}}function qt(e,n,t){let r=Bn(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(l=>{let a=Bn(n(l));return a==null?!1:r==null||r-a<=o});return i.length<=s?i:i.slice(i.length-s)}function sd(e,n,t){let r=Bn(t.now),o=r==null?null:r-n,s=e==="hour"?"1h":"24h",i=t.observations.map(u=>({observation:u,at:Bn(u.observed_at)})).filter(u=>u.at!=null&&ad(u.at,o,r)).sort((u,f)=>u.at-f.at),l=t.outcomes.map(u=>Bn(u.ts)).filter(u=>u!=null&&ad(u,o,r)),a=id(i,u=>u.tokens,"tokens",s),d=id(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:Kg(l.length,n,s),runner_share:ld("runner",i,u=>u.runner,s),model_share:ld("model",i,u=>u.model,s),unavailable:c}}function id(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 Kg(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 ld(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 ad(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function Bn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function ud(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.generated_at=="string"&&dd(n.hour)&&dd(n.day)}function dd(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"&&Xo(n.tokens_per_min)&&Xo(n.tools_per_min)&&Xo(n.issues_per_hour)&&Array.isArray(n.unavailable)}function Xo(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 Vg}from"node:child_process";import{existsSync as qg,readFileSync as Jt,readdirSync as Jg}from"node:fs";import{dirname as Qg,join as Ce}from"node:path";function Fn(e){let n=Wn(e),t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let s=on(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function pd(e){let n=[],t=[];for(let r of e.workers){let o=Fn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(Wn(r).memory_max??Wn(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(zg(r,o,s))}}return{terminations:n,unenforceable:t}}function zg(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 Yg=4096;function fd(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return r;let o={},s={},i={},l=Zg(e,t,n);for(let[u,f]of l){let m=ty(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=sy(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 j of c.get(k)??[])h.push(j)}}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 Xg="/sys/fs/cgroup";function Zg(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let s=t.cgroupRoot??Xg,i=e.filter(a=>a.unit!=null&&a.unit!=="");if(i.length===0)return r;let l=ey(s,t);for(let a of i)for(let d of l){let c=Ce(d,a.unit);if(qg(Ce(c,"memory.current"))){r.set(a.worker_id,c);break}}return r}function ey(e,n){let t=n.selfCgroupPath??ny(),r=[],o=l=>{r.includes(l)||r.push(l)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(Ce(e,s));let l=Qg(s);if(l===s)break;s=l}o(e);let i=n.uid??process.getuid?.();return i!=null&&o(Ce(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),r}function ny(){try{for(let e of Jt("/proc/self/cgroup","utf8").split(`
67
- `))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function ty(e){let n;try{n=Jt(Ce(e,"memory.current"),"utf8")}catch{return null}let t=Number(n.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:ry(e)}}function ry(e){let n;try{n=Jt(Ce(e,"cpu.stat"),"utf8")}catch{return null}return oy(n)}function oy(e){for(let n of e.split(`
68
- `)){let[t,r]=n.trim().split(/\s+/);if(t!=="usage_usec")continue;let o=Number(r);return!Number.isFinite(o)||o<0?null:o/1e6}return null}function sy(e,n){return n.procRoot!=null||e==="linux"?uy(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?dy(iy(n.psTable)):new Map}function iy(e){try{return(e??ly)()}catch{return""}}function ly(){return Vg("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var ay=1024;function dy(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=cy(r[3]);l!=null&&n.set(o,{pid:o,ppid:s,rssBytes:i*ay,cpuSeconds:l})}return n}function cy(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 uy(e){let n=new Map,t;try{t=Jg(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=Jt(Ce(e,r,"stat"),"utf8")}catch{continue}let s=fy(o);s&&n.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*Yg,cpuSeconds:s.cpuTicks/py})}return n}var py=100;function fy(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 my=["api","graphql"],hy=Ho(my);function gy(e,n="https://api.github.com"){return e==="graphql"?`${n}/graphql`:n}var md=100,ns=6e4,yy=2*ns,ky=7*24*60*60*1e3,Zo=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 ts(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new Zo(t.project_label,t.token_ref,n)}function Ry(e,n={now:new Date(0).toISOString()}){wy(e);let t=n.closedWindowMs??ky,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 by(e,n,t){let r=ln(n),o=ln(r.data),s=Array.isArray(r.errors)?r.errors.map(ln):[],i=xy(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=>hd(h.path,a)||hd(h.path,d));if(Qt(f)){let h=gd(f.open_pull_requests),b=gd(f.open_issues),k=Sy(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||_d(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: ${es(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 _y(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 yd(e){if(e.projects.length===0)return _y(e.now);ts(e.projects,e.hostTokenRef);let n=Ry(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return by(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 kd(e){let n=e.stalenessMs??yy,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 Rd(e){if(!Qt(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)&&Qt(n.rate_limit)&&Array.isArray(n.projects)&&typeof n.reason=="string"}function bd(e){let n=e.endpoint??gy(hy),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 wy(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>md)throw new Error(`redskilled activity fetch spans at most ${md} 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 xy(e,n){let t=ln(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(_d),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 _d(e){if(e==null)return!1;let n=es(e.type),t=es(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function hd(e,n){return Array.isArray(e)&&e.includes(n)}function gd(e){let n=ln(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function Sy(e){let n=ln(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function ln(e){return Qt(e)?e:{}}function Qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function es(e){return typeof e=="string"?e:""}var vy=3e4,Ey=4,Py=["logs","vitals","display"];function wd(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:Dy,budget:{...o.budget,used_bytes:null,used_fraction:null}},...r("logs")?{}:{log:jy},...r("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var Dy={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},jy={last_line:null,published_at:null,source:null};function xd(e){let n=e.stalenessMs??vy,t=Hn(e.now),r=e.sampledAt==null?null:Hn(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=>Ly(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=Nt(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:Ny({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:Iy(l),known_projects:$y(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,m)=>f.localeCompare(m)),workers:l,github_balance:Jo({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:kd({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:Oy(e.deaths,e.recentDeathLimit??Ey)},engine:Ay(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function Oy(e,n){let t=[...e].sort((o,s)=>(Hn(s.ts)??0)-(Hn(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 Ay(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 Ly(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=Fn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=Hn(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:Ty(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function Ty(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 $y(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 Iy(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 Ny(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 Hn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function rs(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||Rd(n.repository_activity))&&(n.github_balance===void 0||Qo(n.github_balance))&&(n.deaths===void 0||My(n.deaths))&&(n.engine===void 0||Cy(n.engine))&&(n.metrics===void 0||ud(n.metrics))}function My(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 Cy(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 Sd={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 os(e,n){let t=e.display?.started_at;if(t!=null&&t!==""){let r=Date.parse(t),o=Date.parse(n);if(Number.isFinite(r)&&Number.isFinite(o))return Math.max(0,o-r)}return e.uptime_ms}var F=e=>`\x1B[${e}m`,Wy=F("48;2;114;47;55"),By=F("48;2;88;36;42"),Fy=F("38;2;255;255;255"),Hy=F("38;2;201;150;158"),Uy=F("38;2;255;214;214"),Gy=F("39"),Ky=F("38;2;224;138;148"),Vy=F("38;2;240;110;120"),qy=F("38;2;255;214;214"),Jy=F("38;2;146;84;94"),Qy=F("38;2;255;95;95"),zy=F("49"),zt=F("0"),Yy=F("1"),Xy=F("22");var Zy=/\x1b\[[0-9;]*m/g,ek=/(\x1b\[[0-9;]*m)/,nk=/^\x1b\[[0-9;]*m$/;function vd(e){return e.replace(Zy,"")}function tk(e){return e.slice(2,-1).split(";").every(t=>t===""||Number(t)===0)}function Ee(e){return[...vd(e)].length}function K(e,n){if(n<=0)return"";if(Ee(e)<=n)return e;if(n===1)return"\u2026";let t=n-1,r=0,o=!1,s="";for(let i of e.split(ek))if(i!==""){if(nk.test(i)){s+=i,o=!tk(i);continue}for(let l of i){if(r===t)return`${s}\u2026${o?zt:""}`;s+=l,r+=1}}return`${s}\u2026${o?zt:""}`}function ss(e,n){return e+" ".repeat(Math.max(0,n-Ee(e)))}function G(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 Un(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 Gn(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return Un(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 Kn(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 is(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}var ls="!unregistered",Vn="\u21E1",We="\u2020",an="\u25D0",dn="\u25EF",as="\u21B3",ds="redskilled unreachable \u2014 Worker state unknown";function cn(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function Yt(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function qn(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 cs(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 D={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Be(e,n=D){let t=qn(e,n.project),r=cn(e,n),o=Yt(e,n),s=ok(e,n,r,t),i=cs({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=fk(s,rk(u,n,r,o),n.separator);if(l={detail:u,line:f},Ee(f)<=n.maxWidth)break}let a=K(l.line,n.maxWidth),d=n.verbose&&l.detail==="workers"?uk(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 ps(e){let n=e.options??D,t=K(ds,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 rk(e,n,t,r){return e==="workers"?t.map(o=>ck(o,n)):e==="projects"?r.map(pk):[]}function ok(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(us(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(us(e,n)),t.length===0&&o.push("idle")):r==="name-only"?(o.push(`${n.project} ${t.length}w`),o.push(us(e,n)),o.push(ls)):o.push(ak(n.project,r)),o.push(sk(e));let s=ik(e);s!=null&&o.push(s);let i=lk(e);return i!=null&&o.push(i),e.staleness.stale&&o.push(dk(e)),o.join(" ")}function sk(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${Vn}`}function ik(e){let n=e.github_balance;return n==null?null:n.posture==="spent"?`${dn} quota spent`:n.posture==="reserved"?`${an} quota band`:null}function lk(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${We}${n.count} ${n.latest.sender_class}`}function ak(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 us(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?`${G(t)}/${G(r)}`:G(t)}function dk(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function ck(e,n){let t=Xt(e,n.mode),r=e.vitals.rss_bytes,o=r==null?"?":e.budget.bytes==null?G(r):`${G(r)}/${G(e.budget.bytes)}`;return`${t} ${o}`}function uk(e,n){let t=[];for(let r of e){let o=is(r.log.last_line);o!=null&&t.push(K(` ${as} ${Xt(r,n.mode)}: ${o}`,n.maxWidth))}return t}function Xt(e,n){return n==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function pk(e){return`${e.project_label} ${e.worker_count}w ${G(e.observed_rss_bytes)}`}function fk(e,n,t){return[e,...n].join(t)}var Jn=["wid","run","org","iss","bar","phase","elapsed","eta","hb","loc","tks","ctx","tls","rsn","txt"],ce={mode:"local",project:null,maxWidth:200,maxRows:16},mk=" ",Ed="\u2588",hk="\u25B6",gk="\u2717",yk="\u2591";function un(e,n=ce){let t=qn(e,n.project),r=cn(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(u=>kk(u,n,e.generated_at)),i=vk(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:K(Ek(s[f],i),n.maxWidth)})),a=Rk(e,n,r,t),d=r.length-o.length,c=[a.line,...l.map(u=>u.line)];return d>0&&c.push(K(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),c.push(..._k(e,n)),c.push(...bk(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:Jn,header:a,rows:l,lines:c,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function kk(e,n,t){let r=e.display??Sd,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:Pd(r),phase:[r.phase,r.step].filter(s=>!!s).join("\xB7"),elapsed:Kn(os(e,t)),eta:r.eta==null?"":`eta=${Kn(r.eta*1e3)}`,hb:`hb=${r.heartbeat??"?"}`,loc:Sk(r.added,r.removed),tks:r.tokens==null?"":`tks=${Un(r.tokens)}`,ctx:r.context==null?"":`ctx=${Un(r.context)}`,tls:r.tools==null?"":`tls=${r.tools}`,rsn:r.reasoning==null?"":`rsn=${r.reasoning}`,txt:r.text==null?"":`txt=${r.text}`}}function Pd(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 Ed.repeat(Math.floor(n));let o=e.failed?gk:hk;return`${Ed.repeat(r)}${o}${yk.repeat(Math.floor(n)-r-1)}`}function Rk(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=xk(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?Vn:""}`];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(wk(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:Dd(f.hour);if(h!=null&&m.push(h),u!=null&&u.count>0&&u.latest!=null&&m.push(`${We}${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&&Ee(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:K(k,n.maxWidth)}}function Dd(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${Gn(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${Gn(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${Gn(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 bk(e,n){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let r=t.posture==="spent"?dn:an,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[K(`${r} github budget ${t.posture}${o} \u2014 ${t.reason}`,n.maxWidth)]}function _k(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(s=>K(`${We} ${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(K(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function wk(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${G(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${G(e.memory_used_bytes)}/${G(e.memory_ceiling_bytes)}${n}`}function xk(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 Sk(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 vk(e){let n=Object.fromEntries(Jn.map(t=>[t,0]));for(let t of e)for(let r of Jn)n[r]=Math.max(n[r],Ee(t[r]));return n}function Ek(e,n){return Jn.filter(r=>n[r]>0).map(r=>ss(e[r],n[r])).join(mk).replace(/\s+$/,"")}var Zt=1;async function Qn(e,n){return await Ot(e,n,"redskilled daemon")}function Od(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:Zt,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:Ok(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:pa(n,{hostCeilingBytes:e.hostCeilingBytes??null}),upgrade:Ak(e)}}function Ok(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:Ga(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 Ak(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 Ad(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)&&fa(n.budget_accounting)&&(n.scope===void 0||Wa(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(Bo))&&(n.upgrade===void 0||Lk(n.upgrade))}function Lk(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||Tk(n.major_hold))}function Tk(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 tr}from"node:child_process";import{existsSync as ys}from"node:fs";import{delimiter as Hk,join as Fd}from"node:path";import{join as Ld}from"node:path";import{existsSync as $k}from"node:fs";import{createRequire as Ik}from"node:module";var Td="redskilled-job-object.node",Fe=100;function pn(e){return{available:!1,reason:e}}function Nk(e,n,t){return[Ld(t,"prebuilds",`${e}-${n}`,Td),Ld(t,"native","build","Release",Td)]}function $d(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return pn(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??Ck(),o=e.exists??$k,s=Nk(n,t,r),i=s.find(d=>o(d));if(i==null)return pn(`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??Ik(import.meta.url),a;try{a=l(i)}catch(d){return pn(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return Mk(a)?{available:!0,binding:a}:pn(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function Mk(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function Ck(){return new URL("..",import.meta.url).pathname}function Id(e){let n=e??{},t=[],r=Wk(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<Fe?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 ${Fe}, 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 Wk(e){return Fn({budget:e})}var er=5,Nd=19;function fs(e){return{available:!1,reason:e}}var Bk="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 Cd(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=er;else if(t.cpu_weight<Fe){let l=Math.round(Nd*(Fe-t.cpu_weight)/Fe);o=Math.min(Nd,Math.max(er,l))}else o=er,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${Fe}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${er}`);let s=Md(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=Md(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:Bk,...r.length>0?{note:r.join("; ")}:{}}}function Wd(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 ${Fk(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
71
- `),e.command,...e.args]}function Bd(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 ms(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 Md(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function Fk(e){return`'${e.replace(/'/g,"'\\''")}'`}var Hd="REDSKILLED_PLACEMENT",nr="red-worker",hs="/bin/sh";function Ud(e=process.env,n=process.platform){let t=fs(`POSIX rlimit and priority placement is the macOS backend (platform=${n})`);if(n==="win32")return{platform:n,systemdRun:null,userSession:!1,jobObjects:$d({platform:n}),posix:t};let r=pn(`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:Uk(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&ys(Fd(o,"systemd","private"));return{platform:n,systemdRun:qd("systemd-run",e),userSession:s,jobObjects:r,posix:t}}function Uk(e){return ys(hs)?{available:!0,shell:hs,nice:qd("nice",e)}:fs(`no POSIX shell was found at ${hs}, so there is nothing to apply rlimits or priority in`)}function Gd(e=process.env){let n=(e[Hd]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Gk(e,n,t=nr){return Kd(e,n,t).replace(/\.service$/,"")}function Kd(e,n,t=nr){return`${gs(t,"red-worker",24)}-${gs(e,"project",32)}-${gs(n,"worker",32)}.service`}function Vd(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:Ln({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 ${Hd}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return Vk(e,n,t,r,o,i);if(e.probes.platform==="darwin")return Kk(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=Kd(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=Ln({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=ms(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 Kk(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=Cd(t,{canRenice:s.nice!=null}),l=t.memory_high!=null||t.memory_max!=null,a=Bd(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:Wd({limits:i,nice:s.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:i,warning:a,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Ln({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 Vk(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=Id(t),a=Gk(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:Ln({scope:a,memory_ceiling:r,scope_degradation:null}),...qk(o&&l.note!=null?`${l.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,ms(e.budget))}}function qk(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function qd(e,n){for(let t of(n.PATH??"").split(Hk)){if(!t)continue;let r=Fd(t,e);if(ys(r))return r}return null}function gs(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function ks(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 Jd=3e4;function Qd(e){return e.unit!=null&&e.unit!==""?Jk(e.unit):H(e.pid)}function Jk(e){let n=tr("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var Qk="REDSKILLED_UNIT_DISCOVERY",zd="(unowned)";function Yd(e){let n=tr("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 zk(e=process.env){let n=(e[Qk]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function Xd(e,n,t=process.env){return zk(t)&&e===n}function Zd(e=nr){let n=tr("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 ec(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:zd,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 nc(e){return e.project_label.trim()!==""?e:{...e,project_label:zd,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 tc(e){if(e.unit!=null&&e.unit!==""){let n=tr("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 Yk(e,n=50){if(ic(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 Xk(e,n={}){let t=n.batchSize??50;if(ic(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 Zk(e,n){let t=zn(n),r=zn(t.data),o=Array.isArray(t.errors)?t.errors.map(zn):[],s=nR(r.rateLimit,o);return{projects:e.aliases.map(({alias:l,project:a})=>{let d=rR(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=>tR(u.path,l));return s.exhausted||lc(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: ${Rs(c?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function eR(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 oc(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 sc(e){if(e.projects.length===0)return eR(e.now);let n=e.batchSize??50,t=Yk(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=Xk(s,{batchSize:n});try{let l=await e.transport(i.query),a=Zk(i,l);r.push(...a.projects),o=rc(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=rc(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 ic(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 rc(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 nR(e,n){let t=zn(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(lc)||r===0}}function lc(e){return e==null?!1:Rs(e.type)==="RATE_LIMITED"||/rate limit/i.test(Rs(e.message))}function tR(e,n){return Array.isArray(e)&&e.includes(n)}function rR(e){let n=zn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function zn(e){return oR(e)?e:{}}function oR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rs(e){return typeof e=="string"?e:""}var sR={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},iR=["runner","model","effort","origin","issue","phase","step","heartbeat","started_at"],lR=["phase_index","phase_total","context","eta","added","removed","tokens","tools","reasoning","text"];function ac(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...sR};for(let r of iR){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of lR){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}import{randomUUID as uc}from"node:crypto";import{spawn as uR}from"node:child_process";import{closeSync as pR,mkdirSync as fR,openSync as mR}from"node:fs";import{dirname as hR}from"node:path";import{delimiter as dc,dirname as aR}from"node:path";function dR(e,n=dc){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function cR(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=aR(n);return t===""||t==="."?null:t}function cc(e,n=process.execPath,t=dc){let r=dR(e,t),o=cR(n);return o==null?r.join(t):[o,...r.filter(s=>s!==o)].join(t)}var Yn=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},rr=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function gR(e){if(e==null||e.trim()==="")return null;try{return fR(hR(e),{recursive:!0}),mR(e,"a")}catch{return null}}function yR(e){try{pR(e)}catch{}}function kR(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 Yn(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new Yn("redskilled worker spec args must be an array")}function RR(e){if(e==null)throw new rr("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new rr(e.reason,e)}function fc(e){let{spec:n,admission:t}=e;RR(t),kR(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(n.worker_id??e.workerId??uc()).trim()||uc(),i=e.probes??Ud(r),l=e.openLog===!1?null:gR(n.log_path),a={...n.env??{},PATH:cc(n.env?.PATH??r.PATH,e.execPath??process.execPath)},d=Vd({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??Gd(r),probes:i,pipeOutput:l!==null}),u=(e.spawnFn??uR)(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&&yR(l),u.pid==null)throw u.once("error",()=>{}),new Yn(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${s}`);let f=d.job!=null?bR(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 bR(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: ${pc(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)}: ${pc(i)}. ${o}`}}return{job:s}}function pc(e){return e instanceof Error?e.message:String(e)}import{open as _R,stat as wR}from"node:fs/promises";var xR=16*1024;async function mc(e,n=xR){let t;try{t=(await wR(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let s=await _R(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 SR(o)}function SR(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 WR}from"node:child_process";import{existsSync as BR,readdirSync as FR}from"node:fs";import{dirname as HR,join as bc,resolve as UR}from"node:path";var vR="<version>";function Pe(e,n=[],t){let r=t&&t.trim().length>0?t.trim():vR;return[`npx -y -p ${Me}@${r}`,e,...n].join(" ")}function ne(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 bs(e,n){let t=ne(e),r=ne(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var aP=4*60*60*1e3;ye();ye();import{spawnSync as ER}from"node:child_process";import{mkdir as PR,rm as DR,writeFile as jR}from"node:fs/promises";import{existsSync as OR}from"node:fs";import{homedir as AR}from"node:os";import{dirname as LR,join as _s}from"node:path";var fn="redskilled.service",ws="REDSKILLED_SUPERVISED",TR="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function $R(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||_s(e.HOME?.trim()||AR(),".config");return _s(n,"systemd","user")}function xs(e=process.env){return _s($R(e),fn)}function hc(e,n={}){let t=n.env??process.env,r=$t(n.override??{},n.entryLookup??{}),o=[...r.args,...Ie(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:fn,unitPath:xs(t),command:r.command,args:o,text:IR(r.command,o,e)}}function IR(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${TR}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(NR).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${ws}=1"`,`Environment="REDSKILLED_SESSION=${gc(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
75
- `)}function NR(e){return/[\s"'\\$%]/.test(e)?`"${gc(e)}"`:e}function gc(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function yc(e,n={}){let t=n.writeFile??MR,r=n.run??Ss,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(or("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(or("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function kc(e={}){let n=e.removeFile??CR,t=e.run??Ss,r=xs(e.env??process.env),o=[or("disable",t,["systemctl","--user","disable","--now",fn])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(or("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function Rc(e={}){let n=e.exists??OR,t=e.run??Ss,r=xs(e.env??process.env),o=n(r);return{unitName:fn,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",fn]).status===0,active:o&&t(["systemctl","--user","is-active",fn]).status===0,floor:"auto-spawn"}}function or(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 MR(e,n){await PR(LR(e),{recursive:!0}),await jR(e,n,{encoding:"utf8",mode:420})}async function CR(e){await DR(e,{force:!0})}function Ss(e){let n=ER(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 _c=75,xc=9e5,wc="redskilled-replacement-entry-unresolved",GR="REDSKILLED_NO_REGISTRY_PROBE",Sc="REDSKILLED_BORN_BY_REPLACEMENT";function vc(e=process.env){return e[Sc]==="1"}function Ec(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function Pc(e){let n=e.running.trim();if(Xn(n))return null;let t=e.newest?.trim()??"",r=ne(t),o=ne(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:KR(r.major,e.supervised)}}function KR(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: ${Pe("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 Dc(e){let n=e.running.trim();if(Xn(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||ne(t)===null?{act:"hold",reason:"published-unknown"}:bs(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function Xn(e){let n=e.trim();return ne(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function jc(e=process.env){return e[ws]==="1"}var vs=class extends Error{code=wc;searched;constructor(n,t){super(`${wc}: the published redskilled bundle ${n} exists on no reachable path and the version-pinned dispatch is disabled
65
+ `).filter(Cg).map(Wg)}function Ua(e){let n=new Map;for(let t of e)t.event!=="daemon-stop"&&(t.event==="worker-birth"?n.set(t.worker_id,Ng(t)):n.delete(t.worker_id));return[...n.values()]}function Ng(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 Mg(e){return{...e}}function Cg(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 Wg(e){return{version:1,ts:String(e.ts),event:e.event,worker_id:String(e.worker_id),project_label:we(e.project_label)??"",pid:Number(e.pid??0),workspace_path:we(e.workspace_path)??"",log_path:we(e.log_path),isolated:e.isolated===!0||e.isolated==="true",unit:we(e.unit),memory_high:we(e.memory_high),memory_max:we(e.memory_max),cpu_weight:e.cpu_weight==null||e.cpu_weight===""?null:Number(e.cpu_weight),detail:we(e.detail),exit_code:e.exit_code==null||e.exit_code===""?null:Number(e.exit_code),signal:we(e.signal),reason:we(e.reason)}}function we(e){return e==null||e===""?null:String(e)}function Ga(e){let n=[...e.projects].sort((i,l)=>i.project_label.localeCompare(l.project_label)),t=e.backoffUntilMs??null,r=t!=null&&e.nowMs<t,o=[],s=[];for(let i of n){let l=Math.max(0,e.live[i.project_label]??0),a=Object.prototype.hasOwnProperty.call(e.queue,i.project_label),d=a?e.queue[i.project_label]??null:null,u={project_label:i.project_label,queue_depth:d,target:i.target,live:l};if(r){o.push({...u,outcome:"backing-off",wanted:0,detail:`the host refused a Worker, so no project is asked for one again before ${new Date(t).toISOString()}`});continue}let p=e.birthHaltUntilMs?.[i.project_label];if(p!=null&&e.nowMs<p){o.push({...u,outcome:"birth-halted",wanted:0,detail:`project ${JSON.stringify(i.project_label)} lost 3 Workers in a row inside 60000ms of birth, so it is not asked for another before ${new Date(p).toISOString()} \u2014 a Worker that cannot survive boot will not survive the next one either, and every birth spends host quota shared with every project`});continue}if(d==null){o.push({...u,outcome:"queue-unknown",wanted:0,detail:a?`the last poll produced no depth for project ${JSON.stringify(i.project_label)}, and an absent depth is not a drained queue`:`no poll has counted project ${JSON.stringify(i.project_label)} yet, so it is not asked for a Worker on a depth nobody measured`});continue}if(d===0){o.push({...u,outcome:"queue-drained",wanted:0,detail:`project ${JSON.stringify(i.project_label)} has nothing queued, so it is asked for no Worker`});continue}let f=Math.max(0,Math.min(Math.max(0,i.target),d)-l);if(f===0){o.push({...u,outcome:"at-target",wanted:0,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for none`});continue}o.push({...u,outcome:"asking",wanted:f,detail:`project ${JSON.stringify(i.project_label)} holds ${l} Worker(s) against a target of ${i.target} and a queue of ${d}, so it asks for ${f} more`});for(let m=0;m<f;m+=1)(s[m]??(s[m]=[])).push({project_label:i.project_label,index:l+m,argv:i.argv,workspace_path:i.workspace_path})}return{intents:o,births:s.flat()}}function Ka(e){return{version:1,at:e,requested:0,granted:[],shortfall:0,refusal:null,retry_after:null,projects:[]}}var Vt={shortLifeStreak:0,haltUntilMs:null};function Va(e,n,t){if(n>=6e4)return Vt;let r=e.shortLifeStreak+1;return r<3?{shortLifeStreak:r,haltUntilMs:null}:{shortLifeStreak:r,haltUntilMs:t+6e5}}function qa(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 Qa(e){let n=e.workers.map(Bg),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:Hg({reason:e.reason,socketPath:e.socketPath,daemonVersion:e.daemonVersion,pid:e.pid,held:n.length,projects:t.length,surviving:r.length})}}function za(e){return{version:1,running:!1,stopped:!1,reason:"not-running",socket_path:e,daemon_version:null,pid:null,holding:{workers:[],projects:[]},surviving:[],detail:`no redskilled daemon is answering on ${JSON.stringify(e)}, so there was nothing to stop`}}function Bg(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 Fg(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 Hg(e){let n=`stopping the redskilled daemon (pid ${e.pid}, version ${e.daemonVersion}) on ${JSON.stringify(e.socketPath)}: ${Fg(e.reason)}`;return e.held===0?`${n}; it holds no Workers, so nothing survives the stop`:`${n}; it holds ${Ja(e.held,"Worker")} across ${Ja(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 Ja(e,n){return`${e} ${n}${e===1?"":"s"}`}function Bo(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 Ug,mkdir as Gg,readFile as Kg,rm as Vg,writeFile as qg}from"node:fs/promises";import{dirname as Ya,join as nd}from"node:path";import{tmpdir as Xa}from"node:os";var Jg="redskilled.machine.claim.toon",Qg="REDSKILLED_MACHINE_DIR",zg=8,De=class extends Error{constructor(t,r,o){super(Xg(t,r,o));this.claimPath=t;this.reason=r;this.claim=o;this.name="RedskilledMachineHeldError"}},Za;function td(){return Za??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),uid:typeof process.getuid=="function"?process.getuid():-1},Za}function Yg(e={machineIdHash:"unknown"}){let n=e.env??process.env,t=n[Qg]?.trim();if(t)return t;let o=(e.platform??process.platform)==="win32"?n.PROGRAMDATA?.trim()||Xa():Xa();return nd(o,`redskilled-${e.machineIdHash}`)}function qt(e){return nd(Yg(e),Jg)}function Jt(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??B;async function s(){let a;try{a=await Kg(e,"utf8")}catch(u){if(u.code==="ENOENT"||Fo(u))return;throw u}let d=ey(a);return ny(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 Vg(e,{force:!0}),!0}catch(a){if(Fo(a))return!1;throw a}}return{claimPath:e,read:s,async claim(a){await Gg(Ya(e),{recursive:!0,mode:1023})!=null&&await Ug(Ya(e),1023).catch(()=>{});let u=!1;for(let p=0;p<zg;p+=1){let f=i(a,r());try{return await qg(e,Zg(f),{encoding:"utf8",mode:420,flag:"wx"}),{claimed:!0,reaped:u,claim:f}}catch(g){if(g.code!=="EEXIST"){if(Fo(g))return{claimed:!1,reason:"stale-claim-not-reapable"};throw g}}let m=await s();if(!m){if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable"};u=!0;continue}if(ed(m,a,n.socketPath))return{claimed:!0,reaped:u,claim:m};if(await o(m.pid))return{claimed:!1,reason:"held",claim:m};if(!await l())return{claimed:!1,reason:"stale-claim-not-reapable",claim:m};u=!0}return{claimed:!1,reason:"contended"}},async release(a){let d=await s();return!d||!ed(d,a,n.socketPath)?!1:await l()}}}function rd(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 od(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 Xg(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 Fo(e){let n=e?.code;return n==="EACCES"||n==="EPERM"||n==="EROFS"}function ed(e,n,t){return e.pid===n.pid&&e.start_time===n.startTime&&e.socket_path===t}function Zg(e){return`${W(e,{keyedMapCollapse:!0})}
66
+ `}function ey(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Q(n)}catch{return null}}}function ny(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 ty=["worker_id","slot","workspace_path","log_path"],Ho=class extends Error{constructor(t,r){super(`redskilled cannot expand ${JSON.stringify(`{{${t}}}`)} in ${r}: the facts a birth supplies are ${ty.join(", ")}, and a Worker started with the placeholder left in it is one nobody meant to start`);this.fact=t;this.name="RedskilledLaunchFactError"}},ry=/\{\{([a-z_]+)\}\}/g;function oy(e,n){let t=(i,l)=>i.replace(ry,(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 Ho(d,l)}}),r=e.argv.map((i,l)=>t(i,`argv word ${l}`)),o={};for(let[i,l]of Object.entries(e.env??{}))o[i]=t(l,`env entry ${JSON.stringify(i)}`);let s=e.log_path==null?void 0:t(e.log_path,"the log path");return{argv:r,env:o,...s==null||s===""?{}:{log_path:s}}}function sd(e,n,t){let r=oy(e,n),o=r.log_path??n.log_path,[s,...i]=r.argv;if(s===void 0||s==="")throw new Error(`redskilled cannot start a Worker for project ${JSON.stringify(t.project_label)}: its launch expanded to an argv with no command`);return{worker_id:n.worker_id,project_label:t.project_label,workspace_path:n.workspace_path,...o==null||o===""?{}:{log_path:o},command:s,args:i,env:r.env}}function Uo(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 Go(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 Ko(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 sy=3e5,iy=.5,qo=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 id(e,n){if(n.held!=null)throw new qo(n.held);let t=Vo(e.project_label,"a project label"),r=Vo(e.selector,"a selector"),o=Uo(e.argv,t),s=Ko(e.env,t),i=Go(e.log_path,t),l=Vo(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??sy;if(!Number.isFinite(a)||a<=0)throw new Error(`redskilled needs a positive renewal window to register project ${JSON.stringify(t)}, not ${JSON.stringify(e.renew_within_ms)}: a registration that lapses on arrival is a poll nobody asked for`);let d=Date.parse(n.now);if(!Number.isFinite(d))throw new Error(`redskilled needs an instant to date a registration, not ${JSON.stringify(n.now)}`);return{version:1,project_label:t,selector:r,argv:o,workspace_path:l,env:s,...i==null?{}:{log_path:i},target:e.target,registered_at:new Date(d).toISOString(),renew_within_ms:a,renew_by:new Date(d+a).toISOString(),renewed_at:new Date(d).toISOString(),renewals:0,session_renewals:0,launch_revision:0}}var Qt=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 ld(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:Uo(n.launch.argv,e.project_label),env:Ko(n.launch.env,e.project_label),launch_revision:(e.launch_revision??0)+1},s=n.launch==null?e.log_path:Go(n.launch.log_path,e.project_label),{log_path:i,...l}=e;return{...l,...s==null?{}:{log_path:s},...o,renew_within_ms:r,renewed_at:new Date(t).toISOString(),renew_by:new Date(t+r).toISOString(),renewals:e.renewals+1,session_renewals:(e.session_renewals??e.renewals)+1}}function Jo(e,n){let t=Date.parse(n.now);if(!Number.isFinite(t))throw new Error(`redskilled needs an instant to sustain a registration, not ${JSON.stringify(n.now)}`);let r=JSON.stringify(e.project_label),o=Math.max(0,n.liveWorkers??0),s=n.queue,i=s!=null&&s.outcome==="counted"?s.depth:null,l=i!=null&&i>0?"open-work":o>0?"live-worker":null;if(l==null){let a=i===0?"drained":"uncounted";return{registration:e,verdict:a,detail:a==="drained"?`project ${r} has nothing queued and no Worker running, so nothing holds its registration up and it lapses at ${e.renew_by}`:`no poll counted project ${r}, and an uncounted queue never sustains a registration \u2014 it stands on its own deadline of ${e.renew_by}`}}return{registration:{...e,renew_by:new Date(t+e.renew_within_ms).toISOString(),sustained_at:new Date(t).toISOString(),sustains:(e.sustains??0)+1,sustained_by:l,renewals:e.renewals+1,session_renewals:e.session_renewals??e.renewals},verdict:l,detail:l==="open-work"?`project ${r} has ${i} item(s) queued, so its registration stands past its window`:`project ${r} holds ${o} Worker(s), so its registration stands past its window`}}function ly(e,n){let t=Date.parse(e.renew_by);return Number.isFinite(t)?n>=t:!1}function ad(e,n){let t=Date.parse(e.renewed_at??e.registered_at),r=s=>Number.isFinite(s)&&n-s<=e.renew_within_ms*iy;if(r(t))return"renewing";let o=e.sustained_at==null?Number.NaN:Date.parse(e.sustained_at);return r(o)?"self-renewing":"running-on"}function dd(e,n){let t=[],r=[];for(let o of e)(ly(o,n)?r:t).push(o);return{standing:t,lapsed:r}}function Qo(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.version===1&&typeof n.project_label=="string"&&typeof n.selector=="string"&&Array.isArray(n.argv)&&n.argv.every(t=>typeof t=="string")&&typeof n.workspace_path=="string"&&Number.isInteger(n.target)&&typeof n.registered_at=="string"&&typeof n.renew_within_ms=="number"&&typeof n.renew_by=="string"&&(n.renewed_at===void 0||typeof n.renewed_at=="string")&&(n.renewals===void 0||Number.isInteger(n.renewals))&&(n.session_renewals===void 0||Number.isInteger(n.session_renewals))&&(n.env===void 0||ay(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 ay(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(n=>typeof n=="string")}function Vo(e,n){if(typeof e!="string"||e==="")throw new Error(`redskilled needs ${n} to register a project, not ${JSON.stringify(e)}`);return e}var dy={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 cd(e){return`worker-${e}`}function ud(e){let n=dy[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 pd(e){return e==="single-object"?"rest":"graphql"}function $(e,n,t,r,o){return{key:e,kind:"read",cardinality:n,surface:o??pd(n),budget:t,...o?{only:o}:{},why:r}}function V(e,n,t,r){return{key:e,kind:"write",cardinality:"single-object",surface:n,budget:t,why:r}}var fd=[$("issue view","single-object","rest","one issue by number; REST answers it in one request against the idle pool"),$("pr view","single-object","rest","one pull request by number, polled per Worker per iteration"),$("repo view","single-object","rest","one repository's own metadata"),$("run view","single-object","rest","one Actions run; the Actions API has no GraphQL surface either way"),$("release view","single-object","rest","one release by tag"),$("pr diff","single-object","rest","one pull request's diff, served by a REST media type"),$("issue list","multi-node","graphql","a connection of issues; one GraphQL query beats N REST pages"),$("pr list","multi-node","graphql","a connection of pull requests; one GraphQL query beats N REST pages"),$("pr checks","multi-node","graphql","every check context on one commit, which is a connection, not an object"),$("release list","multi-node","rest","Releases have no GraphQL connection gh reads; REST pages them","rest"),$("run list","multi-node","rest","the Actions API has no GraphQL surface, so a listing draws the request pool","rest"),$("label list","multi-node","graphql","a connection of labels inside one repository"),$("issue list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),$("pr list (search)","multi-node","search","`--search` routes the listing through the search connection, metered 30/min"),$("search issues","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),$("search prs","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),$("search repos","multi-repository","search","gh's `search` drives the REST search endpoints, metered 30/min","rest"),$("api graphql","multi-node","graphql","the caller wrote the query; `gh api graphql` is GraphQL by construction"),$("api rest","single-object","rest","any `gh api <path>` that is not `graphql` is a REST request"),V("issue create","graphql","graphql","gh files an issue with the createIssue mutation \u2014 an exhausted GraphQL pool blocks filing"),V("issue edit","graphql","graphql","gh edits labels, body and assignees with GraphQL mutations"),V("issue close","graphql","graphql","gh closes with the closeIssue mutation"),V("issue reopen","graphql","graphql","gh reopens with the reopenIssue mutation"),V("issue comment","rest","rest","gh POSTs to `repos/{o}/{r}/issues/{n}/comments`, a REST request"),V("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation"),V("pr create","rest","rest","gh POSTs to `repos/{o}/{r}/pulls`, a REST request"),V("pr comment","rest","rest","a pull request comment is an issue comment: the same REST POST"),V("pr merge","graphql","graphql","gh merges with the mergePullRequest mutation"),V("pr close","graphql","graphql","gh closes with a GraphQL mutation"),V("pr edit","graphql","graphql","gh edits with GraphQL mutations"),V("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation"),V("pr update-branch","rest","rest","gh PUTs `repos/{o}/{r}/pulls/{n}/update-branch`, a REST request"),V("label create","rest","rest","gh POSTs `repos/{o}/{r}/labels`, a REST request")],cy=new Map(fd.map(e=>[e.key,e]));function md(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 zo(e){let n=md(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 zt=class extends Error{name="UnclassifiedGithubOperationError";operation;args;constructor(n){let t=zo(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 hd(e){return cy.get(zo(e))??null}function gd(e){let n=hd(e);if(!n)throw new zt(e);return n}function Yo(e){return gd(e).surface}var kd="rate_limit",Rd={rest:"core",graphql:"graphql",search:"search"},xe=["rest","graphql","search"];function er(e,n){return{version:1,origin:"asked",outcome:"unanswered",source:"GET /rate_limit",asked_at:e,request_count:0,pools:{rest:null,graphql:null,search:null},unreported_pools:[...xe],detail:n??"no balance has been asked for yet, so none is known"}}var Zo=15e3,un=.15,Xt=[{at_or_below_fraction:0,every_ms:Zo,why:"spent: the only event that still matters is the reset, so watch for it"},{at_or_below_fraction:un,every_ms:3e4,why:"inside the reserved band: the posture can change between two calls"},{at_or_below_fraction:.5,every_ms:12e4,why:"below half: tightening, because the band is now reachable inside one window"},{at_or_below_fraction:1,every_ms:6e5,why:"above half: rare, because nothing this balance decides is anywhere close"}],Xo=2;function bd(e,n){let t=yd(e),r=yd(t.resources),o={rest:null,graphql:null,search:null},s=[];for(let l of xe){let a=Rd[l],d=r[a],u=fy(l,a,d);o[l]=u,u==null&&s.push(l)}let i=xe.length-s.length;return{version:1,origin:"asked",outcome:i>0?"asked":"unanswered",source:"GET /rate_limit",asked_at:n.askedAt,request_count:1,pools:o,unreported_pools:s,detail:i>0?`the token's own answer for ${i} of ${xe.length} pools`:"the answer carried no pool this repo budgets, so nothing about the token is known"}}async function es(e){try{let n=await e.transport();return bd(n,{askedAt:e.now})}catch(n){let t=n instanceof Error?n.message:String(n);return{...er(e.now,`the balance ask failed before the token answered: ${t}`),request_count:1}}}function ns(e){let n=null;for(let t of xe){let r=e.pools[t];r!=null&&(n==null||r.fraction<n.fraction)&&(n=r)}return n}function nr(e,n){let t=ns(e);if(t==null)return Zt(un).every_ms;let r=Zt(t.fraction);if(t.remaining>0)return r.every_ms;let o=wd(n.now,t.reset_at);return o==null?r.every_ms:Math.max(Zo,Math.min(r.every_ms,o))}function ts(e,n=un){return Math.ceil(e.limit*n)}function _d(e,n,t=un){let r=e.pools[n];return r==null?"unknown":r.remaining<=0?"spent":r.remaining<ts(r,t)?"reserved":"open"}function rs(e){let n=e.reservedFraction??un,t=e.balance;if(t==null)return{version:1,origin:"asked",outcome:"unanswered",asked_at:null,age_ms:null,threshold_ms:Zt(n).every_ms*Xo,stale:!1,posture:"unknown",reserved_fraction:n,next_poll_ms:Zt(n).every_ms,pools:[],unreported_pools:[...xe],reason:"this daemon has asked for no balance, so the token's budget is unknown rather than full"};let r=nr(t,{now:e.now}),o=e.stalenessMs??r*Xo,s=wd(t.asked_at,e.now),i=t.outcome==="asked"&&(s==null||s>o),l=xe.map(u=>t.pools[u]).filter(u=>u!=null),a=py(t,n),d=ns(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`:uy(a,d,t,n)}}function os(e){if(!is(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 uy(e,n,t,r){if(n==null)return t.detail;let o=ts(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 py(e,n){let t="unknown";for(let r of xe){if(e.pools[r]==null)continue;let o=_d(e,r,n);if(o==="spent")return"spent";(o==="reserved"||t==="unknown")&&(t=o)}return t}function Zt(e){for(let n of Xt)if(e<=n.at_or_below_fraction)return n;return Xt[Xt.length-1]}function fy(e,n,t){if(!is(t))return null;let r=Yt(t.limit),o=Yt(t.remaining),s=Yt(t.used),i=Yt(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 ss(e){let n=e.origin??"https://api.github.com",t=e.fetchImpl??fetch;return async()=>{let r=await t(`${n}/${kd}`,{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 wd(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 Yt(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):null}function yd(e){return is(e)?e:{}}function is(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dd(e){return{generated_at:e.now,hour:xd("hour",36e5,e),day:xd("day",864e5,e)}}function Kn(e,n,t){let r=Gn(t.now),o=t.retentionMs??864e5,s=t.limit??8192,i=e.filter(l=>{let a=Gn(n(l));return a==null?!1:r==null||r-a<=o});return i.length<=s?i:i.slice(i.length-s)}function xd(e,n,t){let r=Gn(t.now),o=r==null?null:r-n,s=e==="hour"?"1h":"24h",i=t.observations.map(p=>({observation:p,at:Gn(p.observed_at)})).filter(p=>p.at!=null&&Ed(p.at,o,r)).sort((p,f)=>p.at-f.at),l=t.outcomes.map(p=>Gn(p.ts)).filter(p=>p!=null&&Ed(p,o,r)),a=Sd(i,p=>p.tokens,"tokens",s),d=Sd(i,p=>p.tools,"tools",s),u=[];return i.length===0?u.push("worker-vitals"):(a.samples===0&&u.push("worker-vitals.tokens"),d.samples===0&&u.push("worker-vitals.tools")),l.length===0&&u.push("worker-outcomes"),{window:e,window_ms:n,from:o==null?t.now:new Date(o).toISOString(),to:t.now,tokens_per_min:a,tools_per_min:d,issues_per_hour:my(l.length,n,s),runner_share:vd("runner",i,p=>p.runner,s),model_share:vd("model",i,p=>p.model,s),unavailable:u}}function Sd(e,n,t,r){let o=new Map,s=0;for(let d of e){let u=n(d.observation);if(u==null||!Number.isFinite(u))continue;s+=1;let p=o.get(d.observation.worker_id)??[];p.push({at:d.at,count:u}),o.set(d.observation.worker_id,p)}if(s===0)return{value:null,absent_reason:`no Worker published a ${t} count in the last ${r}`,samples:0};let i=0,l=null,a=null;for(let d of o.values()){if(d.length<2)continue;for(let f=1;f<d.length;f++){let m=d[f-1],g=d[f];m==null||g==null||(i+=Math.max(0,g.count-m.count))}let u=d[0],p=d[d.length-1];u!=null&&(l=l==null?u.at:Math.min(l,u.at)),p!=null&&(a=a==null?p.at:Math.max(a,p.at))}return l==null||a==null||a<=l?{value:null,absent_reason:`the last ${r} holds one sample of ${t} per Worker, and one instant spans no rate`,samples:s}:{value:i/((a-l)/6e4),absent_reason:null,samples:s}}function my(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 vd(e,n,t,r){let o=new Map;for(let d of n){let u=t(d.observation);u!=null?o.set(d.observation.worker_id,u):o.has(d.observation.worker_id)||o.set(d.observation.worker_id,null)}let s=new Map,i=0,l=0;for(let d of o.values()){if(d==null){l+=1;continue}i+=1,s.set(d,(s.get(d)??0)+1)}let a=[...s.entries()].map(([d,u])=>({key:d,worker_count:u,share:u/i})).sort((d,u)=>u.worker_count-d.worker_count||d.key.localeCompare(u.key));return{dimension:e,attributed_workers:i,unattributed_workers:l,shares:a,absent_reason:a.length>0?null:o.size===0?`no Worker was observed in the last ${r}`:`no Worker published a ${e} in the last ${r}`}}function Ed(e,n,t){return n==null||t==null?!0:e>=n&&e<=t}function Gn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function jd(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.generated_at=="string"&&Pd(n.hour)&&Pd(n.day)}function Pd(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"&&ls(n.tokens_per_min)&&ls(n.tools_per_min)&&ls(n.issues_per_hour)&&Array.isArray(n.unavailable)}function ls(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 hy}from"node:child_process";import{existsSync as gy,readFileSync as tr,readdirSync as yy}from"node:fs";import{dirname as ky,join as Fe}from"node:path";function Vn(e){let n=Un(e),t=[["MemoryMax",n.memory_max],["MemoryHigh",n.memory_high]];for(let[r,o]of t){if(o==null)continue;let s=cn(o);return s==null?null:{name:r,declared:o,bytes:s}}return null}function Od(e){let n=[],t=[];for(let r of e.workers){let o=Vn(r);if(o==null){t.push({worker_id:r.worker_id,reason:(Un(r).memory_max??Un(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(Ry(r,o,s))}}return{terminations:n,unenforceable:t}}function Ry(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 by=4096;function Ad(e,n={}){let t=n.platform??process.platform,r={rss:{},cpu_seconds:{},sources:{}};if(e.length===0)return r;let o={},s={},i={},l=wy(e,t,n);for(let[p,f]of l){let m=vy(f);m!=null&&(o[p]=m.memoryBytes,m.cpuSeconds!=null&&(s[p]=m.cpuSeconds),i[p]="cgroup")}let a=e.filter(p=>i[p.worker_id]==null);if(a.length===0)return{rss:o,cpu_seconds:s,sources:i};let d=Dy(t,n);if(d.size===0)return{rss:o,cpu_seconds:s,sources:i};let u=new Map;for(let p of d.values()){let f=u.get(p.ppid);f?f.push(p.pid):u.set(p.ppid,[p.pid])}for(let p of a){if(!d.has(p.pid))continue;let f=0,m=0,g=[p.pid],_=new Set;for(;g.length>0;){let k=g.pop();if(_.has(k))continue;_.add(k);let w=d.get(k);if(w){f+=w.rssBytes,m+=w.cpuSeconds;for(let O of u.get(k)??[])g.push(O)}}o[p.worker_id]=f,s[p.worker_id]=m,i[p.worker_id]="process-tree"}return{rss:o,cpu_seconds:s,sources:i}}var _y="/sys/fs/cgroup";function wy(e,n,t){let r=new Map;if(!(t.cgroupRoot!=null)&&n!=="linux")return r;let s=t.cgroupRoot??_y,i=e.filter(a=>a.unit!=null&&a.unit!=="");if(i.length===0)return r;let l=xy(s,t);for(let a of i)for(let d of l){let u=Fe(d,a.unit);if(gy(Fe(u,"memory.current"))){r.set(a.worker_id,u);break}}return r}function xy(e,n){let t=n.selfCgroupPath??Sy(),r=[],o=l=>{r.includes(l)||r.push(l)},s=t;for(;s!=null&&s!==""&&s!=="/"&&s!==".";){o(Fe(e,s));let l=ky(s);if(l===s)break;s=l}o(e);let i=n.uid??process.getuid?.();return i!=null&&o(Fe(e,"user.slice",`user-${i}.slice`,`user@${i}.service`,"app.slice")),r}function Sy(){try{for(let e of tr("/proc/self/cgroup","utf8").split(`
67
+ `))if(e.startsWith("0::"))return e.slice(3).trim()}catch{}return null}function vy(e){let n;try{n=tr(Fe(e,"memory.current"),"utf8")}catch{return null}let t=Number(n.trim());return!Number.isFinite(t)||t<0?null:{memoryBytes:t,cpuSeconds:Ey(e)}}function Ey(e){let n;try{n=tr(Fe(e,"cpu.stat"),"utf8")}catch{return null}return Py(n)}function Py(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 Dy(e,n){return n.procRoot!=null||e==="linux"?$y(n.procRoot??"/proc"):n.psTable!=null||e==="darwin"?Ly(jy(n.psTable)):new Map}function jy(e){try{return(e??Oy)()}catch{return""}}function Oy(){return hy("ps",["-axo","pid=,ppid=,rss=,time="],{encoding:"utf8",maxBuffer:16*1024*1024})}var Ay=1024;function Ly(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=Ty(r[3]);l!=null&&n.set(o,{pid:o,ppid:s,rssBytes:i*Ay,cpuSeconds:l})}return n}function Ty(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 $y(e){let n=new Map,t;try{t=yy(e)}catch{return n}for(let r of t){if(!/^\d+$/.test(r))continue;let o;try{o=tr(Fe(e,r,"stat"),"utf8")}catch{continue}let s=Ny(o);s&&n.set(s.pid,{pid:s.pid,ppid:s.ppid,rssBytes:s.rssPages*by,cpuSeconds:s.cpuTicks/Iy})}return n}var Iy=100;function Ny(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 My=["api","graphql"],Cy=Yo(My);function Wy(e,n="https://api.github.com"){return e==="graphql"?`${n}/graphql`:n}var Ld=100,cs=6e4,By=2*cs,Fy=7*24*60*60*1e3,as=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 us(e,n){for(let t of e)if(t.token_ref!=null&&t.token_ref!==n)throw new as(t.project_label,t.token_ref,n)}function Hy(e,n={now:new Date(0).toISOString()}){Ky(e);let t=n.closedWindowMs??Fy,r=Date.parse(n.now);if(!Number.isFinite(r))throw new Error(`redskilled activity fetch needs an instant, not ${JSON.stringify(n.now)}`);let o=new Date(r-Math.max(0,t)).toISOString(),s=e.map((a,d)=>({alias:`r${d}`,search_alias:`c${d}`,project:a}));return{query:["query RedskilledRepositoryActivity {"," rateLimit { cost remaining resetAt }",...s.flatMap(({alias:a,search_alias:d,project:u})=>{let p=JSON.stringify(u.owner),f=JSON.stringify(u.name),m=JSON.stringify(`repo:${u.owner}/${u.name} is:closed closed:>=${o}`);return[` ${a}: repository(owner: ${p}, name: ${f}) {`," nameWithOwner"," open_pull_requests: pullRequests(states: OPEN) { totalCount }"," open_issues: issues(states: OPEN) { totalCount }"," }",` ${d}: search(query: ${m}, type: ISSUE, first: 1) { issueCount }`]}),"}"].join(`
70
+ `),aliases:s,closed_since:o}}function Uy(e,n,t){let r=pn(n),o=pn(r.data),s=Array.isArray(r.errors)?r.errors.map(pn):[],i=Vy(o.rateLimit,s),l=e.aliases.map(({alias:a,search_alias:d,project:u})=>{let p=u.owner+"/"+u.name,f=o[a],m=s.find(g=>Td(g.path,a)||Td(g.path,d));if(rr(f)){let g=$d(f.open_pull_requests),_=$d(f.open_issues),k=qy(o[d]);if(g!=null&&_!=null&&k!=null)return{project_label:u.project_label,repository:p,outcome:"counted",counts:{open_pull_requests:g,open_issues:_,recently_closed:k},detail:`counted ${p} for project ${JSON.stringify(u.project_label)}`}}return i.exhausted||Wd(m)?{project_label:u.project_label,repository:p,outcome:"rate-limited",counts:null,detail:`the host token's quota was spent before ${p} answered, so this project has no counts rather than zero counts${i.reset_at==null?"":`; the quota resets at ${i.reset_at}`}`}:{project_label:u.project_label,repository:p,outcome:"unreachable",counts:null,detail:`${p} is not reachable with the host token: ${ds(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 Gy(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 Gy(e.now);us(e.projects,e.hostTokenRef);let n=Hy(e.projects,{now:e.now,closedWindowMs:e.closedWindowMs});try{let t=await e.transport(n.query);return Uy(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 Nd(e){let n=e.stalenessMs??By,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 Md(e){if(!rr(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)&&rr(n.rate_limit)&&Array.isArray(n.projects)&&typeof n.reason=="string"}function Cd(e){let n=e.endpoint??Wy(Cy),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 Ky(e){if(e.length===0)throw new Error("redskilled activity fetch needs at least one registered project");if(e.length>Ld)throw new Error(`redskilled activity fetch spans at most ${Ld} 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 Vy(e,n){let t=pn(e),r=typeof t.remaining=="number"&&Number.isFinite(t.remaining)?t.remaining:null,o=typeof t.resetAt=="string"?t.resetAt:null,s=n.some(Wd),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 Wd(e){if(e==null)return!1;let n=ds(e.type),t=ds(e.message);return n==="RATE_LIMITED"||/rate limit/i.test(t)}function Td(e,n){return Array.isArray(e)&&e.includes(n)}function $d(e){let n=pn(e);return Number.isInteger(n.totalCount)?n.totalCount:null}function qy(e){let n=pn(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function pn(e){return rr(e)?e:{}}function rr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ds(e){return typeof e=="string"?e:""}var Jy=3e4,Qy=4,zy=["logs","vitals","display"];function Bd(e,n){if(n===void 0)return e;let t=zy.filter(o=>n[o]!==!0);if(t.length===0)return e;let r=o=>n[o]===!0;return{...e,workers:e.workers.map(o=>({...o,...r("vitals")?{}:{vitals:Yy,budget:{...o.budget,used_bytes:null,used_fraction:null}},...r("logs")?{}:{log:Xy},...r("display")?{}:{display:null,display_published_at:null}})),withheld:t}}var Yy={rss_bytes:null,sampled_at:null,age_ms:null,fresh:!1,rss_source:null},Xy={last_line:null,published_at:null,source:null};function Fd(e){let n=e.stalenessMs??Jy,t=qn(e.now),r=e.sampledAt==null?null:qn(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=>nk(f,{rss:e.rss,sampledAt:e.sampledAt,ageMs:o,sampleFresh:s,nowMs:t,log:e.logLines?.[f.worker_id],display:e.displays?.[f.worker_id],state:i.has(f.worker_id)?"reattached":"running"})),a=l.filter(f=>f.vitals.rss_bytes==null).map(f=>f.worker_id).sort(),d=l.length-a.length,u=l.reduce((f,m)=>f+(m.vitals.rss_bytes??0),0),p=Kt(e.hostState.workers);return{version:1,generated_at:e.now,daemon:{pid:e.hostState.pid,daemon_version:e.hostState.daemon_version,protocol_version:e.hostState.protocol_version,started_at:e.hostState.started_at,machine_id_hash:e.hostState.machine_id_hash,session_key_hash:e.hostState.session_key_hash},staleness:sk({sampledAt:e.sampledAt,ageMs:o,threshold:n,workerCount:l.length,measuredCount:d,unmeasured:a}),host:{worker_count:l.length,project_count:e.hostState.projects.length,ceiling:e.ceiling,consumption:p,budget_accounting:e.hostState.budget_accounting,observed_rss_bytes:u,measured_worker_count:d,ceiling_used_fraction:e.ceiling.memory_bytes==null||e.ceiling.memory_bytes<=0?null:p.memory_bytes/e.ceiling.memory_bytes},projects:ok(l),known_projects:rk(e.hostState),registered_projects:(e.hostState.registrations??[]).map(f=>f.project_label).sort((f,m)=>f.localeCompare(m)),lapsed_projects:(e.hostState.lapsed_registrations??[]).map(f=>({project_label:f.project_label,at:f.at,reason:f.detail})),workers:l,github_balance:rs({balance:e.githubBalance??null,now:e.now,...e.reservedFraction===void 0?{}:{reservedFraction:e.reservedFraction}}),repository_activity:Nd({activity:e.repositoryActivity??null,now:e.now,stalenessMs:e.activityStalenessMs}),...e.deaths===void 0?{}:{deaths:Zy(e.deaths,e.recentDeathLimit??Qy)},engine:ek(e.hostState),...e.metrics===void 0?{}:{metrics:e.metrics}}}function Zy(e,n){let t=[...e].sort((o,s)=>(qn(s.ts)??0)-(qn(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 ek(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 nk(e,n){let t=n.rss[e.worker_id],r=typeof t=="number"&&Number.isFinite(t)?t:null,o=Vn(e),s=e.budget?.memory_max??e.budget?.memory_high??null,i=qn(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:tk(n.log),display:n.display?.display??null,display_published_at:n.display?.published_at??null}}function tk(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 rk(e){let n=new Set;for(let t of e.registrations??[])n.add(t.project_label);for(let t of e.projects)n.add(t.project_label);for(let t of e.lapsed_registrations??[])n.add(t.project_label);return[...n].sort((t,r)=>t.localeCompare(r))}function ok(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 sk(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 qn(e){let n=Date.parse(e);return Number.isFinite(n)?n:null}function ps(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e,t=n.daemon,r=n.staleness,o=n.host;return n.version===1&&typeof n.generated_at=="string"&&t!=null&&typeof t=="object"&&Number.isInteger(t.pid)&&typeof t.daemon_version=="string"&&typeof t.protocol_version=="number"&&r!=null&&typeof r=="object"&&typeof r.stale=="boolean"&&typeof r.threshold_ms=="number"&&Array.isArray(r.unmeasured_workers)&&o!=null&&typeof o=="object"&&Number.isInteger(o.worker_count)&&Number.isInteger(o.project_count)&&typeof o.observed_rss_bytes=="number"&&Array.isArray(n.projects)&&Array.isArray(n.workers)&&(n.known_projects===void 0||Array.isArray(n.known_projects)&&n.known_projects.every(s=>typeof s=="string"))&&(n.registered_projects===void 0||Array.isArray(n.registered_projects)&&n.registered_projects.every(s=>typeof s=="string"))&&(n.lapsed_projects===void 0||Array.isArray(n.lapsed_projects)&&n.lapsed_projects.every(ik))&&(n.repository_activity===void 0||Md(n.repository_activity))&&(n.github_balance===void 0||os(n.github_balance))&&(n.deaths===void 0||lk(n.deaths))&&(n.engine===void 0||ak(n.engine))&&(n.metrics===void 0||jd(n.metrics))}function ik(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.project_label=="string"&&typeof n.at=="string"&&typeof n.reason=="string"}function lk(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 ak(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 Hd={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 fs(e,n){let t=e.display?.started_at;if(t!=null&&t!==""){let r=Date.parse(t),o=Date.parse(n);if(Number.isFinite(r)&&Number.isFinite(o))return Math.max(0,o-r)}return e.uptime_ms}var U=e=>`\x1B[${e}m`,dk=U("48;2;114;47;55"),ck=U("48;2;88;36;42"),uk=U("38;2;255;255;255"),pk=U("38;2;201;150;158"),ms=U("38;2;255;214;214"),hs=U("39"),Jn=U("38;2;224;138;148"),gs=U("38;2;240;110;120"),ys=U("38;2;255;214;214"),ks=U("38;2;146;84;94"),Rs=U("38;2;255;95;95"),bs=U("49"),fn=U("0"),_s=U("1"),ws=U("22");var fk=/\x1b\[[0-9;]*m/g,mk=/(\x1b\[[0-9;]*m)/,hk=/^\x1b\[[0-9;]*m$/;function Ud(e){return e.replace(fk,"")}function gk(e){return e.slice(2,-1).split(";").every(t=>t===""||Number(t)===0)}function ue(e){return[...Ud(e)].length}function q(e,n){if(n<=0)return"";if(ue(e)<=n)return e;if(n===1)return"\u2026";let t=n-1,r=0,o=!1,s="";for(let i of e.split(mk))if(i!==""){if(hk.test(i)){s+=i,o=!gk(i);continue}for(let l of i){if(r===t)return`${s}\u2026${o?fn:""}`;s+=l,r+=1}}return`${s}\u2026${o?fn:""}`}function Qn(e,n){return e+" ".repeat(Math.max(0,n-ue(e)))}function xs(e){let n=e.toLowerCase();for(let t of["opus","sonnet","haiku","fable"])if(n.includes(t))return t;return e}function te(e){if(!Number.isFinite(e)||e<=0)return"0B";let n=["B","K","M","G","T"],t=e,r=0;for(;t>=1024&&r<n.length-1;)t/=1024,r+=1;return`${t>=100||r===0?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")}${n[r]}`}function zn(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 Yn(e){if(!Number.isFinite(e))return"\u2014";if(e>=10)return zn(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 Xn(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 Ss(e){if(e==null)return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n===""?null:n}var Zn="!unregistered",et="!lapsed",nt="\u21E1",He="\u2020",mn="\u25D0",hn="\u25EF",vs="\u21B3",Es="redskilled unreachable \u2014 Worker state unknown";function gn(e,n){return n.mode==="global"?e.workers:n.project==null?[]:e.workers.filter(t=>t.project_label===n.project)}function or(e,n){return n.mode==="global"?e.projects:e.projects.filter(t=>t.project_label===n.project)}function tt(e,n){return n==null?"unresolved":e.known_projects==null?"matched":e.known_projects.includes(n)?e.registered_projects==null||e.registered_projects.includes(n)?"matched":e.lapsed_projects?.some(t=>t.project_label===n)===!0?"lapsed":"name-only":"unregistered"}function Ps(e){let n=[];return e.workers.length>0&&e.workers.length<=e.maxWorkers&&n.push("workers"),e.mode==="global"&&e.projects.length>0&&e.projects.length<=e.maxProjects&&n.push("projects"),n.push("host"),n}var je=["wid","run","org","iss","bar","phase","elapsed","eta","hb","loc","tks","ctx","tls","rsn","txt"],pe={mode:"local",project:null,maxWidth:200,maxRows:16},yk=" ",Gd="\u2588",kk="\u25B6",Rk="\u2717",bk="\u2591",_k=new Set(["gate","push-pr","merge","cascade"]),wk=new Set(["requeue"]);function yn(e,n=pe){let t=tt(e,n.project),r=gn(e,n),o=r.slice(0,Math.max(0,Math.floor(n.maxRows))),s=o.map(p=>Ds(p,n,e.generated_at)),i=jk(s),l=o.map((p,f)=>({worker_id:p.worker_id,project_label:p.project_label,mine:n.project!=null&&p.project_label===n.project,cells:s[f],line:q(Ok(s[f],i),n.maxWidth)})),a=xk(e,n,r,t),d=r.length-o.length,u=[a.line,...l.map(p=>p.line)];return d>0&&u.push(q(`\u2026 ${d} more Worker(s) \u2014 the row budget is short, not the host`,n.maxWidth)),u.push(...vk(e,n)),u.push(...Sk(e,n)),{version:1,generated_at:e.generated_at,mode:n.mode,project:n.project,columns:je,header:a,rows:l,lines:u,hidden_row_count:Math.max(0,d),stale:e.staleness.stale}}function Ds(e,n,t){let r=e.display??Hd,o=[r.runner,r.model==null?null:xs(r.model),r.effort].filter(l=>!!l).join(" "),s=r.phase!=null&&_k.has(r.phase),i=s||r.origin!=null&&wk.has(r.origin);return{wid:n.mode==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id,run:o===""?"":`run=${o}`,org:s?"org=landing":r.origin==null?"":`org=${r.origin}`,iss:r.issue==null?"":`iss=${r.issue}`,bar:Kd(r),phase:[r.phase,r.step].filter(l=>!!l).join("\xB7"),elapsed:Xn(fs(e,t)),eta:r.eta==null?"":`eta=${Xn(r.eta*1e3)}`,hb:`hb=${r.heartbeat??"?"}`,loc:i?"":Dk(r.added,r.removed),tks:i||r.tokens==null?"":`tks=${zn(r.tokens)}`,ctx:r.context==null?"":`ctx=${zn(r.context)}`,tls:i||r.tools==null?"":`tls=${r.tools}`,rsn:i||r.reasoning==null?"":`rsn=${r.reasoning}`,txt:i||r.text==null?"":`txt=${r.text}`}}function 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 Gd.repeat(Math.floor(n));let o=e.failed?Rk:kk;return`${Gd.repeat(r)}${o}${bk.repeat(Math.floor(n)-r-1)}`}function xk(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=Pk(t),a=o?.repository??n.project,d=e.engine??null,u=d?.running_version??e.daemon.daemon_version,p=e.deaths??null,f=e.metrics??null,m=[`\xBB ${a??"host"} v${u}${d!=null&&d.current===!1?nt:""}`];(r==="unregistered"||r==="name-only")&&m.push(Zn),r==="lapsed"&&m.push(et),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(Ek(i)),s.open_pull_requests!=null&&m.push(`prs=${s.open_pull_requests}`),s.recently_closed!=null&&m.push(`cpr=${s.recently_closed}`),s.open_issues!=null&&m.push(`iss=${s.open_issues}`),s.stale&&m.push("!counts stale");let g=f==null?null:Vd(f.hour);if(g!=null&&m.push(g),p!=null&&p.count>0&&p.latest!=null&&m.push(`${He}${p.count} ${p.latest.sender_class}`),e.staleness.stale){let w=e.staleness.age_ms;m.push(w==null?"!unmeasured":`!stale ${Math.round(w/1e3)}s`)}let _=m.join(" \xB7 "),k=g!=null&&ue(_)>n.maxWidth?m.filter(w=>w!==g).join(" \xB7 "):_;return{repo:a,project:n.project,project_match:r,version:u,engine:d,deaths:p,metrics:f,model:l,windows:i,counts:s,stale:e.staleness.stale,age_ms:e.staleness.age_ms,line:q(k,n.maxWidth)}}function Vd(e){let n=[];e.tokens_per_min.value!=null&&n.push(`tk/m=${Yn(e.tokens_per_min.value)}`),e.tools_per_min.value!=null&&n.push(`tl/m=${Yn(e.tools_per_min.value)}`),e.issues_per_hour.value!=null&&n.push(`iss/h=${Yn(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 Sk(e,n){let t=e.github_balance;if(t==null)return[];if(t.posture!=="spent"&&t.posture!=="reserved")return[];let r=t.posture==="spent"?hn:mn,o=t.age_ms==null?"":` (${Math.round(t.age_ms/1e3)}s ago)`;return[q(`${r} github budget ${t.posture}${o} \u2014 ${t.reason}`,n.maxWidth)]}function vk(e,n){let t=e.deaths;if(t==null||t.count<=0)return[];let r=t.recent.map(s=>q(`${He} ${s.kind} ${s.id} pid=${s.pid} ${s.sender_class}/${s.confidence} phase=${s.last_phase}`+(s.signal==null?"":` signal=${s.signal}`)+(s.evidence==null?"":` \u2014 ${s.evidence}`),n.maxWidth)),o=t.count-t.recent.length;return o>0&&r.push(q(`\u2026 ${o} more posed death(s) \u2014 the lane holds them all`,n.maxWidth)),r}function Ek(e){if(e.memory_ceiling_bytes==null||e.memory_ceiling_bytes<=0)return`mem=${te(e.memory_used_bytes)}`;let n=e.memory_used_fraction==null?"":` ${Math.round(e.memory_used_fraction*100)}%`;return`mem=${te(e.memory_used_bytes)}/${te(e.memory_ceiling_bytes)}${n}`}function Pk(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 Dk(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 jk(e){let n=Object.fromEntries(je.map(t=>[t,0]));for(let t of e)for(let r of je)n[r]=Math.max(n[r],ue(t[r]));return n}function Ok(e,n){return je.filter(r=>n[r]>0).map(r=>Qn(e[r],n[r])).join(yk).replace(/\s+$/,"")}var j={mode:"local",project:null,maxWorkers:4,maxProjects:4,maxWidth:120,separator:" \xB7 ",verbose:!1};function Ue(e,n=j){let t=tt(e,n.project),r=gn(e,n),o=or(e,n),s=Lk(e,n,r,t),i=Ps({mode:n.mode,maxWorkers:n.maxWorkers,maxProjects:n.maxProjects,workers:r,projects:o}),l={detail:"host",line:s};for(let f of i){let m=f==="workers"?s:Uk(s,Ak(f,o),n.separator);if(l={detail:f,line:m},f==="workers"||ue(m)<=n.maxWidth)break}let a=q(l.line,n.maxWidth),d=l.detail==="workers"?Wk(r,n,e.generated_at):{lines:[],degraded:!1},u=l.detail==="workers"?r.flatMap((f,m)=>{let g=n.verbose?Fk(f,n):null;return g==null?[d.lines[m]]:[d.lines[m],g]}):[],p=r.length>0?"workers":"host";return{version:1,line:a,lines:[a,...u],verbose:n.verbose,mode:n.mode,project:n.project,project_match:t,detail:l.detail,degraded:l.detail!==p||a!==l.line||d.degraded,stale:e.staleness.stale,generated_at:e.generated_at}}function Os(e){let n=e.options??j,t=q(Es,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 Ak(e,n){return e==="projects"?n.map(Hk):[]}function Lk(e,n,t,r){let o=[];n.mode==="global"?(o.push(`host ${e.host.worker_count}w/${e.host.project_count}p`),o.push(js(e,n))):r==="matched"?(o.push(`${n.project} ${t.length}w`),o.push(js(e,n)),t.length===0&&o.push("idle")):r==="name-only"||r==="lapsed"?(o.push(`${n.project} ${t.length}w`),o.push(js(e,n)),o.push(r==="lapsed"?et:Zn)):o.push(Nk(n.project,r)),o.push(Tk(e));let s=$k(e);s!=null&&o.push(s);let i=Ik(e);return i!=null&&o.push(i),e.staleness.stale&&o.push(Mk(e)),o.join(" ")}function Tk(e){let n=e.engine,t=n?.running_version??e.daemon.daemon_version;return n==null||n.current!==!1?`v${t}`:`v${t}${nt}`}function $k(e){let n=e.github_balance;return n==null?null:n.posture==="spent"?`${hn} quota spent`:n.posture==="reserved"?`${mn} quota band`:null}function Ik(e){let n=e.deaths;return n==null||n.count<=0||n.latest==null?null:`${He}${n.count} ${n.latest.sender_class}`}function Nk(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 js(e,n){let t=n.mode==="global"?e.host.observed_rss_bytes:e.projects.filter(o=>o.project_label===n.project).reduce((o,s)=>o+s.observed_rss_bytes,0),r=e.host.ceiling.memory_bytes;return n.mode==="global"&&r!=null&&r>0?`${te(t)}/${te(r)}`:te(t)}function Mk(e){let n=e.staleness.age_ms;return n==null?"!unmeasured":`!stale ${Math.round(n/1e3)}s`}function Ck(e,n,t,r){let o=t.map(s=>Bk(s,Qn(e[s],n[s])));return q(`${bs}${Jn}${o.join(" ")}${fn}`,r)}function Wk(e,n,t){let r=e.map(l=>Ds(l,n,t)),o=je.filter(l=>r.some(a=>ue(a[l])>0)),s=[...o],i=qd(r,s);for(;s.length>1&&Jd(i,s)>n.maxWidth;)s.pop(),i=qd(r,s);return{lines:r.map(l=>Ck(l,i,s,n.maxWidth)),degraded:s.length<o.length||Jd(i,s)>n.maxWidth}}function qd(e,n){let t=Object.fromEntries(je.map(r=>[r,0]));for(let r of e)for(let o of n)t[o]=Math.max(t[o],ue(r[o]));return t}function Jd(e,n){return n.reduce((t,r)=>t+e[r],0)+Math.max(0,n.length-1)*2}function Bk(e,n){if(e==="wid")return`${_s}${n}${ws}`;if(e==="bar")return n.replace(/█+/g,r=>`${gs}${r}`).replace("\u25B6",`${ys}\u25B6`).replace("\u2717",`${Rs}\u2717`).replace(/░+/g,r=>`${ks}${r}`)+Jn;let t=n.indexOf("=");return t>0?`${ms}${n.slice(0,t+1)}${hs}${n.slice(t+1)}${Jn}`:n}function Fk(e,n){let t=Ss(e.log.last_line);return t==null?null:q(` ${vs} ${As(e,n.mode)}: ${t}`,n.maxWidth)}function As(e,n){return n==="global"?`${e.project_label}:${e.worker_id}`:e.worker_id}function Hk(e){return`${e.project_label} ${e.worker_count}w ${te(e.observed_rss_bytes)}`}function Uk(e,n,t){return[e,...n].join(t)}var sr=1;async function rt(e,n){return await Wt(e,n,"redskilled daemon")}function zd(e){let n=[...e.workers??[]],t=new Map;for(let r of n)t.set(r.project_label,(t.get(r.project_label)??0)+1);return{version:1,protocol_version:sr,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:qk(e),...e.lapses==null||e.lapses.length===0?{}:{lapsed_registrations:[...e.lapses]},budget_accounting:Aa(n,{hostCeilingBytes:e.hostCeilingBytes??null}),upgrade:Jk(e)}}function qk(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:ad(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 Jk(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 Yd(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)&&La(n.budget_accounting)&&(n.scope===void 0||od(n.scope))&&(n.registrations===void 0||Array.isArray(n.registrations)&&n.registrations.every(Qo))&&(n.upgrade===void 0||Qk(n.upgrade))}function Qk(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.running_version=="string"&&(n.published_version===null||typeof n.published_version=="string")&&typeof n.published_unknown=="number"&&typeof n.newer_published=="number"&&(n.replacement==="none"||n.replacement==="pending"||n.replacement==="in-progress")&&(n.checked_at===null||typeof n.checked_at=="string")&&(n.newest_published_version===void 0||n.newest_published_version===null||typeof n.newest_published_version=="string")&&(n.major_held===void 0||typeof n.major_held=="number")&&(n.checks===void 0||typeof n.checks=="number")&&(n.hold_reason===void 0||n.hold_reason===null||typeof n.hold_reason=="string")&&(n.major_hold===void 0||n.major_hold===null||zk(n.major_hold))}function zk(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return typeof n.version=="string"&&Number.isInteger(n.running_major)&&Number.isInteger(n.held_major)&&typeof n.reason=="string"&&typeof n.action=="string"&&n.action.trim()!==""}import{spawnSync as ar}from"node:child_process";import{existsSync as Ns}from"node:fs";import{delimiter as sR,join as lc}from"node:path";import{join as Xd}from"node:path";import{existsSync as Yk}from"node:fs";import{createRequire as Xk}from"node:module";var Zd="redskilled-job-object.node",Ge=100;function kn(e){return{available:!1,reason:e}}function Zk(e,n,t){return[Xd(t,"prebuilds",`${e}-${n}`,Zd),Xd(t,"native","build","Release",Zd)]}function ec(e={}){let n=e.platform??process.platform,t=e.arch??process.arch;if(n!=="win32")return kn(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);let r=e.packageRoot??nR(),o=e.exists??Yk,s=Zk(n,t,r),i=s.find(d=>o(d));if(i==null)return kn(`no Job Object addon was found for ${n}-${t} (looked in ${s.join(", ")}); either install the prebuild for this platform and architecture or build the addon locally`);let l=e.requireFn??Xk(import.meta.url),a;try{a=l(i)}catch(d){return kn(`the Job Object addon at ${i} could not be loaded: ${d instanceof Error?d.message:String(d)}`)}return eR(a)?{available:!0,binding:a}:kn(`the Job Object addon at ${i} does not export createJobObject, so it cannot be the native reach`)}function eR(e){return typeof e=="object"&&e!=null&&typeof e.createJobObject=="function"}function nR(){return new URL("..",import.meta.url).pathname}function nc(e){let n=e??{},t=[],r=tR(n);r==null&&(n.memory_max??n.memory_high)!=null&&t.push("the declared memory budget could not be reduced to bytes, so the job carries no memory ceiling");let o;return n.cpu_weight!=null&&(n.cpu_weight<Ge?o=Math.max(1,Math.min(100,Math.round(n.cpu_weight))):t.push(`cpu_weight=${n.cpu_weight} is at or above the fair share of ${Ge}, and Windows CPU rate control is an absolute cap rather than a share, so no rate limit is set`)),{...r!=null?{memory_limit_bytes:r.bytes,memory_budget_name:r.name,memory_budget_declared:r.declared}:{},...o!=null?{cpu_rate_percent:o}:{},kill_on_close:!0,...t.length>0?{note:t.join("; ")}:{}}}function tR(e){return Vn({budget:e})}var ir=5,tc=19;function Ls(e){return{available:!1,reason:e}}var rR="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 oc(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=ir;else if(t.cpu_weight<Ge){let l=Math.round(tc*(Ge-t.cpu_weight)/Ge);o=Math.min(tc,Math.max(ir,l))}else o=ir,r.push(`cpu_weight=${t.cpu_weight} is at or above the fair share of ${Ge}, and raising a process's priority requires privilege this daemon does not have, so the Worker keeps the default yield of nice ${ir}`);let s=rc(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=rc(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:rR,...r.length>0?{note:r.join("; ")}:{}}}function sc(e){let{limits:n}=e,t=[];return n.max_processes!=null&&t.push(`ulimit -u ${n.max_processes}`),n.cpu_seconds!=null&&t.push(`ulimit -t ${n.cpu_seconds}`),t.push(n.nice!=null&&e.nice!=null?`exec ${oR(e.nice)} -n ${n.nice} "$0" "$@"`:'exec "$0" "$@"'),["-c",t.join(`
71
+ `),e.command,...e.args]}function ic(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 Ts(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 rc(e){if(e!=null&&!(!Number.isSafeInteger(e)||e<=0))return e}function oR(e){return`'${e.replace(/'/g,"'\\''")}'`}var ac="REDSKILLED_PLACEMENT",lr="red-worker",$s="/bin/sh";function dc(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:ec({platform:n}),posix:t};let r=kn(`Job Object placement is the Windows backend (platform=${n}), so there is no native reach to load here`);if(n==="darwin")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:iR(e)};if(n!=="linux")return{platform:n,systemdRun:null,userSession:!1,jobObjects:r,posix:t};let o=(e.XDG_RUNTIME_DIR??"").trim(),s=o!==""&&Ns(lc(o,"systemd","private"));return{platform:n,systemdRun:fc("systemd-run",e),userSession:s,jobObjects:r,posix:t}}function iR(e){return Ns($s)?{available:!0,shell:$s,nice:fc("nice",e)}:Ls(`no POSIX shell was found at ${$s}, so there is nothing to apply rlimits or priority in`)}function cc(e=process.env){let n=(e[ac]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function lR(e,n,t=lr){return uc(e,n,t).replace(/\.service$/,"")}function uc(e,n,t=lr){return`${Is(t,"red-worker",24)}-${Is(e,"project",32)}-${Is(n,"worker",32)}.service`}function pc(e){let n=[...e.args??[]],t={...e.budget??{},...e.budget?.memory_max==null&&e.memoryCeiling?.memory_max!=null?{memory_max:e.memoryCeiling.memory_max}:{}},r=t.memory_max??t.memory_high??null,o=t.memory_high!=null||t.memory_max!=null||t.cpu_weight!=null,s=e.target??{isolation:"transient-unit"},i=p=>({isolated:!1,backend:"none",command:e.command,args:n,cwd:e.workspacePath,warning:p,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Nn({scope:null,memory_ceiling:r,scope_degradation:p}),...o?{budgetWarning:"a budget was declared but this placement cannot enforce it: the daemon's RSS sampling is the only remaining floor"}:{}});if(s.isolation==="inherit")return i("placement target is `inherit`: the Worker is charged to the daemon's own resource group, so a memory-pressure kill can land on the daemon and every Worker it holds");if(e.enabled===!1)return i(`worker isolation disabled by ${ac}: the Worker is charged to the daemon's own resource group`);if(e.probes.platform==="win32")return dR(e,n,t,r,o,i);if(e.probes.platform==="darwin")return aR(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=uc(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=Nn({scope:l,memory_ceiling:r,scope_degradation:null});for(let[p,f]of Object.entries({...e.env??{},...d}))a.push(`--setenv=${p}=${f}`);let u=Ts(e.budget);return{isolated:!0,backend:"transient-unit",unit:l,command:e.probes.systemdRun,args:[...a,"--",e.command,...n],budget:t,...r!=null?{memoryCeiling:r}:{},environment:d,...u!=null?{budgetWarning:u}:{}}}function aR(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=oc(t,{canRenice:s.nice!=null}),l=t.memory_high!=null||t.memory_max!=null,a=ic(i);return{isolated:!1,backend:"posix-limits",command:s.shell,args:sc({limits:i,nice:s.nice,command:e.command,args:n}),cwd:e.workspacePath,posix:i,warning:a,budget:t,...r!=null?{memoryCeiling:r}:{},environment:Nn({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 dR(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=nc(t),a=lR(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:Nn({scope:a,memory_ceiling:r,scope_degradation:null}),...cR(o&&l.note!=null?`${l.note}; the daemon's RSS sampling floor is the ceiling for that budget`:null,Ts(e.budget))}}function cR(...e){let n=e.filter(t=>t!=null&&t!=="");return n.length>0?{budgetWarning:n.join("; ")}:{}}function fc(e,n){for(let t of(n.PATH??"").split(sR)){if(!t)continue;let r=lc(t,e);if(Ns(r))return r}return null}function Is(e,n,t){return(e||"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).replace(/-+$/g,"")||n}async function Ms(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 mc=3e4;function hc(e){return e.unit!=null&&e.unit!==""?uR(e.unit):B(e.pid)}function uR(e){let n=ar("systemctl",["--user","is-active","--quiet",e],{stdio:"ignore"});return n.error!=null?!1:n.status===0}var pR="REDSKILLED_UNIT_DISCOVERY",gc="(unowned)";function yc(e){let n=ar("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 fR(e=process.env){let n=(e[pR]??"").trim().toLowerCase();return n===""?!0:!["off","false","0","no"].includes(n)}function kc(e,n,t=process.env){return fR(t)&&e===n}function Rc(e=lr){let n=ar("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 bc(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:gc,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 _c(e){return e.project_label.trim()!==""?e:{...e,project_label:gc,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 wc(e){if(e.unit!=null&&e.unit!==""){let n=ar("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 mR(e,n=50){if(Ec(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 hR(e,n={}){let t=n.batchSize??50;if(Ec(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 gR(e,n){let t=ot(n),r=ot(t.data),o=Array.isArray(t.errors)?t.errors.map(ot):[],s=kR(r.rateLimit,o);return{projects:e.aliases.map(({alias:l,project:a})=>{let d=bR(r[l]);if(d!=null)return{project_label:a.project_label,outcome:"counted",depth:d,detail:`project ${JSON.stringify(a.project_label)} has ${d} item(s) matching its selector`};let u=o.find(p=>RR(p.path,l));return s.exhausted||Pc(u)?{project_label:a.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(a.project_label)} answered, so this queue has no depth rather than a depth of zero`+(s.reset_at==null?"":`; the quota resets at ${s.reset_at}`)}:{project_label:a.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(a.project_label)} could not be counted with the host token: ${Cs(u?.message)||"the query returned no count for this selector"}`}}),rate_limit:s}}function yR(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 Sc(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 vc(e){if(e.projects.length===0)return yR(e.now);let n=e.batchSize??50,t=mR(e.projects,n),r=[],o={remaining:null,reset_at:null,exhausted:!1};for(let s of t){let i=hR(s,{batchSize:n});try{let l=await e.transport(i.query),a=gR(i,l);r.push(...a.projects),o=xc(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=xc(o,{remaining:null,reset_at:null,exhausted:d});for(let u of s)r.push({project_label:u.project_label,outcome:d?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(u.project_label)} answered: ${a}`})}}return{version:1,fetched_at:e.now,request_count:t.length,project_count:r.length,batch_size:n,rate_limit:o,projects:r}}function Ec(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 xc(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 kR(e,n){let t=ot(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(Pc)||r===0}}function Pc(e){return e==null?!1:Cs(e.type)==="RATE_LIMITED"||/rate limit/i.test(Cs(e.message))}function RR(e,n){return Array.isArray(e)&&e.includes(n)}function bR(e){let n=ot(e);return Number.isInteger(n.issueCount)?n.issueCount:null}function ot(e){return _R(e)?e:{}}function _R(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cs(e){return typeof e=="string"?e:""}function Dc(e,n,t){let r=e?.rate_limit;if(r==null)return n;if(r.exhausted){let s=r.reset_at==null?Number.NaN:Date.parse(r.reset_at),i=Number.isFinite(s)?s-t+1e3:n*4;return Math.min(wR,Math.max(n,i))}let o=r.remaining;return o==null?n:o<=xR?Math.max(n,3e4):o<=SR?Math.max(n,2e4):n}var wR=1e5,xR=250,SR=1e3;var vR={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},ER=["runner","model","effort","origin","issue","phase","step","heartbeat","started_at"],PR=["phase_index","phase_total","context","eta","added","removed","tokens","tools","reasoning","text"];function jc(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e,t={...vR};for(let r of ER){let o=n[r];t[r]=typeof o=="string"&&o.trim()!==""?o:null}for(let r of PR){let o=n[r];t[r]=typeof o=="number"&&Number.isFinite(o)?o:null}return t.failed=n.failed===!0,t}import{randomUUID as Lc}from"node:crypto";import{spawn as AR}from"node:child_process";import{closeSync as LR,mkdirSync as TR,openSync as $R}from"node:fs";import{dirname as IR}from"node:path";import{delimiter as Oc,dirname as DR}from"node:path";function jR(e,n=Oc){return(e??"").split(n).map(t=>t.trim()).filter(t=>t!=="")}function OR(e=process.execPath){let n=(e??"").trim();if(n==="")return null;let t=DR(n);return t===""||t==="."?null:t}function Ac(e,n=process.execPath,t=Oc){let r=jR(e,t),o=OR(n);return o==null?r.join(t):[o,...r.filter(s=>s!==o)].join(t)}var st=class extends Error{constructor(n){super(n),this.name="RedskilledWorkerSpecError"}},dr=class extends Error{constructor(t,r){super(t);this.admission=r;this.name="RedskilledAdmissionError"}};function NR(e){if(e==null||e.trim()==="")return null;try{return TR(IR(e),{recursive:!0}),$R(e,"a")}catch{return null}}function MR(e){try{LR(e)}catch{}}function CR(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 st(`redskilled worker spec is missing ${t}`);if(e.args!=null&&!Array.isArray(e.args))throw new st("redskilled worker spec args must be an array")}function WR(e){if(e==null)throw new dr("redskilled refused this Worker: no host admission verdict was handed over, and an unjudged birth is an unbudgeted one");if(!e.admitted)throw new dr(e.reason,e)}function $c(e){let{spec:n,admission:t}=e;WR(t),CR(n);let r=e.env??process.env,o=e.clock??(()=>new Date().toISOString()),s=(n.worker_id??e.workerId??Lc()).trim()||Lc(),i=e.probes??dc(r),l=e.openLog===!1?null:NR(n.log_path),a={...n.env??{},PATH:Ac(n.env?.PATH??r.PATH,e.execPath??process.execPath)},d=pc({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??cc(r),probes:i,pipeOutput:l!==null}),p=(e.spawnFn??AR)(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&&MR(l),p.pid==null)throw p.once("error",()=>{}),new st(`redskilled could not spawn ${JSON.stringify(d.command)} for worker ${s}`);let f=d.job!=null?BR(d,i,p.pid):null;p.once("error",()=>{}),p.once("exit",(k,w)=>{try{f?.job?.close()}catch{}e.onExit?.(s,k,w)}),p.unref();let m=d.job!=null?f?.job!=null:d.isolated,g=[d.warning,f?.warning,d.budgetWarning].filter(k=>k!=null);return{worker:{worker_id:s,project_label:n.project_label,pid:p.pid,started_at:o(),workspace_path:n.workspace_path,...n.log_path!=null?{log_path:n.log_path}:{},isolated:m,...d.unit!=null?{unit:d.unit}:{},...n.budget!=null?{budget:n.budget}:{},...Object.keys(d.budget).length>0?{applied_budget:d.budget}:{},...d.memoryCeiling!=null?{memory_ceiling:d.memoryCeiling,memory_ceiling_reason:e.memoryCeiling?.reason??"this Worker's ceiling is the budget its client declared"}:{},warnings:g},admission:t,warnings:g,plan:d,child:p,...f?.job!=null?{job:f.job}:{}}}function BR(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: ${Tc(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)}: ${Tc(i)}. ${o}`}}return{job:s}}function Tc(e){return e instanceof Error?e.message:String(e)}import{open as FR,stat as HR}from"node:fs/promises";var UR=16*1024;async function Ic(e,n=UR){let t;try{t=(await HR(e)).size}catch{return null}if(t<=0)return null;let r=Math.min(n,t),o;try{let s=await FR(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 GR(o)}function GR(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 sb}from"node:child_process";import{existsSync as ib,readdirSync as lb}from"node:fs";import{dirname as ab,join as Fc,resolve as db}from"node:path";var KR="<version>";function Oe(e,n=[],t){let r=t&&t.trim().length>0?t.trim():KR;return[`npx -y -p ${Be}@${r}`,e,...n].join(" ")}function re(e){let n=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return n?{major:Number(n[1]),minor:Number(n[2]),patch:Number(n[3])}:null}function Ws(e,n){let t=re(e),r=re(n);return!t||!r?0:t.major-r.major||t.minor-r.minor||t.patch-r.patch}var TP=4*60*60*1e3;_e();_e();import{spawnSync as VR}from"node:child_process";import{mkdir as qR,rm as JR,writeFile as QR}from"node:fs/promises";import{existsSync as zR}from"node:fs";import{homedir as YR}from"node:os";import{dirname as XR,join as Bs}from"node:path";var Rn="redskilled.service",Fs="REDSKILLED_SUPERVISED",ZR="https://github.com/reddb-io/red-skills/blob/main/.red/adr/0130-redskilled-host-scoped-execution-daemon.md";function eb(e=process.env){let n=e.XDG_CONFIG_HOME?.trim()||Bs(e.HOME?.trim()||YR(),".config");return Bs(n,"systemd","user")}function Hs(e=process.env){return Bs(eb(e),Rn)}function Nc(e,n={}){let t=n.env??process.env,r=Ut(n.override??{},n.entryLookup??{}),o=[...r.args,...Ce(e,n.idleMs==null?{}:{idleMs:n.idleMs})];return{unitName:Rn,unitPath:Hs(t),command:r.command,args:o,text:nb(r.command,o,e)}}function nb(e,n,t){return["[Unit]","Description=redskilled \u2014 the host-scoped execution daemon (ADR 0130)",`Documentation=${ZR}`,"","[Service]","Type=simple",`ExecStart=${[e,...n].map(tb).join(" ")}`,"Restart=on-failure","RestartSec=1",`Environment="${Fs}=1"`,`Environment="REDSKILLED_SESSION=${Mc(t.sessionKey)}"`,"","[Install]","WantedBy=default.target",""].join(`
75
+ `)}function tb(e){return/[\s"'\\$%]/.test(e)?`"${Mc(e)}"`:e}function Mc(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}async function Cc(e,n={}){let t=n.writeFile??rb,r=n.run??Us,o=[];return await t(e.unitPath,e.text),o.push({step:"write-unit",ok:!0,detail:e.unitPath}),o.push(cr("daemon-reload",r,["systemctl","--user","daemon-reload"])),o.push(cr("enable",r,["systemctl","--user","enable","--now",e.unitName])),{unitPath:e.unitPath,installed:o.every(s=>s.ok),steps:o}}async function Wc(e={}){let n=e.removeFile??ob,t=e.run??Us,r=Hs(e.env??process.env),o=[cr("disable",t,["systemctl","--user","disable","--now",Rn])];return await n(r),o.push({step:"remove-unit",ok:!0,detail:r}),o.push(cr("daemon-reload",t,["systemctl","--user","daemon-reload"])),{unitPath:r,installed:!1,steps:o}}function Bc(e={}){let n=e.exists??zR,t=e.run??Us,r=Hs(e.env??process.env),o=n(r);return{unitName:Rn,unitPath:r,installed:o,enabled:o&&t(["systemctl","--user","is-enabled",Rn]).status===0,active:o&&t(["systemctl","--user","is-active",Rn]).status===0,floor:"auto-spawn"}}function cr(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 rb(e,n){await qR(XR(e),{recursive:!0}),await QR(e,n,{encoding:"utf8",mode:420})}async function ob(e){await JR(e,{force:!0})}function Us(e){let n=VR(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 Hc=75,Gc=9e5,Uc="redskilled-replacement-entry-unresolved",cb="REDSKILLED_NO_REGISTRY_PROBE",Kc="REDSKILLED_BORN_BY_REPLACEMENT";function Vc(e=process.env){return e[Kc]==="1"}function qc(e){return e===null||typeof e=="string"?{version:e,newest:null}:{version:e.version,newest:e.newest??null}}function Jc(e){let n=e.running.trim();if(it(n))return null;let t=e.newest?.trim()??"",r=re(t),o=re(n);return r===null||o===null||r.major<=o.major?null:{version:t,running_major:o.major,held_major:r.major,reason:`redskilled ${t} is published and this daemon runs ${n}; a major version is deliberately never adopted by the background check, because a breaking change must not arrive on a machine that is holding Workers`,action:ub(r.major,e.supervised)}}function ub(e,n){let t=`install the ${e}.x bundle (update this machine's plugin pin), then `;return n?`${t}re-point the unit and restart it: ${Oe("red-skills-redskilled",["unit","install"])} && systemctl --user restart redskilled.service`:`${t}stop this daemon \u2014 the next client start resolves the newly installed bundle`}function Qc(e){let n=e.running.trim();if(it(n))return{act:"hold",reason:"local-build"};let t=e.published?.trim()??"";return!t||re(t)===null?{act:"hold",reason:"published-unknown"}:Ws(t,n)<=0?{act:"hold",reason:"no-newer-version"}:{act:"replace",to:t,via:e.supervised?"supervisor-exit":"self-spawn"}}function it(e){let n=e.trim();return re(n)===null?!0:/^\d+\.\d+\.\d+[-+]/.test(n)}function zc(e=process.env){return e[Fs]==="1"}var Gs=class extends Error{code=Uc;searched;constructor(n,t){super(`${Uc}: 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 VR(e,n={}){let t=n.env??process.env,r=n.exists??BR,o=n.execPath??process.execPath,s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,l=[],a=[[bc(Tt(t),i),"bundle-cache"]];s&&a.push([bc(HR(UR(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 vs(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 Oc(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>VR(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function Ac(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??JR)(_c),{...e,exitCode:_c};let o=[...e.entry.args,...Ie(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??qR(r.env))(e.entry,o),e}function qR(e){return(n,t)=>{let r=WR(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[Sc]:"1"}});r.on("error",()=>{}),r.unref()}}function JR(e){process.exitCode=e,process.exit(e)}async function Lc(e,n=process.env,t=QR){let r=$c(n),o=Ic(e,n);if(n[GR]==="1")return{version:o,newest:r};let s=ne(e)===null?"0.0.0":e;try{let i=await ia({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function Tc(e,n=process.env,t){let r=t??Es;return{version:Ic(e,n,r),newest:$c(n,r)}}function $c(e=process.env,n=Es){return Mc(Nc(e,n))}function Ic(e,n=process.env,t=Es){let r=ne(e.trim())?.major;return r===void 0?null:Mc(Nc(n,t).filter(o=>ne(o)?.major===r))}function Nc(e,n){let t=[];for(let r of n(Tt(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||ne(o)===null||t.push(o)}return t}function Mc(e){let n=null;for(let t of e)(n===null||bs(t,n)>0)&&(n=t);return n}function Es(e){try{return FR(e)}catch{return[]}}async function QR(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 zR,readFile as YR,rename as XR,rm as Ps,writeFile as Cc}from"node:fs/promises";import{randomUUID as ZR}from"node:crypto";import{dirname as eb}from"node:path";var sr=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function Zn(e){let n;try{n=await YR(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=nb(n);return tb(t)?t:void 0}var Wc;function Fc(){return Wc??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},Wc}function Hc(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??H;async function s(){return await Zn(e)}async function i(a){let d=`${e}.${a.pid}.${ZR()}.tmp`;await Cc(d,Bc(a),{encoding:"utf8",mode:384}),await XR(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 zR(eb(e),{recursive:!0,mode:448});let d=!1;for(;;){let c=r(),u=l(a,c);try{return await Cc(e,Bc(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 Ps(e,{force:!0}),d=!0;continue}if(Ds(f,a))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await Ps(e,{force:!0}),d=!0}},async renew(a){let d=await s();if(!d||!Ds(d,a))throw new sr(e);let c={...d,renewed_at:r()};return await i(c),c},async release(a){let d=await s();if(!d)return!1;if(!Ds(d,a))throw new sr(e);return await Ps(e,{force:!0}),!0}}}function Ds(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function Bc(e){return`${C(e,{keyedMapCollapse:!0})}
79
- `}function nb(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return J(n)}catch{return null}}}function tb(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 js=3e5,cb=1e4,ub=6e4,pb=15e3,fb=3e4,Uc=16,mn=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},mb="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function Kc(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??js,o=e.clock??(()=>new Date().toISOString()),s=e.launch??fc,i=e.ceiling??ba();e.repositoryActivity!=null&&ts(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??Fc(),a=e.leaseStore??Hc(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??Ma(),c={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},u=e.machineClaimStore??Wt(n.machineClaimPath,c,{clock:o});await lb(db(n.socketPath),{recursive:!0,mode:448});let f=await u.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new mn(n.socketPath):new ve(u.claimPath,f.reason,f.claim);let m=await a.acquire(l);if(!m.acquired)throw await u.release(d).catch(()=>{}),new mn(n.socketPath,m.lease);let h;try{h=await hb(n.socketPath)}catch(p){throw await a.release(l).catch(()=>{}),await u.release(d).catch(()=>{}),p}let b=o(),k=e.eventLane??xa(n.eventLanePath),w=e.liveness??Qd,j=e.livenessGraceMs??Jd,Y=e.stopWorker??tc,pe=e.unitInventory??(()=>Xd(n.machineClaimPath,Ct({machineIdHash:n.machineIdHash}))?Zd():[]),fe=e.unitMainPid??Yd,Ue=e.treeSampler??fd,dr=e.readLogTail??mc,Gs=e.sampleMs??pb,Ks=e.leaseRenewMs??fb,Vs=e.publishedVersion??(p=>Lc(p)),qs=e.replaceCheckMs??xc,Js=e.publishedProbeTimeoutMs??cb,Du=e.localPublishedEvidence??(p=>Tc(p,e.replacementIO?.env??process.env)),ju=e.bornByReplacement??vc(),Qs=e.replaceBootCheckMs??ub,zs=e.supervised??jc(),Ys=e.replacementIO??{},re=e.repositoryActivity,Xs=re?.intervalMs??ns,tt=e.githubBalance,De=e.queueDiscovery,rt=De?.transport??re?.transport,cr=De?.unconfiguredReason??mb,Zs=De?.intervalMs??15e3,ei=e.demandMs??15e3,Ou=e.demandBackoffMs??3e4,v=new Map,be=new Set,Ge=new Map,ot=new Map,ur=[],st=[],$=new Map,pr=new Set,ni={},fr=null,ti=null,mr=null,ri=!1,hr=0,gr=null,gn="none",yr=null,oi=null,kr=null,yn=null,_e=null,it=null,kn=[],Rn=null,lt={},Rr=!1,Ke,bn,_n,wn,xn,at,Sn,Ve,vn,V=!1,br=!1,dt=null,si,_r=new Promise(p=>{si=p});function En(p){ii(p);let g=Date.parse(p),y=Ka($.values(),g);for(let _ of y.lapsed)$.delete(_.project_label),Au(_,g);return y.lapsed}function Au(p,g){let y=Number.isFinite(g)?new Date(g).toISOString():p.renew_by;kn.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`}),kn.length>Uc&&kn.splice(0,kn.length-Uc)}function ii(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((_e?.projects??[]).map(x=>[x.project_label,x]));for(let x of[...$.values()]){let P=_.get(x.project_label),he=Ua(x,{now:p,...P==null?{}:{queue:{outcome:P.outcome,depth:P.depth}},liveWorkers:y[x.project_label]??0});he.registration!==x&&$.set(x.project_label,he.registration)}}function ct(){let p=o();return En(p),Od({now:p,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:l.pid,startedAt:b,scope:Ca(u.claimPath,c,d),workers:[...v.values()],registrations:[...$.values()],lapses:kn,queue:_e,published:{version:ti,checkedAt:mr,newer:ri,replacement:gn,newest:yr,majorHold:oi,checks:hr,holdReason:gr}})}function ut(){return xd({hostState:ct(),ceiling:i,rss:ni,sampledAt:fr,logLines:Object.fromEntries(Ge),displays:Object.fromEntries(ot),now:o(),reattachedWorkerIds:[...be],repositoryActivity:kr,githubBalance:yn,...e.deaths===void 0?{}:{deaths:e.deaths},metrics:cd({observations:ur,outcomes:st,now:o()})})}function Lu(p,g){ur=qt([...ur,{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 Tu(p){st=qt([...st,p],g=>g.ts,{now:o()})}async function wr(){return re==null||re.projects.length===0?null:(kr=await yd({projects:re.projects,hostTokenRef:re.hostTokenRef,transport:re.transport,closedWindowMs:re.closedWindowMs,now:o()}),kr)}async function li(){return tt==null?null:(yn=await Ko({transport:tt.transport,now:o()}),yn)}function $u(){if(V||Ve!=null||tt==null)return;let p=()=>{Ve=void 0,li().catch(()=>{}).then(()=>{if(V)return;let g=tt.intervalMsOverride??Vt(yn??Iu(),{now:o()});Ve=setTimeout(p,g),Ve.unref()})};p()}function Iu(){return Kt(o())}function Nu(){if(!(rt!=null||De?.armTransport==null))try{let p=De.armTransport();if(p.transport!=null){rt=p.transport;return}p.unconfiguredReason!=null&&(cr=p.unconfiguredReason)}catch(p){cr=`this host could not resolve a tracker credential: ${p instanceof Error?p.message:String(p)}`}}async function ai(){let p=o();En(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:(Nu(),rt==null?(_e=oc(g,p,cr),_e):(_e=await sc({projects:g,transport:rt,now:p,...De?.batchSize==null?{}:{batchSize:De.batchSize}}),ii(o()),_e))}async function di(){let p=o();if(Rr)return it??Ea(p);Rr=!0;try{await Sr().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 _e?.projects??[])y[A.project_label]=A.depth;let _=Date.parse(p),x=va({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:Rn,birthHaltUntilMs:Da(lt,Number.isFinite(_)?_:0)}),P=[],he=null;for(let A of x.births){let Je,rp=et(),gt=$.get(A.project_label),wi=Ba({argv:A.argv,...gt?.env==null?{}:{env:gt.env},...gt?.log_path==null?{}:{log_path:gt.log_path}},{worker_id:rp,slot:A.index,workspace_path:A.workspace_path},{project_label:A.project_label});try{Je=xr(wi)}catch(Pr){he=Pr instanceof Error?Pr.message:String(Pr),Rn=(Number.isFinite(_)?_:Date.now())+Ou;break}P.push({project_label:A.project_label,worker_id:Je.worker.worker_id,pid:Je.worker.pid,warnings:wi.log_path==null?[...Je.warnings,`project ${JSON.stringify(A.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(Je.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:Je.warnings})}return he==null&&x.births.length>0&&(Rn=null),it={version:1,at:p,requested:x.births.length,granted:P,shortfall:x.births.length-P.length,refusal:he,retry_after:Rn==null?null:new Date(Rn).toISOString(),projects:x.intents},it}finally{Rr=!1}}function Mu(p){return Be(ut(),{...D,mode:p?.mode??D.mode,project:p?.project??D.project,maxWorkers:p?.max_workers??D.maxWorkers,maxProjects:p?.max_projects??D.maxProjects,maxWidth:p?.max_width??D.maxWidth,verbose:p?.verbose??D.verbose})}function Cu(p){return un(ut(),{mode:p?.mode??ce.mode,project:p?.project??ce.project,maxWidth:p?.max_width??ce.maxWidth,maxRows:p?.max_rows??ce.maxRows})}function qe(p,g,y){return qa({op:p,sessionProject:g??null,targetProject:y})}async function Wu(p){let g=v.get(p.worker_id),y=qe(Va(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 Gu(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 pt(p){v.delete(p),be.delete(p),Ge.delete(p),ot.delete(p)}function ci(p){let g=v.get(p.worker_id),y=qe("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();Ge.set(p.worker_id,{line:p.last_log_line,published_at:_,source:"heartbeat"});let x=p.display===void 0?null:ac(p.display);if(x!=null){let P={display:x,published_at:_};ot.set(p.worker_id,P),Lu(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 Bu(p,g,y){let _=`exit code=${g??"null"} signal=${y??"null"}`;if(p.unit!=null&&p.unit!==""&&await Hu(p)){Uu(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}pt(p.worker_id),me("worker-death",p,_,{exitCode:g,signal:y}),I()}function Fu(p,g){if(!Number.isFinite(g)||g<0){lt[p]=Mt;return}let y=lt[p]??Mt,_=Pa(y,g,Date.parse(o()));lt[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 Hu(p){try{return await w(p)===!0}catch{return!1}}function Uu(p,g){let y=p.unit==null?null:fe(p.unit);v.set(p.worker_id,{...p,...y!=null&&y>0?{pid:y}:{},warnings:[...p.warnings,g]}),be.add(p.worker_id),I()}function ui(p,g){let y=qe("project-register",g,p.project_label);if(!y.permitted)throw new Error(y.reason);let _=o();En(_);let x=Fa(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 pi(p,g={}){let y=qe("project-renew",g.sessionProject,p);if(!y.permitted)throw new Error(y.reason);let _=o();En(_);let x=$.get(p);if(x==null)throw new Bt(p);let P=Ha(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 fi(p,g){let y=qe("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 Gu(p,g){try{await Y(p)}catch{}return pt(p.worker_id),me("worker-death",p,g),I(),!0}function mi(p){return ka({ceiling:i,workers:[...v.values()],budget:p.budget,projectLabel:p.project_label})}function xr(p){let g=Ra({ceiling:i,workers:[...v.values()],budget:p.budget}),y=s({spec:p,admission:mi(p),memoryCeiling:g,clock:o,onExit:(_,x,P)=>{let he=v.get(_);if(he==null){I();return}Bu(he,x,P).catch(()=>{})}});return v.set(y.worker.worker_id,y.worker),me("worker-birth",y.worker,null),I(),y}function me(p,g,y,_={}){if(V)return;let x=o();(p==="worker-death"||p==="worker-budget-kill")&&(Tu({worker_id:g.worker_id,ts:x,outcome:p}),Fu(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 Sr(){let p=Date.parse(o()),g=[...v.values()].filter(_=>{if(be.has(_.worker_id))return!0;let x=Date.parse(_.started_at);return!Number.isFinite(x)||p-x>=j});if(g.length===0)return[];let{dead:y}=await ks(g,w);for(let _ of y)pt(_.worker_id),me("worker-death",_,"the host no longer confirms this Worker");return y.length>0&&I(),y}async function hi(p,g){let y=v.get(p);if(!y)return!1;try{await Y(y)}catch{}return pt(p),me("worker-budget-kill",y,g),I(),!0}async function gi(){let p=[...v.values()];if(p.length===0)return[];let g;try{g=await Ue(p)}catch{return[]}let y=g.rss;ni=y,fr=o(),Ku(g.cpu_seconds,fr);let{terminations:_}=pd({workers:p,rss:y}),x=[];for(let P of _)await hi(P.worker_id,P.reason)&&x.push(P);return x}function Ku(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 Vu(){try{return Js<=0?await Vs(t):await new Promise(p=>{let g=setTimeout(()=>p(vr()),Js);g.unref(),Vs(t).then(y=>{clearTimeout(g),p(y)},()=>{clearTimeout(g),p(vr())})})}catch{return vr()}}function vr(){try{return Du(t)}catch{return null}}async function yi(){if(Xn(t))return hr+=1,mr=o(),gr="local-build",{act:"hold",reason:"local-build"};let p=Ec(await Vu()),g=p.version;ti=g,yr=p.newest??null,mr=o(),oi=Pc({running:t,newest:yr,supervised:zs});let y=Dc({running:t,published:g,supervised:zs});return ri=y.act==="replace",hr+=1,gr=y.act==="hold"?y.reason:null,gn!=="in-progress"&&(gn=y.act==="replace"?"pending":"none"),y}async function ft(){let p=await yi();if(p.act!=="replace"||gn==="in-progress")return p;let g=Oc(p,Ys);return gn="in-progress",await k.flush().catch(()=>{}),await ht({reason:"replaced"}),Ac(g,n,{...r==null?{}:{idleMs:r},io:Ys}),p}function qu(){V||xn!=null||qs<=0||(!ju&&Qs>0&&(at=setTimeout(()=>{ft().catch(()=>{})},Qs),at.unref()),xn=setInterval(()=>{ft().catch(()=>{})},qs),xn.unref())}async function ki(){return await a.renew(l).catch(()=>null)}function Ju(){V||_n!=null||Ks<=0||(_n=setInterval(()=>{ki()},Ks),_n.unref())}function Qu(){V||bn!=null||Gs<=0||(bn=setInterval(()=>{gi().catch(()=>{})},Gs),bn.unref())}function zu(){V||Sn!=null||re==null||re.projects.length===0||Xs<=0||(wr().catch(()=>{}),Sn=setInterval(()=>{wr().catch(()=>{})},Xs),Sn.unref())}function Yu(){V||vn!=null||Zs<=0||(vn=setInterval(()=>{ai().catch(()=>{})},Zs),vn.unref())}function Xu(){V||wn!=null||ei<=0||(wn=setInterval(()=>{di().catch(()=>{})},ei),wn.unref())}function I(){V||(Ke&&clearTimeout(Ke),Ke=setTimeout(()=>{Sr().catch(()=>{}).then(()=>Ri())},r),Ke.unref())}function Ri(){return v.size>0?(I(),"held-by-workers"):(En(o()),$.size>0?(I(),"held-by-registrations"):(Zu(),"exited"))}async function Zu(){if(!Xn(t)){if((await ft().catch(()=>null))?.act==="replace"||br||V)return;if(v.size>0||$.size>0){I();return}}await ht({reason:"idle"})}function mt(p){return Oa({reason:p,socketPath:n.socketPath,daemonVersion:t,pid:l.pid,workers:[...v.values()],projects:[...$.keys()]})}function bi(p){if(dt!=null)return dt;let g=p.reason??"requested",y=p.note?.trim();return dt=k.recordDaemonStop({ts:o(),pid:l.pid,socketPath:n.socketPath,reason:g,detail:y==null||y===""?mt(g).detail:`${mt(g).detail} \u2014 ${y}`,...p.signal==null?{}:{signal:p.signal}}).catch(()=>{}),dt}async function ht(p={}){if(br)return await _r;br=!0,await bi(p),V=!0,Ke&&clearTimeout(Ke),bn&&clearInterval(bn),_n&&clearInterval(_n),xn&&clearInterval(xn),at&&clearTimeout(at),Sn&&clearInterval(Sn),Ve&&clearTimeout(Ve),vn&&clearInterval(vn),wn&&clearInterval(wn),await k.flush().catch(()=>{}),h.close();for(let g of pr)g.destroy();return await new Promise(g=>h.once("close",()=>g())),await Gc(n.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await u.release(d).catch(()=>{}),si(),await _r}let _i=await k.read().catch(()=>[]);st=qt(_i.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 ep=Sa(_i),Er=await ks(ep,w);for(let p of Er.alive){let g=nc(p),y=g.unit==null||H(g.pid)?null:fe(g.unit);v.set(g.worker_id,y!=null&&y>0?{...g,pid:y}:g),be.add(g.worker_id)}for(let p of Er.dead)me("worker-death",p,"the Worker ended while no daemon was watching");let np=ec({units:await Promise.resolve(pe()).catch(()=>[]),held:[...v.values()],mainPid:fe,now:b});for(let p of np)v.set(p.worker_id,p),be.add(p.worker_id),me("worker-birth",p,"adopted from an active unit with no birth on this lane");for(let p of Er.alive){if(p.log_path==null||Ge.has(p.worker_id))continue;let g=await dr(p.log_path).catch(()=>null);g==null||g.trim()===""||Ge.set(p.worker_id,{line:g,published_at:o(),source:"rehydrated"})}h.on("connection",p=>{pr.add(p),p.once("close",()=>pr.delete(p)),I(),gb(p,async(g,y)=>{I();let _=await tp(g);y(_),g.op==="shutdown"&&setImmediate(()=>void ht({reason:"requested"}))})});async function tp(p){try{if(p.op==="ping")return{id:p.id,ok:!0,value:{pong:!0,protocol_version:Zt,daemon_version:t,pid:l.pid}};if(p.op==="host-state")return{id:p.id,ok:!0,value:ct()};if(p.op==="statusline-payload")return{id:p.id,ok:!0,value:wd(ut(),p.extras)};if(p.op==="statusline-string")return{id:p.id,ok:!0,value:Mu(p.render)};if(p.op==="statusline-dashboard")return{id:p.id,ok:!0,value:Cu(p.dashboard)};if(p.op==="worker-heartbeat")return{id:p.id,ok:!0,value:ci(p.heartbeat)};if(p.op==="project-register")return{id:p.id,ok:!0,value:ui(p.registration,p.session_project)};if(p.op==="project-renew")return{id:p.id,ok:!0,value:pi(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:fi(p.project_label,p.session_project)};if(p.op==="worker-command")return{id:p.id,ok:!0,value:await Wu(p.command)};if(p.op==="worker-start"){let y=qe("worker-start",p.session_project,p.spec.project_label);if(!y.permitted)return{id:p.id,ok:!1,error:y.reason};let _=xr(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=mt("requested");return await bi({reason:"requested",...p.detail==null?{}:{note:p.detail}}),{id:p.id,ok:!0,value:y}}let g=p;return{id:g.id??et(),ok:!1,error:`unsupported redskilled op: ${g.op??"unknown"}`}}catch(g){return{id:p.id??et(),ok:!1,error:g instanceof Error?g.message:String(g)}}}return I(),Qu(),Ju(),qu(),zu(),$u(),Yu(),Xu(),{socketPath:n.socketPath,lease:m.lease,startedAt:b,closed:_r,startWorker:xr,admit:mi,ceiling:()=>i,killWorkerOverBudget:hi,sampleMemoryBudgets:gi,renewLease:ki,pollRepositoryActivity:wr,pollGithubBalance:li,githubBalance:()=>yn,pollQueueDiscovery:ai,queueDiscovery:()=>_e,driveDemand:di,demand:()=>it,sweepWorkerLiveness:Sr,publishWorkerHeartbeat:ci,reattached:()=>[...be].map(p=>v.get(p)).filter(p=>p!=null),flushEvents:()=>k.flush(),trackWorker(p){v.set(p.worker_id,p),me("worker-birth",p,null),I()},releaseWorker(p){let g=v.get(p),y=v.delete(p);return be.delete(p),Ge.delete(p),ot.delete(p),g&&me("worker-death",g,"released by the daemon"),I(),y},workerCount:()=>v.size,registerProject:ui,renewProject:pi,deregisterProject:fi,registrations:()=>ct().registrations??[],hostState:ct,statuslinePayload:ut,evaluateIdle:Ri,observePublishedVersion:yi,checkForReplacement:ft,stopReport:mt,stop:ht}}async function hb(e){for(let n=0;n<2;n++){let t=ab();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 te(e))throw new mn(e);await Gc(e,{force:!0})}}throw new mn(e)}async function te(e,n=250){try{return(await Ot({socketPath:e,timeoutMs:n},{id:et(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function gb(e,n){Yl(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??et(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function Os(e){let n=e.socketPath,t=yb(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 ${Vc(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 \`${Pe("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 \`${Pe("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function As(e){return`${e.reason} ${e.repair}`}function yb(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:kb(n.acquired_at,e.now??new Date().toISOString())}}function kb(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 Vc(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`}ye();var Qc=1e4,He=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"?`. ${As(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},Ls=class extends He{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}};async function ir(e,n={}){let t=n.answers??await te(e.socketPath),r=await Zn(e.leasePath).catch(()=>{});return Os({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&H(r.pid)})}async function Ts(e,n={}){try{return await wb(e,n)}catch(t){if(t instanceof ve||t instanceof He)throw t;let r=await ir(e).catch(()=>{});throw new He(e.socketPath,t,r)}}async function wb(e,n){if(await bb(_b(e.socketPath),{recursive:!0,mode:448}),await te(e.socketPath))return"already-running";await vb(e);let t=await Sb(e,n);if(t!=null)return t;let r=await Zl(e.lockPath,{...n.spawnLockMaxAgeMs==null?{}:{maxAgeMs:n.spawnLockMaxAgeMs},onReap:n.onSpawnLockReaped??xb});if(!r.acquired)return await qc(e,n,void 0,r),"joined";try{if(await te(e.socketPath))return"already-running";let o=await Pb(e,n);return await qc(e,n,o),"spawned"}finally{await ea(r)}}function xb(e){process.stderr.write(`redskilled: reaped the spawn lock ${JSON.stringify(e.lockPath)} (${e.reason}, ${Math.round(e.ageMs/1e3)}s old, holder ${e.holder==null?"unnamed":`pid ${e.holder.pid}`}) and went on to spawn
81
- `)}async function Sb(e,n){let t=await ir(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??Qc,o=Date.now()+r;for(;;){if(await te(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(i=>setTimeout(i,25))}let s=await ir(e).catch(()=>{});if(s==null||s.kind!=="held-unresponsive")return null;throw new Ls(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 vb(e){let t=await Wt(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&H(t.pid))throw new ve(e.machineClaimPath,"held",t)}async function zc(e,n,t={}){await Ts(e,t);let r;try{r=await Qn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:Jc()})}catch(o){throw new He(e.socketPath,o,await ir(e).catch(()=>{}))}if(!r.ok)throw new Error(r.error);return r.value}async function Yc(e,n={},t={}){if(!await te(e.socketPath))return Aa(e.socketPath);let r;try{r=await Qn({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:Jc(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new He(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!Lo(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await Eb(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 Eb(e,n){let t=Date.now()+n;for(;;){if(!await te(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function Xc(e,n={}){let t=await zc(e,{op:"host-state"},n);if(!Ad(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function Zc(e,n={},t){let r=await zc(e,{op:"statusline-payload",...n.sessionProject!=null?{session_project:n.sessionProject}:{},...t==null?{}:{extras:t}},n);if(!rs(r))throw new Error("redskilled daemon returned a malformed statusline payload");return r}async function eu(e,n=D,t={}){let r=await Zc(e,t,{vitals:!0,logs:n.verbose,display:!0});return Be(r,n)}async function nu(e,n={},t={}){let r=await Zc(e,t,{vitals:!0,logs:!0,display:!0});return un(r,{...ce,...n})}async function qc(e,n,t,r){let o=Date.now()+(n.readyTimeoutMs??Qc);for(;;){if(await te(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=o){if(r!=null)throw new Error(`no redskilled daemon answered on ${JSON.stringify(e.socketPath)} within the ready window, and ${na(r)}`);let s=t?` from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source})${t.exit?`, which ${t.exit}`:""}`:"";throw new Error(`redskilled daemon did not start on ${JSON.stringify(e.socketPath)}${s}`)}await new Promise(s=>setTimeout(s,25))}}async function Pb(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await ua({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,...Ie(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=Rb(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}ye();import{chmod as au,mkdir as cu,readFile as uu,stat as Cb,writeFile as Wb}from"node:fs/promises";import{homedir as Ns}from"node:os";import{dirname as Bb,join as Ms}from"node:path";import{join as Db}from"node:path";var tu=["local","tmp","host"],jb="local",nt="plugins.dev.workspace.target";var $s=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function ou(e){let n=rn(e,nt),t=Lb(n??"").trim();return t===""?void 0:t}function su(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:jb};let t=tu.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 $s(`${nt}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${tu.join(", ")}) or an absolute parent directory for Workers.`)}function iu(e,n){return e.kind==="preset"?e.preset==="host":Ab(Ob(e.parentDir,n),$e(n))}function Ob(e,n){return e==="~"?ru(n):e.startsWith("~/")?Db(n,e.slice(2)):ru(e)}function Ab(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function ru(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function Lb(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}ye();import{createHash as Tb}from"node:crypto";import{hostname as $b}from"node:os";import{join as lr}from"node:path";var hn="redskilled.sock",Ib="REDSKILLED_SESSION";function Nb(e={}){let n=e.env??process.env,t=n[Ib]?.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 Mb(e={}){return lu(e.host??$b())}function ue(e={}){let n=Nb(e),t=e.runtimeDir??At({key:`redskilled:${n}`,socketFileName:hn,env:e.env,uid:e.uid}),r=Mb(e);return{sessionKey:n,sessionKeyHash:lu(n),machineIdHash:r,runtimeDir:t,socketPath:lr(t,hn),lockPath:lr(t,"redskilled.spawn.lock"),leasePath:lr(t,"redskilled.lease.toon"),eventLanePath:lr(t,wa),machineClaimPath:e.machineClaimPath??Ct({env:e.env,machineIdHash:r,platform:e.platform})}}function lu(e){return Tb("sha256").update(e).digest("hex").slice(0,12)}var Is=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${Pe("red-skills-redskilled",["provision"])}\` directly`;async function pu(e=Ns()){let n=$e(e),t=await Ws(n);return t===void 0?(await cu(n,{recursive:!0,mode:le}),await au(n,le),{path:n,created:!0,tightened:!1,mode:le}):t===le?{path:n,created:!1,tightened:!1,mode:t}:(await au(n,le),{path:n,created:!1,tightened:!0,mode:le})}var fu={needed:!1,declaredBy:`no ${nt} in view`};async function Cs(e={}){let n=e.homeDir??Ns(),t=e.declaredTarget?.trim();if(t)return du(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return fu;let o=Ms(r,".red","config.yaml"),s=await uu(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=ou(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:du(i,n,o)}function du(e,n,t){let r=`${nt}: ${e} (${t})`;try{return{needed:iu(su(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function mu(e){let n=[Fb(e),Hb(e),Ub(e),Gb(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 Fb(e){let n=e.homeNeed??fu;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:Is}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??le;return t!==le?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${le.toString(8)}`,fix:`${Is} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function Hb(e){return de(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 \`${Pe("red-skills-redskilled",["provision"])}\``}}function Ub(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:`${Is} \u2014 it starts the daemon and waits for the socket`}}function Gb(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 hu(e={}){let n=e.env??process.env,t=e.homeDir??Ns(),r=e.paths??ue({env:n}),o=$e(t),[s,i,l]=await Promise.all([Ws(o),te(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):Cs({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:Se(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await Vb(qb(e,n,t),n)}}var Kb="redskilled.service";function gu(e){return Ms(e,"systemd","user",Kb)}function yu(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 ku(e){let n=gu(e.configHome);return await Ws(n)!==void 0?{path:n,status:"already-present"}:(await cu(Bb(n),{recursive:!0}),await Wb(n,e.unit,"utf8"),{path:n,status:"installed"})}async function Vb(e,n){if(process.platform!=="linux")return"unsupported";try{return await uu(gu(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function qb(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??Ms(t,".config")}async function Ws(e){try{return(await Cb(e)).mode&511}catch{return}}import{readdir as bu,rm as Jb,stat as Qb}from"node:fs/promises";import{dirname as zb,join as Bs}from"node:path";var Yb=5*6e4,Xb="redskilled.";function Zb(e={}){let n=e.env??process.env,t=i=>zb(At({key:"redskilled:reclaim-probe",socketFileName:hn,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 _u(e={}){let n=e.roots??Zb(e),t=e.graceMs??Yb,r=e.now??Date.now,o=e.isPidAlive??H,s=e.answers??r_,i=e.dryRun===!0,l=[];for(let a of n){let d;try{d=(await bu(a,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name)}catch{continue}for(let c of d.sort())l.push(await e_(Bs(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 e_(e,n){let t;try{t=(await bu(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:wu(i),removed:[]}}let r=t.filter(i=>i.startsWith(Xb));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await n_(Bs(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 Ru(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(hn)&&await n.answers(Bs(e,hn)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await t_(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 Ru(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function Ru(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await Jb(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:wu(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function n_(e){try{return await Zn(e)}catch{return}}async function t_(e,n){try{return Math.max(0,n()-(await Qb(e)).mtimeMs)}catch{return}}async function r_(e){try{return(await Qn({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function wu(e){return e instanceof Error?e.message:String(e)}var o_="plugins.dev.statusline",s_="dev.statusline";function i_(e){let n=[],t=l=>{for(let a of[o_,s_]){let d=`${a}.${l}`,c=rn(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 l_={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 Fs(e){let{values:n,positionals:t}=Le(e,l_),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 Hs(e={}){let n=e.configText==null?{config:{},warnings:[]}:i_(e.configText),t=e.flags??{};return{options:{...D,mode:t.mode??n.config.mode??D.mode,project:t.project!==void 0?t.project:e.project??D.project,maxWorkers:t.maxWorkers??n.config.maxWorkers??D.maxWorkers,maxProjects:t.maxProjects??n.config.maxProjects??D.maxProjects,maxWidth:t.maxWidth??n.config.maxWidth??D.maxWidth,verbose:t.verbose??n.config.verbose??D.verbose},warnings:n.warnings}}var d_=`Usage: redskilled <command> [options]
78
+ `)}`),this.name="RedskilledReplacementEntryError",this.searched=[...t]}};function pb(e,n={}){let t=n.env??process.env,r=n.exists??ib,o=n.execPath??process.execPath,s=n.callerEntry===void 0?process.argv[1]:n.callerEntry,i=`redskilled-${e}.bundle.min.mjs`,l=[],a=[[Fc(Ht(t),i),"bundle-cache"]];s&&a.push([Fc(ab(db(s)),i),"caller-sibling-bundle"]);for(let[d,u]of a)if(l.push(d),r(d))return{command:o,args:[d],version:e,source:u,searched:l};if(t.RED_SKILLS_NO_PINNED_DISPATCH==="1")throw new Gs(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 Yc(e,n={}){if(e.via==="supervisor-exit")return{via:e.via,to:e.to};let t=n.resolveEntry??(r=>pb(r,n.env==null?{}:{env:n.env}));return{via:e.via,to:e.to,entry:t(e.to)}}function Xc(e,n,t={}){let r=t.io??{};if(e.via==="supervisor-exit"||e.entry==null)return(r.exit??mb)(Hc),{...e,exitCode:Hc};let o=[...e.entry.args,...Ce(n,t.idleMs==null?{}:{idleMs:t.idleMs})];return(r.spawnSuccessor??fb(r.env))(e.entry,o),e}function fb(e){return(n,t)=>{let r=sb(n.command,[...t],{detached:!0,stdio:"ignore",env:{...e??process.env,REDSKILLED_DAEMON:"1",[Kc]:"1"}});r.on("error",()=>{}),r.unref()}}function mb(e){process.exitCode=e,process.exit(e)}async function Zc(e,n=process.env,t=hb){let r=nu(n),o=tu(e,n);if(n[cb]==="1")return{version:o,newest:r};let s=re(e)===null?"0.0.0":e;try{let i=await va({fetchText:t},s);return{version:i.sameMajor??o,newest:i.newest??r}}catch{return{version:o,newest:r}}}function eu(e,n=process.env,t){let r=t??Ks;return{version:tu(e,n,r),newest:nu(n,r)}}function nu(e=process.env,n=Ks){return ou(ru(e,n))}function tu(e,n=process.env,t=Ks){let r=re(e.trim())?.major;return r===void 0?null:ou(ru(n,t).filter(o=>re(o)?.major===r))}function ru(e,n){let t=[];for(let r of n(Ht(e))){let o=/^redskilled-(.+)\.bundle\.min\.mjs$/.exec(r)?.[1];!o||re(o)===null||t.push(o)}return t}function ou(e){let n=null;for(let t of e)(n===null||Ws(t,n)>0)&&(n=t);return n}function Ks(e){try{return lb(e)}catch{return[]}}async function hb(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 gb,readFile as yb,rename as kb,rm as Vs,writeFile as su}from"node:fs/promises";import{randomUUID as Rb}from"node:crypto";import{dirname as bb}from"node:path";var ur=class extends Error{constructor(n){super(`redskilled lease ${JSON.stringify(n)} is held by another owner`),this.name="RedskilledLeaseOwnershipError"}};async function lt(e){let n;try{n=await yb(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}let t=_b(n);return wb(t)?t:void 0}var iu;function au(){return iu??={pid:process.pid,startTime:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString()},iu}function du(e,n,t={}){let r=t.clock??(()=>new Date().toISOString()),o=t.isPidAlive??B;async function s(){return await lt(e)}async function i(a){let d=`${e}.${a.pid}.${Rb()}.tmp`;await su(d,lu(a),{encoding:"utf8",mode:384}),await kb(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 gb(bb(e),{recursive:!0,mode:448});let d=!1;for(;;){let u=r(),p=l(a,u);try{return await su(e,lu(p),{encoding:"utf8",mode:384,flag:"wx"}),{acquired:!0,reaped:d,lease:p}}catch(m){if(m.code!=="EEXIST")throw m}let f=await s();if(!f){await Vs(e,{force:!0}),d=!0;continue}if(qs(f,a))return{acquired:!0,reaped:d,lease:f};if(await o(f.pid))return{acquired:!1,lease:f};await Vs(e,{force:!0}),d=!0}},async renew(a){let d=await s();if(!d||!qs(d,a))throw new ur(e);let u={...d,renewed_at:r()};return await i(u),u},async release(a){let d=await s();if(!d)return!1;if(!qs(d,a))throw new ur(e);return await Vs(e,{force:!0}),!0}}}function qs(e,n){return e.pid===n.pid&&e.start_time===n.startTime}function lu(e){return`${W(e,{keyedMapCollapse:!0})}
79
+ `}function _b(e){let n=e.trim();if(!n)return null;try{return JSON.parse(n)}catch{try{return Q(n)}catch{return null}}}function wb(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 Js=3e5,Ab=1e4,Lb=6e4,Tb=15e3,$b=3e4,Ib=6e4,cu=16;function Nb(e){if(e.event!=="worker-death"&&e.event!=="worker-budget-kill")return null;let n=e.event==="worker-budget-kill",t=e.detail??`redskilled observed exit code=${e.exit_code??"null"} signal=${e.signal??"null"}`;return{version:1,ts:e.ts,kind:"worker",id:e.worker_id,pid:e.pid,last_seen:e.ts,last_phase:"unreported",sender_class:n?"teardown":"unknown",confidence:n?"high":"none",signal:e.signal,host_boot_changed:!1,evidence:n?[t]:[],checked:[`redskilled host event: ${t}`]}}var Ke=class extends Error{constructor(t,r){super(`a redskilled daemon already owns ${JSON.stringify(t)}`);this.socketPath=t;this.lease=r;this.name="RedskilledAlreadyRunningError"}},Mb="no tracker transport was given to this daemon, so no queue depth was ever asked for";async function pu(e){let{paths:n}=e,t=e.daemonVersion??"0.0.0-dev",r=e.idleMs??Js,o=e.clock??(()=>new Date().toISOString()),s=e.launch??$c,i=e.ceiling??Wa();e.repositoryActivity!=null&&us(e.repositoryActivity.projects,e.repositoryActivity.hostTokenRef);let l=e.owner??au(),a=e.leaseStore??du(n.leasePath,{sessionKeyHash:n.sessionKeyHash,machineIdHash:n.machineIdHash,socketPath:n.socketPath},{clock:o}),d=e.machineOwner??td(),u={machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,socketPath:n.socketPath},p=e.machineClaimStore??Jt(n.machineClaimPath,u,{clock:o});await Pb(Ob(n.socketPath),{recursive:!0,mode:448});let f=await p.claim(d);if(!f.claimed)throw f.claim?.socket_path===n.socketPath?new Ke(n.socketPath):new De(p.claimPath,f.reason,f.claim);let m=await a.acquire(l);if(!m.acquired)throw await p.release(d).catch(()=>{}),new Ke(n.socketPath,m.lease);let g;try{g=await Wb(n.socketPath,async()=>{let[c,h]=await Promise.all([a.read().catch(()=>{}),p.read().catch(()=>{})]);return c!=null&&c.pid!==l.pid&&B(c.pid)?!0:h!=null&&h.socket_path===n.socketPath&&h.pid!==d.pid&&B(h.pid)})}catch(c){throw await a.release(l).catch(()=>{}),await p.release(d).catch(()=>{}),c}let _=o(),k=e.eventLane??Ha(n.eventLanePath),w=e.liveness??hc,O=e.livenessGraceMs??mc,X=e.stopWorker??wc,he=e.unitInventory??(()=>kc(n.machineClaimPath,qt({machineIdHash:n.machineIdHash}))?Rc():[]),ge=e.unitMainPid??yc,qe=e.treeSampler??Ad,hr=e.readLogTail??Ic,di=e.sampleMs??Tb,ci=e.leaseRenewMs??$b,ui=e.registrationSustainMs??Ib,pi=e.publishedVersion??(c=>Zc(c)),fi=e.replaceCheckMs??Gc,mi=e.publishedProbeTimeoutMs??Ab,Qu=e.localPublishedEvidence??(c=>eu(c,e.replacementIO?.env??process.env)),zu=e.bornByReplacement??Vc(),hi=e.replaceBootCheckMs??Lb,gi=e.supervised??zc(),yi=e.replacementIO??{},oe=e.repositoryActivity,ki=oe?.intervalMs??cs,ct=e.githubBalance,Ae=e.queueDiscovery,ut=Ae?.transport??oe?.transport,gr=Ae?.unconfiguredReason??Mb,yr=Ae?.intervalMs??15e3,Ri=e.demandMs??15e3,Yu=e.demandBackoffMs??3e4,E=new Map,Se=new Set,Je=new Map,pt=new Map,kr=[],ft=[],mt=e.deaths===void 0?void 0:[...e.deaths],I=new Map,ye=new Map,Rr=new Set,bi={},br=null,_i=null,_r=null,wi=!1,wr=0,xr=null,_n="none",Sr=null,xi=null,vr=null,wn=null,G=null,ht=null,xn=[],Sn=null,gt={},Er=!1,Qe,vn,En,Pn,Dn,jn,yt,On,ze,Ye,K=!1,Pr=!1,kt=null,Si,Dr=new Promise(c=>{Si=c});function Xe(c){vi(c);let h=Date.parse(c),y=dd(I.values(),h);for(let R of y.lapsed){I.delete(R.project_label);let x=G?.projects.find(A=>A.project_label===R.project_label),S=[...E.values()].some(A=>A.project_label===R.project_label);(x?.outcome==="counted"&&(x.depth??0)>0||S)&&ye.set(R.project_label,R),Xu(R,h)}return y.lapsed}function Xu(c,h){let y=Number.isFinite(h)?new Date(h).toISOString():c.renew_by;xn.push({project_label:c.project_label,at:y,renew_by:c.renew_by,renewals:c.renewals,sustains:c.sustains??0,detail:`redskilled dropped the registration for project ${JSON.stringify(c.project_label)}: it stood until ${c.renew_by} and nothing renewed it \u2014 no session spoke for it, and no poll found it work or a Worker to hold it up`}),xn.length>cu&&xn.splice(0,xn.length-cu)}function vi(c){if(I.size===0)return;let h=Date.parse(c);if(!Number.isFinite(h))return;let y={};for(let S of E.values())y[S.project_label]=(y[S.project_label]??0)+1;let R=G==null?Number.NaN:Date.parse(G.fetched_at),x=new Map((G?.projects??[]).map(S=>[S.project_label,S]));for(let S of[...I.values()]){let D=Number.isFinite(R)&&h-R<=S.renew_within_ms?x.get(S.project_label):void 0,Re=Jo(S,{now:c,...D==null?{}:{queue:{outcome:D.outcome,depth:D.depth}},liveWorkers:y[S.project_label]??0});Re.registration!==S&&I.set(S.project_label,Re.registration)}}function Zu(c){if(ye.size===0||G==null)return;let h=Date.parse(c);if(!Number.isFinite(h))return;let y=new Map(G.projects.map(R=>[R.project_label,R]));for(let[R,x]of[...ye]){if(h-Date.parse(x.renew_by)>x.renew_within_ms){ye.delete(R);continue}let S=y.get(R);if(S==null)continue;let A=Jo(x,{now:c,queue:{outcome:S.outcome,depth:S.depth},liveWorkers:[...E.values()].filter(D=>D.project_label===R).length});A.verdict==="open-work"||A.verdict==="live-worker"?(I.set(R,A.registration),ye.delete(R)):A.verdict==="drained"&&ye.delete(R)}}function Rt(){let c=o();return Xe(c),zd({now:c,daemonVersion:t,machineIdHash:n.machineIdHash,sessionKeyHash:n.sessionKeyHash,pid:l.pid,startedAt:_,scope:rd(p.claimPath,u,d),workers:[...E.values()],registrations:[...I.values()],lapses:xn,queue:G,published:{version:_i,checkedAt:_r,newer:wi,replacement:_n,newest:Sr,majorHold:xi,checks:wr,holdReason:xr}})}function bt(){return Fd({hostState:Rt(),ceiling:i,rss:bi,sampledAt:br,logLines:Object.fromEntries(Je),displays:Object.fromEntries(pt),now:o(),reattachedWorkerIds:[...Se],repositoryActivity:vr,githubBalance:wn,...mt===void 0?{}:{deaths:mt},metrics:Dd({observations:kr,outcomes:ft,now:o()})})}function ep(c,h){kr=Kn([...kr,{worker_id:h,observed_at:c.published_at,tokens:c.display.tokens,tools:c.display.tools,runner:c.display.runner,model:c.display.model}],y=>y.observed_at,{now:o()})}function np(c){ft=Kn([...ft,c],h=>h.ts,{now:o()})}async function jr(){return oe==null||oe.projects.length===0?null:(vr=await Id({projects:oe.projects,hostTokenRef:oe.hostTokenRef,transport:oe.transport,closedWindowMs:oe.closedWindowMs,now:o()}),vr)}async function Ei(){return ct==null?null:(wn=await es({transport:ct.transport,now:o()}),wn)}function tp(){if(K||ze!=null||ct==null)return;let c=()=>{ze=void 0,Ei().catch(()=>{}).then(()=>{if(K)return;let h=ct.intervalMsOverride??nr(wn??rp(),{now:o()});ze=setTimeout(c,h),ze.unref()})};c()}function rp(){return er(o())}function op(){if(!(ut!=null||Ae?.armTransport==null))try{let c=Ae.armTransport();if(c.transport!=null){ut=c.transport;return}c.unconfiguredReason!=null&&(gr=c.unconfiguredReason)}catch(c){gr=`this host could not resolve a tracker credential: ${c instanceof Error?c.message:String(c)}`}}async function Pi(){let c=o();Xe(c);let h=Date.parse(c);for(let[S,A]of[...ye])Number.isFinite(h)&&h-Date.parse(A.renew_by)>A.renew_within_ms&&ye.delete(S);let R=[...new Map([...ye,...I]).values()].map(S=>({project_label:S.project_label,selector:S.selector})).sort((S,A)=>S.project_label.localeCompare(A.project_label));if(R.length===0)return null;if(op(),ut==null)return G=Sc(R,c,gr),G;G=await vc({projects:R,transport:ut,now:c,...Ae?.batchSize==null?{}:{batchSize:Ae.batchSize}});let x=o();return Zu(x),vi(x),G}async function Di(){let c=o();if(Er)return ht??Ka(c);Er=!0;try{await Ar().catch(()=>{});let h={};for(let D of E.values())h[D.project_label]=(h[D.project_label]??0)+1;let y={};for(let D of G?.projects??[])y[D.project_label]=D.depth;let R=Date.parse(c),x=Ga({projects:[...I.values()].map(D=>({project_label:D.project_label,selector:D.selector,argv:D.argv,workspace_path:D.workspace_path,target:D.target})),queue:y,live:h,nowMs:Number.isFinite(R)?R:0,backoffUntilMs:Sn,birthHaltUntilMs:qa(gt,Number.isFinite(R)?R:0)}),S=[],A=null;for(let D of x.births){let Re,Ep=at(),vt=I.get(D.project_label),Fi=sd({argv:D.argv,...vt?.env==null?{}:{env:vt.env},...vt?.log_path==null?{}:{log_path:vt.log_path}},{worker_id:Ep,slot:D.index,workspace_path:D.workspace_path},{project_label:D.project_label});try{Re=Or(Fi)}catch(Ir){A=Ir instanceof Error?Ir.message:String(Ir),Sn=(Number.isFinite(R)?R:Date.now())+Yu;break}S.push({project_label:D.project_label,worker_id:Re.worker.worker_id,pid:Re.worker.pid,warnings:Fi.log_path==null?[...Re.warnings,`project ${JSON.stringify(D.project_label)} declared no log path, so no surface can show what Worker ${JSON.stringify(Re.worker.worker_id)} logs unless it publishes a line on its heartbeat`]:Re.warnings})}return A==null&&x.births.length>0&&(Sn=null),ht={version:1,at:c,requested:x.births.length,granted:S,shortfall:x.births.length-S.length,refusal:A,retry_after:Sn==null?null:new Date(Sn).toISOString(),projects:x.intents},ht}finally{Er=!1}}function sp(c){return Ue(bt(),{...j,mode:c?.mode??j.mode,project:c?.project??j.project,maxWorkers:c?.max_workers??j.maxWorkers,maxProjects:c?.max_projects??j.maxProjects,maxWidth:c?.max_width??j.maxWidth,verbose:c?.verbose??j.verbose})}function ip(c){return yn(bt(),{mode:c?.mode??pe.mode,project:c?.project??pe.project,maxWidth:c?.max_width??pe.maxWidth,maxRows:c?.max_rows??pe.maxRows})}function Ze(c,h,y){return ud({op:c,sessionProject:h??null,targetProject:y})}async function lp(c){let h=E.get(c.worker_id),y=Ze(cd(c.command),c.session_project,h?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(c.command!=="stop")throw new Error(`redskilled does not implement ${c.command}: it owns birth, death and limits, and ${c.command} is a work decision the project's own bundle makes on top of them`);let R=h!=null&&await pp(h,c.detail??"stopped by its own project");return{version:1,command:c.command,worker_id:c.worker_id,applied:R,reach:y,detail:R?`redskilled stopped Worker ${JSON.stringify(c.worker_id)} of project ${JSON.stringify(h.project_label)}`:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to stop`}}function _t(c){E.delete(c),Se.delete(c),Je.delete(c),pt.delete(c)}function ji(c){let h=E.get(c.worker_id),y=Ze("worker-heartbeat",c.session_project,h?.project_label??null);if(!y.permitted)throw new Error(y.reason);if(typeof c.last_log_line!="string")throw new Error("redskilled worker heartbeat last_log_line must be a string");if(h==null)return{version:1,worker_id:c.worker_id,accepted:!1,reach:y,published_at:null,detail:`redskilled holds no live Worker ${JSON.stringify(c.worker_id)} to publish a line for`};let R=o();Je.set(c.worker_id,{line:c.last_log_line,published_at:R,source:"heartbeat"});let x=c.display===void 0?null:jc(c.display);if(x!=null){let S={display:x,published_at:R};pt.set(c.worker_id,S),ep(S,c.worker_id)}return{version:1,worker_id:c.worker_id,accepted:!0,reach:y,published_at:R,detail:`redskilled stored a line for Worker ${JSON.stringify(c.worker_id)} without reading it`}}async function ap(c,h,y){let R=`exit code=${h??"null"} signal=${y??"null"}`;if(c.unit!=null&&c.unit!==""&&await cp(c)){up(c,`its launch client ended (${R}) while unit ${JSON.stringify(c.unit)} stayed active, so the daemon holds it by unit name from here on and its death is discovered by asking the host`);return}_t(c.worker_id),ke("worker-death",c,R,{exitCode:h,signal:y}),N()}function dp(c,h){if(!Number.isFinite(h)||h<0){gt[c]=Vt;return}let y=gt[c]??Vt,R=Va(y,h,Date.parse(o()));gt[c]=R,R.haltUntilMs!=null&&y.haltUntilMs==null&&process.stderr.write(`redskilled: project ${JSON.stringify(c)} lost ${R.shortLifeStreak} Workers in a row inside ${6e4}ms of birth; not asking for another until ${new Date(R.haltUntilMs).toISOString()}
80
+ `)}async function cp(c){try{return await w(c)===!0}catch{return!1}}function up(c,h){let y=c.unit==null?null:ge(c.unit);E.set(c.worker_id,{...c,...y!=null&&y>0?{pid:y}:{},warnings:[...c.warnings,h]}),Se.add(c.worker_id),N()}function Oi(c,h){let y=Ze("project-register",h,c.project_label);if(!y.permitted)throw new Error(y.reason);let R=o();Xe(R);let x=id(c,{now:R,held:I.get(c.project_label)});return I.set(x.project_label,x),N(),{version:1,registration:x,reach:y,detail:`redskilled holds a registration for project ${JSON.stringify(x.project_label)} at a target of ${x.target} until ${x.renew_by}, and has read neither its selector nor its argv`}}function Ai(c,h={}){let y=Ze("project-renew",h.sessionProject,c);if(!y.permitted)throw new Error(y.reason);let R=o();Xe(R);let x=I.get(c);if(x==null)throw new Qt(c);let S=ld(x,{now:R,...h.renewWithinMs==null?{}:{renew_within_ms:h.renewWithinMs},...h.launch==null?{}:{launch:h.launch}});return I.set(S.project_label,S),N(),{version:1,registration:S,reach:y,detail:`redskilled renewed the registration for project ${JSON.stringify(S.project_label)}, which now stands until ${S.renew_by} after renewal ${S.renewals}`+(h.launch==null?"":`, carrying launch revision ${S.launch_revision} for its next Worker`)}}function Li(c,h){let y=Ze("project-deregister",h,c);if(!y.permitted)throw new Error(y.reason);let R=I.delete(c);return{version:1,project_label:c,released:R,reach:y,detail:R?`redskilled released the registration for project ${JSON.stringify(c)}`:`redskilled held no registration for project ${JSON.stringify(c)}, so there was nothing to release`}}async function pp(c,h){try{await X(c)}catch{}return _t(c.worker_id),ke("worker-death",c,h),N(),!0}function Ti(c){return Ma({ceiling:i,workers:[...E.values()],budget:c.budget,projectLabel:c.project_label})}function Or(c){let h=Ca({ceiling:i,workers:[...E.values()],budget:c.budget}),y=s({spec:c,admission:Ti(c),memoryCeiling:h,clock:o,onExit:(R,x,S)=>{let A=E.get(R);if(A==null){N();return}ap(A,x,S).catch(()=>{})}});return E.set(y.worker.worker_id,y.worker),ke("worker-birth",y.worker,null),N(),y}function ke(c,h,y,R={}){if(K)return;let x=o();(c==="worker-death"||c==="worker-budget-kill")&&(np({worker_id:h.worker_id,ts:x,outcome:c}),$i({version:1,ts:x,event:c,worker_id:h.worker_id,project_label:h.project_label,pid:h.pid,workspace_path:h.workspace_path,log_path:h.log_path??null,isolated:h.isolated,unit:h.unit??null,memory_high:h.budget?.memory_high??null,memory_max:h.budget?.memory_max??null,cpu_weight:h.budget?.cpu_weight??null,detail:y,reason:null,exit_code:R.exitCode??null,signal:R.signal??null}),dp(h.project_label,Date.parse(x)-Date.parse(h.started_at))),k.record({event:c,worker:h,ts:x,detail:y,...R.exitCode!==void 0?{exitCode:R.exitCode}:{},...R.signal!==void 0?{signal:R.signal}:{}}).catch(()=>{})}function $i(c){let h=Nb(c);if(h==null)return;let y=[h,...(mt??[]).filter(R=>R.kind!==h.kind||R.id!==h.id)].sort((R,x)=>Date.parse(R.ts)-Date.parse(x.ts));mt=Kn(y,R=>R.ts,{now:o()})}async function Ar(){let c=Date.parse(o()),h=[...E.values()].filter(R=>{if(Se.has(R.worker_id))return!0;let x=Date.parse(R.started_at);return!Number.isFinite(x)||c-x>=O});if(h.length===0)return[];let{dead:y}=await Ms(h,w);for(let R of y)_t(R.worker_id),ke("worker-death",R,"the host no longer confirms this Worker");return y.length>0&&N(),y}async function Ii(c,h){let y=E.get(c);if(!y)return!1;try{await X(y)}catch{}return _t(c),ke("worker-budget-kill",y,h),N(),!0}async function Ni(){let c=[...E.values()];if(c.length===0)return[];let h;try{h=await qe(c)}catch{return[]}let y=h.rss;bi=y,br=o(),fp(h.cpu_seconds,br);let{terminations:R}=Od({workers:c,rss:y}),x=[];for(let S of R)await Ii(S.worker_id,S.reason)&&x.push(S);return x}function fp(c,h){for(let[y,R]of Object.entries(c)){if(typeof R!="number"||!Number.isFinite(R))continue;let x=E.get(y);x&&E.set(y,{...x,cpu:{cpu_seconds:R,sampled_at:h}})}}async function mp(){try{return mi<=0?await pi(t):await new Promise(c=>{let h=setTimeout(()=>c(Lr()),mi);h.unref(),pi(t).then(y=>{clearTimeout(h),c(y)},()=>{clearTimeout(h),c(Lr())})})}catch{return Lr()}}function Lr(){try{return Qu(t)}catch{return null}}async function Mi(){if(it(t))return wr+=1,_r=o(),xr="local-build",{act:"hold",reason:"local-build"};let c=qc(await mp()),h=c.version;_i=h,Sr=c.newest??null,_r=o(),xi=Jc({running:t,newest:Sr,supervised:gi});let y=Qc({running:t,published:h,supervised:gi});return wi=y.act==="replace",wr+=1,xr=y.act==="hold"?y.reason:null,_n!=="in-progress"&&(_n=y.act==="replace"?"pending":"none"),y}async function wt(){let c=await Mi();if(c.act!=="replace"||_n==="in-progress")return c;let h=Yc(c,yi);return _n="in-progress",await k.flush().catch(()=>{}),await St({reason:"replaced"}),Xc(h,n,{...r==null?{}:{idleMs:r},io:yi}),c}function hp(){K||jn!=null||fi<=0||(!zu&&hi>0&&(yt=setTimeout(()=>{wt().catch(()=>{})},hi),yt.unref()),jn=setInterval(()=>{wt().catch(()=>{})},fi),jn.unref())}async function Ci(){return await a.renew(l).catch(()=>null)}function gp(){K||En!=null||ci<=0||(En=setInterval(()=>{Ci()},ci),En.unref())}function yp(){K||Pn!=null||ui<=0||(Pn=setInterval(()=>{Xe(o())},ui),Pn.unref())}function kp(){K||vn!=null||di<=0||(vn=setInterval(()=>{Ni().catch(()=>{})},di),vn.unref())}function Rp(){K||On!=null||oe==null||oe.projects.length===0||ki<=0||(jr().catch(()=>{}),On=setInterval(()=>{jr().catch(()=>{})},ki),On.unref())}function bp(){if(K||Ye!=null||yr<=0)return;let c=h=>{Ye=setTimeout(()=>{Ye=void 0,Pi().catch(()=>{}).finally(()=>{if(K)return;let y=Date.parse(o());c(Dc(G,yr,Number.isFinite(y)?y:Date.now()))})},h),Ye.unref()};c(yr)}function _p(){K||Dn!=null||Ri<=0||(Dn=setInterval(()=>{Di().catch(()=>{})},Ri),Dn.unref())}function N(){K||(Qe&&clearTimeout(Qe),Qe=setTimeout(()=>{Ar().catch(()=>{}).then(()=>Wi())},r),Qe.unref())}function Wi(){return E.size>0?(N(),"held-by-workers"):(Xe(o()),I.size>0?(N(),"held-by-registrations"):(wp(),"exited"))}async function wp(){if(!it(t)){if((await wt().catch(()=>null))?.act==="replace"||Pr||K)return;if(E.size>0||I.size>0){N();return}}await St({reason:"idle"})}function xt(c){return Qa({reason:c,socketPath:n.socketPath,daemonVersion:t,pid:l.pid,workers:[...E.values()],projects:[...I.keys()]})}function Bi(c){if(kt!=null)return kt;let h=c.reason??"requested",y=c.note?.trim();return kt=k.recordDaemonStop({ts:o(),pid:l.pid,socketPath:n.socketPath,reason:h,detail:y==null||y===""?xt(h).detail:`${xt(h).detail} \u2014 ${y}`,...c.signal==null?{}:{signal:c.signal}}).catch(()=>{}),kt}async function St(c={}){if(Pr)return await Dr;Pr=!0,await Bi(c),K=!0,Qe&&clearTimeout(Qe),vn&&clearInterval(vn),En&&clearInterval(En),Pn&&clearInterval(Pn),jn&&clearInterval(jn),yt&&clearTimeout(yt),On&&clearInterval(On),ze&&clearTimeout(ze),Ye&&clearTimeout(Ye),Dn&&clearInterval(Dn),await k.flush().catch(()=>{}),g.close();for(let h of Rr)h.destroy();return await new Promise(h=>g.once("close",()=>h())),await uu(n.socketPath,{force:!0}),await a.release(l).catch(()=>{}),await p.release(d).catch(()=>{}),Si(),await Dr}let Tr=await k.read().catch(()=>[]);for(let c of Tr)$i(c);ft=Kn(Tr.filter(c=>c.event==="worker-death"||c.event==="worker-budget-kill").map(c=>({worker_id:c.worker_id,ts:c.ts,outcome:c.event})),c=>c.ts,{now:o()});let xp=Ua(Tr),$r=await Ms(xp,w);for(let c of $r.alive){let h=_c(c),y=h.unit==null||B(h.pid)?null:ge(h.unit);E.set(h.worker_id,y!=null&&y>0?{...h,pid:y}:h),Se.add(h.worker_id)}for(let c of $r.dead)ke("worker-death",c,"the Worker ended while no daemon was watching");let Sp=bc({units:await Promise.resolve(he()).catch(()=>[]),held:[...E.values()],mainPid:ge,now:_});for(let c of Sp)E.set(c.worker_id,c),Se.add(c.worker_id),ke("worker-birth",c,"adopted from an active unit with no birth on this lane");for(let c of $r.alive){if(c.log_path==null||Je.has(c.worker_id))continue;let h=await hr(c.log_path).catch(()=>null);h==null||h.trim()===""||Je.set(c.worker_id,{line:h,published_at:o(),source:"rehydrated"})}g.on("connection",c=>{Rr.add(c),c.once("close",()=>Rr.delete(c)),N(),Bb(c,async(h,y)=>{N();let R=await vp(h);y(R),h.op==="shutdown"&&setImmediate(()=>void St({reason:"requested"}))})});async function vp(c){try{if(c.op==="ping")return{id:c.id,ok:!0,value:{pong:!0,protocol_version:sr,daemon_version:t,pid:l.pid}};if(c.op==="host-state")return{id:c.id,ok:!0,value:Rt()};if(c.op==="statusline-payload")return{id:c.id,ok:!0,value:Bd(bt(),c.extras)};if(c.op==="statusline-string")return{id:c.id,ok:!0,value:sp(c.render)};if(c.op==="statusline-dashboard")return{id:c.id,ok:!0,value:ip(c.dashboard)};if(c.op==="worker-heartbeat")return{id:c.id,ok:!0,value:ji(c.heartbeat)};if(c.op==="project-register")return{id:c.id,ok:!0,value:Oi(c.registration,c.session_project)};if(c.op==="project-renew")return{id:c.id,ok:!0,value:Ai(c.project_label,{...c.session_project==null?{}:{sessionProject:c.session_project},...c.renew_within_ms==null?{}:{renewWithinMs:c.renew_within_ms},...c.launch==null?{}:{launch:c.launch}})};if(c.op==="project-deregister")return{id:c.id,ok:!0,value:Li(c.project_label,c.session_project)};if(c.op==="worker-command")return{id:c.id,ok:!0,value:await lp(c.command)};if(c.op==="worker-start"){let y=Ze("worker-start",c.session_project,c.spec.project_label);if(!y.permitted)return{id:c.id,ok:!1,error:y.reason};let R=Or(c.spec);return await k.flush().catch(()=>{}),{id:c.id,ok:!0,value:{worker:R.worker,admission:R.admission,warnings:R.warnings}}}if(c.op==="shutdown"){let y=xt("requested");return await Bi({reason:"requested",...c.detail==null?{}:{note:c.detail}}),{id:c.id,ok:!0,value:y}}let h=c;return{id:h.id??at(),ok:!1,error:`unsupported redskilled op: ${h.op??"unknown"}`}}catch(h){return{id:c.id??at(),ok:!1,error:h instanceof Error?h.message:String(h)}}}return N(),kp(),gp(),yp(),hp(),Rp(),tp(),bp(),_p(),{socketPath:n.socketPath,lease:m.lease,startedAt:_,closed:Dr,startWorker:Or,admit:Ti,ceiling:()=>i,killWorkerOverBudget:Ii,sampleMemoryBudgets:Ni,renewLease:Ci,pollRepositoryActivity:jr,pollGithubBalance:Ei,githubBalance:()=>wn,pollQueueDiscovery:Pi,queueDiscovery:()=>G,driveDemand:Di,demand:()=>ht,sweepWorkerLiveness:Ar,publishWorkerHeartbeat:ji,reattached:()=>[...Se].map(c=>E.get(c)).filter(c=>c!=null),flushEvents:()=>k.flush(),trackWorker(c){E.set(c.worker_id,c),ke("worker-birth",c,null),N()},releaseWorker(c){let h=E.get(c),y=E.delete(c);return Se.delete(c),Je.delete(c),pt.delete(c),h&&ke("worker-death",h,"released by the daemon"),N(),y},workerCount:()=>E.size,registerProject:Oi,renewProject:Ai,deregisterProject:Li,registrations:()=>Rt().registrations??[],hostState:Rt,statuslinePayload:bt,evaluateIdle:Wi,observePublishedVersion:Mi,checkForReplacement:wt,stopReport:xt,stop:St}}async function Cb(e,n=250){return await new Promise(t=>{let r=Db(e),o=!1,s=l=>{o||(o=!0,clearTimeout(i),r.destroy(),t(l))},i=setTimeout(()=>s("unknown"),n);i.unref?.(),r.once("connect",()=>s("owned")),r.once("error",l=>{s(l.code==="ECONNREFUSED"||l.code==="ENOENT"?"unowned":"unknown")})})}async function Wb(e,n){for(let t=0;t<2;t++){let r=jb();try{return await new Promise((o,s)=>{r.once("error",s),r.listen(e,()=>{r.off("error",s),o()})}),r}catch(o){if(r.close(),o.code!=="EADDRINUSE")throw o;if(await Cb(e)!=="unowned")throw new Ke(e);if(await n?.())throw new Ke(e);await uu(e,{force:!0})}}throw new Ke(e)}async function fe(e,n=250){try{return(await Wt({socketPath:e,timeoutMs:n},{id:at(),op:"ping"},"redskilled daemon")).ok===!0}catch{return!1}}function Bb(e,n){ga(e,(t,r)=>n(t,r),(t,r,o)=>{o({id:r?.id??at(),ok:!1,error:t instanceof Error?t.message:String(t)})})}function Qs(e){let n=e.socketPath,t=Fb(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 ${fu(t.uptime_ms)})`}, but it did not answer a ping \u2014 this is a daemon that could not be REACHED, not one that is missing.`,repair:`Do not provision: a daemon is already running. Inspect it (\`ps -p ${t.pid}\`), or stop it with \`${Oe("red-skills-redskilled",["stop"])}\` and let the next client start a fresh one.`}:{version:1,kind:"absent",socket_path:n,holder:null,reason:`nothing answered on ${JSON.stringify(n)} and no live process holds its lease`,repair:`Install and start one with \`${Oe("red-skills-redskilled",["provision"])}\` (or \`/red-setup\`), then retry.`}}function zs(e){return`${e.reason} ${e.repair}`}function Fb(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:Hb(n.acquired_at,e.now??new Date().toISOString())}}function Hb(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 fu(e){let n=Math.floor(e/1e3),t=Math.floor(n/3600),r=Math.floor(n%3600/60),o=n%60;return t>0?`${t}h${String(r).padStart(2,"0")}m`:r>0?`${r}m${String(o).padStart(2,"0")}s`:`${o}s`}_e();var gu=1e4,Ve=class extends Error{constructor(t,r,o){super(`redskilled daemon is unreachable on ${JSON.stringify(t)}, so no Worker was started: ${r instanceof Error?r.message:String(r)}${o!=null&&o.kind==="held-unresponsive"?`. ${zs(o)}`:""}`);this.socketPath=t;this.cause=r;this.presence=o;this.name="RedskilledUnreachableError"}},Ys=class extends Ve{constructor(t,r,o){super(t,o,r);this.presence=r;this.name="RedskilledDaemonHeldError"}};async function pr(e,n={}){let t=n.answers??await fe(e.socketPath),r=await lt(e.leasePath).catch(()=>{});return Qs({socketPath:e.socketPath,answers:t,lease:r,holderAlive:r!=null&&B(r.pid)})}async function Xs(e,n={}){try{return await Vb(e,n)}catch(t){if(t instanceof De||t instanceof Ve)throw t;let r=await pr(e).catch(()=>{});throw new Ve(e.socketPath,t,r)}}async function Vb(e,n){if(await Gb(Kb(e.socketPath),{recursive:!0,mode:448}),await fe(e.socketPath))return"already-running";await Qb(e);let t=await Jb(e,n);if(t!=null)return t;let r=await ka(e.lockPath,{...n.spawnLockMaxAgeMs==null?{}:{maxAgeMs:n.spawnLockMaxAgeMs},onReap:n.onSpawnLockReaped??qb});if(!r.acquired)return await mu(e,n,void 0,r),"joined";try{if(await fe(e.socketPath))return"already-running";let o=await Yb(e,n);return await mu(e,n,o),"spawned"}finally{await Ra(r)}}function qb(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 Jb(e,n){let t=await pr(e,{answers:!1}).catch(()=>{});if(t==null||t.kind!=="held-unresponsive")return null;let r=n.readyTimeoutMs??gu,o=Date.now()+r;for(;;){if(await fe(e.socketPath))return"joined";if(Date.now()>=o)break;await new Promise(i=>setTimeout(i,25))}let s=await pr(e).catch(()=>{});if(s==null||s.kind!=="held-unresponsive")return null;throw new Ys(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 Qb(e){let t=await Jt(e.machineClaimPath,{machineIdHash:e.machineIdHash,sessionKeyHash:e.sessionKeyHash,socketPath:e.socketPath}).read().catch(()=>{});if(t!=null&&t.socket_path!==e.socketPath&&B(t.pid))throw new De(e.machineClaimPath,"held",t)}async function yu(e,n,t={}){await Xs(e,t);let r;try{r=await rt({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{...n,id:hu()})}catch(o){throw new Ve(e.socketPath,o,await pr(e).catch(()=>{}))}if(!r.ok)throw new Error(r.error);return r.value}async function ku(e,n={},t={}){if(!await fe(e.socketPath))return za(e.socketPath);let r;try{r=await rt({socketPath:e.socketPath,timeoutMs:t.requestTimeoutMs??2e3},{id:hu(),op:"shutdown",...n.detail==null?{}:{detail:n.detail}})}catch(i){throw new Ve(e.socketPath,i)}if(!r.ok)throw new Error(r.error);if(!Bo(r.value))throw new Error("redskilled daemon returned a malformed stop report");let o=r.value;return await zb(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 zb(e,n){let t=Date.now()+n;for(;;){if(!await fe(e))return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,25))}}async function Ru(e,n={}){let t=await yu(e,{op:"host-state"},n);if(!Yd(t))throw new Error("redskilled daemon returned a malformed host state");return t}async function bu(e,n={},t){let r=await yu(e,{op:"statusline-payload",...n.sessionProject!=null?{session_project:n.sessionProject}:{},...t==null?{}:{extras:t}},n);if(!ps(r))throw new Error("redskilled daemon returned a malformed statusline payload");return r}async function _u(e,n=j,t={}){let r=await bu(e,t,{vitals:!0,logs:n.verbose,display:!0});return Ue(r,n)}async function wu(e,n={},t={}){let r=await bu(e,t,{vitals:!0,logs:!0,display:!0});return yn(r,{...pe,...n})}async function mu(e,n,t,r){let o=Date.now()+(n.readyTimeoutMs??gu);for(;;){if(await fe(e.socketPath))return;if(t?.failure)throw new Error(`redskilled daemon failed to start from ${JSON.stringify(t.entry.entry??t.entry.command)} (resolved as ${t.entry.source}): ${t.failure.message}`);if(Date.now()>=o){if(r!=null)throw new Error(`no redskilled daemon answered on ${JSON.stringify(e.socketPath)} within the ready window, and ${ba(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 Yb(e,n){let t=n.serverCommand??(n.serverArgs!=null?process.execPath:void 0),r=await Oa({...t!=null?{serverCommand:t}:{},serverArgs:n.serverArgs},n.entryLookup??{}),o={entry:r},s=[...r.args,...Ce(e,n.idleMs==null?{}:{idleMs:n.idleMs})],i=Ub(r.command,s,{detached:!0,stdio:"ignore",env:{...n.env??process.env,REDSKILLED_DAEMON:"1"}});return i.on("error",l=>{o.failure=l}),i.on("exit",(l,a)=>{o.exit=a?`died on ${a}`:`exited with code ${l??-1}`}),i.unref(),o}_e();import{chmod as ju,mkdir as Au,readFile as Lu,stat as a_,writeFile as d_}from"node:fs/promises";import{homedir as ni}from"node:os";import{dirname as c_,join as ti}from"node:path";import{join as Xb}from"node:path";var xu=["local","tmp","host"],Zb="local",dt="plugins.dev.workspace.target";var Zs=class extends Error{constructor(n){super(n),this.name="WorkspaceConfigError"}};function vu(e){let n=dn(e,dt),t=t_(n??"").trim();return t===""?void 0:t}function Eu(e){let n=(e??"").trim();if(n==="")return{kind:"preset",preset:Zb};let t=xu.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 Zs(`${dt}: unknown workspace target ${JSON.stringify(n)}. Use one of the presets (${xu.join(", ")}) or an absolute parent directory for Workers.`)}function Pu(e,n){return e.kind==="preset"?e.preset==="host":n_(e_(e.parentDir,n),Me(n))}function e_(e,n){return e==="~"?Su(n):e.startsWith("~/")?Xb(n,e.slice(2)):Su(e)}function n_(e,n){return e===n?!0:n==="/"?e.startsWith("/"):e.startsWith(`${n}/`)}function Su(e){let n=e.trim();return n.length>1?n.replace(/\/+$/,""):n}function t_(e){let n=e.trim(),t=/^(["'])(.*)\1$/.exec(n);return t?t[2]:n}_e();import{createHash as r_}from"node:crypto";import{hostname as o_}from"node:os";import{join as fr}from"node:path";var bn="redskilled.sock",s_="REDSKILLED_SESSION";function i_(e={}){let n=e.env??process.env,t=n[s_]?.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 l_(e={}){return Du(e.host??o_())}function me(e={}){let n=i_(e),t=e.runtimeDir??Bt({key:`redskilled:${n}`,socketFileName:bn,env:e.env,uid:e.uid}),r=l_(e);return{sessionKey:n,sessionKeyHash:Du(n),machineIdHash:r,runtimeDir:t,socketPath:fr(t,bn),lockPath:fr(t,"redskilled.spawn.lock"),leasePath:fr(t,"redskilled.lease.toon"),eventLanePath:fr(t,Fa),machineClaimPath:e.machineClaimPath??qt({env:e.env,machineIdHash:r,platform:e.platform})}}function Du(e){return r_("sha256").update(e).digest("hex").slice(0,12)}var ei=`run \`/red-setup\` (Section E3 \u2014 execution daemon), or \`${Oe("red-skills-redskilled",["provision"])}\` directly`;async function Tu(e=ni()){let n=Me(e),t=await oi(n);return t===void 0?(await Au(n,{recursive:!0,mode:ae}),await ju(n,ae),{path:n,created:!0,tightened:!1,mode:ae}):t===ae?{path:n,created:!1,tightened:!1,mode:t}:(await ju(n,ae),{path:n,created:!1,tightened:!0,mode:ae})}var $u={needed:!1,declaredBy:`no ${dt} in view`};async function ri(e={}){let n=e.homeDir??ni(),t=e.declaredTarget?.trim();if(t)return Ou(t,n,"stated on the command line");let r=e.projectRoot?.trim();if(!r)return $u;let o=ti(r,".red","config.yaml"),s=await Lu(o,"utf8").catch(()=>{});if(s===void 0)return{needed:!1,declaredBy:`no ${o}`};let i=vu(s);return i===void 0?{needed:!1,declaredBy:`${o} declares no workspace target (default local)`}:Ou(i,n,o)}function Ou(e,n,t){let r=`${dt}: ${e} (${t})`;try{return{needed:Pu(Eu(e),n),declaredBy:r}}catch{return{needed:!1,declaredBy:`${r} \u2014 off-contract, so it names no lane under the home`}}}function Iu(e){let n=[u_(e),p_(e),f_(e),m_(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 u_(e){let n=e.homeNeed??$u;if(!e.homePresent)return n.needed?{check:"home",verdict:"missing",evidence:`${e.homePath} does not exist, and it is needed \u2014 ${n.declaredBy}`,fix:ei}:{check:"home",verdict:"ok",evidence:`${e.homePath} is absent and unneeded \u2014 ${n.declaredBy}; the daemon never reads it`,fix:""};let t=e.homeMode??ae;return t!==ae?{check:"home",verdict:"degraded",evidence:`${e.homePath} is mode ${t.toString(8)}, not owner-only ${ae.toString(8)}`,fix:`${ei} \u2014 it narrows the home back to owner-only`}:{check:"home",verdict:"ok",evidence:`${e.homePath} (mode ${t.toString(8)})`,fix:""}}function p_(e){return ce(e.entry)?{check:"daemon-entry",verdict:"ok",evidence:`${e.entry.entry??e.entry.command} (resolved as ${e.entry.source})`,fix:""}:{check:"daemon-entry",verdict:"missing",evidence:`no published redskilled bundle; probed ${e.entry.searched.join(", ")||"nothing"}`,fix:`install or warm the RedSkills bundle for this host, then re-run \`${Oe("red-skills-redskilled",["provision"])}\``}}function f_(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:`${ei} \u2014 it starts the daemon and waits for the socket`}}function m_(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??ni(),r=e.paths??me({env:n}),o=Me(t),[s,i,l]=await Promise.all([oi(o),fe(r.socketPath),e.homeNeed?Promise.resolve(e.homeNeed):ri({homeDir:t,projectRoot:e.projectRoot,declaredTarget:e.declaredTarget})]);return{homePath:o,homePresent:s!==void 0,homeMode:s,homeNeed:l,entry:Pe(e.entryOverride??{},{env:n,...e.entryLookup}),socketPath:r.socketPath,reachable:i,supervisorUnit:await g_(y_(e,n,t),n)}}var h_="redskilled.service";function Mu(e){return ti(e,"systemd","user",h_)}function Cu(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 Wu(e){let n=Mu(e.configHome);return await oi(n)!==void 0?{path:n,status:"already-present"}:(await Au(c_(n),{recursive:!0}),await d_(n,e.unit,"utf8"),{path:n,status:"installed"})}async function g_(e,n){if(process.platform!=="linux")return"unsupported";try{return await Lu(Mu(e),"utf8"),"installed"}catch{return n.XDG_RUNTIME_DIR?"absent":"unsupported"}}function y_(e,n,t){return e.configHome??n.XDG_CONFIG_HOME?.trim()??ti(t,".config")}async function oi(e){try{return(await a_(e)).mode&511}catch{return}}import{readdir as Fu,rm as k_,stat as R_}from"node:fs/promises";import{dirname as b_,join as si}from"node:path";var __=5*6e4,w_="redskilled.";function x_(e={}){let n=e.env??process.env,t=i=>b_(Bt({key:"redskilled:reclaim-probe",socketFileName:bn,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 Hu(e={}){let n=e.roots??x_(e),t=e.graceMs??__,r=e.now??Date.now,o=e.isPidAlive??B,s=e.answers??P_,i=e.dryRun===!0,l=[];for(let a of n){let d;try{d=(await Fu(a,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name)}catch{continue}for(let u of d.sort())l.push(await S_(si(a,u),{graceMs:t,now:r,pidAlive:o,answers:s,dryRun:i}))}return{roots:n,scanned:l.length,reclaimed:l.filter(a=>a.verdict==="reclaimed").length,dryRun:i,entries:l}}async function S_(e,n){let t;try{t=(await Fu(e)).sort()}catch(i){return{dir:e,verdict:"failed",reason:Uu(i),removed:[]}}let r=t.filter(i=>i.startsWith(w_));if(t.length>0&&r.length===0)return{dir:e,verdict:"foreign",reason:"holds no redskilled files",removed:[]};let o=await v_(si(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 Bu(e,t,`lease pid ${o.pid} is dead`,n);if(t.includes(bn)&&await n.answers(si(e,bn)))return{dir:e,verdict:"live",reason:"socket answers with no lease",removed:[]};let s=await E_(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 Bu(e,t,t.length===0?"empty and stale":"no lease and stale",n)}async function Bu(e,n,t,r){if(r.dryRun)return{dir:e,verdict:"reclaimed",reason:`${t} (dry run)`,removed:n};try{await k_(e,{recursive:!0,force:!0})}catch(o){return{dir:e,verdict:"failed",reason:Uu(o),removed:[]}}return{dir:e,verdict:"reclaimed",reason:t,removed:n}}async function v_(e){try{return await lt(e)}catch{return}}async function E_(e,n){try{return Math.max(0,n()-(await R_(e)).mtimeMs)}catch{return}}async function P_(e){try{return(await rt({socketPath:e,timeoutMs:250},{id:`redskilled-reclaim-${process.pid}`,op:"ping"})).ok}catch{return!1}}function Uu(e){return e instanceof Error?e.message:String(e)}var D_="plugins.dev.statusline",j_="dev.statusline";function O_(e){let n=[],t=l=>{for(let a of[D_,j_]){let d=`${a}.${l}`,u=dn(e,d)?.trim();if(u!=null&&u!=="")return{key:d,value:u}}},r=t("mode"),o={};r!=null&&(r.value==="local"||r.value==="global"?o.mode=r.value:n.push({...r,reason:"expected `local` or `global`"}));let s=[{leaf:"max_workers",assign:l=>{o.maxWorkers=l}},{leaf:"max_projects",assign:l=>{o.maxProjects=l}},{leaf:"max_width",assign:l=>{o.maxWidth=l}}];for(let l of s){let a=t(l.leaf);if(a==null)continue;let d=Number(a.value);Number.isInteger(d)&&d>=0?l.assign(d):n.push({...a,reason:"expected a whole number of zero or more"})}let i=t("verbose");return i!=null&&(i.value==="true"||i.value==="false"?o.verbose=i.value==="true":n.push({...i,reason:"expected `true` or `false`"})),{config:o,warnings:n}}var A_={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 ii(e){let{values:n,positionals:t}=Ie(e,A_),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 li(e={}){let n=e.configText==null?{config:{},warnings:[]}:O_(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 T_=`Usage: redskilled <command> [options]
83
83
 
84
84
  Commands:
85
85
  host-state (default) print the host's state as JSON
@@ -92,7 +92,7 @@ Commands:
92
92
 
93
93
  Run \`redskilled <command> --help\` for a command's own usage.
94
94
  \`--version\` (\`-v\`) prints the build stamp; both answer offline.
95
- `,c_={serve:`Usage: redskilled serve [options]
95
+ `,$_={serve:`Usage: redskilled serve [options]
96
96
 
97
97
  Runs the daemon in this process. Every path is a flag and none is derived
98
98
  (ADR 0130 rule 3); what is absent falls back to the session derivation.
@@ -166,24 +166,24 @@ Reports every session runtime dir it looked at and why it kept or removed it.
166
166
 
167
167
  --dry-run the same report with nothing removed
168
168
  --grace-ms <n> how long a dir must be idle before it is reclaimed
169
- `};function u_(e){return e==="--help"||e==="-h"||e==="help"}var p_={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)}},vu="REDSKILLED_HOST_TOKEN";function ar(){try{let n=a_("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function Eu(e=process.env,n=ar){let t=(e[vu]??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 f_(e,n=process.env,t=ar){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...xu(e,n,t),armTransport:()=>xu(e,n,t)}}function m_(e,n=process.env,t=ar){let r=Eu(n,t);if(r==null)return null;let o=n.GITHUB_API_URL;return{transport:zo({token:r.token,...o?{origin:o}:{}})}}function xu(e,n=process.env,t=ar){let r=Eu(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${vu}, 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:bd({token:r.token,...o?{endpoint:o}:{}})}}async function h_(e){if(e[0]==="--version"||e[0]==="-v"){let o=qr("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
170
- `:`${il(o)}
171
- `),0}if(u_(e[0]))return process.stdout.write(d_),0;let{command:n,args:t}=cl(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(c_[n]),0;if(n==="serve"){let{values:o}=Le(t,p_),s=f_(o),i=m_(o),l=Su($e(Us()),"state"),a=Ol({stateRoot:l});process.stderr.write(`${Al(a)}
172
- `);let d=vl({lanePath:Tn(l),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),c=await Kc({paths:v_(o),idleMs:o["idle-ms"]??js,daemonVersion:o["daemon-version"]??qr("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 y_(t);if(n==="statusline")return await R_(t);if(n==="dashboard")return await P_(t);if(n==="unit")return await k_(t);if(n==="provision")return await __(t);if(n==="reclaim")return await x_(t);let r=await Xc(ue());return process.stdout.write(`${JSON.stringify(r,null,2)}
173
- `),0}var g_={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function y_(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=Le(e,g_),o=await Yc(n.paths??ue(),{...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 k_(e,n={}){let t=n.write??(s=>process.stdout.write(s)),r=n.paths??ue(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(Rc(n.unitIO??{}),null,2)}
175
- `),0;if(o==="install"){let s=await yc(hc(r),n.unitIO??{});return t(`${JSON.stringify(s,null,2)}
176
- `),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await kc(n.unitIO??{}),null,2)}
177
- `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function R_(e,n={}){let t=n.write??(a=>process.stdout.write(a)),r=n.warn??(a=>process.stderr.write(a)),o=Fs(e),s=Pu(n.cwd??process.cwd()),i=Hs({...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 eu(n.paths??ue(),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=ps({options:i.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${l.lines.join(`
169
+ `};function I_(e){return e==="--help"||e==="-h"||e==="help"}var N_={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)}},Vu="REDSKILLED_HOST_TOKEN";function mr(){try{let n=L_("gh",["auth","token"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n===""?null:n}catch{return null}}function qu(e=process.env,n=mr){let t=(e[Vu]??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 M_(e,n=process.env,t=mr){return{...e["queue-ms"]==null?{}:{intervalMs:e["queue-ms"]},...Gu(e,n,t),armTransport:()=>Gu(e,n,t)}}function C_(e,n=process.env,t=mr){let r=qu(n,t);if(r==null)return null;let o=n.GITHUB_API_URL;return{transport:ss({token:r.token,...o?{origin:o}:{}})}}function Gu(e,n=process.env,t=mr){let r=qu(n,t);if(r==null)return{unconfiguredReason:`no credential names a tracker for this host: ${Vu}, 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:Cd({token:r.token,...o?{endpoint:o}:{}})}}async function W_(e){if(e[0]==="--version"||e[0]==="-v"){let o=no("redskilled");return process.stdout.write(e.includes("--json")?`${JSON.stringify(o)}
170
+ `:`${vl(o)}
171
+ `),0}if(I_(e[0]))return process.stdout.write(T_),0;let{command:n,args:t}=jl(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($_[n]),0;if(n==="serve"){let{values:o}=Ie(t,N_),s=M_(o),i=C_(o),l=Ku(Me(ai()),"state"),a=Ql({stateRoot:l});process.stderr.write(`${zl(a)}
172
+ `);let d=Gl({lanePath:Mn(l),kind:"daemon",id:`daemon:${process.pid}`,phase:"serving"}),u=await pu({paths:Q_(o),idleMs:o["idle-ms"]??Js,daemonVersion:o["daemon-version"]??no("redskilled").version,deaths:a.attributions,queueDiscovery:s,...i==null?{}:{githubBalance:i},...o["demand-ms"]==null?{}:{demandMs:o["demand-ms"]}});for(let p of["SIGTERM","SIGINT"])process.once(p,()=>void u.stop({reason:"signal",signal:p}).catch(()=>{}));return await u.closed,d.phase("closed"),0}if(n==="stop")return await F_(t);if(n==="statusline")return await U_(t);if(n==="dashboard")return await Y_(t);if(n==="unit")return await H_(t);if(n==="provision")return await K_(t);if(n==="reclaim")return await q_(t);let r=await Ru(me());return process.stdout.write(`${JSON.stringify(r,null,2)}
173
+ `),0}var B_={reason:{kind:"value",coerce:e=>e},"settle-timeout-ms":{kind:"value",coerce:e=>Number(e)}};async function F_(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=Ie(e,B_),o=await ku(n.paths??me(),{...r.reason==null?{}:{detail:r.reason},...Number.isFinite(r["settle-timeout-ms"])?{settleTimeoutMs:r["settle-timeout-ms"]}:{}},n.client??{});return t(`${W({running:o.running,stopped:o.stopped,reason:o.reason,socket:o.socket_path,daemon_version:o.daemon_version,pid:o.pid,holding:{workers:o.holding.workers.length,projects:[...o.holding.projects]},surviving:[...o.surviving],workers:o.holding.workers.map(s=>({worker_id:s.worker_id,project_label:s.project_label,pid:s.pid,unit:s.unit,isolated:s.isolated,survives:s.survives})),detail:o.detail})}
174
+ `),o.running&&!o.stopped?1:0}async function H_(e,n={}){let t=n.write??(s=>process.stdout.write(s)),r=n.paths??me(),o=e[0]??"status";if(o==="status")return t(`${JSON.stringify(Bc(n.unitIO??{}),null,2)}
175
+ `),0;if(o==="install"){let s=await Cc(Nc(r),n.unitIO??{});return t(`${JSON.stringify(s,null,2)}
176
+ `),s.installed?0:1}if(o==="uninstall")return t(`${JSON.stringify(await Wc(n.unitIO??{}),null,2)}
177
+ `),0;throw new Error(`unsupported redskilled unit action ${JSON.stringify(o)}: expected install, uninstall or status`)}async function U_(e,n={}){let t=n.write??(a=>process.stdout.write(a)),r=n.warn??(a=>process.stderr.write(a)),o=ii(e),s=Ju(n.cwd??process.cwd()),i=li({...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 _u(n.paths??me(),i.options,{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}})}catch(a){r(`redskilled statusline: ${a instanceof Error?a.message:String(a)}
179
+ `),l=Os({options:i.options,generated_at:(n.now??(()=>new Date().toISOString()))()})}return t(`${l.lines.join(`
180
180
  `)}
181
- `),0}var b_={"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 __(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=Le(e,b_),o=n.paths??ue(),s=n.homeDir??Us(),i=await Cs({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),l=r.check||!i.needed?void 0:await pu(s),a;if(!r.check&&!r["no-start"])try{await Ts(o,n.client??{})}catch(f){a=f instanceof Error?f.message:String(f)}let d=await hu({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"]&&de(d.entry)?await ku({configHome:n.configHome??S_(),unit:yu({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,u=mu(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 w_={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function x_(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=Le(e,w_),o=await _u({...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 S_(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:Su(Us(),".config")}function Pu(e){let n=fo(e);return n.configText==null?{label:null}:{configText:n.configText,label:Wl(e)}}function v_(e){let n=ue();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 E_=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;E_&&h_(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 P_(e,n={}){let t=n.write??(l=>process.stdout.write(l)),r=n.warn??(l=>process.stderr.write(l)),o=Fs(e),s=Pu(n.cwd??process.cwd()),i=Hs({...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 nu(n.paths??ue(),{...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(`
181
+ `),0}var G_={"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 K_(e,n={}){let t=n.write??(f=>process.stdout.write(f)),{values:r}=Ie(e,G_),o=n.paths??me(),s=n.homeDir??ai(),i=await ri({homeDir:s,declaredTarget:r.workspace,projectRoot:r.project??n.projectRoot??process.cwd()}),l=r.check||!i.needed?void 0:await Tu(s),a;if(!r.check&&!r["no-start"])try{await Xs(o,n.client??{})}catch(f){a=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}}}),u=r["install-unit"]&&ce(d.entry)?await Wu({configHome:n.configHome??J_(),unit:Cu({command:[d.entry.command,...d.entry.args].join(" "),socketPath:o.socketPath})}):void 0,p=Iu(d);return t(`${W({verdict:p.verdict,home:{path:l?.path??d.homePath,created:l?.created??!1,tightened:l?.tightened??!1,needed:i.needed,needed_by:i.declaredBy},socket:d.socketPath,...a==null?{}:{start_error:a},...u==null?{}:{unit:{path:u.path,status:u.status}},checks:p.rows.map(f=>({check:f.check,verdict:f.verdict,evidence:f.evidence})),fixes:p.findings.map(f=>({check:f.check,fix:f.fix}))})}
182
+ `),p.verdict==="ok"?0:1}var V_={"dry-run":{kind:"boolean"},"grace-ms":{kind:"value",coerce:e=>Number(e)}};async function q_(e,n={}){let t=n.write??(s=>process.stdout.write(s)),{values:r}=Ie(e,V_),o=await Hu({...n.options??{},dryRun:r["dry-run"]===!0,...Number.isFinite(r["grace-ms"])?{graceMs:r["grace-ms"]}:{}});return t(`${W({roots:[...o.roots],scanned:o.scanned,reclaimed:o.reclaimed,dry_run:o.dryRun,entries:o.entries.map(s=>({dir:s.dir,verdict:s.verdict,reason:s.reason,removed:[...s.removed]}))})}
183
+ `),o.entries.some(s=>s.verdict==="failed")?1:0}function J_(){let e=process.env.XDG_CONFIG_HOME?.trim();return e&&e!==""?e:Ku(ai(),".config")}function Ju(e){let n=_o(e);return n.configText==null?{label:null}:{configText:n.configText,label:oa(e)}}function Q_(e){let n=me();return{...n,socketPath:e.socket??n.socketPath,leasePath:e.lease??n.leasePath,eventLanePath:e.events??n.eventLanePath,sessionKeyHash:e["session-key-hash"]??n.sessionKeyHash,machineIdHash:e["machine-id-hash"]??n.machineIdHash,machineClaimPath:e["machine-claim"]??n.machineClaimPath}}var z_=process.argv[1]!=null&&import.meta.url===new URL(`file://${process.argv[1]}`).href;z_&&W_(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 Y_(e,n={}){let t=n.write??(l=>process.stdout.write(l)),r=n.warn??(l=>process.stderr.write(l)),o=ii(e),s=Ju(n.cwd??process.cwd()),i=li({...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 wu(n.paths??me(),{...i.options.project==null?{}:{project:i.options.project},mode:i.options.mode,...i.options.maxWidth==null?{}:{maxWidth:i.options.maxWidth}},{...n.client??{},...i.options.project==null?{}:{sessionProject:i.options.project}});t(`${l.lines.join(`
186
186
  `)}
187
187
  `)}catch(l){r(`redskilled dashboard: ${l instanceof Error?l.message:String(l)}
188
188
  `),t(`redskilled unreachable \u2014 the host was not asked, so its Workers are unknown
189
- `)}return 0}export{vu as REDSKILLED_HOST_TOKEN_ENV,d_ as REDSKILLED_USAGE,xu as armRedskilledQueueTransport,Eu as resolveRedskilledHostToken,m_ as resolveServeGithubBalance,f_ as resolveServeQueueDiscovery,P_ as runDashboard,__ as runProvision,x_ as runReclaim,h_ as runRedskilledCli,R_ as runStatusline,y_ as runStop,k_ as runUnit};
189
+ `)}return 0}export{Vu as REDSKILLED_HOST_TOKEN_ENV,T_ as REDSKILLED_USAGE,Gu as armRedskilledQueueTransport,qu as resolveRedskilledHostToken,C_ as resolveServeGithubBalance,M_ as resolveServeQueueDiscovery,Y_ as runDashboard,K_ as runProvision,q_ as runReclaim,W_ as runRedskilledCli,U_ as runStatusline,F_ as runStop,H_ as runUnit};